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.
 
 
 
 
 
 

214 lines
7.0 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. for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
  89. $values = [];
  90. $salt = \fast\Random::alnum();
  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. if (!$val){
  98. continue 2;
  99. }
  100. $values[] = is_null($val) ? '' : $val;
  101. }
  102. // $row = [];
  103. $temp = array_combine($fields, $values);
  104. // foreach ($temp as $k => $v) {
  105. // if (isset($fieldArr[$k]) && $k !== '') {
  106. // $row[$fieldArr[$k]] = $v;
  107. // }
  108. // }
  109. // print_r($temp);
  110. // print_r($row);
  111. // if ($row) {
  112. $temp['status']="normal";
  113. $temp['salt']=$salt;
  114. $insert[] = $temp;
  115. // }
  116. }
  117. } catch (Exception $exception) {
  118. $this->error($exception->getMessage());
  119. }
  120. if (!$insert) {
  121. $this->error(__('No rows were updated'));
  122. }
  123. try {
  124. //是否包含admin_id字段
  125. $has_admin_id = false;
  126. foreach ($fieldArr as $name => $key) {
  127. if ($key == 'admin_id') {
  128. $has_admin_id = true;
  129. break;
  130. }
  131. }
  132. if ($has_admin_id) {
  133. $auth = Auth::instance();
  134. foreach ($insert as &$val) {
  135. if (!isset($val['admin_id']) || empty($val['admin_id'])) {
  136. $val['admin_id'] = $auth->isLogin() ? $auth->id : 0;
  137. }
  138. }
  139. }
  140. $this->model->saveAll($insert);
  141. } catch (PDOException $exception) {
  142. $msg = $exception->getMessage();
  143. if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
  144. $msg = "导入失败,包含【{$matches[1]}】的记录已存在";
  145. };
  146. $this->error($msg);
  147. } catch (Exception $e) {
  148. $this->error($e->getMessage());
  149. }
  150. $this->success();
  151. }
  152. /**
  153. * 查看
  154. */
  155. public function index()
  156. {
  157. //设置过滤方法
  158. $this->request->filter(['strip_tags']);
  159. if ($this->request->isAjax()) {
  160. //如果发送的来源是Selectpage,则转发到Selectpage
  161. if ($this->request->request('keyField')) {
  162. return $this->selectpage();
  163. }
  164. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  165. $total = $this->model
  166. ->with('group')
  167. ->where($where)
  168. ->order($sort, $order)
  169. ->count();
  170. $list = $this->model
  171. ->with('group')
  172. ->where($where)
  173. ->order($sort, $order)
  174. ->limit($offset, $limit)
  175. ->select();
  176. foreach ($list as $k => $v) {
  177. $v->hidden(['password', 'salt']);
  178. }
  179. $result = array("total" => $total, "rows" => $list);
  180. return json($result);
  181. }
  182. return $this->view->fetch();
  183. }
  184. /**
  185. * 编辑
  186. */
  187. public function edit($ids = NULL)
  188. {
  189. $row = $this->model->get($ids);
  190. if (!$row)
  191. $this->error(__('No Results were found'));
  192. $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
  193. return parent::edit($ids);
  194. }
  195. }