You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

209 lines
6.8 KiB

  1. <?php
  2. namespace app\admin\controller\user;
  3. use app\admin\library\Auth;
  4. use app\common\controller\Backend;
  5. use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
  6. use PhpOffice\PhpSpreadsheet\Reader\Csv;
  7. use PhpOffice\PhpSpreadsheet\Reader\Xls;
  8. use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
  9. use think\exception\PDOException;
  10. /**
  11. * 会员管理
  12. *
  13. * @icon fa fa-user
  14. */
  15. class User extends Backend
  16. {
  17. protected $relationSearch = true;
  18. /**
  19. * @var \app\admin\model\User
  20. */
  21. protected $model = null;
  22. public function _initialize()
  23. {
  24. parent::_initialize();
  25. $this->model = model('User');
  26. }
  27. public function import()
  28. {
  29. $file = $this->request->request('file');
  30. if (!$file) {
  31. $this->error(__('Parameter %s can not be empty', 'file'));
  32. }
  33. $filePath = ROOT_PATH . DS . 'public' . DS . $file;
  34. if (!is_file($filePath)) {
  35. $this->error(__('No results were found'));
  36. }
  37. //实例化reader
  38. $ext = pathinfo($filePath, PATHINFO_EXTENSION);
  39. if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
  40. $this->error(__('Unknown data format'));
  41. }
  42. if ($ext === 'csv') {
  43. $file = fopen($filePath, 'r');
  44. $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
  45. $fp = fopen($filePath, "w");
  46. $n = 0;
  47. while ($line = fgets($file)) {
  48. $line = rtrim($line, "\n\r\0");
  49. $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
  50. if ($encoding != 'utf-8') {
  51. $line = mb_convert_encoding($line, 'utf-8', $encoding);
  52. }
  53. if ($n == 0 || preg_match('/^".*"$/', $line)) {
  54. fwrite($fp, $line . "\n");
  55. } else {
  56. fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
  57. }
  58. $n++;
  59. }
  60. fclose($file) || fclose($fp);
  61. $reader = new Csv();
  62. } elseif ($ext === 'xls') {
  63. $reader = new Xls();
  64. } else {
  65. $reader = new Xlsx();
  66. }
  67. //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
  68. $fieldArr = [ 'nickname',
  69. 'username',
  70. 'password',
  71. 'email',];
  72. //加载文件
  73. $insert = [];
  74. try {
  75. if (!$PHPExcel = $reader->load($filePath)) {
  76. $this->error(__('Unknown data format'));
  77. }
  78. $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
  79. $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
  80. $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
  81. // $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
  82. $fields = [
  83. 'nickname',
  84. 'username',
  85. 'password',
  86. 'email',
  87. ];
  88. $salt = \fast\Random::alnum();
  89. for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
  90. $values = [];
  91. for ($currentColumn = 1; $currentColumn <= 4; $currentColumn++) {
  92. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  93. if ($currentColumn==3){
  94. //修改的是密码
  95. $val= \app\common\library\Auth::instance()->getEncryptPassword($val, $salt);
  96. }
  97. $values[] = is_null($val) ? '' : $val;
  98. }
  99. // $row = [];
  100. $temp = array_combine($fields, $values);
  101. // foreach ($temp as $k => $v) {
  102. // if (isset($fieldArr[$k]) && $k !== '') {
  103. // $row[$fieldArr[$k]] = $v;
  104. // }
  105. // }
  106. // print_r($temp);
  107. // print_r($row);
  108. // if ($row) {
  109. $insert[] = $temp;
  110. // }
  111. }
  112. } catch (Exception $exception) {
  113. $this->error($exception->getMessage());
  114. }
  115. if (!$insert) {
  116. $this->error(__('No rows were updated'));
  117. }
  118. try {
  119. //是否包含admin_id字段
  120. $has_admin_id = false;
  121. foreach ($fieldArr as $name => $key) {
  122. if ($key == 'admin_id') {
  123. $has_admin_id = true;
  124. break;
  125. }
  126. }
  127. if ($has_admin_id) {
  128. $auth = Auth::instance();
  129. foreach ($insert as &$val) {
  130. if (!isset($val['admin_id']) || empty($val['admin_id'])) {
  131. $val['admin_id'] = $auth->isLogin() ? $auth->id : 0;
  132. }
  133. }
  134. }
  135. $this->model->saveAll($insert);
  136. } catch (PDOException $exception) {
  137. $msg = $exception->getMessage();
  138. if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
  139. $msg = "导入失败,包含【{$matches[1]}】的记录已存在";
  140. };
  141. $this->error($msg);
  142. } catch (Exception $e) {
  143. $this->error($e->getMessage());
  144. }
  145. $this->success();
  146. }
  147. /**
  148. * 查看
  149. */
  150. public function index()
  151. {
  152. //设置过滤方法
  153. $this->request->filter(['strip_tags']);
  154. if ($this->request->isAjax()) {
  155. //如果发送的来源是Selectpage,则转发到Selectpage
  156. if ($this->request->request('keyField')) {
  157. return $this->selectpage();
  158. }
  159. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  160. $total = $this->model
  161. ->with('group')
  162. ->where($where)
  163. ->order($sort, $order)
  164. ->count();
  165. $list = $this->model
  166. ->with('group')
  167. ->where($where)
  168. ->order($sort, $order)
  169. ->limit($offset, $limit)
  170. ->select();
  171. foreach ($list as $k => $v) {
  172. $v->hidden(['password', 'salt']);
  173. }
  174. $result = array("total" => $total, "rows" => $list);
  175. return json($result);
  176. }
  177. return $this->view->fetch();
  178. }
  179. /**
  180. * 编辑
  181. */
  182. public function edit($ids = NULL)
  183. {
  184. $row = $this->model->get($ids);
  185. if (!$row)
  186. $this->error(__('No Results were found'));
  187. $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
  188. return parent::edit($ids);
  189. }
  190. }