common.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. <?php
  2. use think\Db;
  3. use think\File;
  4. /**
  5. * @param $account
  6. * @return string
  7. * @throws \think\db\exception\DataNotFoundException
  8. * @throws \think\db\exception\DbException
  9. * @throws \think\db\exception\ModelNotFoundException
  10. * @throws \think\exception\DbException
  11. */
  12. function makeToken($account){
  13. $now=time();
  14. $str = $account['username'].$account['salt'].$now;
  15. $token = base64_encode($str);
  16. $has = Db::name("admin_token")->where(["adminid"=>$account['id']])->find();
  17. if($has){
  18. Db::name("admin_token")->where(["adminid"=>$account['id']])->update(["token"=>$token,"expiretime"=>date("Y-m-d H:i:s",$now+1800)]);
  19. }else{
  20. Db::name("admin_token")->insert(["token"=>$token,"expiretime"=>date("Y-m-d H:i:s",$now+1800),"addtime"=>date("Y-m-d H:i:s"),
  21. "adminid"=>$account['id']]);
  22. }
  23. return $token;
  24. }
  25. /**
  26. * @param $token
  27. */
  28. function verifyToken($token){
  29. $has = Db::name("admin_token")->where(["token"=>$token])->find();
  30. if(!$has){
  31. return ["code"=>101,"msg"=>"token不存在"];
  32. }
  33. if(strtotime($has['expiretime'])<=time()){
  34. return ["code"=>102,"msg"=>"token已失效"];
  35. }
  36. $account = Db::name("admin")->where(["id"=>$has['adminid'],"is_del"=>0])->find();
  37. if(!$account){
  38. return ["code"=>103,"msg"=>"未找到账户"];
  39. }
  40. if($account['status']!=1){
  41. return ["code"=>104,"msg"=>"账户已禁用"];
  42. }
  43. $token_str = base64_decode($token);
  44. $account_str= substr($token_str,0,-10);
  45. if($account_str==$account['username'].$account['salt']){
  46. Db::name("admin_token")->where(["token"=>$token])->update(["expiretime"=>date("Y-m-d H:i:s",time()+1800)]);
  47. return ["code"=>0,"msg"=>"账户有效"];
  48. }else{
  49. return ["code"=>105,"msg"=>"账户token无效"];
  50. }
  51. }
  52. /**
  53. * @param $username
  54. * @return bool 账户正则匹配
  55. */
  56. function checkAccount($username){
  57. $match ='/^(1745)([\d]{6})$/';
  58. return preg_match($match,$username)?true:false;
  59. }
  60. /**
  61. * @param $pawd
  62. * @return bool 账户正则匹配
  63. */
  64. function checkPasswd($pawd){
  65. $match ='/^([a-zA-z]{2})([\d]{4})$/';
  66. return preg_match($match,$pawd)?true:false;
  67. }
  68. function UploadImg($files){
  69. $savename = [];
  70. $files= !is_array($files) ? [$files] : $files;
  71. // var_dump($files);
  72. try{
  73. foreach($files as $file){
  74. $info= $file->validate(['size'=>10240000,'ext'=>'jpg,jpeg,png,bmp,gif'])->move(ROOT_PATH .'public' .DS .'upload');
  75. if($info){
  76. $temp = ['url'=>'upload/'. $info->getSaveName()];
  77. $savename[]=$temp;
  78. }else{
  79. return "";
  80. }
  81. }
  82. return $savename;
  83. }catch (\think\exception\ValidateException $e) {
  84. return $e->getMessage();
  85. }
  86. }
  87. function QueuePush($data,$queue="createOrderJob"){
  88. //当前任务将由哪个类来负责处理
  89. $jobHandlerClassName = 'app\admin\JobInv';
  90. //业务数据 对象需要手动转序列化
  91. $jobQueueName = $queue;
  92. $isPushed = Queue::push($jobHandlerClassName, $data,$jobQueueName);
  93. if( $isPushed !== false ){
  94. Log::write("{$jobQueueName} 任务失败:{$data['id']}");
  95. }
  96. }
  97. function checkRole($roleid,$menu){
  98. $roleinfo = \think\facade\Db::name("role_action")->where([['role_id',"=",$roleid],["status","=",1]])->find();
  99. if($roleinfo['private_data']!=""){
  100. $private = explode(",",$roleinfo['private_data']);
  101. if(in_array($menu,$private)){
  102. return true;
  103. }
  104. }
  105. return false;
  106. }
  107. function excelSave($fileName = '', $headArr = [], $data = [])
  108. {
  109. $objPHPExcel = new PHPExcel();
  110. $objPHPExcel->getProperties();
  111. $keyA = 0; // 设置表头
  112. foreach ($headArr as $v) {
  113. $colum = PHPExcel_Cell::stringFromColumnIndex($keyA);
  114. $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
  115. $keyA += 1;
  116. }
  117. $column = 2;
  118. $objActSheet = $objPHPExcel->getActiveSheet();
  119. foreach ($data as $key => $rows) { // 行写入
  120. $span = 0;
  121. foreach ($rows as $keyName => $value) { // 列写入
  122. //判断数据是否有数组,如果有数组,转换成字符串
  123. if(is_array($value)){
  124. $value = implode("、", $value);
  125. }
  126. $objActSheet->setCellValue(PHPExcel_Cell::stringFromColumnIndex($span) . $column, $value);
  127. $span++;
  128. }
  129. $column++;
  130. }
  131. // var_dump($objActSheet->getActiveCell());
  132. $file = $fileName. ".xls";
  133. //$fileName .= "_" . date("Y_m_d", Request()->instance()->time()) . ".xls";
  134. //$fileName = iconv("utf-8", "gb2312", $fileName); // 重命名表
  135. $dir =ROOT_PATH. 'public/storage/report/'.date("YmdHis")."/";
  136. if(!is_dir($dir)){
  137. mkdir($dir,0777,true);
  138. }
  139. $objPHPExcel->setActiveSheetIndex(0); // 设置活动单指数到第一个表,所以Excel打开这是第一个表
  140. $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  141. $objWriter->save($dir . $file); // 文件通过浏览器下载
  142. $url = $dir . $file;
  143. if(!file_exists($url)){
  144. echo "文件生成失败";
  145. }
  146. $saveDir = ROOT_PATH."public/storage/zip/";
  147. if(!is_dir( $saveDir)){
  148. mkdir($saveDir,0777,true);
  149. }
  150. $datetime = date("Y-m-d H:i:s");
  151. $file_dir = $saveDir.$datetime.".zip";
  152. # 5.1 文件打包,提示:使用本类,linux需开启zlib,windows需取消php_zip.dll前的注释
  153. $zip = new \ZipArchive ();
  154. # 5.2 文件不存在则生成一个新的文件 用CREATE打开文件会追加内容至zip
  155. if ($zip->open($file_dir, \ZipArchive::OVERWRITE) !== true && $zip->open($file_dir, \ZipArchive::CREATE) !==
  156. true) echo '无法打开文件或者文件创建失败';
  157. # 5.3 批量写入压缩包
  158. $zip->addEmptyDir($fileName);
  159. // @$zip->addFile($v['file_path'], 'resume'.DIRECTORY_SEPARATOR.basename($headername));
  160. @$zip->addFile($url,$fileName.DIRECTORY_SEPARATOR.basename($url));
  161. # 5.4 关闭压缩包写入
  162. $zip->close();
  163. @deldir($dir);
  164. # 6. 检查文件是否存在,并输出文件
  165. if (! file_exists ( $file_dir )) echo '简历文件不存在';
  166. ob_clean();
  167. flush();
  168. header("Cache-Control: max-age=0");
  169. header("Content-Description: File Transfer");
  170. header('Content-disposition: attachment; filename=' . basename($file_dir)); # 处理文件名
  171. header("Content-Type: application/octet-stream"); # 流文件输出
  172. header("Content-Transfer-Encoding: binary"); # 告诉浏览器,这是二进制文件
  173. header('Content-Length: ' . filesize($file_dir)); # 告诉浏览器,文件大小
  174. readfile($file_dir); # 输出文件
  175. @ unlink($file_dir);
  176. exit();
  177. }
  178. function deldir($path){
  179. //如果是目录则继续
  180. if(is_dir($path)){
  181. //扫描一个文件夹内的所有文件夹和文件并返回数组
  182. $p = scandir($path);
  183. //如果 $p 中有两个以上的元素则说明当前 $path 不为空
  184. if(count($p)>2){
  185. foreach($p as $val){
  186. //排除目录中的.和..
  187. if($val !="." && $val !=".."){
  188. //如果是目录则递归子目录,继续操作
  189. if(is_dir($path.$val)){
  190. //子目录中操作删除文件夹和文件
  191. deldir($path.$val.'/');
  192. }else{
  193. //如果是文件直接删除
  194. unlink($path.$val);
  195. }
  196. }
  197. }
  198. }
  199. }
  200. //删除目录
  201. return rmdir($path);
  202. }
  203. function excelExport($fileName = '', $headArr = [], $data = [])
  204. {
  205. $objPHPExcel = new PHPExcel();
  206. $objPHPExcel->getProperties();
  207. $keyA = 0; // 设置表头
  208. foreach ($headArr as $v) {
  209. $colum = PHPExcel_Cell::stringFromColumnIndex($keyA);
  210. $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
  211. $keyA += 1;
  212. }
  213. $column = 2;
  214. $objActSheet = $objPHPExcel->getActiveSheet();
  215. foreach ($data as $key => $rows) { // 行写入
  216. $span = 0;
  217. foreach ($rows as $keyName => $value) { // 列写入
  218. //判断数据是否有数组,如果有数组,转换成字符串
  219. if(is_array($value)){
  220. $value = implode("、", $value);
  221. }
  222. $objActSheet->setCellValue(PHPExcel_Cell::stringFromColumnIndex($span) . $column, $value);
  223. $span++;
  224. }
  225. $column++;
  226. }
  227. // var_dump($objActSheet->getActiveCell());
  228. $fileName .= "_" . date("Y_m_d", time()) . ".xls";
  229. //$fileName .= "_" . date("Y_m_d", Request()->instance()->time()) . ".xls";
  230. //$fileName = iconv("utf-8", "gb2312", $fileName); // 重命名表
  231. $objPHPExcel->setActiveSheetIndex(0); // 设置活动单指数到第一个表,所以Excel打开这是第一个表
  232. // Redirect output to a client’s web browser (Excel2007)
  233. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  234. header('Content-Disposition: attachment;filename="'.$fileName.'"');
  235. header('Cache-Control: max-age=0');
  236. // If you're serving to IE 9, then the following may be needed
  237. header('Cache-Control: max-age=1');
  238. // If you're serving to IE over SSL, then the following may be needed
  239. header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  240. header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
  241. header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
  242. header ('Pragma: public'); // HTTP/1.0
  243. // header("Content-Type: application/octet-stream"); # 流文件输出
  244. // header("Content-Transfer-Encoding: binary"); # 告诉浏览器,这是二进制文件
  245. $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  246. $objWriter->save('php://output'); // 文件通过浏览器下载
  247. exit();
  248. }