common.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. <?php
  2. use think\facade\Db;
  3. use think\facade\Filesystem;
  4. use think\facade\Queue;
  5. use think\facade\Log;
  6. use think\facade\Config;
  7. // 这是系统自动生成的公共文件
  8. function make_verify(){
  9. $code = round(100000,999999);
  10. return $code;
  11. }
  12. /**
  13. * 发送短信接口
  14. * @param type $phone
  15. * @param type $code
  16. */
  17. function sendMessage($phone, $code) {
  18. //1.下列选项必填
  19. $url = 'https://rtcsms.cn-north-1.myhuaweicloud.com:10743/sms/batchSendSms/v1'; //APP接入地址+接口访问URI
  20. $APP_KEY = 'ww3mKZEWh3fhboNZ791pL5fhSNfJ'; //APP_Key
  21. $APP_SECRET = 'nvXKrQQeEkQRp5750M2p85ILs4xC'; //APP_Secret
  22. $sender = '99200620888880002777'; //国内短信签名通道号或国际/港澳台短信通道号
  23. $TEMPLATE_ID = '54b09b74ee764cca90571b65bfb20f9f'; //模板ID
  24. //$sender = '8821032432899'; //国内短信签名通道号或国际/港澳台短信通道号
  25. //$TEMPLATE_ID = 'faa13c0b2deb4646a31304434c07b856'; //模板ID
  26. $signature = '泰康广源'; //签名名称
  27. //必填,全局号码格式(包含国家码),示例:+8615123456789,多个号码之间用英文逗号分隔
  28. $receiver = '+86'.$phone; //短信接收人号码
  29. //选填,短信状态报告接收地址,推荐使用域名,为空或者不填表示不接收状态报告
  30. $statusCallback = '';
  31. /**
  32. * 选填,使用无变量模板时请赋空值 $TEMPLATE_PARAS = '';
  33. * 单变量模板示例:模板内容为"您的验证码是${NUM_6}"时,$TEMPLATE_PARAS可填写为'["369751"]'
  34. * 双变量模板示例:模板内容为"您有${NUM_2}件快递请到${TXT_32}领取"时,$TEMPLATE_PARAS可填写为'["3","人民公园正门"]'
  35. * 查看更多模板变量规则:常见问题>业务规则>短信模板内容审核标准
  36. * @var string $TEMPLATE_PARAS
  37. */
  38. $TEMPLATE_PARAS = '["'.$code.'"]'; //模板变量,根据自身使用的模板,其值长度和个数与模板对应
  39. //请求Headers
  40. $headers = [
  41. 'Content-Type: application/x-www-form-urlencoded',
  42. 'Authorization: WSSE realm="SDP",profile="UsernameToken",type="Appkey"',
  43. 'X-WSSE: '.buildWsseHeader($APP_KEY, $APP_SECRET)
  44. ];
  45. //请求Body
  46. $data = http_build_query([
  47. 'from' => $sender,
  48. 'to' => $receiver,
  49. 'templateId' => $TEMPLATE_ID,
  50. 'templateParas' => $TEMPLATE_PARAS,
  51. 'statusCallback' => $statusCallback,
  52. 'signature' => $signature //使用国内短信通用模板时,必须填写签名名称
  53. ]);
  54. $ch = curl_init();
  55. curl_setopt ($ch, CURLOPT_URL, $url);
  56. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  57. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  58. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  59. curl_setopt($ch, CURLOPT_POST, true);
  60. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  61. curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
  62. curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT,10);
  63. $response = curl_exec($ch);
  64. return $response;
  65. }
  66. /**手机号验证
  67. * @param $mobile
  68. * @return bool
  69. */
  70. function checkMobile($mobile){
  71. if (!is_numeric($mobile)) {
  72. return false;
  73. }
  74. return preg_match('#^1[3,4,5,6,7,8,9]{1}[\d]{9}$#', $mobile) ? true : false;
  75. }
  76. function checkTel($tel){
  77. if (!$tel) {
  78. return false;
  79. }
  80. return preg_match('/^(0[0-9]{2,3}\-)([0-9]{7,8})+(\-[0-9]{1,4})?$/', $tel) ? true : false;
  81. }
  82. /**邮箱验证
  83. * @param $email
  84. * @return bool
  85. */
  86. function checkEmail($email){
  87. if (!$email) {
  88. return false;
  89. }
  90. return preg_match('#[a-z0-9&\-_.]+@[\w\-_]+([\w\-.]+)?\.[\w\-]+#is', $email) ? true : false;
  91. }
  92. /**
  93. * @param
  94. * @return int
  95. */
  96. function makeSalt(){
  97. $salt = rand(10000000,99999999);
  98. return $salt;
  99. }
  100. /**
  101. * @param $token
  102. * @return array
  103. * @throws \think\db\exception\DataNotFoundException
  104. * @throws \think\db\exception\DbException
  105. * @throws \think\db\exception\ModelNotFoundException
  106. * @throws \think\exception\DbException
  107. */
  108. function VerifyTokens($token){
  109. $host = Config::get("app");
  110. $url = $host["api_host"]."/Api/verify_token";
  111. $data=[
  112. "token"=>$token
  113. ];
  114. $response=curl_request($url,$data);
  115. return json_decode($response,true);
  116. }
  117. /**
  118. * @param $token
  119. * @param $condition
  120. * @return mixed
  121. */
  122. function GetUserlist($token,$condition){
  123. $host = Config::get("app");
  124. $url = $host["api_host"]."/Api/getuserlist";
  125. $condition['token']=$token;
  126. $response=curl_request($url,$condition);
  127. return json_decode($response,true);
  128. }
  129. /**
  130. * @param $token
  131. * @param $condition
  132. * @return mixed
  133. */
  134. function GetAccountall($token){
  135. $host = Config::get("app");
  136. $url = $host["api_host"]."/Api/userall";
  137. $condition['token']=$token;
  138. $response=curl_request($url,$condition);
  139. return json_decode($response,true);
  140. }
  141. function GetList($token,$condition){
  142. $host = Config::get("app");
  143. $url = $host["api_host"]."/Api/userlist";
  144. $condition['token']=$token;
  145. $response=curl_request($url,$condition);
  146. return json_decode($response,true);
  147. }
  148. function GetInfoById($token,$condition){
  149. $host = Config::get("app");
  150. $url = $host["api_host"]."/Api/userinfobyid";
  151. $condition['token']=$token;
  152. $response=curl_request($url,$condition);
  153. return json_decode($response,true);
  154. }
  155. function makeNo($str){
  156. $date=date("mdHis");
  157. $year = date("Y")-2000;
  158. $msec=randomkeys(4);
  159. return $str.$msec.$year.$date;
  160. }
  161. function randomkeys($length) {
  162. $returnStr='';
  163. $pattern = '1234567890abcdefghijklmnopqrstuvwxyz';//ABCDEFGHIJKLOMNOPQRSTUVWXYZ
  164. for($i = 0; $i < $length; $i ++) {
  165. $returnStr .= $pattern[mt_rand ( 0, strlen($pattern)-1 )]; //生成php随机数
  166. }
  167. return $returnStr;
  168. }
  169. /**
  170. * @param $files
  171. * @return array
  172. */
  173. function UploadImg($files){
  174. $savename = [];
  175. $files= !is_array($files) ? [$files] : $files;
  176. try{
  177. //验证
  178. validate(['imgFile'=>['fileSize'=>10240000,'fileExt'=>'jpg,jpeg,png,bmp,gif', 'fileMime'=>'image/jpeg,image/png,image/gif']])->check(['imgFile'=>$files]);
  179. foreach($files as $file){
  180. $url= Filesystem::disk('public')->putFile( 'topic/'.date("Ymd"), $file,function ()use($file){
  181. return str_replace('.'.$file->getOriginalExtension(),'',$file->getOriginalName()."_".date('YmdHis'));
  182. });
  183. $name = str_replace('.'.$file->getOriginalExtension(),'',$file->getOriginalName());
  184. $temp = ["url"=>$url,"name"=>$name];
  185. $savename[]=$temp;
  186. }
  187. return $savename;
  188. }catch (\think\exception\ValidateException $e) {
  189. return $e->getMessage();
  190. }
  191. }
  192. function QueuePush($data,$queue="createOrderJob"){
  193. //当前任务将由哪个类来负责处理
  194. $jobHandlerClassName = 'app\admin\JobInv';
  195. //业务数据 对象需要手动转序列化
  196. $jobQueueName = $queue;
  197. $isPushed = Queue::push($jobHandlerClassName, $data,$jobQueueName);
  198. if( $isPushed !== false ){
  199. Log::write("{$jobQueueName} 任务失败:{$data['id']}");
  200. }
  201. }
  202. function checkRole($roleid,$menu){
  203. $roleinfo = \think\facade\Db::name("role_action")->where([['role_id',"=",$roleid],["status","=",1]])->find();
  204. if($roleinfo['private_data']!=""){
  205. $private = explode(",",$roleinfo['private_data']);
  206. if(in_array($menu,$private)){
  207. return true;
  208. }
  209. }
  210. return false;
  211. }
  212. function upload_ll($files,$extend="xls")
  213. {
  214. // 获取表单上传文件
  215. try {
  216. validate([
  217. 'file' => [
  218. // 限制文件大小(单位b),这里限制为4M
  219. //fileSize' => 4 * 1024 * 1024,
  220. 'fileExt' => 'xlsx,xls'
  221. ]
  222. ],
  223. [
  224. //'file.fileSize' => '文件太大',
  225. 'file.fileExt' => '不支持的文件',
  226. ]
  227. )->check(['file' => $files]);
  228. $name = $files->getOriginalExtension();
  229. if ($extend == 'xlsx') {
  230. $objReader = PHPExcel_IOFactory::createReader('Excel2007');
  231. } else {
  232. $objReader = PHPExcel_IOFactory::createReader('Excel5');
  233. }
  234. $savename = Filesystem::disk('public')->putFile('topic/excel', $files);
  235. $import_path = root_path() . 'public/storage/' . $savename;
  236. $spreadsheet = $objReader->load($import_path);
  237. $sheet = $spreadsheet->getActiveSheet();
  238. $sheetData = $sheet->toArray();
  239. if (empty($sheetData) || !is_array($sheetData)) {
  240. return ['code' => 1003, "msg" => '数据不能为空'];
  241. }
  242. return ['code' => 0, "msg" => '数据解析成功', 'data' => $sheetData];
  243. } catch (think\exception\ValidateException $e) {
  244. // echo $e->getMessage();
  245. return ['code' => 1003, "msg" => $e->getMessage()];
  246. }
  247. }
  248. /**
  249. * @param string $fileName
  250. * @param array $headArr
  251. * @param array $data
  252. */
  253. function excelExport($fileName = '', $headArr = [], $data = [])
  254. {
  255. $objPHPExcel = new PHPExcel();
  256. $objPHPExcel->getProperties();
  257. $keyA = 0; // 设置表头
  258. foreach ($headArr as $v) {
  259. $colum = PHPExcel_Cell::stringFromColumnIndex($keyA);
  260. $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
  261. $keyA += 1;
  262. }
  263. $column = 2;
  264. $objActSheet = $objPHPExcel->getActiveSheet();
  265. foreach ($data as $key => $rows) { // 行写入
  266. $span = 0;
  267. foreach ($rows as $keyName => $value) { // 列写入
  268. //判断数据是否有数组,如果有数组,转换成字符串
  269. if(is_array($value)){
  270. $value = implode("、", $value);
  271. }
  272. $objActSheet->setCellValue(PHPExcel_Cell::stringFromColumnIndex($span) . $column, $value);
  273. $span++;
  274. }
  275. $column++;
  276. }
  277. // var_dump($objActSheet->getActiveCell());
  278. $fileName .= "_" . date("Y_m_d", time()) . ".xls";
  279. //$fileName .= "_" . date("Y_m_d", Request()->instance()->time()) . ".xls";
  280. //$fileName = iconv("utf-8", "gb2312", $fileName); // 重命名表
  281. $objPHPExcel->setActiveSheetIndex(0); // 设置活动单指数到第一个表,所以Excel打开这是第一个表
  282. // Redirect output to a client’s web browser (Excel2007)
  283. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  284. header('Content-Disposition: attachment;filename="'.$fileName.'"');
  285. header('Cache-Control: max-age=0');
  286. // If you're serving to IE 9, then the following may be needed
  287. header('Cache-Control: max-age=1');
  288. // If you're serving to IE over SSL, then the following may be needed
  289. header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  290. header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
  291. header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
  292. header ('Pragma: public'); // HTTP/1.0
  293. // header("Content-Type: application/octet-stream"); # 流文件输出
  294. // header("Content-Transfer-Encoding: binary"); # 告诉浏览器,这是二进制文件
  295. $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  296. $objWriter->save('php://output'); // 文件通过浏览器下载
  297. exit();
  298. }
  299. /**
  300. * @param $files
  301. * @param string $extend
  302. * @return array
  303. * @throws PHPExcel_Exception
  304. * @throws PHPExcel_Reader_Exception
  305. */
  306. function upload_excel($files,$extend="xls")
  307. {
  308. // 获取表单上传文件
  309. try {
  310. validate([
  311. 'file' => [
  312. // 限制文件大小(单位b),这里限制为4M
  313. //fileSize' => 4 * 1024 * 1024,
  314. 'fileExt' => 'xlsx,xls'
  315. ]
  316. ],
  317. [
  318. //'file.fileSize' => '文件太大',
  319. 'file.fileExt' => '不支持的文件',
  320. ]
  321. )->check(['file' => $files]);
  322. // $name = $files->getOriginalExtension();
  323. if ($extend == 'xlsx') {
  324. $objReader = PHPExcel_IOFactory::createReader('Excel2007');
  325. } else {
  326. $objReader = PHPExcel_IOFactory::createReader('Excel5');
  327. }
  328. $savename = Filesystem::disk('public')->putFile('topic/excel', $files);
  329. $import_path = root_path() . 'public/storage/' . $savename;
  330. $spreadsheet = $objReader->load($import_path);
  331. $sheet = $spreadsheet->getActiveSheet();
  332. $sheetData = $sheet->toArray();
  333. if (empty($sheetData) || !is_array($sheetData)) {
  334. return ['code' => 1003, "msg" => '数据不能为空'];
  335. }
  336. $list = [];
  337. foreach ($sheetData as $key => $value) {
  338. $list[] = $value;
  339. }
  340. return ['code' => 0, "msg" => '数据解析成功', 'data' => $list];
  341. } catch (think\exception\ValidateException $e) {
  342. // echo $e->getMessage();
  343. return ['code' => 1003, "msg" => $e->getMessage()];
  344. }
  345. }
  346. /**
  347. * @param string $fileName
  348. * @param array $headArr
  349. * @param array $data
  350. */
  351. function excelSave($fileName = '', $headArr = [], $data = [])
  352. {
  353. $objPHPExcel = new PHPExcel();
  354. $objPHPExcel->getProperties();
  355. $keyA = 0; // 设置表头
  356. foreach ($headArr as $v) {
  357. $colum = PHPExcel_Cell::stringFromColumnIndex($keyA);
  358. $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
  359. $keyA += 1;
  360. }
  361. $column = 2;
  362. $objActSheet = $objPHPExcel->getActiveSheet();
  363. foreach ($data as $key => $rows) { // 行写入
  364. $span = 0;
  365. foreach ($rows as $keyName => $value) { // 列写入
  366. //判断数据是否有数组,如果有数组,转换成字符串
  367. if(is_array($value)){
  368. $value = implode("、", $value);
  369. }
  370. $objActSheet->setCellValue(PHPExcel_Cell::stringFromColumnIndex($span) . $column, $value);
  371. $span++;
  372. }
  373. $column++;
  374. }
  375. // var_dump($objActSheet->getActiveCell());
  376. $file = $fileName. ".xls";
  377. //$fileName .= "_" . date("Y_m_d", Request()->instance()->time()) . ".xls";
  378. //$fileName = iconv("utf-8", "gb2312", $fileName); // 重命名表
  379. $dir =root_path() . 'public/storage/report/'.date("YmdHis")."/";
  380. if(!is_dir($dir)){
  381. mkdir($dir,0777,true);
  382. }
  383. $objPHPExcel->setActiveSheetIndex(0); // 设置活动单指数到第一个表,所以Excel打开这是第一个表
  384. $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  385. $objWriter->save($dir . $file); // 文件通过浏览器下载
  386. $url = $dir . $file;
  387. if(!file_exists($url)){
  388. echo "文件生成失败";
  389. }
  390. $saveDir = root_path()."public/storage/zip/";
  391. if(!is_dir( $saveDir)){
  392. mkdir($saveDir,0777,true);
  393. }
  394. $datetime = date("Y-m-d H:i:s");
  395. $file_dir = $saveDir.$datetime.".zip";
  396. # 5.1 文件打包,提示:使用本类,linux需开启zlib,windows需取消php_zip.dll前的注释
  397. $zip = new \ZipArchive ();
  398. # 5.2 文件不存在则生成一个新的文件 用CREATE打开文件会追加内容至zip
  399. if ($zip->open($file_dir, \ZipArchive::OVERWRITE) !== true && $zip->open($file_dir, \ZipArchive::CREATE) !==
  400. true) echo '无法打开文件或者文件创建失败';
  401. # 5.3 批量写入压缩包
  402. $zip->addEmptyDir($fileName);
  403. // @$zip->addFile($v['file_path'], 'resume'.DIRECTORY_SEPARATOR.basename($headername));
  404. @$zip->addFile($url,$fileName.DIRECTORY_SEPARATOR.basename($url));
  405. # 5.4 关闭压缩包写入
  406. $zip->close();
  407. @deldir($dir);
  408. # 6. 检查文件是否存在,并输出文件
  409. if (! file_exists ( $file_dir )) echo '简历文件不存在';
  410. ob_clean();
  411. flush();
  412. header("Cache-Control: max-age=0");
  413. header("Content-Description: File Transfer");
  414. header('Content-disposition: attachment; filename=' . basename($file_dir)); # 处理文件名
  415. header("Content-Type: application/octet-stream"); # 流文件输出
  416. header("Content-Transfer-Encoding: binary"); # 告诉浏览器,这是二进制文件
  417. header('Content-Length: ' . filesize($file_dir)); # 告诉浏览器,文件大小
  418. readfile($file_dir); # 输出文件
  419. @ unlink($file_dir);
  420. exit();
  421. }
  422. /**
  423. * 处理压缩文件路径
  424. * @param type $path
  425. * @param type $zip
  426. */
  427. function addFileToZip($path, $zip)
  428. {
  429. $handler = opendir($path); //打开当前文件夹由$path指定。
  430. while (($filename = readdir($handler)) !== false) {
  431. if ($filename != "." && $filename != "..") {//文件夹文件名字为'.'和‘..’,不要对他们进行操作
  432. if (is_dir($path . "/" . $filename)) {// 如果读取的某个对象是文件夹,则递归
  433. addFileToZip($path . "/" . $filename, $zip);
  434. } else { //将文件加入zip对象
  435. $zip->addFile($path . "/" . $filename);
  436. }
  437. }
  438. }
  439. @closedir($path);
  440. }
  441. function deldir($path){
  442. //如果是目录则继续
  443. if(is_dir($path)){
  444. //扫描一个文件夹内的所有文件夹和文件并返回数组
  445. $p = scandir($path);
  446. //如果 $p 中有两个以上的元素则说明当前 $path 不为空
  447. if(count($p)>2){
  448. foreach($p as $val){
  449. //排除目录中的.和..
  450. if($val !="." && $val !=".."){
  451. //如果是目录则递归子目录,继续操作
  452. if(is_dir($path.$val)){
  453. //子目录中操作删除文件夹和文件
  454. deldir($path.$val.'/');
  455. }else{
  456. //如果是文件直接删除
  457. unlink($path.$val);
  458. }
  459. }
  460. }
  461. }
  462. }
  463. //删除目录
  464. return rmdir($path);
  465. }