common.php 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189
  1. <?php
  2. // 应用公共文件
  3. use think\facade\Config;
  4. use think\facade\Db;
  5. use think\facade\Filesystem;
  6. // 应用公共文件
  7. function app_show($code=0,$message="",$data=[]){
  8. $result = ['code'=>$code,"message"=>$message,"data"=>$data];
  9. echo json_encode($result,JSON_UNESCAPED_UNICODE);
  10. die();
  11. }
  12. // 应用公共文件
  13. function error_show($code=0,$message=""){
  14. $result = ['code'=>$code,"message"=>$message];
  15. echo json_encode($result,JSON_UNESCAPED_UNICODE);
  16. die();
  17. }
  18. function GetUserInfo($token){
  19. $host = Config::get("app");
  20. $url = $host["api_host"]."/Api/userinfo";
  21. $data=[
  22. "token"=>$token
  23. ];
  24. $response=curl_request($url,$data);
  25. return json_decode($response,true);
  26. }
  27. //参数1:访问的URL,参数2:post数据(不填则为GET),参数3:提交的$cookies,参数4:是否返回$cookies
  28. function curl_request($url,$post=''){
  29. $curl = curl_init();
  30. curl_setopt($curl, CURLOPT_URL, $url);
  31. curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)');
  32. curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
  33. curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
  34. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  35. if($post) {
  36. curl_setopt($curl, CURLOPT_POST, 1);
  37. curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));
  38. }
  39. curl_setopt($curl, CURLOPT_TIMEOUT, 10);
  40. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  41. $data = curl_exec($curl);
  42. if (curl_errno($curl)) {
  43. return curl_error($curl);
  44. }
  45. curl_close($curl);
  46. return $data;
  47. }
  48. /**手机号验证
  49. * @param $mobile
  50. * @return bool
  51. */
  52. function checkMobile($mobile){
  53. if (!is_numeric($mobile)) {
  54. return false;
  55. }
  56. return preg_match('#^1[3,4,5,6,7,8,9]{1}[\d]{9}$#', $mobile) ? true : false;
  57. }
  58. function checkTel($tel){
  59. if (!$tel) {
  60. return false;
  61. }
  62. return preg_match('/^(0[0-9]{2,3}\-)([0-9]{7,8})+(\-[0-9]{1,4})?$/', $tel) ? true : false;
  63. }
  64. /**邮箱验证
  65. * @param $email
  66. * @return bool
  67. */
  68. function checkEmail($email){
  69. if (!$email) {
  70. return false;
  71. }
  72. return preg_match('#[a-z0-9&\-_.]+@[\w\-_]+([\w\-.]+)?\.[\w\-]+#is', $email) ? true : false;
  73. }
  74. /**
  75. * @param
  76. * @return int
  77. */
  78. function makeSalt(){
  79. $salt = rand(10000000,99999999);
  80. return $salt;
  81. }
  82. /**
  83. * @param $token
  84. * @return array
  85. * @throws \think\db\exception\DataNotFoundException
  86. * @throws \think\db\exception\DbException
  87. * @throws \think\db\exception\ModelNotFoundException
  88. * @throws \think\exception\DbException
  89. */
  90. function VerifyTokens($token){
  91. $host = Config::get("app");
  92. $url = $host["api_host"]."/Api/verify_token";
  93. $data=[
  94. "token"=>$token
  95. ];
  96. $response=curl_request($url,$data);
  97. return json_decode($response,true);
  98. }
  99. /**
  100. * @param $token
  101. * @param $condition
  102. * @return mixed
  103. */
  104. function GetUserlist($token,$condition){
  105. $host = Config::get("app");
  106. $url = $host["api_host"]."/Api/getuserlist";
  107. $condition['token']=$token;
  108. $response=curl_request($url,$condition);
  109. return json_decode($response,true);
  110. }
  111. /**
  112. * @param $token
  113. * @param $condition
  114. * @return mixed
  115. */
  116. function GetAccountall($token, $condition){
  117. $host = Config::get("app");
  118. $url = $host["api_host"]."/Api/userall";
  119. $condition['token']=$token;
  120. $response=curl_request($url,$condition);
  121. return json_decode($response,true);
  122. }
  123. function GetList($token,$condition){
  124. $host = Config::get("app");
  125. $url = $host["api_host"]."/Api/userlist";
  126. $condition['token']=$token;
  127. $response=curl_request($url,$condition);
  128. return json_decode($response,true);
  129. }
  130. /**
  131. * @param $token
  132. * @param $condition ['id'=>1]
  133. * @return mixed
  134. */
  135. function GetInfoById($token,$condition){
  136. $host = Config::get("app");
  137. $url = $host["api_host"]."/Api/userinfobyid";
  138. $condition['token']=$token;
  139. $response=curl_request($url,$condition);
  140. return json_decode($response,true);
  141. }
  142. function GetInfoNoToken($condition){
  143. $host = Config::get("app");
  144. $url = $host["api_host"]."/Api/uinfo";
  145. $response=curl_request($url,$condition);
  146. return json_decode($response,true);
  147. }
  148. function makeNo($str){
  149. $date=date("mdHis");
  150. $year = date("Y")-2000;
  151. $msec=rand(1000,9999);
  152. return $str.$year.$date.$msec;
  153. }
  154. function randomkeys($length) {
  155. $returnStr='';
  156. $pattern = '1234567890abcdefghijklmnopqrstuvwxyz';//ABCDEFGHIJKLOMNOPQRSTUVWXYZ
  157. for($i = 0; $i < $length; $i ++) {
  158. $returnStr .= $pattern[mt_rand ( 0, strlen($pattern)-1 )]; //生成php随机数
  159. }
  160. return $returnStr;
  161. }
  162. function tree(){
  163. }
  164. /**
  165. * @param $files
  166. * @return array
  167. */
  168. function UploadImg($files)
  169. {
  170. $savename = [];
  171. $files = !is_array($files) ? [$files] : $files;
  172. try {
  173. //验证
  174. validate(['imgFile' => ['fileSize' => 10240000, 'fileExt' => 'jpg,jpeg,png,bmp,gif', 'fileMime' => 'image/jpeg,image/png,image/gif']])->check(['imgFile' => $files]);
  175. foreach ($files as $file) {
  176. $url = Filesystem::disk('public')->putFile('topic/' . date("Ymd"), $file, function () use ($file) {
  177. return str_replace('.' . $file->getOriginalExtension(), '', $file->getOriginalName() . "_" . date('YmdHis'));
  178. });
  179. $name = str_replace('.' . $file->getOriginalExtension(), '', $file->getOriginalName());
  180. $temp = ["url" => $url, "name" => $name];
  181. $savename[] = $temp;
  182. }
  183. return $savename;
  184. } catch (\think\exception\ValidateException $e) {
  185. return $e->getMessage();
  186. }
  187. }
  188. /**
  189. * @param $files
  190. * @return array
  191. */
  192. function UploadFile($files)
  193. {
  194. $savename = [];
  195. $files = !is_array($files) ? [$files] : $files;
  196. try {
  197. //验证
  198. validate(['imgFile' => ['fileSize' => 10240000,'fileExt' => 'xlsx,xls,pdf,zip,rar,7z,doc,docx']])->check(['imgFile' =>
  199. $files]);
  200. foreach ($files as $file) {
  201. $url = Filesystem::disk('public')->putFile('files/' . date("Ymd"), $file, function () use ($file) {
  202. return str_replace('.' . $file->getOriginalExtension(), '', $file->getOriginalName() . "_" . date('YmdHis'));
  203. });
  204. $name = str_replace('.' . $file->getOriginalExtension(), '', $file->getOriginalName());
  205. $temp = ["url" => $url, "name" => $name];
  206. $savename[] = $temp;
  207. }
  208. return $savename;
  209. } catch (\think\exception\ValidateException $e) {
  210. return $e->getMessage();
  211. }
  212. }
  213. /**
  214. * @param $files
  215. * @return array
  216. */
  217. function UploadVideo($files)
  218. {
  219. $savename = [];
  220. $files = !is_array($files) ? [$files] : $files;
  221. try {
  222. //验证
  223. validate(['videoFile' => ['fileSize' => 10240000,'fileExt' => 'mp4,mp3,avi']])->check(['videoFile' => $files]);
  224. foreach ($files as $file) {
  225. $url = Filesystem::disk('public')->putFile('video/' . date("Ymd"), $file, function () use ($file) {
  226. return str_replace('.' . $file->getOriginalExtension(), '', $file->getOriginalName() . "_" . date('YmdHis'));
  227. });
  228. $name = str_replace('.' . $file->getOriginalExtension(), '', $file->getOriginalName());
  229. $temp = ["url" => $url, "name" => $name];
  230. $savename[] = $temp;
  231. }
  232. return $savename;
  233. } catch (\think\exception\ValidateException $e) {
  234. return $e->getMessage();
  235. }
  236. }
  237. /**
  238. * @param $token
  239. * @param $condition
  240. * @return mixed
  241. */
  242. function resetpwd($token,$condition){
  243. $host = Config::get("app");
  244. $url = $host["api_host"]."/Api/passset";
  245. $condition['token']=$token;
  246. $response=curl_request($url,$condition);
  247. return json_decode($response,true);
  248. }
  249. function resetpasswd($token,$condition){
  250. $host = Config::get("app");
  251. $url = $host["api_host"]."/Api/passsave";
  252. $condition['token']=$token;
  253. $response=curl_request($url,$condition);
  254. return json_decode($response,true);
  255. }
  256. /**
  257. * @param $token
  258. * @param $condition
  259. * @return mixed
  260. */
  261. function resetinfo($token,$condition){
  262. $host = Config::get("app");
  263. $url = $host["api_host"]."/Api/usersave";
  264. $condition['token']=$token;
  265. $response=curl_request($url,$condition);
  266. return json_decode($response,true);
  267. }
  268. /**
  269. * @param $token
  270. * @param $condition
  271. * @return mixed
  272. */
  273. function resetstatus($token,$condition){
  274. $host = Config::get("app");
  275. $url = $host["api_host"]."/Api/userstatus";
  276. $condition['token']=$token;
  277. $response=curl_request($url,$condition);
  278. return json_decode($response,true);
  279. }
  280. /**
  281. * @param $data
  282. * @throws \think\db\exception\DataNotFoundException
  283. * @throws \think\db\exception\DbException
  284. * @throws \think\db\exception\ModelNotFoundException
  285. */
  286. function crea($data,$vio=0)
  287. {
  288. $db = Db::name("company_item")->where(['pid'=>$data['id'],'is_del'=>0])->select()->toArray();
  289. if($vio==1){
  290. $d = Db::name("depart_user")->where(['itemid'=>$data['id'],'is_del'=>0])->select()->toArray();
  291. if(empty($d)){
  292. $data['item']=[];
  293. }else{
  294. $data['item']=$d;
  295. }
  296. }
  297. if(empty($db)){
  298. $data['child']=[];
  299. return $data;
  300. }
  301. //var_dump($db);
  302. foreach ($db as $p){
  303. $data['child'][]=crea($p,$vio);
  304. }
  305. return $data;
  306. }
  307. function GetPart($id,$data=[]){
  308. $db = Db::name("company_item")->where(['id'=>$id,'is_del'=>0])->find();
  309. if($db==false){
  310. return [];
  311. }
  312. $tem=[];
  313. $tem['id']=$db['id'];
  314. $tem['name']=$db['name'];
  315. array_unshift($data,$tem);
  316. if($db['pid']==0){
  317. // krsort($data);
  318. return $data;
  319. }else{
  320. return GetPart($db['pid'],$data);
  321. }
  322. }
  323. function stro($data){
  324. $db=Db::name('cat')->where(['pid'=>$data['id']])->select()->toArray();
  325. if(empty($db)){
  326. $data['child']=[];
  327. return $data;
  328. }
  329. foreach ($db as $item) {
  330. $data['child'][]=stro($item);
  331. }
  332. return $data;
  333. }
  334. function coco($data){
  335. $db=Db::name('exclusive')->where(['pid'=>$data['id']])->select()->toArray();
  336. if(empty($db)){
  337. $data['child']=[];
  338. return $data;
  339. }
  340. foreach ($db as $item) {
  341. $data['child'][]=coco($item);
  342. }
  343. return $data;
  344. }
  345. function mai($var,$data=[]){
  346. $str = Db::name('exclusive')->where(['id'=>$var])->find();
  347. if($str==false){
  348. return [];
  349. }
  350. $vmn =[];
  351. $vmn['id'] =$str['id'];
  352. $vmn['rname'] =$str['name'];
  353. array_unshift($data,$vmn);
  354. // $var['id']=made();
  355. if($str['pid']==0){
  356. // krsort($data);
  357. return $data;
  358. }else{
  359. return mai($str['pid'],$data);
  360. }
  361. }
  362. function made($var,$data=[]){
  363. $str = Db::name('cat')->where(['id'=>$var])->find();
  364. if($str==false){
  365. return [];
  366. }
  367. $vmn =[];
  368. $vmn['id'] =$str['id'];
  369. $vmn['name'] =$str['cat_name'];
  370. array_unshift($data,$vmn);
  371. // $var['id']=made();
  372. if($str['pid']==0){
  373. // krsort($data);
  374. return $data;
  375. }else{
  376. return made($str['pid'],$data);
  377. }
  378. }
  379. //获取有赞分类信息
  380. function made_youzan(int $yz_cat_id=0,$data=[]){
  381. $rs = get_yz_cat_info($yz_cat_id);
  382. if(empty($rs)) return [];
  383. $vmn =[];
  384. $vmn['yz_cat_id'] =$rs['id'];
  385. $vmn['yz_cat_name'] =$rs['yz_cat_name'];
  386. array_unshift($data,$vmn);
  387. if($rs['parent_cid']==0) return $data;
  388. else return made_youzan($rs['parent_cid'],$data);
  389. }
  390. //跨数据库获取有赞分类信息
  391. if(!function_exists('get_yz_cat_info')){
  392. function get_yz_cat_info(int $yz_cat_id=0){
  393. $key = 'yz_cat_item_'.(string)$yz_cat_id;
  394. $rs = \think\facade\Cache::get($key);
  395. if(!$rs){
  396. $rs = Db::connect('mysql_yz')
  397. ->table('yz_cat')
  398. ->field('id,yz_cat_name,parent_cid')
  399. ->where(['id'=>$yz_cat_id,'status'=>1])
  400. ->findOrEmpty();
  401. if($rs) \think\facade\Cache::set($key,$rs,36000);
  402. }
  403. return $rs;
  404. }
  405. }
  406. function catChild($var,&$data=[]){
  407. $str = Db::name('cat')->where(['id'=>$var])->find();
  408. if($str==false){
  409. return;
  410. }
  411. $data[]=$var;
  412. $lsit = Db::name("cat")->where(["pid"=>$var,"status"=>1,"is_del"=>0])->column("id");
  413. if(!empty($lsit)){
  414. foreach ($lsit as $value){
  415. catChild($value,$data);
  416. }
  417. }
  418. return $data;
  419. }
  420. function makeExcluse($var,$data=[]){
  421. $str = Db::name('exclusive')->where(['id'=>$var])->find();
  422. if($str==false){
  423. return [];
  424. }
  425. $vmn =[];
  426. $vmn['id'] =$str['id'];
  427. $vmn['name'] =$str['name'];
  428. array_unshift($data,$vmn);
  429. // $var['id']=made();
  430. if($str['pid']==0){
  431. // krsort($data);
  432. return $data;
  433. }else{
  434. return makeExcluse($str['pid'],$data);
  435. }
  436. }
  437. function sear($id){
  438. $item = Db::name('cat')->where(['id'=>$id])->field("search")->find();
  439. if($item==false){
  440. return false;
  441. }else{
  442. $temp = Db::name('cat')->where(['pid'=>$id,'is_del'=>0])->select();
  443. if ($temp==false){
  444. return false;
  445. }
  446. }
  447. foreach ($temp as $value){
  448. $value['search']=$item['search']."_".$value['cat_name'];
  449. $list = Db::name('cat')->save($value);
  450. sear($value['id']);
  451. }
  452. }
  453. function manger($list=[],$level=1){
  454. $var = Db::name('cat')->where(['pid'=>$list,'level'=>$level+1])->column("id");
  455. if(empty($var)){
  456. return $list;
  457. }
  458. $a=array_merge($list,$var);
  459. return manger($a,$level+1);
  460. }
  461. /**
  462. * @param $files
  463. * @param string $extend
  464. * @return array
  465. * @throws PHPExcel_Exception
  466. * @throws PHPExcel_Reader_Exception
  467. */
  468. function upload_excel($files,$extend="xls")
  469. {
  470. // 获取表单上传文件
  471. try {
  472. validate([
  473. 'file' => [
  474. // 限制文件大小(单位b),这里限制为4M
  475. //fileSize' => 4 * 1024 * 1024,
  476. 'fileExt' => 'xlsx,xls'
  477. ]
  478. ],
  479. [
  480. //'file.fileSize' => '文件太大',
  481. 'file.fileExt' => '不支持的文件',
  482. ]
  483. )->check(['file' => $files]);
  484. // $name = $files->getOriginalExtension();
  485. if ($extend == 'xlsx') {
  486. $objReader = PHPExcel_IOFactory::createReader('Excel2007');
  487. } else {
  488. $objReader = PHPExcel_IOFactory::createReader('Excel5');
  489. }
  490. $savename = Filesystem::disk('public')->putFile('topic/excel', $files);
  491. $import_path = root_path() . 'public/storage/' . $savename;
  492. $spreadsheet = $objReader->load($import_path);
  493. $sheet = $spreadsheet->getActiveSheet();
  494. $sheetData = $sheet->toArray();
  495. if (empty($sheetData) || !is_array($sheetData)) {
  496. return ['code' => 1003, "msg" => '数据不能为空'];
  497. }
  498. $list = [];
  499. foreach ($sheetData as $key => $value) {
  500. $list[] = $value;
  501. }
  502. return ['code' => 0, "msg" => '数据解析成功', 'data' => $list];
  503. } catch (think\exception\ValidateException $e) {
  504. // echo $e->getMessage();
  505. return ['code' => 1003, "msg" => $e->getMessage()];
  506. }
  507. }
  508. /**
  509. * @param string $fileName
  510. * @param array $headArr
  511. * @param array $data
  512. */
  513. function excelSave($fileName = '', $headArr = [], $data = [])
  514. {
  515. $objPHPExcel = new PHPExcel();
  516. $objPHPExcel->getProperties();
  517. $keyA = 0; // 设置表头
  518. foreach ($headArr as $v) {
  519. $colum = PHPExcel_Cell::stringFromColumnIndex($keyA);
  520. $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
  521. $keyA += 1;
  522. }
  523. $column = 2;
  524. $objActSheet = $objPHPExcel->getActiveSheet();
  525. foreach ($data as $key => $rows) { // 行写入
  526. $span = 0;
  527. foreach ($rows as $keyName => $value) { // 列写入
  528. //判断数据是否有数组,如果有数组,转换成字符串
  529. if(is_array($value)){
  530. $value = implode("、", $value);
  531. }
  532. $objActSheet->setCellValue(PHPExcel_Cell::stringFromColumnIndex($span) . $column, $value);
  533. $span++;
  534. }
  535. $column++;
  536. }
  537. // var_dump($objActSheet->getActiveCell());
  538. $file = $fileName. ".xls";
  539. //$fileName .= "_" . date("Y_m_d", Request()->instance()->time()) . ".xls";
  540. //$fileName = iconv("utf-8", "gb2312", $fileName); // 重命名表
  541. $dir =root_path() . 'public/storage/report/'.date("YmdHis")."/";
  542. if(!is_dir($dir)){
  543. mkdir($dir,0777,true);
  544. }
  545. PHPExcel_Settings::setCacheStorageMethod(PHPExcel_CachedObjectStorageFactory::cache_in_memory_serialized);
  546. $objPHPExcel->setActiveSheetIndex(0); // 设置活动单指数到第一个表,所以Excel打开这是第一个表
  547. $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  548. $objWriter->save($dir . $file); // 文件通过浏览器下载
  549. $url = $dir . $file;
  550. if(!file_exists($url)){
  551. echo "文件生成失败";
  552. }
  553. $saveDir = root_path()."public/storage/zip/";
  554. if(!is_dir( $saveDir)){
  555. mkdir($saveDir,0777,true);
  556. }
  557. $datetime = date("Y-m-d H:i:s");
  558. $file_dir = $saveDir.$datetime.".zip";
  559. # 5.1 文件打包,提示:使用本类,linux需开启zlib,windows需取消php_zip.dll前的注释
  560. $zip = new \ZipArchive ();
  561. # 5.2 文件不存在则生成一个新的文件 用CREATE打开文件会追加内容至zip
  562. if ($zip->open($file_dir, \ZipArchive::OVERWRITE) !== true && $zip->open($file_dir, \ZipArchive::CREATE) !==
  563. true) echo '无法打开文件或者文件创建失败';
  564. # 5.3 批量写入压缩包
  565. $zip->addEmptyDir($fileName);
  566. // @$zip->addFile($v['file_path'], 'resume'.DIRECTORY_SEPARATOR.basename($headername));
  567. @$zip->addFile($url,$fileName.DIRECTORY_SEPARATOR.basename($url));
  568. # 5.4 关闭压缩包写入
  569. $zip->close();
  570. @deldir($dir);
  571. # 6. 检查文件是否存在,并输出文件
  572. if (! file_exists ( $file_dir )) echo '简历文件不存在';
  573. ob_clean();
  574. flush();
  575. header("Cache-Control: max-age=0");
  576. header("Content-Description: File Transfer");
  577. header('Content-disposition: attachment; filename=' . basename($file_dir)); # 处理文件名
  578. header("Content-Type: application/octet-stream"); # 流文件输出
  579. header("Content-Transfer-Encoding: binary"); # 告诉浏览器,这是二进制文件
  580. // header('Content-Length: ' . filesize($file_dir)); # 告诉浏览器,文件大小
  581. // readfile($file_dir); # 输出文件
  582. $res = read_big_file($file_dir);
  583. foreach ($res as $val) {
  584. echo $val;
  585. }
  586. @ unlink($file_dir);
  587. exit();
  588. }
  589. //读取大文件
  590. if (!function_exists('read_big_file')){
  591. function read_big_file(string $file=''){
  592. $handle = fopen($file, 'rb');
  593. while (feof($handle) === false) {
  594. yield fgets($handle);
  595. }
  596. fclose($handle);
  597. }
  598. }
  599. function deldir($path){
  600. //如果是目录则继续
  601. if(is_dir($path)){
  602. //扫描一个文件夹内的所有文件夹和文件并返回数组
  603. $p = scandir($path);
  604. //如果 $p 中有两个以上的元素则说明当前 $path 不为空
  605. if(count($p)>2){
  606. foreach($p as $val){
  607. //排除目录中的.和..
  608. if($val !="." && $val !=".."){
  609. //如果是目录则递归子目录,继续操作
  610. if(is_dir($path.$val)){
  611. //子目录中操作删除文件夹和文件
  612. deldir($path.$val.'/');
  613. }else{
  614. //如果是文件直接删除
  615. unlink($path.$val);
  616. }
  617. }
  618. }
  619. }
  620. }
  621. //删除目录
  622. return rmdir($path);
  623. }
  624. /**
  625. * @param string $AddrJson
  626. */
  627. function GetAddr($AddrJson=""){
  628. if($AddrJson==""){
  629. return '';
  630. }
  631. $adr = json_decode($AddrJson,true);
  632. if(!is_array($adr)){
  633. return '';
  634. }
  635. $addr='';
  636. if(isset($adr['provice_code'])&&$adr['provice_code']!=''){
  637. $provice = Db::name("province")->where(["province_code"=>$adr['provice_code']])->find();
  638. $addr.=isset($provice['name']) ? $provice['name']:"";
  639. }
  640. if(isset($adr['city_code'])&&$adr['city_code']!=''){
  641. $city = Db::name("city")->where(["city_code"=>$adr['city_code']])->find();
  642. $addr.=isset($city['name']) ? $city['name']:"";
  643. }
  644. if(isset($adr['area_code'])&&$adr['area_code']!=''){
  645. $area = Db::name("area")->where(["area_code"=>$adr['area_code']])->find();
  646. $addr.=isset($area['name']) ? $area['name']:"";
  647. }
  648. return $addr;
  649. }
  650. /**
  651. * POST 请求
  652. * @param string $url
  653. * @param array $param
  654. * @param boolean $post_file 是否文件上传
  655. * @return string content
  656. */
  657. function post($url,$data,$header=[])
  658. {
  659. //对空格进行转义
  660. $url = str_replace(' ','+',$url);
  661. $ch = curl_init();
  662. //设置选项,包括URL
  663. curl_setopt($ch, CURLOPT_URL, "$url");
  664. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  665. curl_setopt($ch, CURLOPT_HEADER, 0);
  666. curl_setopt($ch,CURLOPT_TIMEOUT,3); //定义超时3秒钟
  667. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  668. // POST数据
  669. // curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  670. curl_setopt($ch, CURLOPT_POST, 1);
  671. // 把post的变量加上
  672. curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //所需传的数组用http_bulid_query()函数处理一下,就ok了
  673. curl_setopt($ch, CURLOPT_HEADER, true);
  674. //执行并获取url地址的内容
  675. $output = curl_exec($ch);
  676. $errorCode = curl_errno($ch);
  677. //释放curl句柄
  678. $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
  679. // 根据头大小去获取头信息内容
  680. $header = substr($output, 0, $headerSize);
  681. curl_close($ch);
  682. if(0 !== $errorCode) {
  683. return false;
  684. }
  685. return $header;
  686. }
  687. function post2($url,$data,$header=[])
  688. {
  689. //对空格进行转义
  690. $url = str_replace(' ','+',$url);
  691. $ch = curl_init();
  692. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  693. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  694. //设置选项,包括URL
  695. curl_setopt($ch, CURLOPT_URL, "$url");
  696. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  697. curl_setopt($ch, CURLOPT_HEADER, 0);
  698. // POST数据
  699. curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  700. curl_setopt($ch, CURLOPT_POST, 1);
  701. // 把post的变量加上
  702. curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //所需传的数组用http_bulid_query()函数处理一下,就ok了
  703. $output = curl_exec($ch);
  704. $errorCode = curl_errno($ch);
  705. curl_close($ch);
  706. if(0 !== $errorCode) {
  707. return false;
  708. }
  709. return $output;
  710. }
  711. function GoldPrice($data,$cost_rate=0){
  712. $gold = Db::name("gold_price1")->where(["type"=>$data["metal_id"],"is_del"=>0,"status"=>1])->order("addtime desc")
  713. ->find();
  714. // $rate = $data['open_fee']/$data['num'] + $data['weight']* $gold["price"] + $data['cost_fee']/(1-$cost_rate) *
  715. // $data['weight']+$data['packing_fee']+$data["mark_fee"]+$data["cert_fee"]+$data['nake_fee'];
  716. $saleprice = ($data['demo_fee']/$data['num']+$data['delivery_fee']+$data['open_fee']/$data['num']+ $data['weight']*
  717. $gold["price"] + $data['cost_fee'] *$data['weight'] + $data['packing_fee']+ $data["mark_fee"]+ $data["cert_fee"]+$data['nake_fee']) / (1 - $cost_rate);
  718. return $saleprice;
  719. }
  720. function GoodPrice($data,$cost_rate=0){
  721. $rate = ($data['open_fee']/$data['num']+ $data['cost_fee']+$data['packing_fee']+$data["mark_fee"]+$data["cert_fee"]+$data['nake_fee'])/(1-$cost_rate
  722. );
  723. return $rate;
  724. }
  725. function checkRole($roleid,$menu){
  726. $roleinfo = Db::name("role_action")->where([['role_id',"=",$roleid],["status","=",1]])->find();
  727. if($roleinfo['private_data']!=""){
  728. $private = explode(",",$roleinfo['private_data']);
  729. if(in_array($menu,$private)){
  730. return true;
  731. }
  732. }
  733. return false;
  734. }
  735. /**
  736. * 根据地址解析省市区
  737. * @param 详细地址,类似于'北京市顺义区xxx路xxx号'
  738. */
  739. if (!function_exists('get_address')) {
  740. function get_address(string $address = '')
  741. {
  742. preg_match('/(.*?(省|自治区|北京市|天津市|上海市|重庆市|澳门特别行政区|香港特别行政区))/', $address, $matches);
  743. if (count($matches) > 1) {
  744. $province = $matches[count($matches) - 2];
  745. $address = preg_replace('/(.*?(省|自治区|北京市|天津市|上海市|重庆市|澳门特别行政区|香港特别行政区))/', '', $address, 1);
  746. }
  747. preg_match('/(.*?(市|自治州|地区|区划|县))/', $address, $matches);
  748. if (count($matches) > 1) {
  749. $city = $matches[count($matches) - 2];
  750. $address = str_replace($city, '', $address);
  751. }
  752. preg_match('/(.*?(区|县|镇|乡|街道))/', $address, $matches);
  753. if (count($matches) > 1) {
  754. $area = $matches[count($matches) - 2];
  755. $address = str_replace($area, '', $address);
  756. }
  757. return [
  758. 'province' => isset($province) ? $province : '',
  759. 'city' => isset($city) ? $city : '',
  760. 'district' => isset($area) ? $area : '',
  761. "address" => $address
  762. ];
  763. }
  764. }
  765. /**
  766. * 批量生成多个文件excel,生成压缩包
  767. */
  768. if (!function_exists('excelSaveBatch')) {
  769. function excelSaveBatch(array $datas = [])
  770. {
  771. $urls = [];
  772. $dir = root_path() . 'public/storage/report/' . date("YmdHis") . "/";
  773. if (!is_dir($dir)) {
  774. mkdir($dir, 0777, true);
  775. }
  776. foreach ($datas as $item) {
  777. $objPHPExcel = new PHPExcel();
  778. $objPHPExcel->getProperties();
  779. $keyA = 0; // 设置表头
  780. foreach ($item['head'] as $v) {
  781. $colum = PHPExcel_Cell::stringFromColumnIndex($keyA);
  782. $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
  783. $keyA += 1;
  784. }
  785. $column = 2;
  786. $objActSheet = $objPHPExcel->getActiveSheet();
  787. foreach ($item['list'] as $key => $rows) { // 行写入
  788. $span = 0;
  789. foreach ($rows as $keyName => $value) { // 列写入
  790. //判断数据是否有数组,如果有数组,转换成字符串
  791. if (is_array($value)) {
  792. $value = implode("、", $value);
  793. }
  794. $objActSheet->setCellValue(PHPExcel_Cell::stringFromColumnIndex($span) . $column, $value);
  795. $span++;
  796. }
  797. $column++;
  798. }
  799. // var_dump($objActSheet->getActiveCell());
  800. $file = $item['filename'] . ".xls";
  801. //$fileName .= "_" . date("Y_m_d", Request()->instance()->time()) . ".xls";
  802. //$fileName = iconv("utf-8", "gb2312", $fileName); // 重命名表
  803. $objPHPExcel->setActiveSheetIndex(0); // 设置活动单指数到第一个表,所以Excel打开这是第一个表
  804. $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  805. $objWriter->save($dir . $file); // 文件通过浏览器下载
  806. $url = $dir . $file;
  807. if (!file_exists($url)) {
  808. echo "文件生成失败";
  809. } else {
  810. $urls[] = $url;
  811. }
  812. }
  813. $saveDir = root_path() . "public/storage/zip/";
  814. if (!is_dir($saveDir)) {
  815. mkdir($saveDir, 0777, true);
  816. }
  817. $datetime = date("YmdHis");
  818. $file_dir = $saveDir . $datetime . ".zip";
  819. # 5.1 文件打包,提示:使用本类,linux需开启zlib,windows需取消php_zip.dll前的注释
  820. $zip = new \ZipArchive ();
  821. # 5.2 文件不存在则生成一个新的文件 用CREATE打开文件会追加内容至zip
  822. if ($zip->open($file_dir, \ZipArchive::OVERWRITE) !== true && $zip->open($file_dir, \ZipArchive::CREATE) !== true) echo '无法打开文件或者文件创建失败';
  823. # 5.3 批量写入压缩包
  824. // $zip->addEmptyDir($fileName);//往zip压缩包写入空目录
  825. foreach ($urls as $fileName) {
  826. // @$zip->addFile($fileName);
  827. @$zip->addFile($fileName, DIRECTORY_SEPARATOR.basename($fileName));
  828. }
  829. // @$zip->addFile($v['file_path'], 'resume'.DIRECTORY_SEPARATOR.basename($headername));
  830. # 5.4 关闭压缩包写入
  831. $zip->close();
  832. @deldir($dir);//删除已生成的文件及目录
  833. //6. 检查文件是否存在,并输出文件
  834. if (!file_exists($file_dir)) echo '压缩包文件不存在';
  835. ob_clean();
  836. flush();
  837. header("Cache-Control: max-age=0");
  838. header("Content-Description: File Transfer");
  839. header('Content-disposition: attachment; filename=' . basename($file_dir)); # 处理文件名
  840. header("Content-Type: application/octet-stream"); # 流文件输出
  841. header("Content-Transfer-Encoding: binary"); # 告诉浏览器,这是二进制文件
  842. // header('Content-Length: ' . filesize($file_dir)); # 告诉浏览器,文件大小
  843. // readfile($file_dir);//输出文件
  844. $res = read_big_file($file_dir);
  845. foreach ($res as $val) {
  846. echo $val;
  847. }
  848. @unlink($file_dir);
  849. exit();
  850. }
  851. }
  852. /**
  853. * 批量生成多个文件excel,生成压缩包,保存到本地,返回文件链接
  854. * datas 生成器
  855. * header array 头部字段
  856. * filename string 文件名
  857. */
  858. if (!function_exists('excelSaveFile')) {
  859. function excelSaveFile($datas, string $filename = '')
  860. {
  861. // $urls = [];
  862. $dir = root_path() . 'public/storage/report/' . date("YmdHis") . "/";
  863. if (!is_dir($dir)) mkdir($dir, 0777, true);
  864. // foreach ($datas as $item) {
  865. PHPExcel_CachedObjectStorageFactory::cache_in_memory_gzip;//单元格缓存为MemoryGZip
  866. $objPHPExcel = new PHPExcel();
  867. $keyA = 0; // 设置表头
  868. $column = 2;
  869. $objActSheet = $objPHPExcel->getActiveSheet();
  870. foreach ($datas as $key => $rows) { // 行写入
  871. //第一行取key作表头
  872. if($key==0){
  873. $objPHPExcel->getProperties();
  874. foreach ($rows as $k=>$v) {
  875. $colum = PHPExcel_Cell::stringFromColumnIndex($keyA);
  876. $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $k);
  877. $keyA += 1;
  878. }
  879. }
  880. //写入列
  881. $span = 0;
  882. foreach ($rows as $keyName => $value) {
  883. //判断数据是否有数组,如果有数组,转换成字符串
  884. if (is_array($value)) $value = implode("、", $value);
  885. $objActSheet->setCellValue(PHPExcel_Cell::stringFromColumnIndex($span) . $column, $value);
  886. $span++;
  887. }
  888. $column++;
  889. }
  890. $file = $filename . ".xls";
  891. $objPHPExcel->setActiveSheetIndex(0); // 设置活动单指数到第一个表,所以Excel打开这是第一个表
  892. PHPExcel_Settings::setCacheStorageMethod(PHPExcel_CachedObjectStorageFactory::cache_in_memory_serialized);
  893. $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  894. $objWriter->save($dir . $file); // 文件通过浏览器下载
  895. $url = $dir . $file;
  896. if (!file_exists($url)) throw new Exception('文件生成失败');
  897. $saveDir = root_path() . "public/storage/zip/" . date('Ymd') . '/';
  898. if (!is_dir($saveDir)) mkdir($saveDir, 0777, true);
  899. $file_dir = $saveDir . $filename . ".zip";
  900. # 5.1 文件打包,提示:使用本类,linux需开启zlib,windows需取消php_zip.dll前的注释
  901. $zip = new \ZipArchive ();
  902. # 5.2 文件不存在则生成一个新的文件 用CREATE打开文件会追加内容至zip
  903. if ($zip->open($file_dir, \ZipArchive::OVERWRITE) !== true && $zip->open($file_dir, \ZipArchive::CREATE) !== true) echo '无法打开文件或者文件创建失败';
  904. # 5.3 批量写入压缩包
  905. // $zip->addEmptyDir($fileName);//往zip压缩包写入空目录
  906. // foreach ($urls as $fileName) {
  907. @$zip->addFile($url, DIRECTORY_SEPARATOR . basename($url));
  908. // }
  909. // @$zip->addFile($v['file_path'], 'resume'.DIRECTORY_SEPARATOR.basename($headername));
  910. # 5.4 关闭压缩包写入
  911. $zip->close();
  912. @deldir($dir);//删除已生成的文件及目录
  913. //6. 检查文件是否存在,并输出文件
  914. if (!file_exists($file_dir)) throw new Exception('压缩包文件不存在');
  915. // return $file_dir;
  916. return str_replace(root_path() . "public/", '', $file_dir);
  917. }
  918. }
  919. //通过快递网的api获取物流信息
  920. if (!function_exists('get_logistics_information')) {
  921. function get_logistics_information(string $post_code = '', string $phone = '')
  922. {
  923. if ($post_code == '') throw new Exception('快递单号不能为空');
  924. $signer = new \app\admin\common\HuaweiSigner();
  925. //设置相关参数
  926. $signer->Key = '1b4cfe41d72d4fbdb6778a5e0193c4b5';
  927. $signer->Secret = '0fd04c5d5287424eb0d25f8f620aeb78';
  928. $req = new \app\admin\common\HuaweiRequest('GET', 'http://kuaidi.apistore.huaweicloud.com/kuaidiinfo?nu=' . $post_code . '&phone=' . $phone);
  929. $req->headers = array(
  930. 'content-type' => 'application/json',
  931. 'x-stage' => 'RELEASE',
  932. );
  933. $req->body = '';//如果是post/put请求的话,要往请求体中添加内容
  934. $curl = $signer->Sign($req);
  935. $response = curl_exec($curl);
  936. $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  937. $curl_error = curl_error($curl);
  938. curl_close($curl);
  939. if ($status == 200) return json_decode($response, true);
  940. else throw new Exception('请求失败:' . $curl_error);
  941. }
  942. }
  943. //获取三级架构
  944. if (!function_exists('get_top_customer_org')) {
  945. function get_top_customer_org($var, $data = [])
  946. {
  947. $str = Db::name('customer_org1')
  948. ->field('id,name,pid,level')
  949. ->where(['id' => $var])
  950. ->find();
  951. if ($str == false) {
  952. return [];
  953. }
  954. $vmn = [];
  955. $vmn['id'] = $str['id'];
  956. $vmn['name'] = $str['name'];
  957. $vmn['level'] = $str['level'];
  958. array_unshift($data, $vmn);
  959. // $var['id']=made();
  960. if ($str['pid'] == 0) {
  961. // krsort($data);
  962. return $data;
  963. } else {
  964. return get_top_customer_org($str['pid'], $data);
  965. }
  966. }
  967. }
  968. //根据某个关键字匹配所有子级部门及用户
  969. /**
  970. * $company_name string 部门名称
  971. * $off bool 是否查询离职人员,默认不查询
  972. */
  973. if (!function_exists('get_company_item_user_by_name')) {
  974. function get_company_item_user_by_name(string $company_name = '', bool $off = false)
  975. {
  976. $data = [];
  977. //查询符合条件的部门id
  978. $company_ids = Db::name("company_item")
  979. ->field('id,level')
  980. ->where(['is_del' => 0])
  981. ->whereLike('name', '%' . $company_name . '%')
  982. ->select()
  983. ->toArray();
  984. if (!empty($company_ids)) {
  985. $level_temp = $company_ids[0]['level'] + 1;
  986. $company_ids = array_column($company_ids, 'id');
  987. for ($level = $level_temp; $level > 0; $level++) {
  988. if (!empty($company_ids)) {
  989. //根据部门id找人
  990. $uids = Db::name('depart_user')
  991. ->where(['is_del' => 0])
  992. ->order('uid')
  993. ->whereIn('itemid', $company_ids);
  994. if (!$off) $uids->where('status', 1);
  995. $uids = $uids->column('uid');
  996. $data = array_unique(array_merge($data, $uids));
  997. $company_ids = Db::name("company_item")
  998. ->where(['is_del' => 0, 'level' => $level])
  999. ->whereIn('pid', $company_ids)
  1000. ->column('id');
  1001. } else break;
  1002. }
  1003. }
  1004. return $data;
  1005. }
  1006. }
  1007. //获取某个用户所属部门名称
  1008. //$uid int 用户id
  1009. //$cache bool 是否启用缓存,(默认启用,不启用的话直接从数据库查)
  1010. //$get_tops bool 是否获取多级部门,例如 万宇恒通/采购部/仓储物流,默认不获取
  1011. if (!function_exists('get_company_name_by_uid')) {
  1012. function get_company_name_by_uid(int $uid = 0, bool $cache = true, bool $get_tops = false)
  1013. {
  1014. $rs = '';
  1015. $key = 'get_company_name_by_uid_' . $uid.'_'.$get_tops;
  1016. if ($cache) $rs = \think\facade\Cache::get($key);
  1017. if (empty($rs)) {
  1018. $itemid = Db::name('depart_user')->where(['is_del' => 0, 'uid' => $uid])->value('itemid', 0);
  1019. if ($get_tops) $rs = implode('/', array_column(GetPart($itemid), 'name'));
  1020. else $rs = Db::name('company_item')->where(['is_del' => 0, 'id' => $itemid])->value('name');
  1021. \think\facade\Cache::set($key, $rs, 3600);
  1022. }
  1023. return $rs;
  1024. }
  1025. }
  1026. //返回json格式的响应信息,方便中间件记录,目前在abutmenu应用中有用到
  1027. if (!function_exists('json_show')) {
  1028. function json_show(int $code = 0, string $message = '请求成功', array $data = [])
  1029. {
  1030. return json(['code' => $code, 'message' => $message, 'data' => $data]);
  1031. }
  1032. }