common.php 36 KB

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