123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378 |
- <?php
- // 应用公共文件
- use think\facade\Filesystem;
- use think\facade\Config;
- use think\facade\Cache;
- use think\facade\Log;
- use app\model\AdminTokenModel;
- use app\model\AdminModel;
- use think\exception\ValidateException;
- use app\model\CommonModel;
- //返回响应数据
- 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_password')) {
- function get_password(string $password = '', string $salt = ''): string
- {
- return sha1($password . $salt);
- }
- }
- //获取token
- //@param $admin_id int 运营账号表id
- //@param $username string 账户
- //@param $salt string 盐值
- if (!function_exists('make_token')) {
- function make_token(int $admin_id = 0, string $username = '', string $salt = ''): string
- {
- $now = time();
- $str = $username . $salt . (string)$now;
- $token = base64_encode($str);
- AdminTokenModel::handleToken($admin_id, $token);
- return $token;
- }
- }
- //校验token
- //@param $salt string 盐值
- if (!function_exists('verify_token')) {
- function verify_token(string $token = '')
- {
- $has = AdminTokenModel::where(['token' => $token])->findOrEmpty();
- if ($has->isEmpty()) throw new ValidateException('token不存在');
- if (strtotime($has->expiretime) <= time()) throw new ValidateException('token已失效');
- $account = AdminModel::where(['id' => $has['adminid'], 'is_del' => CommonModel::$del_normal])->findOrEmpty();
- if ($account->isEmpty()) throw new ValidateException('未找到账户');
- if ($account->status != CommonModel::$status_normal) throw new ValidateException('账户已禁用');
- $token_str = base64_decode($token);
- $account_str = substr($token_str, 0, -10);
- if ($account_str == $account->username . $account->salt) {
- AdminTokenModel::where(['token' => $token])
- ->save(['expiretime' => date('Y-m-d H:i:s', time() + Config::get('common.expire'))]);
- return ['uid' => $account->id, 'uname' => $account->nickname, 'roleid' => $account->role_id];
- } else throw new ValidateException('账户token无效');
- }
- }
- //发送post的curl请求
- if (!function_exists('curl_request')) {
- function curl_request(string $url = '', array $data = [], array $header = [])
- {
- $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 ($data) {
- curl_setopt($curl, CURLOPT_POST, 1);
- curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
- }
- curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);
- if (!$header) $header = [
- 'uid:' . request()->development['id'],
- 'nickname:' . request()->development['contactor'],
- 'mobile:' . request()->development['mobile'],
- // 'email:',
- 'supplierNo:' . request()->development['supplierNo'],
- 'supplierName:' . request()->development['supplierName']
- ];
- curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
- 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 $str string 前缀
- if (!function_exists('make_no')) {
- function make_no(string $str = ''): string
- {
- $date = date("ymdHis");
- // $year = date("Y")-2000;
- $msec = randomkeys(4);
- return $str . $msec . $date;
- }
- }
- //生成随机字符串
- //@param $length int 长度,默认4
- if (!function_exists('randomkeys')) {
- function randomkeys(int $length = 4): string
- {
- $returnStr = '';
- $pattern = 'abcdefghijklmnopqrstuvwxyz';//ABCDEFGHIJKLOMNOPQRSTUVWXYZ
- $min = 0;
- $max = strlen($pattern) - 1;
- for ($i = 0; $i < $length; $i++) {
- $returnStr .= $pattern[mt_rand($min, $max)]; //生成php随机数
- }
- return $returnStr;
- }
- }
- //上传图片
- /**
- * @param $files
- * @return array
- */
- if (!function_exists('upload_img')) {
- function upload_img($files): array
- {
- $savename = [];
- $files = !is_array($files) ? [$files] : $files;
- //验证
- 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;
- }
- }
- //导出文件成压缩包
- if (!function_exists('excel_save')) {
- function excel_save($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)) throw new \think\Exception('文件生成失败');
- $saveDir = root_path() . "public/storage/zip/";
- if (!is_dir($saveDir)) mkdir($saveDir, 0777, true);
- // $datetime = date("YmdHis");
- $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) throw new \think\Exception('无法打开文件或者文件创建失败');
- # 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();
- @del_dir($dir);
- # 6. 检查文件是否存在,并输出文件
- if (!file_exists($file_dir)) throw new \think\Exception('导出文件不存在');
- 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);
- }
- }
- //递归删除目录内的所有文件和本目录
- if (!function_exists('del_dir')) {
- function del_dir($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)) {
- //子目录中操作删除文件夹和文件
- del_dir($path . $val . '/');
- } else {
- //如果是文件直接删除
- unlink($path . $val);
- }
- }
- }
- }
- }
- //删除目录
- return rmdir($path);
- }
- }
- //根据省市区编码获取省市区名称
- if (!function_exists('get_addr_name')) {
- function get_addr_name(string $addr_code = ''): string
- {
- $rs = \think\facade\Db::name('area')
- ->whereIn('code', $addr_code)
- ->column('name');
- return implode('', $rs);
- }
- }
- //根据省市区编码获取省市区名称,返回数组
- if (!function_exists('get_addr_name_array')) {
- function get_addr_name_array(string $addr_code = ''): array
- {
- return \think\facade\Db::name('area')
- ->whereIn('code', $addr_code)
- ->column('name');
- }
- }
- /**
- * 获取微信操作对象(单例模式)
- * @staticvar array $wechat 静态对象缓存对象
- * @param type $type 接口名称 ( Card|Custom|Device|Extend|Media|Oauth|Pay|Receive|Script|User )
- * @return \Wehcat\WechatReceive 返回接口对接
- */
- if (!function_exists('load_wechat')) {
- function & load_wechat(string $type = '')
- {
- static $wechat = array();
- $index = md5(strtolower($type));
- if (!isset($wechat[$index])) {
- // 定义微信公众号配置参数(这里是可以从数据库读取的哦)
- $options = array(
- 'token' => '', // 填写你设定的key
- 'appid' => '', // 填写高级调用功能的app id, 请在微信开发模式后台查询
- 'appsecret' => '', // 填写高级调用功能的密钥
- 'encodingaeskey' => '', // 填写加密用的EncodingAESKey(可选,接口传输选择加密时必需)
- 'mch_id' => '', // 微信支付,商户ID(可选)
- 'partnerkey' => '', // 微信支付,密钥(可选)
- 'ssl_cer' => '', // 微信支付,双向证书(可选,操作退款或打款时必需)
- 'ssl_key' => '', // 微信支付,双向证书(可选,操作退款或打款时必需)
- 'cachepath' => '', // 设置SDK缓存目录(可选,默认位置在Wechat/Cache下,请保证写权限)
- );
- Wechat\Loader::config($options);
- //修改sdk的缓存方式
- // 缓存写入
- // $name 缓存字段名称
- // $value 缓存字段内容值
- // $expired 缓存有效时间(单位秒),0 表示永久缓存
- Wechat\Loader::register('CacheSet', function ($name, $value, $expired) {
- return Cache::set($name, $value, $expired);
- });
- //缓存读取
- // $name 缓存字段名称,一定要有return回去哦
- Wechat\Loader::register('CacheGet', function ($name) {
- return Cache::get($name);
- });
- //缓存删除
- // $name 缓存字段名称
- Wechat\Loader::register('CacheDel', function ($name) {
- return Cache::delete($name);
- });
- //日志记录
- // $line 单行日志内容
- // $filename 日志的文件(可以重新定义)
- Wechat\Loader::register('CachePut', function ($line, $filename) {
- return Log::record($line, 'notice');
- });
- $wechat[$index] = Wechat\Loader::get($type);
- }
- return $wechat[$index];
- }
- }
|