common.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. <?php
  2. // 应用公共文件
  3. use think\facade\Filesystem;
  4. use think\facade\Config;
  5. use app\model\AdminTokenModel;
  6. use app\model\AdminModel;
  7. use think\exception\ValidateException;
  8. use app\model\CommonModel;
  9. //返回响应数据
  10. if (!function_exists('json_show')) {
  11. function json_show(int $code = 0, string $message = '请求成功', array $data = [])
  12. {
  13. return json(['code' => $code, 'message' => $message, 'data' => $data]);
  14. }
  15. }
  16. //获取加密后的密码
  17. //@param $password string 密码
  18. //@param $salt string 盐值
  19. if (!function_exists('get_password')) {
  20. function get_password(string $password = '', string $salt = ''): string
  21. {
  22. return sha1($password . $salt);
  23. }
  24. }
  25. //获取token
  26. //@param $admin_id int 运营账号表id
  27. //@param $username string 账户
  28. //@param $salt string 盐值
  29. if (!function_exists('make_token')) {
  30. function make_token(int $admin_id = 0, string $username = '', string $salt = ''): string
  31. {
  32. $now = time();
  33. $str = $username . $salt . (string)$now;
  34. $token = base64_encode($str);
  35. AdminTokenModel::handleToken($admin_id, $token);
  36. return $token;
  37. }
  38. }
  39. //校验token
  40. //@param $salt string 盐值
  41. if (!function_exists('verify_token')) {
  42. function verify_token(string $token = '')
  43. {
  44. $has = AdminTokenModel::where(['token' => $token])->findOrEmpty();
  45. if ($has->isEmpty()) throw new ValidateException('token不存在');
  46. if (strtotime($has->expiretime) <= time()) throw new ValidateException('token已失效');
  47. $account = AdminModel::where(['id' => $has['adminid'], 'is_del' => CommonModel::$del_normal])->findOrEmpty();
  48. if ($account->isEmpty()) throw new ValidateException('未找到账户');
  49. if ($account->status != CommonModel::$status_normal) throw new ValidateException('账户已禁用');
  50. $token_str = base64_decode($token);
  51. $account_str = substr($token_str, 0, -10);
  52. if ($account_str == $account->username . $account->salt) {
  53. AdminTokenModel::where(['token' => $token])
  54. ->save(['expiretime' => date('Y-m-d H:i:s', time() + Config::get('common.expire'))]);
  55. return ['uid' => $account->id, 'uname' => $account->nickname, 'roleid' => $account->role_id];
  56. } else throw new ValidateException('账户token无效');
  57. }
  58. }
  59. //发送post的curl请求
  60. if (!function_exists('curl_request')) {
  61. function curl_request(string $url = '', array $data = [], array $header = [])
  62. {
  63. $curl = curl_init();
  64. curl_setopt($curl, CURLOPT_URL, $url);
  65. curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)');
  66. curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
  67. curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
  68. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  69. if ($data) {
  70. curl_setopt($curl, CURLOPT_POST, 1);
  71. curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
  72. }
  73. curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);
  74. if (!$header) $header = [
  75. 'uid:' . request()->development['id'],
  76. 'nickname:' . request()->development['contactor'],
  77. 'mobile:' . request()->development['mobile'],
  78. // 'email:',
  79. 'supplierNo:' . request()->development['supplierNo'],
  80. 'supplierName:' . request()->development['supplierName']
  81. ];
  82. curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
  83. curl_setopt($curl, CURLOPT_TIMEOUT, 10);
  84. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  85. $data = curl_exec($curl);
  86. if (curl_errno($curl)) {
  87. return curl_error($curl);
  88. }
  89. curl_close($curl);
  90. return $data;
  91. }
  92. }
  93. //生成编码
  94. //@param $str string 前缀
  95. if (!function_exists('make_no')) {
  96. function make_no(string $str = ''): string
  97. {
  98. $date = date("ymdHis");
  99. // $year = date("Y")-2000;
  100. $msec = randomkeys(4);
  101. return $str . $msec . $date;
  102. }
  103. }
  104. //生成随机字符串
  105. //@param $length int 长度,默认4
  106. if (!function_exists('randomkeys')) {
  107. function randomkeys(int $length = 4): string
  108. {
  109. $returnStr = '';
  110. $pattern = 'abcdefghijklmnopqrstuvwxyz';//ABCDEFGHIJKLOMNOPQRSTUVWXYZ
  111. $min = 0;
  112. $max = strlen($pattern) - 1;
  113. for ($i = 0; $i < $length; $i++) {
  114. $returnStr .= $pattern[mt_rand($min, $max)]; //生成php随机数
  115. }
  116. return $returnStr;
  117. }
  118. }
  119. //上传图片
  120. /**
  121. * @param $files
  122. * @return array
  123. */
  124. if (!function_exists('upload_img')) {
  125. function upload_img($files): array
  126. {
  127. $savename = [];
  128. $files = !is_array($files) ? [$files] : $files;
  129. //验证
  130. validate([
  131. 'imgFile' => [
  132. 'fileSize' => 10240000,
  133. 'fileExt' => 'jpg,jpeg,png,bmp,gif',
  134. 'fileMime' => 'image/jpeg,image/png,image/gif'
  135. ]
  136. ])->check(['imgFile' => $files]);
  137. foreach ($files as $file) {
  138. $url = Filesystem::disk('public')
  139. ->putFile('topic/' . date("Ymd"), $file, function () use ($file) {
  140. return str_replace('.' . $file->getOriginalExtension(), '', $file->getOriginalName() . "_" . date('YmdHis'));
  141. });
  142. $name = str_replace('.' . $file->getOriginalExtension(), '', $file->getOriginalName());
  143. $temp = ["url" => $url, "name" => $name];
  144. $savename[] = $temp;
  145. }
  146. return $savename;
  147. }
  148. }
  149. //导出文件成压缩包
  150. if (!function_exists('excel_save')) {
  151. function excel_save($fileName = '', $headArr = [], $data = [])
  152. {
  153. $objPHPExcel = new PHPExcel();
  154. $objPHPExcel->getProperties();
  155. $keyA = 0; // 设置表头
  156. foreach ($headArr as $v) {
  157. $colum = PHPExcel_Cell::stringFromColumnIndex($keyA);
  158. $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
  159. $keyA += 1;
  160. }
  161. $column = 2;
  162. $objActSheet = $objPHPExcel->getActiveSheet();
  163. foreach ($data as $key => $rows) { // 行写入
  164. $span = 0;
  165. foreach ($rows as $keyName => $value) { // 列写入
  166. //判断数据是否有数组,如果有数组,转换成字符串
  167. if (is_array($value)) $value = implode("、", $value);
  168. $objActSheet->setCellValue(PHPExcel_Cell::stringFromColumnIndex($span) . $column, $value);
  169. $span++;
  170. }
  171. $column++;
  172. }
  173. // var_dump($objActSheet->getActiveCell());
  174. $file = $fileName . ".xls";
  175. //$fileName .= "_" . date("Y_m_d", Request()->instance()->time()) . ".xls";
  176. //$fileName = iconv("utf-8", "gb2312", $fileName); // 重命名表
  177. $dir = root_path() . 'public/storage/report/' . date("YmdHis") . "/";
  178. if (!is_dir($dir)) mkdir($dir, 0777, true);
  179. PHPExcel_Settings::setCacheStorageMethod(PHPExcel_CachedObjectStorageFactory::cache_in_memory_serialized);
  180. $objPHPExcel->setActiveSheetIndex(0); // 设置活动单指数到第一个表,所以Excel打开这是第一个表
  181. $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  182. $objWriter->save($dir . $file); // 文件通过浏览器下载
  183. $url = $dir . $file;
  184. if (!file_exists($url)) throw new \think\Exception('文件生成失败');
  185. $saveDir = root_path() . "public/storage/zip/";
  186. if (!is_dir($saveDir)) mkdir($saveDir, 0777, true);
  187. // $datetime = date("YmdHis");
  188. $file_dir = $saveDir . $fileName . ".zip";
  189. # 5.1 文件打包,提示:使用本类,linux需开启zlib,windows需取消php_zip.dll前的注释
  190. $zip = new \ZipArchive ();
  191. # 5.2 文件不存在则生成一个新的文件 用CREATE打开文件会追加内容至zip
  192. if ($zip->open($file_dir, \ZipArchive::OVERWRITE) !== true && $zip->open($file_dir, \ZipArchive::CREATE) !== true) throw new \think\Exception('无法打开文件或者文件创建失败');
  193. # 5.3 批量写入压缩包
  194. $zip->addEmptyDir($fileName);
  195. // @$zip->addFile($v['file_path'], 'resume'.DIRECTORY_SEPARATOR.basename($headername));
  196. @$zip->addFile($url, $fileName . DIRECTORY_SEPARATOR . basename($url));
  197. # 5.4 关闭压缩包写入
  198. $zip->close();
  199. @del_dir($dir);
  200. # 6. 检查文件是否存在,并输出文件
  201. if (!file_exists($file_dir)) throw new \think\Exception('导出文件不存在');
  202. ob_clean();
  203. flush();
  204. header("Cache-Control: max-age=0");
  205. header("Content-Description: File Transfer");
  206. header('Content-disposition: attachment; filename=' . basename($file_dir)); # 处理文件名
  207. header("Content-Type: application/octet-stream"); # 流文件输出
  208. header("Content-Transfer-Encoding: binary"); # 告诉浏览器,这是二进制文件
  209. // header('Content-Length: ' . filesize($file_dir)); # 告诉浏览器,文件大小
  210. // readfile($file_dir); # 输出文件
  211. $res = read_big_file($file_dir);
  212. foreach ($res as $val) {
  213. echo $val;
  214. }
  215. @ unlink($file_dir);
  216. exit();
  217. }
  218. }
  219. //读取大文件
  220. if (!function_exists('read_big_file')) {
  221. function read_big_file(string $file = '')
  222. {
  223. $handle = fopen($file, 'rb');
  224. while (feof($handle) === false) {
  225. yield fgets($handle);
  226. }
  227. fclose($handle);
  228. }
  229. }
  230. //递归删除目录内的所有文件和本目录
  231. if (!function_exists('del_dir')) {
  232. function del_dir($path)
  233. {
  234. //如果是目录则继续
  235. if (is_dir($path)) {
  236. //扫描一个文件夹内的所有文件夹和文件并返回数组
  237. $p = scandir($path);
  238. //如果 $p 中有两个以上的元素则说明当前 $path 不为空
  239. if (count($p) > 2) {
  240. foreach ($p as $val) {
  241. //排除目录中的.和..
  242. if ($val != "." && $val != "..") {
  243. //如果是目录则递归子目录,继续操作
  244. if (is_dir($path . $val)) {
  245. //子目录中操作删除文件夹和文件
  246. del_dir($path . $val . '/');
  247. } else {
  248. //如果是文件直接删除
  249. unlink($path . $val);
  250. }
  251. }
  252. }
  253. }
  254. }
  255. //删除目录
  256. return rmdir($path);
  257. }
  258. }
  259. //根据省市区编码获取省市区名称
  260. if (!function_exists('get_addr_name')) {
  261. function get_addr_name(string $addr_code = ''): string
  262. {
  263. $rs = \think\facade\Db::name('area')
  264. ->whereIn('code', $addr_code)
  265. ->column('name');
  266. return implode('', $rs);
  267. }
  268. }