12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289 |
- <?php
- // 应用公共文件
- use think\facade\Config;
- use think\facade\Db;
- use think\facade\Filesystem;
- use think\helper\Str;
- // 应用公共文件
- function app_show($code=0,$message="",$data=[]){
- $result = ['code'=>$code,"message"=>$message,"data"=>$data];
- echo json_encode($result,JSON_UNESCAPED_UNICODE);
- die();
- }
- // 应用公共文件
- function error_show($code=0,$message=""){
- $result = ['code'=>$code,"message"=>$message];
- echo json_encode($result,JSON_UNESCAPED_UNICODE);
- die();
- }
- function GetUserInfo($token){
- $host = Config::get("app");
- $url = $host["api_host"]."/Api/userinfo";
- $data=[
- "token"=>$token
- ];
- $response=curl_request($url,$data);
- return json_decode($response,true);
- }
- //参数1:访问的URL,参数2:post数据(不填则为GET),参数3:提交的$cookies,参数4:是否返回$cookies
- function curl_request($url,$post=''){
- $curl = curl_init();
- curl_setopt($curl, CURLOPT_URL, $url);
- curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)');
- curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
- curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
- curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
- if($post) {
- curl_setopt($curl, CURLOPT_POST, 1);
- curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));
- }
- curl_setopt($curl, CURLOPT_TIMEOUT, 10);
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
- $data = curl_exec($curl);
- if (curl_errno($curl)) {
- return curl_error($curl);
- }
- curl_close($curl);
- return $data;
- }
- /**手机号验证
- * @param $mobile
- * @return bool
- */
- function checkMobile($mobile){
- if (!is_numeric($mobile)) {
- return false;
- }
- return preg_match('#^1[3,4,5,6,7,8,9]{1}[\d]{9}$#', $mobile) ? true : false;
- }
- function checkTel($tel){
- if (!$tel) {
- return false;
- }
- return preg_match('/^(0[0-9]{2,3}\-)([0-9]{7,8})+(\-[0-9]{1,4})?$/', $tel) ? true : false;
- }
- /**邮箱验证
- * @param $email
- * @return bool
- */
- function checkEmail($email){
- if (!$email) {
- return false;
- }
- return preg_match('#[a-z0-9&\-_.]+@[\w\-_]+([\w\-.]+)?\.[\w\-]+#is', $email) ? true : false;
- }
- /**
- * @param
- * @return int
- */
- function makeSalt(){
- $salt = rand(10000000,99999999);
- return $salt;
- }
- /**
- * @param $token
- * @return array
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\DbException
- * @throws \think\db\exception\ModelNotFoundException
- * @throws \think\exception\DbException
- */
- function VerifyTokens($token){
- $host = Config::get("app");
- $url = $host["api_host"]."/Api/verify_token";
- $data=[
- "token"=>$token
- ];
- $response=curl_request($url,$data);
- return json_decode($response,true);
- }
- /**
- * @param $token
- * @param $condition
- * @return mixed
- */
- function GetUserlist($token,$condition){
- $host = Config::get("app");
- $url = $host["api_host"]."/Api/getuserlist";
- $condition['token']=$token;
- $response=curl_request($url,$condition);
- return json_decode($response,true);
- }
- /**
- * @param $token
- * @param $condition
- * @return mixed
- */
- function GetAccountall($token, $condition){
- $host = Config::get("app");
- $url = $host["api_host"]."/Api/userall";
- $condition['token']=$token;
- $response=curl_request($url,$condition);
- return json_decode($response,true);
- }
- function GetList($token,$condition){
- $host = Config::get("app");
- $url = $host["api_host"]."/Api/userlist";
- $condition['token']=$token;
- $response=curl_request($url,$condition);
- return json_decode($response,true);
- }
- /**
- * @param $token
- * @param $condition ['id'=>1]
- * @return mixed
- */
- function GetInfoById($token,$condition){
- $host = Config::get("app");
- $url = $host["api_host"]."/Api/userinfobyid";
- $condition['token']=$token;
- $response=curl_request($url,$condition);
- return json_decode($response,true);
- }
- function GetInfoNoToken($condition){
- $host = Config::get("app");
- $url = $host["api_host"]."/Api/uinfo";
- $response=curl_request($url,$condition);
- return json_decode($response,true);
- }
- function makeNo($str){
- $date=date("mdHis");
- $year = date("Y")-2000;
- $msec=rand(1000,9999);
- return $str.$year.$date.$msec;
- }
- function randomkeys($length) {
- $returnStr='';
- $pattern = '1234567890abcdefghijklmnopqrstuvwxyz';//ABCDEFGHIJKLOMNOPQRSTUVWXYZ
- for($i = 0; $i < $length; $i ++) {
- $returnStr .= $pattern[mt_rand ( 0, strlen($pattern)-1 )]; //生成php随机数
- }
- return $returnStr;
- }
- function tree(){
- }
- /**
- * @param $files
- * @return array
- */
- function UploadImg($files)
- {
- $savename = [];
- $files = !is_array($files) ? [$files] : $files;
- try {
- //验证
- validate(['imgFile' => ['fileSize' => 10240000, 'fileExt' => 'jpg,jpeg,png,bmp,gif', 'fileMime' => 'image/jpeg,image/png,image/gif']])->check(['imgFile' => $files]);
- foreach ($files as $file) {
- $url = Filesystem::disk('public')->putFile('topic/' . date("Ymd"), $file, function () use ($file) {
- return str_replace('.' . $file->getOriginalExtension(), '', $file->getOriginalName() . "_" . date('YmdHis'));
- });
- $name = str_replace('.' . $file->getOriginalExtension(), '', $file->getOriginalName());
- $temp = ["url" => $url, "name" => $name];
- $savename[] = $temp;
- }
- return $savename;
- } catch (\think\exception\ValidateException $e) {
- return $e->getMessage();
- }
- }
- /**
- * @param $files
- * @return array
- */
- function UploadFile($files)
- {
- $savename = [];
- $files = !is_array($files) ? [$files] : $files;
- try {
- //验证
- validate(['imgFile' => ['fileSize' => 10240000,'fileExt' => 'xlsx,xls,pdf,zip,rar,7z,doc,docx']])->check(['imgFile' =>
- $files]);
- foreach ($files as $file) {
- $url = Filesystem::disk('public')->putFile('files/' . date("Ymd"), $file, function () use ($file) {
- return str_replace('.' . $file->getOriginalExtension(), '', $file->getOriginalName() . "_" . date('YmdHis'));
- });
- $name = str_replace('.' . $file->getOriginalExtension(), '', $file->getOriginalName());
- $temp = ["url" => $url, "name" => $name];
- $savename[] = $temp;
- }
- return $savename;
- } catch (\think\exception\ValidateException $e) {
- return $e->getMessage();
- }
- }
- /**
- * @param $files
- * @return array
- */
- function UploadVideo($files)
- {
- $savename = [];
- $files = !is_array($files) ? [$files] : $files;
- try {
- //验证
- validate(['videoFile' => ['fileSize' => 10240000,'fileExt' => 'mp4,mp3,avi']])->check(['videoFile' => $files]);
- foreach ($files as $file) {
- $url = Filesystem::disk('public')->putFile('video/' . date("Ymd"), $file, function () use ($file) {
- return str_replace('.' . $file->getOriginalExtension(), '', $file->getOriginalName() . "_" . date('YmdHis'));
- });
- $name = str_replace('.' . $file->getOriginalExtension(), '', $file->getOriginalName());
- $temp = ["url" => $url, "name" => $name];
- $savename[] = $temp;
- }
- return $savename;
- } catch (\think\exception\ValidateException $e) {
- return $e->getMessage();
- }
- }
- /**
- * @param $token
- * @param $condition
- * @return mixed
- */
- function resetpwd($token,$condition){
- $host = Config::get("app");
- $url = $host["api_host"]."/Api/passset";
- $condition['token']=$token;
- $response=curl_request($url,$condition);
- return json_decode($response,true);
- }
- function resetpasswd($token,$condition){
- $host = Config::get("app");
- $url = $host["api_host"]."/Api/passsave";
- $condition['token']=$token;
- $response=curl_request($url,$condition);
- return json_decode($response,true);
- }
- /**
- * @param $token
- * @param $condition
- * @return mixed
- */
- function resetinfo($token,$condition){
- $host = Config::get("app");
- $url = $host["api_host"]."/Api/usersave";
- $condition['token']=$token;
- $response=curl_request($url,$condition);
- return json_decode($response,true);
- }
- /**
- * @param $token
- * @param $condition
- * @return mixed
- */
- function resetstatus($token,$condition){
- $host = Config::get("app");
- $url = $host["api_host"]."/Api/userstatus";
- $condition['token']=$token;
- $response=curl_request($url,$condition);
- return json_decode($response,true);
- }
- /**
- * @param $data
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\DbException
- * @throws \think\db\exception\ModelNotFoundException
- */
- function crea($data,$vio=0)
- {
- $db = Db::name("company_item")->where(['pid'=>$data['id'],'is_del'=>0])->select()->toArray();
- if($vio==1){
- $d = Db::name("depart_user")->where(['itemid'=>$data['id'],'is_del'=>0])->select()->toArray();
- if(empty($d)){
- $data['item']=[];
- }else{
- $data['item']=$d;
- }
- }
- if(empty($db)){
- $data['child']=[];
- return $data;
- }
- //var_dump($db);
- foreach ($db as $p){
- $data['child'][]=crea($p,$vio);
- }
- return $data;
- }
- function GetPart($id,$data=[]){
- $db = Db::name("company_item")->where(['id'=>$id,'is_del'=>0])->find();
- if($db==false){
- return [];
- }
- $tem=[];
- $tem['id']=$db['id'];
- $tem['name']=$db['name'];
- array_unshift($data,$tem);
- if($db['pid']==0){
- // krsort($data);
- return $data;
- }else{
- return GetPart($db['pid'],$data);
- }
- }
- function stro($data){
- $db=Db::name('cat')->where(['pid'=>$data['id']])->select()->toArray();
- if(empty($db)){
- $data['child']=[];
- return $data;
- }
- foreach ($db as $item) {
- $data['child'][]=stro($item);
- }
- return $data;
- }
- function coco($data){
- $db=Db::name('exclusive')->where(['pid'=>$data['id']])->select()->toArray();
- if(empty($db)){
- $data['child']=[];
- return $data;
- }
- foreach ($db as $item) {
- $data['child'][]=coco($item);
- }
- return $data;
- }
- function mai($var,$data=[]){
- $str = Db::name('exclusive')->where(['id'=>$var])->find();
- if($str==false){
- return [];
- }
- $vmn =[];
- $vmn['id'] =$str['id'];
- $vmn['rname'] =$str['name'];
- array_unshift($data,$vmn);
- // $var['id']=made();
- if($str['pid']==0){
- // krsort($data);
- return $data;
- }else{
- return mai($str['pid'],$data);
- }
- }
- function made($var,$data=[]){
- $str = Db::name('cat')->where(['id'=>$var])->find();
- if($str==false){
- return [];
- }
- $vmn =[];
- $vmn['id'] =$str['id'];
- $vmn['name'] =$str['cat_name'];
- array_unshift($data,$vmn);
- // $var['id']=made();
- if($str['pid']==0){
- // krsort($data);
- return $data;
- }else{
- return made($str['pid'],$data);
- }
- }
- //获取有赞分类信息
- function made_youzan(int $yz_cat_id=0,$data=[]){
- $rs = get_yz_cat_info($yz_cat_id);
- if(empty($rs)) return [];
- $vmn =[];
- $vmn['yz_cat_id'] =$rs['id'];
- $vmn['yz_cat_name'] =$rs['yz_cat_name'];
- array_unshift($data,$vmn);
- if($rs['parent_cid']==0) return $data;
- else return made_youzan($rs['parent_cid'],$data);
- }
- //跨数据库获取有赞分类信息
- if(!function_exists('get_yz_cat_info')){
- function get_yz_cat_info(int $yz_cat_id=0){
- $key = 'yz_cat_item_'.(string)$yz_cat_id;
- $rs = \think\facade\Cache::get($key);
- if(!$rs){
- $rs = Db::connect('mysql_yz')
- ->table('yz_cat')
- ->field('id,yz_cat_name,parent_cid')
- ->where(['id'=>$yz_cat_id,'status'=>1])
- ->findOrEmpty();
- if($rs) \think\facade\Cache::set($key,$rs,36000);
- }
- return $rs;
- }
- }
- function catChild($var,&$data=[]){
- $str = Db::name('cat')->where(['id'=>$var])->find();
- if($str==false){
- return;
- }
- $data[]=$var;
- $lsit = Db::name("cat")->where(["pid"=>$var,"status"=>1,"is_del"=>0])->column("id");
- if(!empty($lsit)){
- foreach ($lsit as $value){
- catChild($value,$data);
- }
- }
- return $data;
- }
- function makeExcluse($var,$data=[]){
- $str = Db::name('exclusive')->where(['id'=>$var])->find();
- if($str==false){
- return [];
- }
- $vmn =[];
- $vmn['id'] =$str['id'];
- $vmn['name'] =$str['name'];
- array_unshift($data,$vmn);
- // $var['id']=made();
- if($str['pid']==0){
- // krsort($data);
- return $data;
- }else{
- return makeExcluse($str['pid'],$data);
- }
- }
- function sear($id){
- $item = Db::name('cat')->where(['id'=>$id])->field("search")->find();
- if($item==false){
- return false;
- }else{
- $temp = Db::name('cat')->where(['pid'=>$id,'is_del'=>0])->select();
- if ($temp==false){
- return false;
- }
- }
- foreach ($temp as $value){
- $value['search']=$item['search']."_".$value['cat_name'];
- $list = Db::name('cat')->save($value);
- sear($value['id']);
- }
- }
- function manger($list=[],$level=1){
- $var = Db::name('cat')->where(['pid'=>$list,'level'=>$level+1])->column("id");
- if(empty($var)){
- return $list;
- }
- $a=array_merge($list,$var);
- return manger($a,$level+1);
- }
- /**
- * @param $files
- * @param string $extend
- * @return array
- * @throws PHPExcel_Exception
- * @throws PHPExcel_Reader_Exception
- */
- function upload_excel($files,$extend="xls")
- {
- // 获取表单上传文件
- try {
- validate([
- 'file' => [
- // 限制文件大小(单位b),这里限制为4M
- //fileSize' => 4 * 1024 * 1024,
- 'fileExt' => 'xlsx,xls'
- ]
- ],
- [
- //'file.fileSize' => '文件太大',
- 'file.fileExt' => '不支持的文件',
- ]
- )->check(['file' => $files]);
- // $name = $files->getOriginalExtension();
- if ($extend == 'xlsx') {
- $objReader = PHPExcel_IOFactory::createReader('Excel2007');
- } else {
- $objReader = PHPExcel_IOFactory::createReader('Excel5');
- }
- $savename = Filesystem::disk('public')->putFile('topic/excel', $files);
- $import_path = root_path() . 'public/storage/' . $savename;
- $spreadsheet = $objReader->load($import_path);
- $sheet = $spreadsheet->getActiveSheet();
- $sheetData = $sheet->toArray();
- if (empty($sheetData) || !is_array($sheetData)) {
- return ['code' => 1003, "msg" => '数据不能为空'];
- }
- $list = [];
- foreach ($sheetData as $key => $value) {
- $list[] = $value;
- }
- return ['code' => 0, "msg" => '数据解析成功', 'data' => $list];
- } catch (think\exception\ValidateException $e) {
- // echo $e->getMessage();
- return ['code' => 1003, "msg" => $e->getMessage()];
- }
- }
- /**
- * @param string $fileName
- * @param array $headArr
- * @param array $data
- */
- function excelSave($fileName = '', $headArr = [], $data = [])
- {
- $objPHPExcel = new PHPExcel();
- $objPHPExcel->getProperties();
- $keyA = 0; // 设置表头
- foreach ($headArr as $v) {
- $colum = PHPExcel_Cell::stringFromColumnIndex($keyA);
- $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
- $keyA += 1;
- }
- $column = 2;
- $objActSheet = $objPHPExcel->getActiveSheet();
- foreach ($data as $key => $rows) { // 行写入
- $span = 0;
- foreach ($rows as $keyName => $value) { // 列写入
- //判断数据是否有数组,如果有数组,转换成字符串
- if(is_array($value)){
- $value = implode("、", $value);
- }
- $objActSheet->setCellValue(PHPExcel_Cell::stringFromColumnIndex($span) . $column, $value);
- $span++;
- }
- $column++;
- }
- // var_dump($objActSheet->getActiveCell());
- $file = $fileName. ".xls";
- //$fileName .= "_" . date("Y_m_d", Request()->instance()->time()) . ".xls";
- //$fileName = iconv("utf-8", "gb2312", $fileName); // 重命名表
- $dir =root_path() . 'public/storage/report/'.date("YmdHis")."/";
- if(!is_dir($dir)){
- mkdir($dir,0777,true);
- }
- PHPExcel_Settings::setCacheStorageMethod(PHPExcel_CachedObjectStorageFactory::cache_in_memory_serialized);
- $objPHPExcel->setActiveSheetIndex(0); // 设置活动单指数到第一个表,所以Excel打开这是第一个表
- $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
- $objWriter->save($dir . $file); // 文件通过浏览器下载
- $url = $dir . $file;
- if(!file_exists($url)){
- echo "文件生成失败";
- }
- $saveDir = root_path()."public/storage/zip/";
- if(!is_dir( $saveDir)){
- mkdir($saveDir,0777,true);
- }
- $datetime = date("Y-m-d H:i:s");
- $file_dir = $saveDir.$datetime.".zip";
- # 5.1 文件打包,提示:使用本类,linux需开启zlib,windows需取消php_zip.dll前的注释
- $zip = new \ZipArchive ();
- # 5.2 文件不存在则生成一个新的文件 用CREATE打开文件会追加内容至zip
- if ($zip->open($file_dir, \ZipArchive::OVERWRITE) !== true && $zip->open($file_dir, \ZipArchive::CREATE) !==
- true) echo '无法打开文件或者文件创建失败';
- # 5.3 批量写入压缩包
- $zip->addEmptyDir($fileName);
- // @$zip->addFile($v['file_path'], 'resume'.DIRECTORY_SEPARATOR.basename($headername));
- @$zip->addFile($url,$fileName.DIRECTORY_SEPARATOR.basename($url));
- # 5.4 关闭压缩包写入
- $zip->close();
- @deldir($dir);
- # 6. 检查文件是否存在,并输出文件
- if (! file_exists ( $file_dir )) echo '简历文件不存在';
- ob_clean();
- flush();
- header("Cache-Control: max-age=0");
- header("Content-Description: File Transfer");
- header('Content-disposition: attachment; filename=' . basename($file_dir)); # 处理文件名
- header("Content-Type: application/octet-stream"); # 流文件输出
- header("Content-Transfer-Encoding: binary"); # 告诉浏览器,这是二进制文件
- // header('Content-Length: ' . filesize($file_dir)); # 告诉浏览器,文件大小
- // readfile($file_dir); # 输出文件
- $res = read_big_file($file_dir);
- foreach ($res as $val) {
- echo $val;
- }
- @ unlink($file_dir);
- exit();
- }
- //读取大文件
- if (!function_exists('read_big_file')){
- function read_big_file(string $file=''){
- $handle = fopen($file, 'rb');
- while (feof($handle) === false) {
- yield fgets($handle);
- }
- fclose($handle);
- }
- }
- function deldir($path){
- //如果是目录则继续
- if(is_dir($path)){
- //扫描一个文件夹内的所有文件夹和文件并返回数组
- $p = scandir($path);
- //如果 $p 中有两个以上的元素则说明当前 $path 不为空
- if(count($p)>2){
- foreach($p as $val){
- //排除目录中的.和..
- if($val !="." && $val !=".."){
- //如果是目录则递归子目录,继续操作
- if(is_dir($path.$val)){
- //子目录中操作删除文件夹和文件
- deldir($path.$val.'/');
- }else{
- //如果是文件直接删除
- unlink($path.$val);
- }
- }
- }
- }
- }
- //删除目录
- return rmdir($path);
- }
- /**
- * @param string $AddrJson
- */
- function GetAddr($AddrJson=""){
- if($AddrJson==""){
- return '';
- }
- $adr = json_decode($AddrJson,true);
- if(!is_array($adr)){
- return '';
- }
- $addr='';
- if(isset($adr['provice_code'])&&$adr['provice_code']!=''){
- $provice = Db::name("province")->where(["province_code"=>$adr['provice_code']])->find();
- $addr.=isset($provice['name']) ? $provice['name']:"";
- }
- if(isset($adr['city_code'])&&$adr['city_code']!=''){
- $city = Db::name("city")->where(["city_code"=>$adr['city_code']])->find();
- $addr.=isset($city['name']) ? $city['name']:"";
- }
- if(isset($adr['area_code'])&&$adr['area_code']!=''){
- $area = Db::name("area")->where(["area_code"=>$adr['area_code']])->find();
- $addr.=isset($area['name']) ? $area['name']:"";
- }
- return $addr;
- }
- /**
- * POST 请求
- * @param string $url
- * @param array $param
- * @param boolean $post_file 是否文件上传
- * @return string content
- */
- function post($url,$data,$header=[])
- {
- //对空格进行转义
- $url = str_replace(' ','+',$url);
- $ch = curl_init();
- //设置选项,包括URL
- curl_setopt($ch, CURLOPT_URL, "$url");
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_HEADER, 0);
- curl_setopt($ch,CURLOPT_TIMEOUT,3); //定义超时3秒钟
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- // POST数据
- // curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
- curl_setopt($ch, CURLOPT_POST, 1);
- // 把post的变量加上
- curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //所需传的数组用http_bulid_query()函数处理一下,就ok了
- curl_setopt($ch, CURLOPT_HEADER, true);
- //执行并获取url地址的内容
- $output = curl_exec($ch);
- $errorCode = curl_errno($ch);
- //释放curl句柄
- $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
- // 根据头大小去获取头信息内容
- $header = substr($output, 0, $headerSize);
- curl_close($ch);
- if(0 !== $errorCode) {
- return false;
- }
- return $header;
- }
- function post2($url,$data,$header=[])
- {
- //对空格进行转义
- $url = str_replace(' ','+',$url);
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
- //设置选项,包括URL
- curl_setopt($ch, CURLOPT_URL, "$url");
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_HEADER, 0);
- // POST数据
- curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
- curl_setopt($ch, CURLOPT_POST, 1);
- // 把post的变量加上
- curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //所需传的数组用http_bulid_query()函数处理一下,就ok了
- $output = curl_exec($ch);
- $errorCode = curl_errno($ch);
- curl_close($ch);
- if(0 !== $errorCode) {
- return false;
- }
- return $output;
- }
- function GoldPrice($data,$cost_rate=0){
- $gold = Db::name("gold_price1")->where(["type"=>$data["metal_id"],"is_del"=>0,"status"=>1])->order("addtime desc")
- ->find();
- // $rate = $data['open_fee']/$data['num'] + $data['weight']* $gold["price"] + $data['cost_fee']/(1-$cost_rate) *
- // $data['weight']+$data['packing_fee']+$data["mark_fee"]+$data["cert_fee"]+$data['nake_fee'];
- $saleprice = ($data['demo_fee']/$data['num']+$data['delivery_fee']+$data['open_fee']/$data['num']+ $data['weight']*
- $gold["price"] + $data['cost_fee'] *$data['weight'] + $data['packing_fee']+ $data["mark_fee"]+ $data["cert_fee"]+$data['nake_fee']) / (1 - $cost_rate);
- return $saleprice;
- }
- function GoodPrice($data,$cost_rate=0){
- $rate = ($data['open_fee']/$data['num']+ $data['cost_fee']+$data['packing_fee']+$data["mark_fee"]+$data["cert_fee"]+$data['nake_fee'])/(1-$cost_rate
- );
- return $rate;
- }
- function checkRole($roleid,$menu){
- $roleinfo = Db::name("role_action")->where([['role_id',"=",$roleid],["status","=",1]])->find();
- if($roleinfo['private_data']!=""){
- $private = explode(",",$roleinfo['private_data']);
- if(in_array($menu,$private)){
- return true;
- }
- }
- return false;
- }
- /**
- * 根据地址解析省市区
- * @param 详细地址,类似于'北京市顺义区xxx路xxx号'
- */
- if (!function_exists('get_address')) {
- function get_address(string $address = '')
- {
- preg_match('/(.*?(省|自治区|北京市|天津市|上海市|重庆市|澳门特别行政区|香港特别行政区))/', $address, $matches);
- if (count($matches) > 1) {
- $province = $matches[count($matches) - 2];
- $address = preg_replace('/(.*?(省|自治区|北京市|天津市|上海市|重庆市|澳门特别行政区|香港特别行政区))/', '', $address, 1);
- }
- preg_match('/(.*?(市|自治州|地区|区划|县))/', $address, $matches);
- if (count($matches) > 1) {
- $city = $matches[count($matches) - 2];
- $address = str_replace($city, '', $address);
- }
- preg_match('/(.*?(区|县|镇|乡|街道))/', $address, $matches);
- if (count($matches) > 1) {
- $area = $matches[count($matches) - 2];
- $address = str_replace($area, '', $address);
- }
- return [
- 'province' => isset($province) ? $province : '',
- 'city' => isset($city) ? $city : '',
- 'district' => isset($area) ? $area : '',
- "address" => $address
- ];
- }
- }
- /**
- * 批量生成多个文件excel,生成压缩包
- */
- if (!function_exists('excelSaveBatch')) {
- function excelSaveBatch(array $datas = [])
- {
- $urls = [];
- $dir = root_path() . 'public/storage/report/' . date("YmdHis") . "/";
- if (!is_dir($dir)) {
- mkdir($dir, 0777, true);
- }
- foreach ($datas as $item) {
- $objPHPExcel = new PHPExcel();
- $objPHPExcel->getProperties();
- $keyA = 0; // 设置表头
- foreach ($item['head'] as $v) {
- $colum = PHPExcel_Cell::stringFromColumnIndex($keyA);
- $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
- $keyA += 1;
- }
- $column = 2;
- $objActSheet = $objPHPExcel->getActiveSheet();
- foreach ($item['list'] as $key => $rows) { // 行写入
- $span = 0;
- foreach ($rows as $keyName => $value) { // 列写入
- //判断数据是否有数组,如果有数组,转换成字符串
- if (is_array($value)) {
- $value = implode("、", $value);
- }
- $objActSheet->setCellValue(PHPExcel_Cell::stringFromColumnIndex($span) . $column, $value);
- $span++;
- }
- $column++;
- }
- // var_dump($objActSheet->getActiveCell());
- $file = $item['filename'] . ".xls";
- //$fileName .= "_" . date("Y_m_d", Request()->instance()->time()) . ".xls";
- //$fileName = iconv("utf-8", "gb2312", $fileName); // 重命名表
- $objPHPExcel->setActiveSheetIndex(0); // 设置活动单指数到第一个表,所以Excel打开这是第一个表
- $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
- $objWriter->save($dir . $file); // 文件通过浏览器下载
- $url = $dir . $file;
- if (!file_exists($url)) {
- echo "文件生成失败";
- } else {
- $urls[] = $url;
- }
- }
- $saveDir = root_path() . "public/storage/zip/";
- if (!is_dir($saveDir)) {
- mkdir($saveDir, 0777, true);
- }
- $datetime = date("YmdHis");
- $file_dir = $saveDir . $datetime . ".zip";
- # 5.1 文件打包,提示:使用本类,linux需开启zlib,windows需取消php_zip.dll前的注释
- $zip = new \ZipArchive ();
- # 5.2 文件不存在则生成一个新的文件 用CREATE打开文件会追加内容至zip
- if ($zip->open($file_dir, \ZipArchive::OVERWRITE) !== true && $zip->open($file_dir, \ZipArchive::CREATE) !== true) echo '无法打开文件或者文件创建失败';
- # 5.3 批量写入压缩包
- // $zip->addEmptyDir($fileName);//往zip压缩包写入空目录
- foreach ($urls as $fileName) {
- // @$zip->addFile($fileName);
- @$zip->addFile($fileName, DIRECTORY_SEPARATOR.basename($fileName));
- }
- // @$zip->addFile($v['file_path'], 'resume'.DIRECTORY_SEPARATOR.basename($headername));
- # 5.4 关闭压缩包写入
- $zip->close();
- @deldir($dir);//删除已生成的文件及目录
- //6. 检查文件是否存在,并输出文件
- if (!file_exists($file_dir)) echo '压缩包文件不存在';
- ob_clean();
- flush();
- header("Cache-Control: max-age=0");
- header("Content-Description: File Transfer");
- header('Content-disposition: attachment; filename=' . basename($file_dir)); # 处理文件名
- header("Content-Type: application/octet-stream"); # 流文件输出
- header("Content-Transfer-Encoding: binary"); # 告诉浏览器,这是二进制文件
- // header('Content-Length: ' . filesize($file_dir)); # 告诉浏览器,文件大小
- // readfile($file_dir);//输出文件
- $res = read_big_file($file_dir);
- foreach ($res as $val) {
- echo $val;
- }
- @unlink($file_dir);
- exit();
- }
- }
- /**
- * 批量生成多个文件excel,生成压缩包,保存到本地,返回文件链接
- * datas 生成器
- * header array 头部字段
- * filename string 文件名
- */
- if (!function_exists('excelSaveFile')) {
- function excelSaveFile($datas, string $filename = '')
- {
- // $urls = [];
- $dir = root_path() . 'public/storage/report/' . date("YmdHis") . "/";
- if (!is_dir($dir)) mkdir($dir, 0777, true);
- // foreach ($datas as $item) {
- PHPExcel_Settings::setCacheStorageMethod();
- PHPExcel_CachedObjectStorageFactory::cache_in_memory_gzip;//单元格缓存为MemoryGZip
- $objPHPExcel = new PHPExcel();
- $keyA = 0; // 设置表头
- $column = 2;
- $objActSheet = $objPHPExcel->getActiveSheet();
- foreach ($datas as $key => $rows) { // 行写入
- //第一行取key作表头
- if($key==0){
- $objPHPExcel->getProperties();
- foreach ($rows as $k=>$v) {
- $colum = PHPExcel_Cell::stringFromColumnIndex($keyA);
- $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $k);
- $keyA += 1;
- }
- }
- //写入列
- $span = 0;
- foreach ($rows as $keyName => $value) {
- //判断数据是否有数组,如果有数组,转换成字符串
- if (is_array($value)) $value = implode("、", $value);
- $objActSheet->setCellValue(PHPExcel_Cell::stringFromColumnIndex($span) . $column, $value);
- $span++;
- }
- $column++;
- }
- $file = $filename . ".xls";
- $objPHPExcel->setActiveSheetIndex(0);
- $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
- $objWriter->save($dir . $file); // 文件通过浏览器下载
- $url = $dir . $file;
- if (!file_exists($url)) throw new Exception('文件生成失败');
- $saveDir = root_path() . "public/storage/zip/" . date('Ymd') . '/';
- if (!is_dir($saveDir)) mkdir($saveDir, 0777, true);
- $file_dir = $saveDir . $filename . ".zip";
- # 5.1 文件打包,提示:使用本类,linux需开启zlib,windows需取消php_zip.dll前的注释
- $zip = new \ZipArchive ();
- # 5.2 文件不存在则生成一个新的文件 用CREATE打开文件会追加内容至zip
- if ($zip->open($file_dir, \ZipArchive::OVERWRITE) !== true && $zip->open($file_dir, \ZipArchive::CREATE) !== true) echo '无法打开文件或者文件创建失败';
- # 5.3 批量写入压缩包
- // $zip->addEmptyDir($fileName);//往zip压缩包写入空目录
- // foreach ($urls as $fileName) {
- @$zip->addFile($url, DIRECTORY_SEPARATOR . basename($url));
- // }
- // @$zip->addFile($v['file_path'], 'resume'.DIRECTORY_SEPARATOR.basename($headername));
- # 5.4 关闭压缩包写入
- $zip->close();
- @deldir($dir);//删除已生成的文件及目录
- //6. 检查文件是否存在,并输出文件
- if (!file_exists($file_dir)) throw new Exception('压缩包文件不存在');
- // return $file_dir;
- return str_replace(root_path() . "public/", '', $file_dir);
- }
- }
- //通过快递网的api获取物流信息
- if (!function_exists('get_logistics_information')) {
- function get_logistics_information(string $post_code = '', string $phone = '')
- {
- if ($post_code == '') throw new Exception('快递单号不能为空');
- $signer = new \app\admin\common\HuaweiSigner();
- //设置相关参数
- $signer->Key = '1b4cfe41d72d4fbdb6778a5e0193c4b5';
- $signer->Secret = '0fd04c5d5287424eb0d25f8f620aeb78';
- $req = new \app\admin\common\HuaweiRequest('GET', 'http://kuaidi.apistore.huaweicloud.com/kuaidiinfo?nu=' . $post_code . '&phone=' . $phone);
- $req->headers = array(
- 'content-type' => 'application/json',
- 'x-stage' => 'RELEASE',
- );
- $req->body = '';//如果是post/put请求的话,要往请求体中添加内容
- $curl = $signer->Sign($req);
- $response = curl_exec($curl);
- $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
- $curl_error = curl_error($curl);
- curl_close($curl);
- if ($status == 200) return json_decode($response, true);
- else throw new Exception('请求失败:' . $curl_error);
- }
- }
- //获取三级架构
- if (!function_exists('get_top_customer_org')) {
- function get_top_customer_org($var, $data = [])
- {
- $str = Db::name('customer_org1')
- ->field('id,name,pid,level')
- ->where(['id' => $var])
- ->find();
- if ($str == false) {
- return [];
- }
- $vmn = [];
- $vmn['id'] = $str['id'];
- $vmn['name'] = $str['name'];
- $vmn['level'] = $str['level'];
- array_unshift($data, $vmn);
- // $var['id']=made();
- if ($str['pid'] == 0) {
- // krsort($data);
- return $data;
- } else {
- return get_top_customer_org($str['pid'], $data);
- }
- }
- }
- //根据某个关键字匹配所有子级部门及用户
- /**
- * $company_name string 部门名称
- * $off bool 是否查询离职人员,默认不查询
- */
- if (!function_exists('get_company_item_user_by_name')) {
- function get_company_item_user_by_name(string $company_name = '', bool $off = false)
- {
- $data = [];
- //查询符合条件的部门id
- $company_ids = Db::name("company_item")
- ->field('id,level')
- ->where(['is_del' => 0])
- ->whereLike('name', '%' . $company_name . '%')
- ->select()
- ->toArray();
- if (!empty($company_ids)) {
- $level_temp = $company_ids[0]['level'] + 1;
- $company_ids = array_column($company_ids, 'id');
- for ($level = $level_temp; $level > 0; $level++) {
- if (!empty($company_ids)) {
- //根据部门id找人
- $uids = Db::name('depart_user')
- ->where(['is_del' => 0])
- ->order('uid')
- ->whereIn('itemid', $company_ids);
- if (!$off) $uids->where('status', 1);
- $uids = $uids->column('uid');
- $data = array_unique(array_merge($data, $uids));
- $company_ids = Db::name("company_item")
- ->where(['is_del' => 0, 'level' => $level])
- ->whereIn('pid', $company_ids)
- ->column('id');
- } else break;
- }
- }
- return $data;
- }
- }
- //获取某个用户所属部门名称
- //$uid int 用户id
- //$cache bool 是否启用缓存,(默认启用,不启用的话直接从数据库查)
- //$get_tops bool 是否获取多级部门,例如 万宇恒通/采购部/仓储物流,默认不获取
- if (!function_exists('get_company_name_by_uid')) {
- function get_company_name_by_uid(int $uid = 0, bool $cache = true, bool $get_tops = false)
- {
- $rs = '';
- $key = 'get_company_name_by_uid_' . $uid.'_'.$get_tops;
- if ($cache) $rs = \think\facade\Cache::get($key);
- if (empty($rs)) {
- $itemid = Db::name('depart_user')->where(['is_del' => 0, 'uid' => $uid])->value('itemid', 0);
- if ($get_tops) $rs = implode('/', array_column(GetPart($itemid), 'name'));
- else $rs = Db::name('company_item')->where(['is_del' => 0, 'id' => $itemid])->value('name');
- \think\facade\Cache::set($key, $rs, 3600);
- }
- return $rs;
- }
- }
- //返回json格式的响应信息,方便中间件记录,目前在abutmenu应用中有用到
- if (!function_exists('json_show')) {
- function json_show(int $code = 0, string $message = '请求成功', array $data = [])
- {
- return json(['code' => $code, 'message' => $message, 'data' => $data]);
- }
- }
- //获取加密后的密码密文
- /**
- * @param $password string 密码明文
- * @param $salt string 盐值(不传的话随机生成一个)
- */
- if (!function_exists('get_encryption_password')) {
- function get_encryption_password(string $password = '',string $salt=''):array
- {
- if($salt=='') $salt = Str::random(mt_rand(10, 30), -1);
- return [
- 'password' => md5($salt . $password . $salt . $salt),
- 'salt' => $salt
- ];
- }
- }
- //检查供应商是否有开通账号
- if (!function_exists('checkHasAccountBySupplierNos')) {
- function checkHasAccountBySupplierNos(array $supplierNo = []): array
- {
- return \app\abutment\model\SupplierRelationUser::where('is_del', \app\abutment\model\SupplierUser::$is_del_normal)
- ->whereIn('supplierNo', $supplierNo)
- ->where('status', \app\abutment\model\SupplierUser::$status_normal)
- ->column('uid','supplierNo');
- }
- }
- //获取当前操作人(待办列表)
- if (!function_exists('get_handle_user_list')) {
- //$action_process_id 节点id
- //$holder_id 所有人uid
- //$api_url 接口路径,匹配菜单使用
- //$person_id 供应商负责人(供应商端)
- function get_handle_user_list(int $action_process_id = 0, int $holder_id = 0, string $api_url = '',int $person_id=0)
- {
- //筛选符合流程权限的角色id集合
- $roleids = Db::name('role_process')
- ->where('is_del', 0)
- ->where('role_id', '<>', 1)//排除超级管理员
- ->whereFindInSet('action_data', $action_process_id)
- ->field('role_id')
- ->buildSql();
- //根据角色id筛选用户id
- $data = Db::name('user_role')
- ->where(['is_del' => 0, 'status' => 1])
- ->where('roleid IN ' . $roleids)
- ->column('uid');
- //根据菜单筛选符合条件的共享数据
- //当前请求的接口地址
- if ($api_url == '') $api_url = app('http')->getName() . '/' . request()->pathinfo();
- $menu_id = Db::name('admin_menu')
- ->where(['is_del' => 0, 'menu_api' => $api_url])
- ->value('id', 0);
- $tmp = [];
- if ($menu_id) {
- //共享规则
- $share = Db::name('role_share')
- ->field('id,to_user,to_group')
- ->where([
- 'share_user' => $holder_id,
- 'is_del' => 0,
- 'status' => 1,
- ])
- ->whereFindInSet('action_collect', $menu_id)
- ->cursor();
- foreach ($share as $s) {
- if ($s['to_user']) $tmp[] = $s['to_user'];
- elseif ($s['to_group']) {
- $group_user = Db::name('role_group')
- ->where([
- 'id' => $s['to_group'],
- 'is_del' => 0,
- 'status' => 1,
- ])->value('group_user');
- $tmp = array_merge($tmp, explode(',', $group_user));
- }
- }
- }
- $res = array_intersect($tmp, $data);//流程权限和数据权限取交集
- //如果本人有流程权限的话,加入到数组中
- if (in_array($holder_id, $data)) $res[] = $holder_id;
- if ($person_id) $res[] = $person_id;
- sort($res);
- $res = array_unique($res);
- return $res;
- }
- }
|