123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005 |
- <?php
- // 公共助手函数
- use Symfony\Component\VarExporter\VarExporter;
- use think\exception\HttpResponseException;
- use think\Response;
- use think\Db;
- if (!function_exists('__')) {
- /**
- * 获取语言变量值
- * @param string $name 语言变量名
- * @param array $vars 动态变量值
- * @param string $lang 语言
- * @return mixed
- */
- function __($name, $vars = [], $lang = '')
- {
- if (is_numeric($name) || !$name) {
- return $name;
- }
- if (!is_array($vars)) {
- $vars = func_get_args();
- array_shift($vars);
- $lang = '';
- }
- return \think\Lang::get($name, $vars, $lang);
- }
- }
- if (!function_exists('format_bytes')) {
- /**
- * 将字节转换为可读文本
- * @param int $size 大小
- * @param string $delimiter 分隔符
- * @param int $precision 小数位数
- * @return string
- */
- function format_bytes($size, $delimiter = '', $precision = 2)
- {
- $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
- for ($i = 0; $size >= 1024 && $i < 6; $i++) {
- $size /= 1024;
- }
- return round($size, $precision) . $delimiter . $units[$i];
- }
- }
- if (!function_exists('datetime')) {
- /**
- * 将时间戳转换为日期时间
- * @param int $time 时间戳
- * @param string $format 日期时间格式
- * @return string
- */
- function datetime($time, $format = 'Y-m-d H:i:s')
- {
- $time = is_numeric($time) ? $time : strtotime($time);
- return date($format, $time);
- }
- }
- if (!function_exists('human_date')) {
- /**
- * 获取语义化时间
- * @param int $time 时间
- * @param int $local 本地时间
- * @return string
- */
- function human_date($time, $local = null)
- {
- return \fast\Date::human($time, $local);
- }
- }
- if (!function_exists('cdnurl')) {
- /**
- * 获取上传资源的CDN的地址
- * @param string $url 资源相对地址
- * @param boolean $domain 是否显示域名 或者直接传入域名
- * @return string
- */
- function cdnurl($url, $domain = false)
- {
- $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
- $cdnurl = \think\Config::get('upload.cdnurl');
- $url = preg_match($regex, $url) || ($cdnurl && stripos($url, $cdnurl) === 0) ? $url : $cdnurl . $url;
- if ($domain && !preg_match($regex, $url)) {
- $domain = is_bool($domain) ? request()->domain() : $domain;
- $url = $domain . $url;
- }
- return $url;
- }
- }
- if (!function_exists('is_really_writable')) {
- /**
- * 判断文件或文件夹是否可写
- * @param string $file 文件或目录
- * @return bool
- */
- function is_really_writable($file)
- {
- if (DIRECTORY_SEPARATOR === '/') {
- return is_writable($file);
- }
- if (is_dir($file)) {
- $file = rtrim($file, '/') . '/' . md5(mt_rand());
- if (($fp = @fopen($file, 'ab')) === false) {
- return false;
- }
- fclose($fp);
- @chmod($file, 0777);
- @unlink($file);
- return true;
- } elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
- return false;
- }
- fclose($fp);
- return true;
- }
- }
- if (!function_exists('rmdirs')) {
- /**
- * 删除文件夹
- * @param string $dirname 目录
- * @param bool $withself 是否删除自身
- * @return boolean
- */
- function rmdirs($dirname, $withself = true)
- {
- if (!is_dir($dirname)) {
- return false;
- }
- $files = new RecursiveIteratorIterator(
- new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
- RecursiveIteratorIterator::CHILD_FIRST
- );
- foreach ($files as $fileinfo) {
- $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
- $todo($fileinfo->getRealPath());
- }
- if ($withself) {
- @rmdir($dirname);
- }
- return true;
- }
- }
- if (!function_exists('copydirs')) {
- /**
- * 复制文件夹
- * @param string $source 源文件夹
- * @param string $dest 目标文件夹
- */
- function copydirs($source, $dest)
- {
- if (!is_dir($dest)) {
- mkdir($dest, 0755, true);
- }
- foreach (
- $iterator = new RecursiveIteratorIterator(
- new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
- RecursiveIteratorIterator::SELF_FIRST
- ) as $item
- ) {
- if ($item->isDir()) {
- $sontDir = $dest . DS . $iterator->getSubPathName();
- if (!is_dir($sontDir)) {
- mkdir($sontDir, 0755, true);
- }
- } else {
- copy($item, $dest . DS . $iterator->getSubPathName());
- }
- }
- }
- }
- if (!function_exists('mb_ucfirst')) {
- function mb_ucfirst($string)
- {
- return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
- }
- }
- if (!function_exists('addtion')) {
- /**
- * 附加关联字段数据
- * @param array $items 数据列表
- * @param mixed $fields 渲染的来源字段
- * @return array
- */
- function addtion($items, $fields)
- {
- if (!$items || !$fields) {
- return $items;
- }
- $fieldsArr = [];
- if (!is_array($fields)) {
- $arr = explode(',', $fields);
- foreach ($arr as $k => $v) {
- $fieldsArr[$v] = ['field' => $v];
- }
- } else {
- foreach ($fields as $k => $v) {
- if (is_array($v)) {
- $v['field'] = isset($v['field']) ? $v['field'] : $k;
- } else {
- $v = ['field' => $v];
- }
- $fieldsArr[$v['field']] = $v;
- }
- }
- foreach ($fieldsArr as $k => &$v) {
- $v = is_array($v) ? $v : ['field' => $v];
- $v['display'] = isset($v['display']) ? $v['display'] : str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
- $v['primary'] = isset($v['primary']) ? $v['primary'] : '';
- $v['column'] = isset($v['column']) ? $v['column'] : 'name';
- $v['model'] = isset($v['model']) ? $v['model'] : '';
- $v['table'] = isset($v['table']) ? $v['table'] : '';
- $v['name'] = isset($v['name']) ? $v['name'] : str_replace(['_ids', '_id'], '', $v['field']);
- }
- unset($v);
- $ids = [];
- $fields = array_keys($fieldsArr);
- foreach ($items as $k => $v) {
- foreach ($fields as $m => $n) {
- if (isset($v[$n])) {
- $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
- }
- }
- }
- $result = [];
- foreach ($fieldsArr as $k => $v) {
- if ($v['model']) {
- $model = new $v['model'];
- } else {
- $model = $v['name'] ? \think\Db::name($v['name']) : \think\Db::table($v['table']);
- }
- $primary = $v['primary'] ? $v['primary'] : $model->getPk();
- $result[$v['field']] = isset($ids[$v['field']]) ? $model->where($primary, 'in', $ids[$v['field']])->column("{$primary},{$v['column']}") : [];
- }
- foreach ($items as $k => &$v) {
- foreach ($fields as $m => $n) {
- if (isset($v[$n])) {
- $curr = array_flip(explode(',', $v[$n]));
- $v[$fieldsArr[$n]['display']] = implode(',', array_intersect_key($result[$n], $curr));
- }
- }
- }
- return $items;
- }
- }
- if (!function_exists('var_export_short')) {
- /**
- * 使用短标签打印或返回数组结构
- * @param mixed $data
- * @param boolean $return 是否返回数据
- * @return string
- */
- function var_export_short($data, $return = true)
- {
- return var_export($data, $return);
- $replaced = [];
- $count = 0;
- //判断是否是对象
- if (is_resource($data) || is_object($data)) {
- return var_export($data, $return);
- }
- //判断是否有特殊的键名
- $specialKey = false;
- array_walk_recursive($data, function (&$value, &$key) use (&$specialKey) {
- if (is_string($key) && (stripos($key, "\n") !== false || stripos($key, "array (") !== false)) {
- $specialKey = true;
- }
- });
- if ($specialKey) {
- return var_export($data, $return);
- }
- array_walk_recursive($data, function (&$value, &$key) use (&$replaced, &$count, &$stringcheck) {
- if (is_object($value) || is_resource($value)) {
- $replaced[$count] = var_export($value, true);
- $value = "##<{$count}>##";
- } else {
- if (is_string($value) && (stripos($value, "\n") !== false || stripos($value, "array (") !== false)) {
- $index = array_search($value, $replaced);
- if ($index === false) {
- $replaced[$count] = var_export($value, true);
- $value = "##<{$count}>##";
- } else {
- $value = "##<{$index}>##";
- }
- }
- }
- $count++;
- });
- $dump = var_export($data, true);
- $dump = preg_replace('#(?:\A|\n)([ ]*)array \(#i', '[', $dump); // Starts
- $dump = preg_replace('#\n([ ]*)\),#', "\n$1],", $dump); // Ends
- $dump = preg_replace('#=> \[\n\s+\],\n#', "=> [],\n", $dump); // Empties
- $dump = preg_replace('#\)$#', "]", $dump); //End
- if ($replaced) {
- $dump = preg_replace_callback("/'##<(\d+)>##'/", function ($matches) use ($replaced) {
- return isset($replaced[$matches[1]]) ? $replaced[$matches[1]] : "''";
- }, $dump);
- }
- if ($return === true) {
- return $dump;
- } else {
- echo $dump;
- }
- }
- }
- if (!function_exists('letter_avatar')) {
- /**
- * 首字母头像
- * @param $text
- * @return string
- */
- function letter_avatar($text)
- {
- $total = unpack('L', hash('adler32', $text, true))[1];
- $hue = $total % 360;
- list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);
- $bg = "rgb({$r},{$g},{$b})";
- $color = "#ffffff";
- $first = mb_strtoupper(mb_substr($text, 0, 1));
- $src = base64_encode('<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100" width="100"><rect fill="' . $bg . '" x="0" y="0" width="100" height="100"></rect><text x="50" y="50" font-size="50" text-copy="fast" fill="' . $color . '" text-anchor="middle" text-rights="admin" dominant-baseline="central">' . $first . '</text></svg>');
- $value = 'data:image/svg+xml;base64,' . $src;
- return $value;
- }
- }
- if (!function_exists('hsv2rgb')) {
- function hsv2rgb($h, $s, $v)
- {
- $r = $g = $b = 0;
- $i = floor($h * 6);
- $f = $h * 6 - $i;
- $p = $v * (1 - $s);
- $q = $v * (1 - $f * $s);
- $t = $v * (1 - (1 - $f) * $s);
- switch ($i % 6) {
- case 0:
- $r = $v;
- $g = $t;
- $b = $p;
- break;
- case 1:
- $r = $q;
- $g = $v;
- $b = $p;
- break;
- case 2:
- $r = $p;
- $g = $v;
- $b = $t;
- break;
- case 3:
- $r = $p;
- $g = $q;
- $b = $v;
- break;
- case 4:
- $r = $t;
- $g = $p;
- $b = $v;
- break;
- case 5:
- $r = $v;
- $g = $p;
- $b = $q;
- break;
- }
- return [
- floor($r * 255),
- floor($g * 255),
- floor($b * 255)
- ];
- }
- }
- if (!function_exists('check_nav_active')) {
- /**
- * 检测会员中心导航是否高亮
- */
- function check_nav_active($url, $classname = 'active')
- {
- $auth = \app\common\library\Auth::instance();
- $requestUrl = $auth->getRequestUri();
- $url = ltrim($url, '/');
- return $requestUrl === str_replace(".", "/", $url) ? $classname : '';
- }
- }
- if (!function_exists('check_cors_request')) {
- /**
- * 跨域检测
- */
- function check_cors_request()
- {
- if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN']) {
- $info = parse_url($_SERVER['HTTP_ORIGIN']);
- $domainArr = explode(',', config('fastadmin.cors_request_domain'));
- $domainArr[] = request()->host(true);
- if (in_array("*", $domainArr) || in_array($_SERVER['HTTP_ORIGIN'], $domainArr) || (isset($info['host']) && in_array($info['host'], $domainArr))) {
- header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
- } else {
- $response = Response::create('跨域检测无效', 'html', 403);
- throw new HttpResponseException($response);
- }
- header('Access-Control-Allow-Credentials: true');
- header('Access-Control-Max-Age: 86400');
- if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
- if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
- header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
- }
- if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
- header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
- }
- $response = Response::create('', 'html');
- throw new HttpResponseException($response);
- }
- }
- }
- }
- if (!function_exists('xss_clean')) {
- /**
- * 清理XSS
- */
- function xss_clean($content, $is_image = false)
- {
- return \app\common\library\Security::instance()->xss_clean($content, $is_image);
- }
- }
- if (!function_exists('check_ip_allowed')) {
- /**
- * 检测IP是否允许
- * @param string $ip IP地址
- */
- function check_ip_allowed($ip = null)
- {
- $ip = is_null($ip) ? request()->ip() : $ip;
- $forbiddenipArr = config('site.forbiddenip');
- $forbiddenipArr = !$forbiddenipArr ? [] : $forbiddenipArr;
- $forbiddenipArr = is_array($forbiddenipArr) ? $forbiddenipArr : array_filter(explode("\n", str_replace("\r\n", "\n", $forbiddenipArr)));
- if ($forbiddenipArr && \Symfony\Component\HttpFoundation\IpUtils::checkIp($ip, $forbiddenipArr)) {
- $response = Response::create('请求无权访问', 'html', 403);
- throw new HttpResponseException($response);
- }
- }
- }
- //结果集信息里,生日转换年龄
- function list_birthday_age($list){
- if(!$list || empty($list)){
- return $list;
- }
- foreach($list as $vo => $info){
- $list[$vo]['age'] = birthtime_to_age($info['birthday']);
- }
- return $list;
- }
- //结果集信息里,多个字段需要增加domain_cdnurl
- function list_domain_image($list,$field){
- if(!$list || empty($list)){
- return $list;
- }
- foreach($list as $vo => $info){
- $list[$vo] = info_domain_image($info,$field);
- }
- return $list;
- }
- //单条信息里,多个字段需要增加domain_cdnurl
- //支持image,images
- function info_domain_image($data,$field){
- if(!$data || empty($data)){
- return $data;
- }
- foreach($data as $key => $val){
- if(in_array($key,$field)){
- $data[$key] = one_domain_image($val);
- }
- }
- return $data;
- }
- //支持单个字段,需要增加domain_cdnurl
- //支持image,images
- function one_domain_image($one){
- if(!$one){
- return $one;
- }
- if(strpos($one,',')){
- //逗号隔开的多个图片
- $one = explode(',',$one);
- foreach($one as $k => $v){
- $one[$k] = localpath_to_netpath($v);
- }
- $one = implode(',',$one);
- }else{
- $one = localpath_to_netpath($one);
- }
- return $one;
- }
- //本地地址转换为网络地址
- function localpath_to_netpath($path)
- {
- if (empty($path)) {
- return '';
- } elseif (strrpos($path, 'http') !== false) {
- return $path;
- } else {
- return config('upload.cdnurl') . str_replace("\\", "/", $path);
- }
- }
- //秒 转换 日月分
- function Sec2Time($time){
- if(is_numeric($time)){
- $value = array(
- 'years' => 0, 'days' => 0, 'hours' => 0,
- 'minutes' => 0, 'seconds' => 0,
- );
- /*if($time >= 31556926){
- $value['years'] = floor($time/31556926);
- $time = ($time%31556926);
- }*/
- if($time >= 86400){
- $value['days'] = floor($time/86400);
- $time = ($time%86400);
- }
- if($time >= 3600){
- $value['hours'] = floor($time/3600);
- $time = ($time%3600);
- }
- if($time >= 60){
- $value['minutes'] = floor($time/60);
- $time = ($time%60);
- }
- $value['seconds'] = floor($time);
- //return (array) $value;
- //$t=$value['years'] .'年'. $value['days'] .'天'.' '. $value['hours'] .'小时'. $value['minutes'] .'分'.$value['seconds'].'秒';
- $t = $value['days'] .'天' . $value['hours'] .'小时'. $value['minutes'] .'分';
- return $t;
- }else{
- return '0天';
- }
- }
- //生日转年龄
- function birthtime_to_age($birthtime){
- // $birthtime = strtotime('1990-11-06');
- if(!$birthtime){
- return 0;
- }
- list($y1,$m1,$d1) = explode("-",date("Y-m-d",$birthtime));
- list($y2,$m2,$d2) = explode("-",date("Y-m-d",time()));
- $age = $y2 - $y1;
- if((int)($m2.$d2) < (int)($m1.$d1))
- {$age -= 1;}
- if($age < 0){
- $age = 0;
- }
- return $age;
- }
- if(!function_exists('mk_dir')) {
- /**
- * 新建目录
- */
- function mk_dir($dir, $mode = 0770, $tmp = true)
- {
- $mode = 0770;
- if(is_file($dir)) {
- //有同名文件
- return false;
- } else {
- if(!is_dir($dir)) { //目录不存在
- $dir_up = dirname($dir); //上级目录
- if(!is_dir($dir_up)) {
- //上级不存在
- $rs = @mk_dir($dir_up);
- if(!$rs) return false;
- }
- $rs = @mkdir($dir, $mode); //新建
- if(!$rs) return false;
- $rs = @chmod($dir, $mode); //改权限
- if(!$rs) return false;
- }
- return true;
- }
- }
- }
- /**
- * 在线支付日志
- */
- function filePut($info,$text='notify.txt'){
- if(is_array($info)) {
- $info = json_encode($info, JSON_UNESCAPED_UNICODE);
- }
- if(!file_exist(RUNTIME_PATH.'paylog/')) {
- mk_dir(RUNTIME_PATH.'paylog/');
- }
- $file = RUNTIME_PATH.'paylog/'.$text;
- touch_file($file);
- file_put_contents($file, "\r\n".date('Y-m-d H:i:s').' '.$info, FILE_APPEND);
- }
- if(!function_exists('touch_file')) {
- /**
- * 新建文件
- */
- function touch_file($file = '')
- {
- if($file) {
- if(!file_exists($file)) {
- @touch($file);
- @chmod($file, 0770);
- }
- }
- }
- }
- if(!function_exists('file_exist')) {
- /**
- * 检测文件是否存在
- * @param $file
- * @return string
- */
- function file_exist($file)
- {
- if(false === strpos($file, 'http')) { //本地文件
- if(0 === strpos($file, '/upload')) {
- $file = '.'.$file;
- }
- return file_exists($file);
- } else { //网络文件
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $file);
- curl_setopt($ch, CURLOPT_TIMEOUT, 2);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_exec($ch);
- $status = curl_getinfo($ch,CURLINFO_HTTP_CODE);
- curl_close($ch);
- if(in_array(substr($status, 0, 1), [2, 3])) {
- return true;
- } else {
- return false;
- }
- }
- }
- }
- /**
- * 发起HTTPS请求
- */
- function curl_post($url, $data, $header = '', $timeOut = 0)
- {
- //初始化curl
- $ch = curl_init();
- //参数设置
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
- curl_setopt($ch, CURLOPT_TIMEOUT, $timeOut);
- curl_setopt($ch, CURLOPT_HEADER, 0);
- curl_setopt($ch, CURLOPT_POST, 1);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- if($header != '') {
- curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
- }
- $result = curl_exec($ch);
- //连接失败
- if($result == FALSE) {
- //\think\Log::record('[ CURL ] ERROR ' . curl_error($ch)."\n".var_export(debug_backtrace(), true)."\n", 'error');
- }
- curl_close($ch);
- return $result;
- }
- /**
- * 发起HTTP GET请求
- */
- function curl_get($url)
- {
- $oCurl = curl_init();
- if(stripos($url, "https://") !== FALSE) {
- curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
- curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
- curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
- }
- curl_setopt($oCurl, CURLOPT_TIMEOUT, 3);
- curl_setopt($oCurl, CURLOPT_URL, $url);
- curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
- $sContent = curl_exec($oCurl);
- $aStatus = curl_getinfo($oCurl);
- $error = curl_error($oCurl);
- curl_close($oCurl);
- if($error) {
- $sContent = file_get_contents($url);
- return $sContent;
- }
- if(intval($aStatus["http_code"]) == 200) {
- return $sContent;
- } else {
- return false;
- }
- }
- //创建订单号
- function createUniqueNo($prifix = 'P',$id = 0)
- {
- $s = 0;
- $ms = 0;
- list($ms, $s) = explode(' ', microtime());
- $ms = substr($ms, 2, 6); //获取微妙
- $rt = $prifix.date('ymdHis', $s).$ms.$id; //年月日时分秒.用户id对10取余.微秒
- return $rt;
- }
- //时间转换
- function get_last_time($time = NULL) {
- $text = '';
- $time = $time === NULL || $time > time() ? time() : intval($time);
- $t = time() - $time; //时间差 (秒)
- $y = date('Y', $time)-date('Y', time());//是否跨年
- switch($t){
- case $t == 0:
- $text = '刚刚';
- break;
- case $t < 60:
- $text = $t . '秒前'; // 一分钟内
- break;
- case $t < 60 * 60:
- $text = floor($t / 60) . '分钟前'; //一小时内
- break;
- case $t < 60 * 60 * 24:
- $text = floor($t / (60 * 60)) . '小时前'; // 一天内
- break;
- case $t < 60 * 60 * 24 * 3:
- $text = floor($time/(60*60*24)) ==1 ?'昨天 ' . date('H:i', $time) : '前天 ' . date('H:i', $time) ; //昨天和前天
- break;
- case $t < 60 * 60 * 24 * 30:
- $text = date('m月d日 H:i', $time); //一个月内
- break;
- case $t < 60 * 60 * 24 * 365&&$y==0:
- $text = date('m月d日', $time); //一年内
- break;
- default:
- $text = date('Y年m月d日', $time); //一年以前
- break;
- }
- return $text;
- }
- //增加亲密度
- function addintimacy($uid = 0, $other_uid = 0, $value = 0) {
- //增加亲密度
- $level_remark = ''; //亲密度等级是否变动: 0未变动 >0是亲密度等级
- $user_intimacy_info = Db::name('user_intimacy')->where(['uid' => $uid, 'other_uid' => $other_uid])->find();
- if ($user_intimacy_info) {
- $user_intimacy_data['value'] = $user_intimacy_info['value'] + $value;
- $user_intimacy_data['updatetime'] = time();
- $level = Db::name('intimacy_level')->where(['value' => ['elt', $user_intimacy_data['value']]])->order('id desc')->find();
- if ($level) {
- $user_intimacy_data['level'] = $level['level'];
- if ($level['level'] != $user_intimacy_info['level']) {
- $level_remark = "恭喜你们亲密度达到".$level['level']."级,获得称号'".$level['name']."'";
- }
- }
- $user_intimacy_rs = Db::name('user_intimacy')->where(['uid' => $uid, 'other_uid' => $other_uid])->setField($user_intimacy_data);
- } else {
- $user_intimacy_data['uid'] = $uid;
- $user_intimacy_data['other_uid'] = $other_uid;
- $user_intimacy_data['value'] = $value;
- $user_intimacy_data['createtime'] = time();
- $user_intimacy_data['updatetime'] = time();
- $level = Db::name('intimacy_level')->where(['value' => ['elt', $value]])->order('id desc')->find();
- if ($level) {
- $user_intimacy_data['level'] = $level['level'];
- $level_remark = "恭喜你们亲密度达到".$level['level']."级,获得称号'".$level['name']."'";
- }
- $user_intimacy_rs = Db::name('user_intimacy')->insertGetId($user_intimacy_data);
- }
- return ['status' => $user_intimacy_rs, 'level_remark' => $level_remark];
- }
- /**
- * [getMillisecond 获取毫秒级时间戳]
- * @return [type] [description]
- */
- function getMillisecond() {
- list($t1, $t2) = explode(' ', microtime());
- return (float)sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
- }
- function p($arr) {
- header('content-type:text/html;charset=utf-8');
- echo '<pre>';
- print_r($arr);
- echo '</pre>';
- }
- //获取支付宝用户信息
- function getAlipayInfo($auth_code = '') {
- if (!$auth_code) {
- return ['status' => 0, 'info' => '授权码缺失'];
- }
- $aliPayPath = '../extend/AliPay/aop/';
- require_once $aliPayPath . 'AopClient.php';
- require_once $aliPayPath . 'AopCertClient.php';
- require_once $aliPayPath . 'AopCertification.php';
- require_once $aliPayPath . 'AlipayConfig.php';
- require_once $aliPayPath . 'request/AlipaySystemOauthTokenRequest.php';
- require_once $aliPayPath . 'request/AlipayUserInfoShareRequest.php';
- $privateKey = config('private_key');//"<-- 请填写您的应用私钥,例如:MIIEvQIBADANB ... ... -->";
- $alipayConfig = new AlipayConfig();
- $alipayConfig->setPrivateKey($privateKey);
- $alipayConfig->setServerUrl("https://openapi.alipay.com/gateway.do");
- $alipayConfig->setAppId(config('ali_app_id')); //"<-- 请填写您的AppId,例如:2019091767145019 -->"
- $alipayConfig->setCharset("UTF-8");
- $alipayConfig->setSignType("RSA2");
- $alipayConfig->setEncryptKey("");
- $alipayConfig->setFormat("json");
- $alipayConfig->setAppCertPath('../extend/AliPay/cert/appCertPublicKey_2021003139615320.crt');//"<-- 请填写您的应用公钥证书文件路径,例如:/foo/appCertPublicKey_2019051064521003.crt -->"
- $alipayConfig->setAlipayPublicCertPath('../extend/AliPay/cert/alipayCertPublicKey_RSA2.crt');//"<-- 请填写您的支付宝公钥证书文件路径,例如:/foo/alipayCertPublicKey_RSA2.crt -->"
- $alipayConfig->setRootCertPath('../extend/AliPay/cert/alipayRootCert.crt');//"<-- 请填写您的支付宝根证书文件路径,例如:/foo/alipayRootCert.crt -->"
- $alipayClient = new AopCertClient($alipayConfig);
- $alipayClient->isCheckAlipayPublicCert = true;
- $request = new AlipaySystemOauthTokenRequest();
- $request->setGrantType("authorization_code");
- $request->setCode($auth_code);//设置授权码
- $result = $alipayClient->execute($request);
- $result = json_decode(json_encode($result), true);
- /*$aliPayPath = '../extend/AliPay/alipay-sdk/';
- require_once($aliPayPath . "aop/AopClient.php");
- require_once($aliPayPath . "aop/SignData.php");
- require_once($aliPayPath . 'aop/request/AlipaySystemOauthTokenRequest.php');
- require_once($aliPayPath . 'aop/request/AlipayUserInfoShareRequest.php');
- $aop = new \AopClient ();
- $aop->appId = config('ali_app_id');
- $aop->rsaPrivateKey = config('private_key');
- $aop->alipayrsaPublicKey = config('ali_public_key');
- $aop->signType = 'RSA2';
- $request = new \AlipaySystemOauthTokenRequest ();
- $request->setGrantType("authorization_code");
- $request->setCode($auth_code);//设置授权码
- // $request->setRefreshToken("201208134b203fe6c11548bcabd8da5bb087a83b"); //刷刷新令牌,上次换取访问令牌时得到
- $result = $aop->execute ($request);
- $result = json_decode(json_encode($result), true);*/
- if (!isset($result['alipay_system_oauth_token_response'])) {
- return ['status' => 0, 'info' => '获取用户授权失败'];
- }
- //用户访问令牌
- $access_token = $result['alipay_system_oauth_token_response']['access_token'];
- if (empty($access_token)) {
- return ['status' => 0, 'info' => '获取用户授权失败'];
- }
- //获取用户信息
- $request_two = new \AlipayUserInfoShareRequest ();
- $rs = $alipayClient->execute ($request_two , $access_token );
- $rs = json_decode(json_encode($rs), true);
- /*
- * Array(
- [alipay_user_info_share_response] => Array
- (
- [code] => 10000
- [msg] => Success
- [avatar] => https://tfs.alipayobjects.com/images/partner/T1BQJsXhhbXXXXXXXX 头像
- [city] => 临沂市 市名称。
- [gender] => m 【注意】只有is_certified为T的时候才有意义,否则不保证准确性. 性别(F:女性;M:男性)。
- [is_certified] => T 是否通过实名认证。T是通过 F是没有实名认证。
- [is_student_certified] => F 是否是学生 T是 F否
- [nick_name] => 风的追求 用户昵称
- [province] => 山东省 省份名称
- [user_id] => 2088902918001020 支付宝用户的userId
- [user_status] => T 用户状态(Q/T/B/W)。 Q代表快速注册用户 T代表已认证用户 B代表被冻结账户 W代表已注册,未激活的账户
- [user_type] => 2 用户类型(1/2) 1代表公司账户2代表个人账户
- )
- )
- */
- return ['status' => 1, 'info' => '支付宝用户信息', 'data' => $rs['alipay_user_info_share_response']];
- }
- if (!function_exists('day_now')) {
- //返回今天的开始时间和结束时间
- function day_now()
- {
- $arr = [
- mktime(0, 0, 0, date('m'), date('d'), date('Y')),
- mktime(23, 59, 59, date('m'), date('d'), date('Y')),
- ];
- return $arr;
- }
- }
- if (!function_exists('day_yesterday')) {
- //返回昨天开始结束时间 改造上边的方法
- function day_yesterday()
- {
- $yesterday = date('d') - 1;
- $arr = [
- mktime(0, 0, 0, date('m'), $yesterday, date('Y')),
- mktime(23, 59, 59, date('m'), $yesterday, date('Y')),
- ];
- return $arr;
- }
- }
- if (!function_exists('week_now')) {
- //获取当前时间的本周开始结束时间
- function week_now()
- {
- $arr = [
- mktime(0, 0 , 0,date("m"),date("d")-date("N")+1,date("Y")),
- mktime(23,59,59,date("m"),date("d")-date("N")+7,date("Y")),
- ];
- return $arr;
- }
- }
- if (!function_exists('last_week')) {
- //返回上周开始和结束的时间戳
- function last_week()
- {
- $arr = [
- strtotime('last week Monday', time()),
- strtotime('last week Sunday +1 days -1 seconds', time())
- ];
- return $arr;
- }
- }
- if (!function_exists('now_month')) {
- //返回上周开始和结束的时间戳
- function now_month()
- {
- $arr = [
- //strtotime('-30 day', time()),
- mktime(0, 0 , 0,date("m"),date("d")-30,date("Y")),
- mktime(23, 59 , 59,date("m"),date("d"),date("Y")),
- ];
- return $arr;
- }
- }
- if (!function_exists('dd')) {
- function dd(...$vars){
- foreach ($vars as $v) {
- dump($v);
- }
- exit();
- }
- }
|