123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525 |
- <?php
- use think\facade\Db;
- use think\facade\Filesystem;
- use think\facade\Queue;
- use think\facade\Log;
- use think\facade\Config;
- // 这是系统自动生成的公共文件
- function make_verify(){
- $code = round(100000,999999);
- return $code;
- }
- /**
- * 发送短信接口
- * @param type $phone
- * @param type $code
- */
- function sendMessage($phone, $code) {
- //1.下列选项必填
- $url = 'https://rtcsms.cn-north-1.myhuaweicloud.com:10743/sms/batchSendSms/v1'; //APP接入地址+接口访问URI
- $APP_KEY = 'ww3mKZEWh3fhboNZ791pL5fhSNfJ'; //APP_Key
- $APP_SECRET = 'nvXKrQQeEkQRp5750M2p85ILs4xC'; //APP_Secret
- $sender = '99200620888880002777'; //国内短信签名通道号或国际/港澳台短信通道号
- $TEMPLATE_ID = '54b09b74ee764cca90571b65bfb20f9f'; //模板ID
- //$sender = '8821032432899'; //国内短信签名通道号或国际/港澳台短信通道号
- //$TEMPLATE_ID = 'faa13c0b2deb4646a31304434c07b856'; //模板ID
- $signature = '泰康广源'; //签名名称
- //必填,全局号码格式(包含国家码),示例:+8615123456789,多个号码之间用英文逗号分隔
- $receiver = '+86'.$phone; //短信接收人号码
- //选填,短信状态报告接收地址,推荐使用域名,为空或者不填表示不接收状态报告
- $statusCallback = '';
- /**
- * 选填,使用无变量模板时请赋空值 $TEMPLATE_PARAS = '';
- * 单变量模板示例:模板内容为"您的验证码是${NUM_6}"时,$TEMPLATE_PARAS可填写为'["369751"]'
- * 双变量模板示例:模板内容为"您有${NUM_2}件快递请到${TXT_32}领取"时,$TEMPLATE_PARAS可填写为'["3","人民公园正门"]'
- * 查看更多模板变量规则:常见问题>业务规则>短信模板内容审核标准
- * @var string $TEMPLATE_PARAS
- */
- $TEMPLATE_PARAS = '["'.$code.'"]'; //模板变量,根据自身使用的模板,其值长度和个数与模板对应
- //请求Headers
- $headers = [
- 'Content-Type: application/x-www-form-urlencoded',
- 'Authorization: WSSE realm="SDP",profile="UsernameToken",type="Appkey"',
- 'X-WSSE: '.buildWsseHeader($APP_KEY, $APP_SECRET)
- ];
- //请求Body
- $data = http_build_query([
- 'from' => $sender,
- 'to' => $receiver,
- 'templateId' => $TEMPLATE_ID,
- 'templateParas' => $TEMPLATE_PARAS,
- 'statusCallback' => $statusCallback,
- 'signature' => $signature //使用国内短信通用模板时,必须填写签名名称
- ]);
- $ch = curl_init();
- curl_setopt ($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
- curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
- curl_setopt($ch, CURLOPT_POST, true);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
- curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT,10);
- $response = curl_exec($ch);
- return $response;
- }
- /**手机号验证
- * @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){
- $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);
- }
- 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 makeNo($str){
- $date=date("mdHis");
- $year = date("Y")-2000;
- $msec=randomkeys(4);
- return $str.$msec.$year.$date;
- }
- function randomkeys($length) {
- $returnStr='';
- $pattern = '1234567890abcdefghijklmnopqrstuvwxyz';//ABCDEFGHIJKLOMNOPQRSTUVWXYZ
- for($i = 0; $i < $length; $i ++) {
- $returnStr .= $pattern[mt_rand ( 0, strlen($pattern)-1 )]; //生成php随机数
- }
- return $returnStr;
- }
- /**
- * @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();
- }
- }
- function QueuePush($data,$queue="createOrderJob"){
- //当前任务将由哪个类来负责处理
- $jobHandlerClassName = 'app\admin\JobInv';
- //业务数据 对象需要手动转序列化
- $jobQueueName = $queue;
- $isPushed = Queue::push($jobHandlerClassName, $data,$jobQueueName);
- if( $isPushed !== false ){
- Log::write("{$jobQueueName} 任务失败:{$data['id']}");
- }
- }
- function checkRole($roleid,$menu){
- $roleinfo = \think\facade\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;
- }
- function upload_ll($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" => '数据不能为空'];
- }
- return ['code' => 0, "msg" => '数据解析成功', 'data' => $sheetData];
- } catch (think\exception\ValidateException $e) {
- // echo $e->getMessage();
- return ['code' => 1003, "msg" => $e->getMessage()];
- }
- }
- /**
- * @param string $fileName
- * @param array $headArr
- * @param array $data
- */
- function excelExport($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());
- $fileName .= "_" . date("Y_m_d", time()) . ".xls";
- //$fileName .= "_" . date("Y_m_d", Request()->instance()->time()) . ".xls";
- //$fileName = iconv("utf-8", "gb2312", $fileName); // 重命名表
- $objPHPExcel->setActiveSheetIndex(0); // 设置活动单指数到第一个表,所以Excel打开这是第一个表
- // Redirect output to a client’s web browser (Excel2007)
- header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
- header('Content-Disposition: attachment;filename="'.$fileName.'"');
- header('Cache-Control: max-age=0');
- // If you're serving to IE 9, then the following may be needed
- header('Cache-Control: max-age=1');
- // If you're serving to IE over SSL, then the following may be needed
- header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
- header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
- header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
- header ('Pragma: public'); // HTTP/1.0
- // header("Content-Type: application/octet-stream"); # 流文件输出
- // header("Content-Transfer-Encoding: binary"); # 告诉浏览器,这是二进制文件
- $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
- $objWriter->save('php://output'); // 文件通过浏览器下载
- exit();
- }
- /**
- * @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);
- }
- $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); # 输出文件
- @ unlink($file_dir);
- exit();
- }
- /**
- * 处理压缩文件路径
- * @param type $path
- * @param type $zip
- */
- function addFileToZip($path, $zip)
- {
- $handler = opendir($path); //打开当前文件夹由$path指定。
- while (($filename = readdir($handler)) !== false) {
- if ($filename != "." && $filename != "..") {//文件夹文件名字为'.'和‘..’,不要对他们进行操作
- if (is_dir($path . "/" . $filename)) {// 如果读取的某个对象是文件夹,则递归
- addFileToZip($path . "/" . $filename, $zip);
- } else { //将文件加入zip对象
- $zip->addFile($path . "/" . $filename);
- }
- }
- }
- @closedir($path);
- }
- 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);
- }
|