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.
 
 
 
 
 
 

217 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. 'floor'
  73. ];
  74. //加载文件
  75. $insert = [];
  76. try {
  77. if (!$PHPExcel = $reader->load($filePath)) {
  78. $this->error(__('Unknown data format'));
  79. }
  80. $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
  81. $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
  82. $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
  83. // $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
  84. $fields = [
  85. 'nickname',
  86. 'username',
  87. 'password',
  88. 'email',
  89. 'floor'
  90. ];
  91. for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
  92. $values = [];
  93. $salt = \fast\Random::alnum();
  94. for ($currentColumn = 1; $currentColumn <= 5; $currentColumn++) {
  95. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  96. if ($currentColumn==3){
  97. //修改的是密码
  98. $val= \app\common\library\Auth::instance()->getEncryptPassword($val, $salt);
  99. }
  100. if (!$val){
  101. continue 2;
  102. }
  103. $values[] = is_null($val) ? '' : $val;
  104. }
  105. // $row = [];
  106. $temp = array_combine($fields, $values);
  107. // foreach ($temp as $k => $v) {
  108. // if (isset($fieldArr[$k]) && $k !== '') {
  109. // $row[$fieldArr[$k]] = $v;
  110. // }
  111. // }
  112. // print_r($temp);
  113. // print_r($row);
  114. // if ($row) {
  115. $temp['status']="normal";
  116. $temp['salt']=$salt;
  117. $insert[] = $temp;
  118. // }
  119. }
  120. } catch (Exception $exception) {
  121. $this->error($exception->getMessage());
  122. }
  123. if (!$insert) {
  124. $this->error(__('No rows were updated'));
  125. }
  126. try {
  127. //是否包含admin_id字段
  128. $has_admin_id = false;
  129. foreach ($fieldArr as $name => $key) {
  130. if ($key == 'admin_id') {
  131. $has_admin_id = true;
  132. break;
  133. }
  134. }
  135. if ($has_admin_id) {
  136. $auth = Auth::instance();
  137. foreach ($insert as &$val) {
  138. if (!isset($val['admin_id']) || empty($val['admin_id'])) {
  139. $val['admin_id'] = $auth->isLogin() ? $auth->id : 0;
  140. }
  141. }
  142. }
  143. $this->model->saveAll($insert);
  144. } catch (PDOException $exception) {
  145. $msg = $exception->getMessage();
  146. if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
  147. $msg = "导入失败,包含【{$matches[1]}】的记录已存在";
  148. };
  149. $this->error($msg);
  150. } catch (Exception $e) {
  151. $this->error($e->getMessage());
  152. }
  153. $this->success();
  154. }
  155. /**
  156. * 查看
  157. */
  158. public function index()
  159. {
  160. //设置过滤方法
  161. $this->request->filter(['strip_tags']);
  162. if ($this->request->isAjax()) {
  163. //如果发送的来源是Selectpage,则转发到Selectpage
  164. if ($this->request->request('keyField')) {
  165. return $this->selectpage();
  166. }
  167. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  168. $total = $this->model
  169. ->with('group')
  170. ->where($where)
  171. ->order($sort, $order)
  172. ->count();
  173. $list = $this->model
  174. ->with('group')
  175. ->where($where)
  176. ->order($sort, $order)
  177. ->limit($offset, $limit)
  178. ->select();
  179. foreach ($list as $k => $v) {
  180. $v->hidden(['password', 'salt']);
  181. }
  182. $result = array("total" => $total, "rows" => $list);
  183. return json($result);
  184. }
  185. return $this->view->fetch();
  186. }
  187. /**
  188. * 编辑
  189. */
  190. public function edit($ids = NULL)
  191. {
  192. $row = $this->model->get($ids);
  193. if (!$row)
  194. $this->error(__('No Results were found'));
  195. $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
  196. return parent::edit($ids);
  197. }
  198. }