common.php 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115
  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. @ unlink($file_dir);
  549. exit();
  550. }
  551. function deldir($path){
  552. //如果是目录则继续
  553. if(is_dir($path)){
  554. //扫描一个文件夹内的所有文件夹和文件并返回数组
  555. $p = scandir($path);
  556. //如果 $p 中有两个以上的元素则说明当前 $path 不为空
  557. if(count($p)>2){
  558. foreach($p as $val){
  559. //排除目录中的.和..
  560. if($val !="." && $val !=".."){
  561. //如果是目录则递归子目录,继续操作
  562. if(is_dir($path.$val)){
  563. //子目录中操作删除文件夹和文件
  564. deldir($path.$val.'/');
  565. }else{
  566. //如果是文件直接删除
  567. unlink($path.$val);
  568. }
  569. }
  570. }
  571. }
  572. }
  573. //删除目录
  574. return rmdir($path);
  575. }
  576. /**
  577. * @param string $AddrJson
  578. */
  579. function GetAddr($AddrJson=""){
  580. if($AddrJson==""){
  581. return '';
  582. }
  583. $adr = json_decode($AddrJson,true);
  584. if(!is_array($adr)){
  585. return '';
  586. }
  587. $addr='';
  588. if(isset($adr['provice_code'])&&$adr['provice_code']!=''){
  589. $provice = Db::name("province")->where(["province_code"=>$adr['provice_code']])->find();
  590. $addr.=isset($provice['name']) ? $provice['name']:"";
  591. }
  592. if(isset($adr['city_code'])&&$adr['city_code']!=''){
  593. $city = Db::name("city")->where(["city_code"=>$adr['city_code']])->find();
  594. $addr.=isset($city['name']) ? $city['name']:"";
  595. }
  596. if(isset($adr['area_code'])&&$adr['area_code']!=''){
  597. $area = Db::name("area")->where(["area_code"=>$adr['area_code']])->find();
  598. $addr.=isset($area['name']) ? $area['name']:"";
  599. }
  600. return $addr;
  601. }
  602. /**
  603. * POST 请求
  604. * @param string $url
  605. * @param array $param
  606. * @param boolean $post_file 是否文件上传
  607. * @return string content
  608. */
  609. function post($url,$data,$header=[])
  610. {
  611. //对空格进行转义
  612. $url = str_replace(' ','+',$url);
  613. $ch = curl_init();
  614. //设置选项,包括URL
  615. curl_setopt($ch, CURLOPT_URL, "$url");
  616. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  617. curl_setopt($ch, CURLOPT_HEADER, 0);
  618. curl_setopt($ch,CURLOPT_TIMEOUT,3); //定义超时3秒钟
  619. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  620. // POST数据
  621. // curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  622. curl_setopt($ch, CURLOPT_POST, 1);
  623. // 把post的变量加上
  624. curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //所需传的数组用http_bulid_query()函数处理一下,就ok了
  625. curl_setopt($ch, CURLOPT_HEADER, true);
  626. //执行并获取url地址的内容
  627. $output = curl_exec($ch);
  628. $errorCode = curl_errno($ch);
  629. //释放curl句柄
  630. $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
  631. // 根据头大小去获取头信息内容
  632. $header = substr($output, 0, $headerSize);
  633. curl_close($ch);
  634. if(0 !== $errorCode) {
  635. return false;
  636. }
  637. return $header;
  638. }
  639. function post2($url,$data,$header=[])
  640. {
  641. //对空格进行转义
  642. $url = str_replace(' ','+',$url);
  643. $ch = curl_init();
  644. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  645. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  646. //设置选项,包括URL
  647. curl_setopt($ch, CURLOPT_URL, "$url");
  648. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  649. curl_setopt($ch, CURLOPT_HEADER, 0);
  650. // POST数据
  651. curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  652. curl_setopt($ch, CURLOPT_POST, 1);
  653. // 把post的变量加上
  654. curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //所需传的数组用http_bulid_query()函数处理一下,就ok了
  655. $output = curl_exec($ch);
  656. $errorCode = curl_errno($ch);
  657. curl_close($ch);
  658. if(0 !== $errorCode) {
  659. return false;
  660. }
  661. return $output;
  662. }
  663. function GoldPrice($data,$cost_rate=0){
  664. $gold = Db::name("gold_price1")->where(["type"=>$data["metal_id"],"is_del"=>0,"status"=>1])->order("addtime desc")
  665. ->find();
  666. // $rate = $data['open_fee']/$data['num'] + $data['weight']* $gold["price"] + $data['cost_fee']/(1-$cost_rate) *
  667. // $data['weight']+$data['packing_fee']+$data["mark_fee"]+$data["cert_fee"]+$data['nake_fee'];
  668. $saleprice = ($data['demo_fee']/$data['num']+$data['delivery_fee']+$data['open_fee']/$data['num']+ $data['weight']*
  669. $gold["price"] + $data['cost_fee'] *$data['weight'] + $data['packing_fee']+ $data["mark_fee"]+ $data["cert_fee"]+$data['nake_fee']) / (1 - $cost_rate);
  670. return $saleprice;
  671. }
  672. function GoodPrice($data,$cost_rate=0){
  673. $rate = ($data['open_fee']/$data['num']+ $data['cost_fee']+$data['packing_fee']+$data["mark_fee"]+$data["cert_fee"]+$data['nake_fee'])/(1-$cost_rate
  674. );
  675. return $rate;
  676. }
  677. function checkRole($roleid,$menu){
  678. $roleinfo = Db::name("role_action")->where([['role_id',"=",$roleid],["status","=",1]])->find();
  679. if($roleinfo['private_data']!=""){
  680. $private = explode(",",$roleinfo['private_data']);
  681. if(in_array($menu,$private)){
  682. return true;
  683. }
  684. }
  685. return false;
  686. }
  687. /**
  688. * 根据地址解析省市区
  689. * @param 详细地址,类似于'北京市顺义区xxx路xxx号'
  690. */
  691. if (!function_exists('get_address')) {
  692. function get_address(string $address = '')
  693. {
  694. preg_match('/(.*?(省|自治区|北京市|天津市|上海市|重庆市|澳门特别行政区|香港特别行政区))/', $address, $matches);
  695. if (count($matches) > 1) {
  696. $province = $matches[count($matches) - 2];
  697. $address = preg_replace('/(.*?(省|自治区|北京市|天津市|上海市|重庆市|澳门特别行政区|香港特别行政区))/', '', $address, 1);
  698. }
  699. preg_match('/(.*?(市|自治州|地区|区划|县))/', $address, $matches);
  700. if (count($matches) > 1) {
  701. $city = $matches[count($matches) - 2];
  702. $address = str_replace($city, '', $address);
  703. }
  704. preg_match('/(.*?(区|县|镇|乡|街道))/', $address, $matches);
  705. if (count($matches) > 1) {
  706. $area = $matches[count($matches) - 2];
  707. $address = str_replace($area, '', $address);
  708. }
  709. return [
  710. 'province' => isset($province) ? $province : '',
  711. 'city' => isset($city) ? $city : '',
  712. 'district' => isset($area) ? $area : '',
  713. "address" => $address
  714. ];
  715. }
  716. }
  717. /**
  718. * 批量生成多个文件excel,生成压缩包
  719. */
  720. if (!function_exists('excelSaveBatch')) {
  721. function excelSaveBatch(array $datas = [])
  722. {
  723. $urls = [];
  724. $dir = root_path() . 'public/storage/report/' . date("YmdHis") . "/";
  725. if (!is_dir($dir)) {
  726. mkdir($dir, 0777, true);
  727. }
  728. foreach ($datas as $item) {
  729. $objPHPExcel = new PHPExcel();
  730. $objPHPExcel->getProperties();
  731. $keyA = 0; // 设置表头
  732. foreach ($item['head'] as $v) {
  733. $colum = PHPExcel_Cell::stringFromColumnIndex($keyA);
  734. $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
  735. $keyA += 1;
  736. }
  737. $column = 2;
  738. $objActSheet = $objPHPExcel->getActiveSheet();
  739. foreach ($item['list'] as $key => $rows) { // 行写入
  740. $span = 0;
  741. foreach ($rows as $keyName => $value) { // 列写入
  742. //判断数据是否有数组,如果有数组,转换成字符串
  743. if (is_array($value)) {
  744. $value = implode("、", $value);
  745. }
  746. $objActSheet->setCellValue(PHPExcel_Cell::stringFromColumnIndex($span) . $column, $value);
  747. $span++;
  748. }
  749. $column++;
  750. }
  751. // var_dump($objActSheet->getActiveCell());
  752. $file = $item['filename'] . ".xls";
  753. //$fileName .= "_" . date("Y_m_d", Request()->instance()->time()) . ".xls";
  754. //$fileName = iconv("utf-8", "gb2312", $fileName); // 重命名表
  755. $objPHPExcel->setActiveSheetIndex(0); // 设置活动单指数到第一个表,所以Excel打开这是第一个表
  756. $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  757. $objWriter->save($dir . $file); // 文件通过浏览器下载
  758. $url = $dir . $file;
  759. if (!file_exists($url)) {
  760. echo "文件生成失败";
  761. } else {
  762. $urls[] = $url;
  763. }
  764. }
  765. $saveDir = root_path() . "public/storage/zip/";
  766. if (!is_dir($saveDir)) {
  767. mkdir($saveDir, 0777, true);
  768. }
  769. $datetime = date("YmdHis");
  770. $file_dir = $saveDir . $datetime . ".zip";
  771. # 5.1 文件打包,提示:使用本类,linux需开启zlib,windows需取消php_zip.dll前的注释
  772. $zip = new \ZipArchive ();
  773. # 5.2 文件不存在则生成一个新的文件 用CREATE打开文件会追加内容至zip
  774. if ($zip->open($file_dir, \ZipArchive::OVERWRITE) !== true && $zip->open($file_dir, \ZipArchive::CREATE) !== true) echo '无法打开文件或者文件创建失败';
  775. # 5.3 批量写入压缩包
  776. // $zip->addEmptyDir($fileName);//往zip压缩包写入空目录
  777. foreach ($urls as $fileName) {
  778. // @$zip->addFile($fileName);
  779. @$zip->addFile($fileName, DIRECTORY_SEPARATOR.basename($fileName));
  780. }
  781. // @$zip->addFile($v['file_path'], 'resume'.DIRECTORY_SEPARATOR.basename($headername));
  782. # 5.4 关闭压缩包写入
  783. $zip->close();
  784. @deldir($dir);//删除已生成的文件及目录
  785. //6. 检查文件是否存在,并输出文件
  786. if (!file_exists($file_dir)) echo '压缩包文件不存在';
  787. ob_clean();
  788. flush();
  789. header("Cache-Control: max-age=0");
  790. header("Content-Description: File Transfer");
  791. header('Content-disposition: attachment; filename=' . basename($file_dir)); # 处理文件名
  792. header("Content-Type: application/octet-stream"); # 流文件输出
  793. header("Content-Transfer-Encoding: binary"); # 告诉浏览器,这是二进制文件
  794. header('Content-Length: ' . filesize($file_dir)); # 告诉浏览器,文件大小
  795. readfile($file_dir);//输出文件
  796. @unlink($file_dir);
  797. exit();
  798. }
  799. }
  800. /**
  801. * 批量生成多个文件excel,生成压缩包,保存到本地,返回文件链接
  802. * datas 生成器
  803. * header array 头部字段
  804. * filename string 文件名
  805. */
  806. if (!function_exists('excelSaveFile')) {
  807. function excelSaveFile($datas, string $filename = '')
  808. {
  809. // $urls = [];
  810. $dir = root_path() . 'public/storage/report/' . date("YmdHis") . "/";
  811. if (!is_dir($dir)) mkdir($dir, 0777, true);
  812. // foreach ($datas as $item) {
  813. PHPExcel_CachedObjectStorageFactory::cache_in_memory_gzip;//单元格缓存为MemoryGZip
  814. $objPHPExcel = new PHPExcel();
  815. $keyA = 0; // 设置表头
  816. $column = 2;
  817. $objActSheet = $objPHPExcel->getActiveSheet();
  818. foreach ($datas as $key => $rows) { // 行写入
  819. //第一行取key作表头
  820. if($key==0){
  821. $objPHPExcel->getProperties();
  822. foreach ($rows as $k=>$v) {
  823. $colum = PHPExcel_Cell::stringFromColumnIndex($keyA);
  824. $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $k);
  825. $keyA += 1;
  826. }
  827. }
  828. //写入列
  829. $span = 0;
  830. foreach ($rows as $keyName => $value) {
  831. //判断数据是否有数组,如果有数组,转换成字符串
  832. if (is_array($value)) $value = implode("、", $value);
  833. $objActSheet->setCellValue(PHPExcel_Cell::stringFromColumnIndex($span) . $column, $value);
  834. $span++;
  835. }
  836. $column++;
  837. }
  838. $file = $filename . ".xls";
  839. $objPHPExcel->setActiveSheetIndex(0); // 设置活动单指数到第一个表,所以Excel打开这是第一个表
  840. $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  841. $objWriter->save($dir . $file); // 文件通过浏览器下载
  842. $url = $dir . $file;
  843. if (!file_exists($url)) throw new Exception('文件生成失败');
  844. $saveDir = root_path() . "public/storage/zip/" . date('Ymd') . '/';
  845. if (!is_dir($saveDir)) mkdir($saveDir, 0777, true);
  846. $file_dir = $saveDir . $filename . ".zip";
  847. # 5.1 文件打包,提示:使用本类,linux需开启zlib,windows需取消php_zip.dll前的注释
  848. $zip = new \ZipArchive ();
  849. # 5.2 文件不存在则生成一个新的文件 用CREATE打开文件会追加内容至zip
  850. if ($zip->open($file_dir, \ZipArchive::OVERWRITE) !== true && $zip->open($file_dir, \ZipArchive::CREATE) !== true) echo '无法打开文件或者文件创建失败';
  851. # 5.3 批量写入压缩包
  852. // $zip->addEmptyDir($fileName);//往zip压缩包写入空目录
  853. // foreach ($urls as $fileName) {
  854. @$zip->addFile($url, DIRECTORY_SEPARATOR . basename($url));
  855. // }
  856. // @$zip->addFile($v['file_path'], 'resume'.DIRECTORY_SEPARATOR.basename($headername));
  857. # 5.4 关闭压缩包写入
  858. $zip->close();
  859. @deldir($dir);//删除已生成的文件及目录
  860. //6. 检查文件是否存在,并输出文件
  861. if (!file_exists($file_dir)) throw new Exception('压缩包文件不存在');
  862. // return $file_dir;
  863. return str_replace(root_path() . "public/", '', $file_dir);
  864. }
  865. }
  866. //通过快递网的api获取物流信息
  867. if (!function_exists('get_logistics_information')) {
  868. function get_logistics_information(string $post_code = '', string $phone = '')
  869. {
  870. if ($post_code == '') throw new Exception('快递单号不能为空');
  871. $signer = new \app\admin\common\HuaweiSigner();
  872. //设置相关参数
  873. $signer->Key = '1b4cfe41d72d4fbdb6778a5e0193c4b5';
  874. $signer->Secret = '0fd04c5d5287424eb0d25f8f620aeb78';
  875. $req = new \app\admin\common\HuaweiRequest('GET', 'http://kuaidi.apistore.huaweicloud.com/kuaidiinfo?nu=' . $post_code . '&phone=' . $phone);
  876. $req->headers = array(
  877. 'content-type' => 'application/json',
  878. 'x-stage' => 'RELEASE',
  879. );
  880. $req->body = '';//如果是post/put请求的话,要往请求体中添加内容
  881. $curl = $signer->Sign($req);
  882. $response = curl_exec($curl);
  883. $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  884. $curl_error = curl_error($curl);
  885. curl_close($curl);
  886. if ($status == 200) return json_decode($response, true);
  887. else throw new Exception('请求失败:' . $curl_error);
  888. }
  889. }
  890. //获取三级架构
  891. if (!function_exists('get_top_customer_org')) {
  892. function get_top_customer_org($var, $data = [])
  893. {
  894. $str = Db::name('customer_org1')
  895. ->field('id,name,pid,level')
  896. ->where(['id' => $var])
  897. ->find();
  898. if ($str == false) {
  899. return [];
  900. }
  901. $vmn = [];
  902. $vmn['id'] = $str['id'];
  903. $vmn['name'] = $str['name'];
  904. $vmn['level'] = $str['level'];
  905. array_unshift($data, $vmn);
  906. // $var['id']=made();
  907. if ($str['pid'] == 0) {
  908. // krsort($data);
  909. return $data;
  910. } else {
  911. return get_top_customer_org($str['pid'], $data);
  912. }
  913. }
  914. }
  915. //根据某个关键字匹配所有子级部门及用户
  916. /**
  917. * $company_name string 部门名称
  918. * $off bool 是否查询离职人员,默认不查询
  919. */
  920. if (!function_exists('get_company_item_user_by_name')) {
  921. function get_company_item_user_by_name(string $company_name = '', bool $off = false)
  922. {
  923. $data = [];
  924. //查询符合条件的部门id
  925. $company_ids = Db::name("company_item")
  926. ->field('id,level')
  927. ->where(['is_del' => 0])
  928. ->whereLike('name', '%' . $company_name . '%')
  929. ->select()
  930. ->toArray();
  931. if (!empty($company_ids)) {
  932. $level_temp = $company_ids[0]['level'] + 1;
  933. $company_ids = array_column($company_ids, 'id');
  934. for ($level = $level_temp; $level > 0; $level++) {
  935. if (!empty($company_ids)) {
  936. //根据部门id找人
  937. $uids = Db::name('depart_user')
  938. ->where(['is_del' => 0])
  939. ->order('uid')
  940. ->whereIn('itemid', $company_ids);
  941. if (!$off) $uids->where('status', 1);
  942. $uids = $uids->column('uid');
  943. $data = array_unique(array_merge($data, $uids));
  944. $company_ids = Db::name("company_item")
  945. ->where(['is_del' => 0, 'level' => $level])
  946. ->whereIn('pid', $company_ids)
  947. ->column('id');
  948. } else break;
  949. }
  950. }
  951. return $data;
  952. }
  953. }
  954. //获取某个用户所属部门名称
  955. //$uid int 用户id
  956. //$cache bool 是否启用缓存,(默认启用,不启用的话直接从数据库查)
  957. //$get_tops bool 是否获取多级部门,例如 万宇恒通/采购部/仓储物流,默认不获取
  958. if (!function_exists('get_company_name_by_uid')) {
  959. function get_company_name_by_uid(int $uid = 0, bool $cache = true, bool $get_tops = false)
  960. {
  961. $rs = '';
  962. $key = 'get_company_name_by_uid_' . $uid.'_'.$get_tops;
  963. if ($cache) $rs = \think\facade\Cache::get($key);
  964. if (empty($rs)) {
  965. $itemid = Db::name('depart_user')->where(['is_del' => 0, 'uid' => $uid])->value('itemid', 0);
  966. if ($get_tops) $rs = implode('/', array_column(GetPart($itemid), 'name'));
  967. else $rs = Db::name('company_item')->where(['is_del' => 0, 'id' => $itemid])->value('name');
  968. \think\facade\Cache::set($key, $rs, 3600);
  969. }
  970. return $rs;
  971. }
  972. }