common.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131
  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. function catChild($var,&$data=[]){
  374. $str = Db::name('cat')->where(['id'=>$var])->find();
  375. if($str==false){
  376. return;
  377. }
  378. $data[]=$var;
  379. $lsit = Db::name("cat")->where(["pid"=>$var,"status"=>1,"is_del"=>0])->column("id");
  380. if(!empty($lsit)){
  381. foreach ($lsit as $value){
  382. catChild($value,$data);
  383. }
  384. }
  385. return $data;
  386. }
  387. function makeExcluse($var,$data=[]){
  388. $str = Db::name('exclusive')->where(['id'=>$var])->find();
  389. if($str==false){
  390. return [];
  391. }
  392. $vmn =[];
  393. $vmn['id'] =$str['id'];
  394. $vmn['name'] =$str['name'];
  395. array_unshift($data,$vmn);
  396. // $var['id']=made();
  397. if($str['pid']==0){
  398. // krsort($data);
  399. return $data;
  400. }else{
  401. return makeExcluse($str['pid'],$data);
  402. }
  403. }
  404. function sear($id){
  405. $item = Db::name('cat')->where(['id'=>$id])->field("search")->find();
  406. if($item==false){
  407. return false;
  408. }else{
  409. $temp = Db::name('cat')->where(['pid'=>$id,'is_del'=>0])->select();
  410. if ($temp==false){
  411. return false;
  412. }
  413. }
  414. foreach ($temp as $value){
  415. $value['search']=$item['search']."_".$value['cat_name'];
  416. $list = Db::name('cat')->save($value);
  417. sear($id);
  418. }
  419. }
  420. function manger($list=[],$level=1){
  421. $var = Db::name('cat')->where(['pid'=>$list,'level'=>$level+1])->column("id");
  422. if(empty($var)){
  423. return $list;
  424. }
  425. $a=array_merge($list,$var);
  426. return manger($a,$level+1);
  427. }
  428. /**
  429. * @param $files
  430. * @param string $extend
  431. * @return array
  432. * @throws PHPExcel_Exception
  433. * @throws PHPExcel_Reader_Exception
  434. */
  435. function upload_excel($files,$extend="xls")
  436. {
  437. // 获取表单上传文件
  438. try {
  439. validate([
  440. 'file' => [
  441. // 限制文件大小(单位b),这里限制为4M
  442. //fileSize' => 4 * 1024 * 1024,
  443. 'fileExt' => 'xlsx,xls'
  444. ]
  445. ],
  446. [
  447. //'file.fileSize' => '文件太大',
  448. 'file.fileExt' => '不支持的文件',
  449. ]
  450. )->check(['file' => $files]);
  451. // $name = $files->getOriginalExtension();
  452. if ($extend == 'xlsx') {
  453. $objReader = PHPExcel_IOFactory::createReader('Excel2007');
  454. } else {
  455. $objReader = PHPExcel_IOFactory::createReader('Excel5');
  456. }
  457. $savename = Filesystem::disk('public')->putFile('topic/excel', $files);
  458. $import_path = root_path() . 'public/storage/' . $savename;
  459. $spreadsheet = $objReader->load($import_path);
  460. $sheet = $spreadsheet->getActiveSheet();
  461. $sheetData = $sheet->toArray();
  462. if (empty($sheetData) || !is_array($sheetData)) {
  463. return ['code' => 1003, "msg" => '数据不能为空'];
  464. }
  465. $list = [];
  466. foreach ($sheetData as $key => $value) {
  467. $list[] = $value;
  468. }
  469. return ['code' => 0, "msg" => '数据解析成功', 'data' => $list];
  470. } catch (think\exception\ValidateException $e) {
  471. // echo $e->getMessage();
  472. return ['code' => 1003, "msg" => $e->getMessage()];
  473. }
  474. }
  475. /**
  476. * @param string $fileName
  477. * @param array $headArr
  478. * @param array $data
  479. */
  480. function excelSave($fileName = '', $headArr = [], $data = [])
  481. {
  482. $objPHPExcel = new PHPExcel();
  483. $objPHPExcel->getProperties();
  484. $keyA = 0; // 设置表头
  485. foreach ($headArr as $v) {
  486. $colum = PHPExcel_Cell::stringFromColumnIndex($keyA);
  487. $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
  488. $keyA += 1;
  489. }
  490. $column = 2;
  491. $objActSheet = $objPHPExcel->getActiveSheet();
  492. foreach ($data as $key => $rows) { // 行写入
  493. $span = 0;
  494. foreach ($rows as $keyName => $value) { // 列写入
  495. //判断数据是否有数组,如果有数组,转换成字符串
  496. if(is_array($value)){
  497. $value = implode("、", $value);
  498. }
  499. $objActSheet->setCellValue(PHPExcel_Cell::stringFromColumnIndex($span) . $column, $value);
  500. $span++;
  501. }
  502. $column++;
  503. }
  504. // var_dump($objActSheet->getActiveCell());
  505. $file = $fileName. ".xls";
  506. //$fileName .= "_" . date("Y_m_d", Request()->instance()->time()) . ".xls";
  507. //$fileName = iconv("utf-8", "gb2312", $fileName); // 重命名表
  508. $dir =root_path() . 'public/storage/report/'.date("YmdHis")."/";
  509. if(!is_dir($dir)){
  510. mkdir($dir,0777,true);
  511. }
  512. $objPHPExcel->setActiveSheetIndex(0); // 设置活动单指数到第一个表,所以Excel打开这是第一个表
  513. $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  514. $objWriter->save($dir . $file); // 文件通过浏览器下载
  515. $url = $dir . $file;
  516. if(!file_exists($url)){
  517. echo "文件生成失败";
  518. }
  519. $saveDir = root_path()."public/storage/zip/";
  520. if(!is_dir( $saveDir)){
  521. mkdir($saveDir,0777,true);
  522. }
  523. $datetime = date("Y-m-d H:i:s");
  524. $file_dir = $saveDir.$datetime.".zip";
  525. # 5.1 文件打包,提示:使用本类,linux需开启zlib,windows需取消php_zip.dll前的注释
  526. $zip = new \ZipArchive ();
  527. # 5.2 文件不存在则生成一个新的文件 用CREATE打开文件会追加内容至zip
  528. if ($zip->open($file_dir, \ZipArchive::OVERWRITE) !== true && $zip->open($file_dir, \ZipArchive::CREATE) !==
  529. true) echo '无法打开文件或者文件创建失败';
  530. # 5.3 批量写入压缩包
  531. $zip->addEmptyDir($fileName);
  532. // @$zip->addFile($v['file_path'], 'resume'.DIRECTORY_SEPARATOR.basename($headername));
  533. @$zip->addFile($url,$fileName.DIRECTORY_SEPARATOR.basename($url));
  534. # 5.4 关闭压缩包写入
  535. $zip->close();
  536. @deldir($dir);
  537. # 6. 检查文件是否存在,并输出文件
  538. if (! file_exists ( $file_dir )) echo '简历文件不存在';
  539. ob_clean();
  540. flush();
  541. header("Cache-Control: max-age=0");
  542. header("Content-Description: File Transfer");
  543. header('Content-disposition: attachment; filename=' . basename($file_dir)); # 处理文件名
  544. header("Content-Type: application/octet-stream"); # 流文件输出
  545. header("Content-Transfer-Encoding: binary"); # 告诉浏览器,这是二进制文件
  546. // header('Content-Length: ' . filesize($file_dir)); # 告诉浏览器,文件大小
  547. // readfile($file_dir); # 输出文件
  548. $res = read_big_file($file_dir);
  549. foreach ($res as $val) {
  550. echo $val;
  551. }
  552. @ unlink($file_dir);
  553. exit();
  554. }
  555. //读取大文件
  556. if (!function_exists('read_big_file')){
  557. function read_big_file(string $file=''){
  558. $handle = fopen($file, 'rb');
  559. while (feof($handle) === false) {
  560. yield fgets($handle);
  561. }
  562. fclose($handle);
  563. }
  564. }
  565. function deldir($path){
  566. //如果是目录则继续
  567. if(is_dir($path)){
  568. //扫描一个文件夹内的所有文件夹和文件并返回数组
  569. $p = scandir($path);
  570. //如果 $p 中有两个以上的元素则说明当前 $path 不为空
  571. if(count($p)>2){
  572. foreach($p as $val){
  573. //排除目录中的.和..
  574. if($val !="." && $val !=".."){
  575. //如果是目录则递归子目录,继续操作
  576. if(is_dir($path.$val)){
  577. //子目录中操作删除文件夹和文件
  578. deldir($path.$val.'/');
  579. }else{
  580. //如果是文件直接删除
  581. unlink($path.$val);
  582. }
  583. }
  584. }
  585. }
  586. }
  587. //删除目录
  588. return rmdir($path);
  589. }
  590. /**
  591. * @param string $AddrJson
  592. */
  593. function GetAddr($AddrJson=""){
  594. if($AddrJson==""){
  595. return '';
  596. }
  597. $adr = json_decode($AddrJson,true);
  598. if(!is_array($adr)){
  599. return '';
  600. }
  601. $addr='';
  602. if(isset($adr['provice_code'])&&$adr['provice_code']!=''){
  603. $provice = Db::name("province")->where(["province_code"=>$adr['provice_code']])->find();
  604. $addr.=isset($provice['name']) ? $provice['name']:"";
  605. }
  606. if(isset($adr['city_code'])&&$adr['city_code']!=''){
  607. $city = Db::name("city")->where(["city_code"=>$adr['city_code']])->find();
  608. $addr.=isset($city['name']) ? $city['name']:"";
  609. }
  610. if(isset($adr['area_code'])&&$adr['area_code']!=''){
  611. $area = Db::name("area")->where(["area_code"=>$adr['area_code']])->find();
  612. $addr.=isset($area['name']) ? $area['name']:"";
  613. }
  614. return $addr;
  615. }
  616. /**
  617. * POST 请求
  618. * @param string $url
  619. * @param array $param
  620. * @param boolean $post_file 是否文件上传
  621. * @return string content
  622. */
  623. function post($url,$data,$header=[])
  624. {
  625. //对空格进行转义
  626. $url = str_replace(' ','+',$url);
  627. $ch = curl_init();
  628. //设置选项,包括URL
  629. curl_setopt($ch, CURLOPT_URL, "$url");
  630. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  631. curl_setopt($ch, CURLOPT_HEADER, 0);
  632. curl_setopt($ch,CURLOPT_TIMEOUT,3); //定义超时3秒钟
  633. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  634. // POST数据
  635. // curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  636. curl_setopt($ch, CURLOPT_POST, 1);
  637. // 把post的变量加上
  638. curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //所需传的数组用http_bulid_query()函数处理一下,就ok了
  639. curl_setopt($ch, CURLOPT_HEADER, true);
  640. //执行并获取url地址的内容
  641. $output = curl_exec($ch);
  642. $errorCode = curl_errno($ch);
  643. //释放curl句柄
  644. $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
  645. // 根据头大小去获取头信息内容
  646. $header = substr($output, 0, $headerSize);
  647. curl_close($ch);
  648. if(0 !== $errorCode) {
  649. return false;
  650. }
  651. return $header;
  652. }
  653. function post2($url,$data,$header=[])
  654. {
  655. //对空格进行转义
  656. $url = str_replace(' ','+',$url);
  657. $ch = curl_init();
  658. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  659. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  660. //设置选项,包括URL
  661. curl_setopt($ch, CURLOPT_URL, "$url");
  662. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  663. curl_setopt($ch, CURLOPT_HEADER, 0);
  664. // POST数据
  665. curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  666. curl_setopt($ch, CURLOPT_POST, 1);
  667. // 把post的变量加上
  668. curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //所需传的数组用http_bulid_query()函数处理一下,就ok了
  669. $output = curl_exec($ch);
  670. $errorCode = curl_errno($ch);
  671. curl_close($ch);
  672. if(0 !== $errorCode) {
  673. return false;
  674. }
  675. return $output;
  676. }
  677. function GoldPrice($data,$cost_rate=0){
  678. $gold = Db::name("gold_price1")->where(["type"=>$data["metal_id"],"is_del"=>0,"status"=>1])->order("addtime desc")
  679. ->find();
  680. // $rate = $data['open_fee']/$data['num'] + $data['weight']* $gold["price"] + $data['cost_fee']/(1-$cost_rate) *
  681. // $data['weight']+$data['packing_fee']+$data["mark_fee"]+$data["cert_fee"]+$data['nake_fee'];
  682. $saleprice = ($data['demo_fee']/$data['num']+$data['delivery_fee']+$data['open_fee']/$data['num']+ $data['weight']*
  683. $gold["price"] + $data['cost_fee'] *$data['weight'] + $data['packing_fee']+ $data["mark_fee"]+ $data["cert_fee"]+$data['nake_fee']) / (1 - $cost_rate);
  684. return $saleprice;
  685. }
  686. function GoodPrice($data,$cost_rate=0){
  687. $rate = ($data['open_fee']/$data['num']+ $data['cost_fee']+$data['packing_fee']+$data["mark_fee"]+$data["cert_fee"]+$data['nake_fee'])/(1-$cost_rate
  688. );
  689. return $rate;
  690. }
  691. function checkRole($roleid,$menu){
  692. $roleinfo = Db::name("role_action")->where([['role_id',"=",$roleid],["status","=",1]])->find();
  693. if($roleinfo['private_data']!=""){
  694. $private = explode(",",$roleinfo['private_data']);
  695. if(in_array($menu,$private)){
  696. return true;
  697. }
  698. }
  699. return false;
  700. }
  701. /**
  702. * 根据地址解析省市区
  703. * @param 详细地址,类似于'北京市顺义区xxx路xxx号'
  704. */
  705. if (!function_exists('get_address')) {
  706. function get_address(string $address = '')
  707. {
  708. preg_match('/(.*?(省|自治区|北京市|天津市|上海市|重庆市|澳门特别行政区|香港特别行政区))/', $address, $matches);
  709. if (count($matches) > 1) {
  710. $province = $matches[count($matches) - 2];
  711. $address = preg_replace('/(.*?(省|自治区|北京市|天津市|上海市|重庆市|澳门特别行政区|香港特别行政区))/', '', $address, 1);
  712. }
  713. preg_match('/(.*?(市|自治州|地区|区划|县))/', $address, $matches);
  714. if (count($matches) > 1) {
  715. $city = $matches[count($matches) - 2];
  716. $address = str_replace($city, '', $address);
  717. }
  718. preg_match('/(.*?(区|县|镇|乡|街道))/', $address, $matches);
  719. if (count($matches) > 1) {
  720. $area = $matches[count($matches) - 2];
  721. $address = str_replace($area, '', $address);
  722. }
  723. return [
  724. 'province' => isset($province) ? $province : '',
  725. 'city' => isset($city) ? $city : '',
  726. 'district' => isset($area) ? $area : '',
  727. "address" => $address
  728. ];
  729. }
  730. }
  731. /**
  732. * 批量生成多个文件excel,生成压缩包
  733. */
  734. if (!function_exists('excelSaveBatch')) {
  735. function excelSaveBatch(array $datas = [])
  736. {
  737. $urls = [];
  738. $dir = root_path() . 'public/storage/report/' . date("YmdHis") . "/";
  739. if (!is_dir($dir)) {
  740. mkdir($dir, 0777, true);
  741. }
  742. foreach ($datas as $item) {
  743. $objPHPExcel = new PHPExcel();
  744. $objPHPExcel->getProperties();
  745. $keyA = 0; // 设置表头
  746. foreach ($item['head'] as $v) {
  747. $colum = PHPExcel_Cell::stringFromColumnIndex($keyA);
  748. $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
  749. $keyA += 1;
  750. }
  751. $column = 2;
  752. $objActSheet = $objPHPExcel->getActiveSheet();
  753. foreach ($item['list'] as $key => $rows) { // 行写入
  754. $span = 0;
  755. foreach ($rows as $keyName => $value) { // 列写入
  756. //判断数据是否有数组,如果有数组,转换成字符串
  757. if (is_array($value)) {
  758. $value = implode("、", $value);
  759. }
  760. $objActSheet->setCellValue(PHPExcel_Cell::stringFromColumnIndex($span) . $column, $value);
  761. $span++;
  762. }
  763. $column++;
  764. }
  765. // var_dump($objActSheet->getActiveCell());
  766. $file = $item['filename'] . ".xls";
  767. //$fileName .= "_" . date("Y_m_d", Request()->instance()->time()) . ".xls";
  768. //$fileName = iconv("utf-8", "gb2312", $fileName); // 重命名表
  769. $objPHPExcel->setActiveSheetIndex(0); // 设置活动单指数到第一个表,所以Excel打开这是第一个表
  770. $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  771. $objWriter->save($dir . $file); // 文件通过浏览器下载
  772. $url = $dir . $file;
  773. if (!file_exists($url)) {
  774. echo "文件生成失败";
  775. } else {
  776. $urls[] = $url;
  777. }
  778. }
  779. $saveDir = root_path() . "public/storage/zip/";
  780. if (!is_dir($saveDir)) {
  781. mkdir($saveDir, 0777, true);
  782. }
  783. $datetime = date("YmdHis");
  784. $file_dir = $saveDir . $datetime . ".zip";
  785. # 5.1 文件打包,提示:使用本类,linux需开启zlib,windows需取消php_zip.dll前的注释
  786. $zip = new \ZipArchive ();
  787. # 5.2 文件不存在则生成一个新的文件 用CREATE打开文件会追加内容至zip
  788. if ($zip->open($file_dir, \ZipArchive::OVERWRITE) !== true && $zip->open($file_dir, \ZipArchive::CREATE) !== true) echo '无法打开文件或者文件创建失败';
  789. # 5.3 批量写入压缩包
  790. // $zip->addEmptyDir($fileName);//往zip压缩包写入空目录
  791. foreach ($urls as $fileName) {
  792. // @$zip->addFile($fileName);
  793. @$zip->addFile($fileName, DIRECTORY_SEPARATOR.basename($fileName));
  794. }
  795. // @$zip->addFile($v['file_path'], 'resume'.DIRECTORY_SEPARATOR.basename($headername));
  796. # 5.4 关闭压缩包写入
  797. $zip->close();
  798. @deldir($dir);//删除已生成的文件及目录
  799. //6. 检查文件是否存在,并输出文件
  800. if (!file_exists($file_dir)) echo '压缩包文件不存在';
  801. ob_clean();
  802. flush();
  803. header("Cache-Control: max-age=0");
  804. header("Content-Description: File Transfer");
  805. header('Content-disposition: attachment; filename=' . basename($file_dir)); # 处理文件名
  806. header("Content-Type: application/octet-stream"); # 流文件输出
  807. header("Content-Transfer-Encoding: binary"); # 告诉浏览器,这是二进制文件
  808. header('Content-Length: ' . filesize($file_dir)); # 告诉浏览器,文件大小
  809. readfile($file_dir);//输出文件
  810. @unlink($file_dir);
  811. exit();
  812. }
  813. }
  814. /**
  815. * 批量生成多个文件excel,生成压缩包,保存到本地,返回文件链接
  816. * datas 生成器
  817. * header array 头部字段
  818. * filename string 文件名
  819. */
  820. if (!function_exists('excelSaveFile')) {
  821. function excelSaveFile($datas, string $filename = '')
  822. {
  823. // $urls = [];
  824. $dir = root_path() . 'public/storage/report/' . date("YmdHis") . "/";
  825. if (!is_dir($dir)) mkdir($dir, 0777, true);
  826. // foreach ($datas as $item) {
  827. PHPExcel_CachedObjectStorageFactory::cache_in_memory_gzip;//单元格缓存为MemoryGZip
  828. $objPHPExcel = new PHPExcel();
  829. $keyA = 0; // 设置表头
  830. $column = 2;
  831. $objActSheet = $objPHPExcel->getActiveSheet();
  832. foreach ($datas as $key => $rows) { // 行写入
  833. //第一行取key作表头
  834. if($key==0){
  835. $objPHPExcel->getProperties();
  836. foreach ($rows as $k=>$v) {
  837. $colum = PHPExcel_Cell::stringFromColumnIndex($keyA);
  838. $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $k);
  839. $keyA += 1;
  840. }
  841. }
  842. //写入列
  843. $span = 0;
  844. foreach ($rows as $keyName => $value) {
  845. //判断数据是否有数组,如果有数组,转换成字符串
  846. if (is_array($value)) $value = implode("、", $value);
  847. $objActSheet->setCellValue(PHPExcel_Cell::stringFromColumnIndex($span) . $column, $value);
  848. $span++;
  849. }
  850. $column++;
  851. }
  852. $file = $filename . ".xls";
  853. $objPHPExcel->setActiveSheetIndex(0); // 设置活动单指数到第一个表,所以Excel打开这是第一个表
  854. $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  855. $objWriter->save($dir . $file); // 文件通过浏览器下载
  856. $url = $dir . $file;
  857. if (!file_exists($url)) throw new Exception('文件生成失败');
  858. $saveDir = root_path() . "public/storage/zip/" . date('Ymd') . '/';
  859. if (!is_dir($saveDir)) mkdir($saveDir, 0777, true);
  860. $file_dir = $saveDir . $filename . ".zip";
  861. # 5.1 文件打包,提示:使用本类,linux需开启zlib,windows需取消php_zip.dll前的注释
  862. $zip = new \ZipArchive ();
  863. # 5.2 文件不存在则生成一个新的文件 用CREATE打开文件会追加内容至zip
  864. if ($zip->open($file_dir, \ZipArchive::OVERWRITE) !== true && $zip->open($file_dir, \ZipArchive::CREATE) !== true) echo '无法打开文件或者文件创建失败';
  865. # 5.3 批量写入压缩包
  866. // $zip->addEmptyDir($fileName);//往zip压缩包写入空目录
  867. // foreach ($urls as $fileName) {
  868. @$zip->addFile($url, DIRECTORY_SEPARATOR . basename($url));
  869. // }
  870. // @$zip->addFile($v['file_path'], 'resume'.DIRECTORY_SEPARATOR.basename($headername));
  871. # 5.4 关闭压缩包写入
  872. $zip->close();
  873. @deldir($dir);//删除已生成的文件及目录
  874. //6. 检查文件是否存在,并输出文件
  875. if (!file_exists($file_dir)) throw new Exception('压缩包文件不存在');
  876. // return $file_dir;
  877. return str_replace(root_path() . "public/", '', $file_dir);
  878. }
  879. }
  880. //通过快递网的api获取物流信息
  881. if (!function_exists('get_logistics_information')) {
  882. function get_logistics_information(string $post_code = '', string $phone = '')
  883. {
  884. if ($post_code == '') throw new Exception('快递单号不能为空');
  885. $signer = new \app\admin\common\HuaweiSigner();
  886. //设置相关参数
  887. $signer->Key = '1b4cfe41d72d4fbdb6778a5e0193c4b5';
  888. $signer->Secret = '0fd04c5d5287424eb0d25f8f620aeb78';
  889. $req = new \app\admin\common\HuaweiRequest('GET', 'http://kuaidi.apistore.huaweicloud.com/kuaidiinfo?nu=' . $post_code . '&phone=' . $phone);
  890. $req->headers = array(
  891. 'content-type' => 'application/json',
  892. 'x-stage' => 'RELEASE',
  893. );
  894. $req->body = '';//如果是post/put请求的话,要往请求体中添加内容
  895. $curl = $signer->Sign($req);
  896. $response = curl_exec($curl);
  897. $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  898. $curl_error = curl_error($curl);
  899. curl_close($curl);
  900. if ($status == 200) return json_decode($response, true);
  901. else throw new Exception('请求失败:' . $curl_error);
  902. }
  903. }
  904. //获取三级架构
  905. if (!function_exists('get_top_customer_org')) {
  906. function get_top_customer_org($var, $data = [])
  907. {
  908. $str = Db::name('customer_org1')
  909. ->field('id,name,pid,level')
  910. ->where(['id' => $var])
  911. ->find();
  912. if ($str == false) {
  913. return [];
  914. }
  915. $vmn = [];
  916. $vmn['id'] = $str['id'];
  917. $vmn['name'] = $str['name'];
  918. $vmn['level'] = $str['level'];
  919. array_unshift($data, $vmn);
  920. // $var['id']=made();
  921. if ($str['pid'] == 0) {
  922. // krsort($data);
  923. return $data;
  924. } else {
  925. return get_top_customer_org($str['pid'], $data);
  926. }
  927. }
  928. }
  929. //根据某个关键字匹配所有子级部门及用户
  930. /**
  931. * $company_name string 部门名称
  932. * $off bool 是否查询离职人员,默认不查询
  933. */
  934. if (!function_exists('get_company_item_user_by_name')) {
  935. function get_company_item_user_by_name(string $company_name = '', bool $off = false)
  936. {
  937. $data = [];
  938. //查询符合条件的部门id
  939. $company_ids = Db::name("company_item")
  940. ->field('id,level')
  941. ->where(['is_del' => 0])
  942. ->whereLike('name', '%' . $company_name . '%')
  943. ->select()
  944. ->toArray();
  945. if (!empty($company_ids)) {
  946. $level_temp = $company_ids[0]['level'] + 1;
  947. $company_ids = array_column($company_ids, 'id');
  948. for ($level = $level_temp; $level > 0; $level++) {
  949. if (!empty($company_ids)) {
  950. //根据部门id找人
  951. $uids = Db::name('depart_user')
  952. ->where(['is_del' => 0])
  953. ->order('uid')
  954. ->whereIn('itemid', $company_ids);
  955. if (!$off) $uids->where('status', 1);
  956. $uids = $uids->column('uid');
  957. $data = array_unique(array_merge($data, $uids));
  958. $company_ids = Db::name("company_item")
  959. ->where(['is_del' => 0, 'level' => $level])
  960. ->whereIn('pid', $company_ids)
  961. ->column('id');
  962. } else break;
  963. }
  964. }
  965. return $data;
  966. }
  967. }
  968. //获取某个用户所属部门名称
  969. //$uid int 用户id
  970. //$cache bool 是否启用缓存,(默认启用,不启用的话直接从数据库查)
  971. //$get_tops bool 是否获取多级部门,例如 万宇恒通/采购部/仓储物流,默认不获取
  972. if (!function_exists('get_company_name_by_uid')) {
  973. function get_company_name_by_uid(int $uid = 0, bool $cache = true, bool $get_tops = false)
  974. {
  975. $rs = '';
  976. $key = 'get_company_name_by_uid_' . $uid.'_'.$get_tops;
  977. if ($cache) $rs = \think\facade\Cache::get($key);
  978. if (empty($rs)) {
  979. $itemid = Db::name('depart_user')->where(['is_del' => 0, 'uid' => $uid])->value('itemid', 0);
  980. if ($get_tops) $rs = implode('/', array_column(GetPart($itemid), 'name'));
  981. else $rs = Db::name('company_item')->where(['is_del' => 0, 'id' => $itemid])->value('name');
  982. \think\facade\Cache::set($key, $rs, 3600);
  983. }
  984. return $rs;
  985. }
  986. }