build(); } } if (!function_exists('system_box_typesetting')) { /** * 构建URL地址 * @param string $url * @param array $vars * @param bool $suffix * @param bool $domain * @return string */ function system_box_typesetting(string $url = '', array $vars = [], $suffix = true, $domain = false) { return [ ['id'=>10, 'name'=>'普通'], ['id'=>20, 'name'=>'稀有'], ['id'=>30, 'name'=>'史诗'], ['id'=>40, 'name'=>'传说'] ]; } } if (!function_exists('get_client_ip')) { /** * 获取客户端IP地址 * @param int $type 返回类型 0 返回IP地址 1 返回IPV4地址数字 * @param bool $adv 否进行高级模式获取(有可能被伪装) * @return mixed 返回IP * @date 2019/5/23 */ function get_client_ip($type = 0, $adv = false) { $type = $type ? 1 : 0; static $ip = null; if ($ip !== null) { return $ip[$type]; } if ($adv) { if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); $pos = array_search('unknown', $arr); if (false !== $pos) { unset($arr[$pos]); } $ip = trim($arr[0]); } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; } elseif (isset($_SERVER['REMOTE_ADDR'])) { $ip = $_SERVER['REMOTE_ADDR']; } } elseif (isset($_SERVER['REMOTE_ADDR'])) { $ip = $_SERVER['REMOTE_ADDR']; } // IP地址合法验证 $long = sprintf("%u", ip2long($ip)); $ip = $long ? array($ip, $long) : array('0.0.0.0', 0); return $ip[$type]; } } /** * 请求 */ if (!function_exists('_curlrequest')) { function _curlrequest (string $url, $data = null, string $type = 'get', array $header = null) { // 拼装url if (!empty($data) && $type == 'get') { $url = $url . '?' . http_build_query($data); } $ch = curl_init(); // 初始化curl // 设置选项 curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 这个是重点 if ($type == 'post') { // post curl_setopt($ch, CURLOPT_POST, 1); // 设置为post curl_setopt($ch, CURLOPT_POSTFIELDS, $data); } //设置header头 if (!empty($header)) { curl_setopt($ch, CURLOPT_HTTPHEADER, $header); } // 执行并获取内容 $output = curl_exec($ch); // 释放curl句柄 curl_close($ch); return $output; } } if (!function_exists('shumei_event')) { // enevtId 事件 比如 register login tokenId 用户的id deviceId前端的id function shumei_event($eventId, $tokenId, $deviceId) { return ; if (env('APP.CUR_SYS_PARAMS') != 1){ $ip = get_real_ip(); if ($ip=='127.0.0.1'){ $ip = '123.45.32.55'; } $params = array( 'accessKey'=>env('app.SM_accessKey'), 'appId'=>env('app.SM_appId'), 'eventId'=>$eventId, 'data'=>array('tokenId'=>strval($tokenId), 'ip'=>$ip,'timestamp'=>intval(time().'000'), 'deviceId'=>$deviceId) ); $res = _curlrequest('http://api-skynet-bj.fengkongcloud.com/v4/event', json_encode($params),'post'); // sr_log(json_encode($res)); } } } if (!function_exists('password')) { /** * 密码加密算法 * @param $value 需要加密的值 * @param $type 加密类型,默认为md5 (md5, hash) * @return mixed */ function password($value) { $value = sha1('blog_') . md5($value) . md5('_encrypt') . sha1($value); return sha1($value); } } /** * debug调试 * @deprecated 不建议使用,建议直接使用框架自带的log组件 * @param string|array $data 打印信息 * @param string $type 类型 * @param string $suffix 文件后缀名 * @param bool $force * @param null $file */ //if (!function_exists('xdebug')) { // function xdebug($data, $type = 'xdebug', $suffix = null, $force = false, $file = null) // { // !is_dir(runtime_path() . 'xdebug/') && mkdir(runtime_path() . 'xdebug/'); // if (is_null($file)) { // $file = is_null($suffix) ? runtime_path() . 'xdebug/' . date('Ymd') . '.txt' : runtime_path() . 'xdebug/' . date('Ymd') . "_{$suffix}" . '.txt'; // } // file_put_contents($file, "[" . date('Y-m-d H:i:s') . "] " . "========================= {$type} ===========================" . PHP_EOL, FILE_APPEND); // $str = (is_string($data) ? $data : (is_array($data) || is_object($data)) ? print_r($data, true) : var_export($data, true)) . PHP_EOL; // $force ? file_put_contents($file, $str) : file_put_contents($file, $str, FILE_APPEND); // } //} function sr_randFloat($min=0, $max=1){ return $min + mt_rand()/mt_getrandmax() * ($max-$min); } if (!function_exists('sysconfig')) { /** * 获取系统配置信息 * @param $group * @param null $name * @return array|mixed */ function sysconfig($group, $name = null) { $where = ['group' => $group]; $value = empty($name) ? Cache::get("sysconfig_{$group}") : Cache::get("sysconfig_{$group}_{$name}"); if (empty($value)) { if (!empty($name)) { $where['name'] = $name; $value = \app\common\model\SystemConfig::where($where)->value('value'); Cache::tag('sysconfig')->set("sysconfig_{$group}_{$name}", $value, 3600); } else { $value = \app\common\model\SystemConfig::where($where)->column('value', 'name'); Cache::tag('sysconfig')->set("sysconfig_{$group}", $value, 3600); } } return $value; } } if (!function_exists('array_format_key')) { /** * 二位数组重新组合数据 * @param $array * @param $key * @return array */ function array_format_key($array, $key) { $newArray = []; foreach ($array as $vo) { $newArray[$vo[$key]] = $vo; } return $newArray; } } if (!function_exists('auth')) { /** * auth权限验证 * @param $node * @return bool * @throws \think\db\exception\DataNotFoundException * @throws \think\db\exception\DbException * @throws \think\db\exception\ModelNotFoundException */ function auth($node = null) { $authService = new AuthService(session('admin.id')); $check = $authService->checkNode($node); return $check; } } if (!function_exists('sr_getcurtime')) { // 获取当前时间字符串 function sr_getcurtime($time, $format='Y-m-d H:i:s') { return date($format, $time); } } /* * json 返回失败 */ if (!function_exists('api_error_return')){ function api_error_return($msg){ $json = new Json(); return $json->json_error($msg); } } /* * json 返回成功 */ if (!function_exists('api_succ_return')){ function api_succ_return($msg){ $json = new Json(); return $json->json_success($msg); } } /** * 对象转数组 */ if (!function_exists('object_array')) { function object_array ($array) { if (is_object($array)) { $array = (array)$array; } if (is_array($array)) { foreach ($array as $key => $value) { $array[$key] = object_array($value); } } return $array; } } /* * 校验是否满足公共参数 return true不满足 returnfalse 有公共参数 * */ function ISNOTREQUESTPASS($data) { if (!isset($data['app_sources'])){ return true; } // sys_model 系统型号 if (in_array($data['app_sources'],['ios', 'android'] )){ if (!isset($data['app_version']) || !isset($data['app_sources']) || !isset($data['timestamp']) || !isset($data['sys_version']) || !isset($data['sys_model']) || !isset($data['udid'])){ return true; } } if (isset($data['app_sources']) && !in_array($data['app_sources'], ['ios', 'android', 'miniapp'])){ return true; } return false; } function toUrlParams ($params) { $string = ''; if (!empty($params)) { $array = array(); foreach ($params as $key => $value) { $array[] = $key . '=' . $value; } $string = implode("&", $array); } return $string; } function getUrlParams($url){ $arr = explode('?', $url); if (isset($arr[1])){ $arr1 = explode('&', $arr[1]); $res = []; foreach ($arr1 as $key=>$val){ $arr3 = explode('=', $val); $res[$arr3[0]] = $arr3[1]; } return $res; }else{ return []; } } // 验证密码是否合规 if (!function_exists('vertifyPass')) { function vertifyPass (string $pass) { if (strlen($pass) < 8){ return false; } // 包含字母 并且包含数字 if (preg_match('/\d+/', $pass) && preg_match('/[a-zA-Z]+/', $pass)){ return true; } return false; } } // 验证用户名是否合规 if (!function_exists('vertifyUserName')) { function vertifyUserName (string $pass) { if (strlen($pass) < 7 || strlen($pass) > 15){ return false; } // 包含字母 并且包含数字 if (preg_match('/\d+/', $pass) && preg_match('/[a-zA-Z]+/', $pass)){ return true; } return false; } } // 验证支付密码是否合规 必须是六位数字 if (!function_exists('vertifySecurityPass')) { function vertifySecurityPass (string $pass) { if (strlen($pass) != 6){ return false; } // 包含字母 并且包含数字 if (preg_match("/^\d*$/", $pass)){ return true; } return false; } } // 解密 function AESjiemi($str){ return \utils\AES::decrypt($str); } // 加密 function AESjiami($str){ return \utils\AES::encrypt($str); } /* * 前端品味数娱签名 * */ if (!function_exists('createPwApiSign')) { function createApiSigncreatePwApiSign (array $params): string { //第一步、参数名ASCII码从小到大排序(字典序),区分大小写,参数为空也参与签名。 ksort($params); //第二步、将排序好的参数使用URI参数的方式拼接密钥,得到字符串 waitSignParamsStr。 $waitSignParamsStr = http_build_query($params); //第三步、使用 '&key=apiKey’方式拼接到waitSignParamsStr字符结尾,得到字符串waitSign。 $app_key = env('xzthird.PINWEIKEY', ''); $waitSign = $waitSignParamsStr.'&key='.$app_key; // 此时$waitSign = 'appid=WBSGTRTMR6&key=D5W7AsARzGWAiznSNKnjqeg61cU44w51' //第四步、对waitSign字符串MD5摘要,并转换为全大写。 $sign = strtoupper(md5($waitSign)); //此时$sign = '2323481C19EDAE9560705A321072EBF0'; return $sign; // unset($params['sign']); // //签名步骤一:按字典序排序数组参数 // ksort($params); // $string = toUrlParams($params); // // // //签名步骤二:在string后加入KEY // $app_key = env('xzthird.PINWEIKEY', ''); // $string = trim($string . "&key=" . $app_key); // //// $string = str_replace(' ', '', $string); // // 防止前端传数组字符串的 双引号被编码了 // $string = htmlspecialchars_decode($string); ////return $string; // //签名步骤三:MD5加密 // $string = md5($string); // //签名步骤四:所有字符转为大写 // $result = strtoupper($string); // return $result; } } /* * 前端生成签名 * */ if (!function_exists('createApiSign')) { function createApiSign (array $params): string { unset($params['sign']); //签名步骤一:按字典序排序数组参数 ksort($params); $string = toUrlParams($params); //签名步骤二:在string后加入KEY $app_key = env('api.APP_KEY'); $string = trim($string . "&key=" . $app_key); // sr_log('addKey:'.$string); // $string = str_replace(' ', '', $string); // 防止前端传数组字符串的 双引号被编码了 $string = htmlspecialchars_decode($string); // sr_log('addTrim:'.$string); //签名步骤三:MD5加密 // $string = md5($string); $string = AESjiami($string); // sr_log('sign:'.$string); //签名步骤四:所有字符转为大写 $result = strtoupper($string); return $result; } } /** * 手机验证码验证 */ if (!function_exists('sms_code_verify')) { function sms_code_verify ($param, $type = '') { /** @var \sms\Sms $sms */ $sms = app()->make(\sms\Sms::class); if (!$sms->scene($type)->check($param['mobile'], $param['code'])) { // 验证手机验证码 header('Content-Type:application/json; charset=utf-8'); echo json_encode(['msg' => $sms->getErrorMsg(), 'code' => 500, 'data' => []]); exit; } } } /** * 生成随机不重复的六位数 */ if (!function_exists('create_invite_code')) { function create_invite_code () { $count = 0; do { $d = date('his', time()).sprintf('%03d', rand(0, 99)); $count = Db::name('user')->where('code|px_code', $d)->count(); //保证生成的邀请码不会重复,查询表是否存在此邀请码 } while ($count > 0); return $d; // 生成八位英文跟字母 保证不会重复 // if (true){ // $count = 0; // do { // $code = 'ABCDEFGHJKLMNPQRSTUVWXYZ'; // $rand = $code[rand(0,23)] // .strtoupper(dechex(date('m'))) // .date('d').substr(time(),-5) // .substr(microtime(),2,5) // .sprintf('%02d',rand(0,99)); // for( // $a = md5( $rand, true ), // $s = '0123456789ABCDEFGHIJKLMNOPQRSTUV', // $d = '', // $f = 0; // $f < 8; // $g = ord( $a[ $f ] ), // $d .= $s[ ( $g ^ ord( $a[ $f + 8 ] ) ) - $g & 0x1F ], // $f++ // ); // // $count = Db::name('user')->where('code', $d)->count(); //保证生成的邀请码不会重复,查询表是否存在此邀请码 // } while ($count > 0); // // return $d; // } // 生成六位的编码 数字跟英文 // if (true){ // $v0 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; // $v1 = $v0[rand(0, 25)] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99)); // for ($v2 = md5($v1, !0), $v3 = '0123456789ABCDEFGHIJKLMNOPQRSTUV', $v4 = '', $v5 = 0; $v5 < 6; $v6 = ord($v2[$v5]), $v4 .= $v3[($v6 ^ ord($v2[$v5 + 6])) - $v6 & 31], $v5++) { // } // return $v4; // } } } /** * 获取网站的url */ function getWebUrl() { $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https' : 'http'; return $http_type.'://' . input('server.HTTP_HOST') ; } if (!function_exists('__HTTPLOCALIMG')) { function __HTTPLOCALIMG($img_path) { if (empty($img_path)){ return ''; } return getWebUrl() .'/'.$img_path; } } if (!function_exists('__HTTPIMG')) { function __HTTPIMG($img_path) { if (empty($img_path)){ return ''; } return getWebUrl() .'/'.$img_path; } } if (!function_exists('__HTTPSAVEIMGADMIN')) { function __HTTPSAVEIMGADMIN($img_path) { $arr = explode('upload/', $img_path); return 'upload/'.$arr[1]; } } if (!function_exists('__HTTPGETIMGADMIN')) { function __HTTPGETIMGADMIN($img_path) { return env('APP.API_WEB_URL').'/'.$img_path; } } // 加密 :encrypt('str','E','nowamagic'); // 解密 :encrypt('被加密过的字符串','D','nowamagic'); // 参数说明: // $string :需要加密解密的字符串 // $operation:判断是加密还是解密:E:加密 D:解密 // $key :加密的钥匙(密匙); if (!function_exists('cryption')) { function cryption($string, $operation, $key = '') { $key = md5($key); $key_length = strlen($key); $string = $operation == 'D' ? base64_decode($string) : substr(md5($string . $key), 0, 8) . $string; $string_length = strlen($string); $rndkey = $box = array(); $result = ''; for ($i = 0; $i <= 255; $i++) { $rndkey[$i] = ord($key[$i % $key_length]); $box[$i] = $i; } for ($j = $i = 0; $i < 256; $i++) { $j = ($j + $box[$i] + $rndkey[$i]) % 256; $tmp = $box[$i]; $box[$i] = $box[$j]; $box[$j] = $tmp; } for ($a = $j = $i = 0; $i < $string_length; $i++) { $a = ($a + 1) % 256; $j = ($j + $box[$a]) % 256; $tmp = $box[$a]; $box[$a] = $box[$j]; $box[$j] = $tmp; $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256])); } if ($operation == 'D') { if (substr($result, 0, 8) == substr(md5(substr($result, 8) . $key), 0, 8)) { return substr($result, 8); } else { return ''; } } else { return str_replace('=', '', base64_encode($result)); } } } /** * 删除字符串中的所有空格 */ if (!function_exists('trim_string')) { function trim_string (string $str): string { $q = array(" ", " ", "\t", "\n", "\r"); $h = array("", "", "", "", ""); return str_replace($q, $h, $str); } } /** * 获取系统配置 */ if (!function_exists('get_config')) { function get_config (int $type = 1, $name = 'default') { $key = md5("system_configs:{$type}"); if (($result = Cache($key)) === false || empty($result) || true) { $result = \think\facade\Db::name('configs')->where('type', $type)->column('value', 'name'); if (empty($result)) return null; \cache($key, $result); } if ($name != 'default') { if (!isset($result[$name])) return null; if (!is_null(json_decode($result[$name], true))) $result = json_decode($result[$name], true); else $result = $result[$name]; } else { foreach ($result as $key => $value) { if (!is_null(json_decode($result[$key], true))) $result[$key] = json_decode($result[$key], true); } } return $result; } } /** * 加密 */ if (!function_exists('encode')) { function encode ($str = '') { $spool = array( 0 => 'm047gl8f1j', 1 => 'wg3h0ca22l', 2 => 'j6oyw8kc3h', 3 => 'tods62c44i', 4 => 'c9f5aeb65v', 5 => 'kim7plty6w', 6 => 'pkneclga7z', 7 => '3kf46cxa8h', 8 => 'qo83ezx544', 9 => 'ivbondxc37', 10 => 's8pw43u2hf', 11 => '09xzmjr163', 12 => 'wbyn6ha23d', 13 => 'q7v92643jl', 14 => 'gh6jxkd4bt', 15 => 'kpo0zt156a', ); $len_mask = 'd6a45fe94c35211'; $str = $str . ''; if (empty($str)) return ''; $total_len = 16; $len = strlen($str); if ($len + 1 > $total_len) return ''; $tmp = ''; for ($i = 0; $i < $len; $i++) { $tmp .= $spool[$i][$str[$i]]; } $last_char = $str[$i - 1]; for ($i; $i < $total_len - 1; $i++) { $tmp .= $spool[$last_char][$i % 10]; } return $tmp . $len_mask[$len - 1]; } } /** * 解密 */ if (!function_exists('decode')) { function decode ($str = '') { $spool = array( 0 => 'm047gl8f1j', 1 => 'wg3h0ca22l', 2 => 'j6oyw8kc3h', 3 => 'tods62c44i', 4 => 'c9f5aeb65v', 5 => 'kim7plty6w', 6 => 'pkneclga7z', 7 => '3kf46cxa8h', 8 => 'qo83ezx544', 9 => 'ivbondxc37', 10 => 's8pw43u2hf', 11 => '09xzmjr163', 12 => 'wbyn6ha23d', 13 => 'q7v92643jl', 14 => 'gh6jxkd4bt', 15 => 'kpo0zt156a', ); $len_mask = 'd6a45fe94c35211'; $str = $str . ''; if (empty($str)) return ''; $total_len = 16; $len = strlen($str); if ($len != $total_len) return ''; $tmp = ''; $count = strpos($len_mask, substr($str, 15, 1)) + 1; for ($i = 0; $i < $count; $i++) { $tmp .= strpos($spool[$i], $str[$i]); } return $tmp; } } function sr_redislimit($uid = 0) { $redis = new \Redis(); $redis->connect('127.0.0.1', 6379); //单个用户每分钟访问数 $initNum = 1; $expire = 30; $key = $uid . '_minNum'; $redis->watch($key); $limitVal = $redis->get($key); if ($limitVal) { $limitVal = json_decode($limitVal, true); $nowtime = time(); //计算当前时刻与上次访问的时间差乘以速率就是此次可以补充的令牌个数 $newNum = min($initNum, ($limitVal['num'] - 1) + (($initNum / $expire) * ($nowtime - $limitVal['time']))); if ($newNum > 0) { $redisVal = json_encode(['num' => intval($newNum), 'time' => time()]); } else { // exit(json_encode(['status' => false, 'msg' => '当前时刻令牌消耗完!'])); $end = strval(90 - ($nowtime - $limitVal['time'])); if (intval($end) > 0){ // $message = '请'. $end.'秒后再试'; $message = '请稍后在试'; throw new \think\Exception($message); }else{ //时间已经超过90秒之后 $redisVal = json_encode(['num' => $initNum, 'time' => time()]); } } } else { //第一次访问时初始化令牌个数 $redisVal = json_encode(['num' => $initNum, 'time' => time()]); } $redis->multi(); $redis->set($key, $redisVal); $result = $redis->exec(); if (!$result) { throw new \think\Exception('请稍后在试'); // exit(json_encode(['status' => false, 'msg' => '访问频次过多!'])); } //其他操作 } function SendSmsDuanxinbao($phone,$smscode) { // 配置信息 $statusStr = array( "0" => "短信发送成功", "-1" => "参数不全", "-2" => "服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!", "30" => "密码错误", "40" => "账号不存在", "41" => "余额不足", "42" => "帐户已过期", "43" => "IP地址限制", "50" => "内容含有敏感词" ); // 18271779493 key:5f0e9ae3e0f5401ba225001af1a3cd09 // meikangjiwu key:5f0e9ae3e0f5401ba225001af1a3cd09 $smsapi = "http://api.smsbao.com/"; $user = "meikangjiwu"; //短信平台帐号 $content='您的验证码为:'.$smscode.',您正在进行身份验证,平台不会询问你的验证码请勿告诉其他人!';//要发送的短信内容 $phone = $phone;//要发送短信的手机号码 $sendurl = $smsapi."sms?u=".$user."&p=6012f5bf64d34644b0870b92fe239397"."&m=".$phone."&c=".urlencode($content); $result =file_get_contents($sendurl) ; if ($result == 0){ return 0; }else { sr_log('短信发送失败:'.$phone.json_encode($result)); // sr_testDb(json_encode(['phone'=>$phone, 'smscode'=>$smscode, 'status'=>isset($statusStr[$result])?$statusStr[$result]:'未知错误']), 2); return 1; } return 1; // require EXTEND_APP_PATH.'dayu/Dayu.php'; //获取短信配置 // f8fcf9a5c50f485c8d4b538ac3706948 $data = [ 'appkey'=>'LTAIvnKzL5PPlDeh', 'secretkey'=>'Js4YjCUyJEK6YgFWPSQAZ78gXz7rwu', 'name'=>'至亲久久', 'temp_id'=>'SMS_153445402' ]; $dayuApi = new \Dayu($data['appkey'],$data['secretkey'],$data['name'],$data['temp_id']); $backs = $dayuApi->sendSms($phone,$smscode); if($backs['Message'] =='OK'){ return 0; }else{ return 1; } } function get_real_ip() { $ip=FALSE; //客户端IP 或 NONE if(!empty($_SERVER["HTTP_CLIENT_IP"])){ $ip = $_SERVER["HTTP_CLIENT_IP"]; } //多重代理服务器下的客户端真实IP地址(可能伪造),如果没有使用代理,此字段为空 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ips = explode (", ", $_SERVER['HTTP_X_FORWARDED_FOR']); if ($ip) { array_unshift($ips, $ip); $ip = FALSE; } for ($i = 0; $i < count($ips); $i++) { if (!preg_match("^(10│172.16│192.168).", $ips[$i])) { $ip = $ips[$i]; break; } } } //客户端IP 或 (最后一个)代理服务器 IP return ($ip ? $ip : $_SERVER['REMOTE_ADDR']); } function sr_isphone($phone){ $g = "/^1[345789]\d{9}$/"; if (preg_match($g, $phone)){ return true; }else{ return false; } return false; } if (!function_exists('sr_throw')) { function sr_throw($text = '测试调试', $id=0) { $str = $text; if ($id){$str = $text + $id;} throw new \think\Exception($str); } } //if (!function_exists('redisLock')) { // function redisLock ($key, $va = 3, $msg = '请求过于频繁') // { // $redis = new \think\cache\driver\Redis(); // $check = $redis->exists($key); // if ($check) { // $redis->incr($key); // $count = $redis->get($key); // if ($count >= 10) { // $redis->del($key); // } else { // if ($count > 1) { // $result = [ // 'code' => 500, // 'msg' => '请求过于频繁', // 'data' => (object)[], // ]; // header('Content-Type:application/json; charset=utf-8'); // echo json_encode($result); // die; // } // } // // } else { // $redis->incr($key); // $redis->expire($key, $va); // } // } //} // 同一个用户在请求同一个接口 返回的code function apiPingFanCode(){ return env('api.API_PINGFAN_CODE'); } // redis 锁定 接口跟用户的key 请求 //if (!function_exists('redisLock')) { // function redisLock ($key, $msg='正在处理中') // { // $redis = new \think\cache\driver\Redis(); // if ($redis->get($key) == 1){ // if (env('app.IS_REDIS_LOCK')){ // throw new \think\Exception($msg, apiPingFanCode()); // }else{ // $redis->delete($key); // } // }else{ // $redis->set($key, '1'); // } // } //} // redis释放 接口跟用户的key //if (!function_exists('redisFree')) { // function redisFree ($key) // { // $redis = new \think\cache\driver\Redis(); // $redis->delete($key); // } //} /** * 频率控制 */ if (!function_exists('_limit_frequency')) { function _limit_frequency (string $name = 'limit_frequency_', string $sign = '', int $time = 1): bool { $key = $name . '_' . $sign; if (apc_fetch($key)) { return true; } apc_add($key, 1, $time); return false; } } // 校验系统订单 是否存在多并发问题 function getSysOrderStatusBackError(){ $sql = "select * from zy_score_log where type=5 GROUP BY create_at,score,uid HAVING count(create_at) > 1"; $res = Db::query($sql); $error_count = env('API.ORDER_ERROR_BOTH_COUNT', 20); if (count($res) > $error_count){ // 并且最后一个的type是买商品送积分 而且时间一样 而且积分一样 return true; } return false; } function edit_user_couponnum($type, $uid, $money){ return; $state = ['more', 'less', 'less', 'less', 'more', 'more'][$type-1]; $modeluser = new \app\common\model\UserModel(); $modelscorelog = new \app\common\model\CouponnumLogModel(); $info = $modeluser->where('id', $uid)->find(); if (!$info){ return; } // if ($state == 'less' && $info['coupon_num']<$money ){ // $money = $info['coupon_num']; // } if ($state == 'more'){ $modeluser->where('id', $uid)->inc('coupon_num', $money)->update(); }else{ $modeluser->where('id', $uid)->dec('coupon_num', $money)->update(); } $modelscorelog->insert([ 'uid'=>$uid, 'type'=>$type, 'score'=>$money, 'create_at'=>sr_getcurtime(time()), 'state'=>$state=='more'?1:2, 'before_score'=>$info['coupon_num'], 'after_score'=>$state=='more'?($info['coupon_num']+$money):($info['coupon_num']-$money) ]); } function edit_user_medal($type, $uid, $money, $uid2 = 0, $shouxu = 0){ $state = ['more', 'less', 'more', 'less', 'more', 'more'][$type-1]; $modeluser = new \app\common\model\UserModel(); $modelscorelog = new \app\common\model\MedalLogModel(); $info = $modeluser->where('id', $uid)->find(); if (!$info){ return; } // if ($state == 'less' && $info['medal']<$money ){ // $money = $info['medal']; // } if ($state == 'more'){ $modeluser->where('id', $uid)->inc('medal', $money)->update(); }else{ $modeluser->where('id', $uid)->dec('medal', $money)->update(); } $modelscorelog->insert([ 'uid'=>$uid, 'type'=>$type, 'money'=>$money, 'create_at'=>sr_getcurtime(time()), 'state'=>$state=='more'?1:2, 'before_money'=>$info['medal'], 'after_money'=>$state=='more'?($info['medal']+$money):($info['medal']-$money), 'uid2'=>$uid2, 'shouxu_num'=>$shouxu ]); } function edit_user_active($type, $uid, $money){ $state = ['more', 'more', 'less', 'less', 'more'][$type-1]; $modeluser = new \app\common\model\UserModel(); $modelscorelog = new \app\common\model\ActiveLogModel(); $info = $modeluser->where('id', $uid)->find(); if (!$info){ return; } // if ($state == 'less' && $info['active_me']<$money ){ // $money = $info['active_me']; // } if ($state == 'more'){ $modeluser->where('id', $uid)->inc('active_me', $money)->update(); $modeluser->where('id', $uid)->inc('total_active', $money)->update(); // 上级团队活跃点增加 if (!empty($info['path'])){ \think\facade\Db::name('user')->where('id', 'in', $info['path'])->inc('total_active', $money)->update(); } }else{ $modeluser->where('id', $uid)->dec('active_me', $money)->update(); $modeluser->where('id', $uid)->dec('total_active', $money)->update(); // 上级团队活跃点扣除 if (!empty($info['path'])){ \think\facade\Db::name('user')->where('id', 'in', $info['path'])->dec('total_active', $money)->update(); } } $after_score = number_format(($state=='more'?($info['active_me']+$money):($info['active_me']-$money)), 4, '.', ''); // sr_log('after_score'.$after_score); $modelscorelog->insert([ 'uid'=>$uid, 'type'=>$type, 'score'=>$money, 'create_at'=>sr_getcurtime(time()), 'state'=>$state=='more'?1:2, 'before_score'=>$info['active_me'], 'after_score'=>$after_score ]); } /* 你上面的方法我觉得不怎么好,介绍一下我写的一个方法。方法函数如下,这样当你要的结果001的话,方法:dispRepair('1',3,'0') 功能:补位函数 str:原字符串 type:类型,0为后补,1为前补 len:新字符串长度 msg:填补字符 */ function dispRepair($str,$len,$msg,$type='1') { $length = $len - strlen($str); if($length<1)return $str; if ($type == 1) { $str = str_repeat($msg,$length).$str; } else { $str .= str_repeat($msg,$length); } return $str; } function edit_user_scoreaway($type, $uid, $money, $id = 0, $uid2 = 0){ $state = ['more', 'less', 'less', 'more', 'more', 'more', 'less', 'less'][$type-1]; $modeluser = new \app\common\model\UserModel(); $modelscorelog = new \app\common\model\ScoreAwayLogModel(); $info = $modeluser->where('id', $uid)->find(); if (!$info){ return; } if ($state == 'more'){ $modeluser->where('id', $uid)->inc('score_away', $money)->update(); }else{ $scoreAway = $modeluser->where('id', $uid)->value('score_away'); if($money>$scoreAway){ return; } $modeluser->where('id', $uid)->dec('score_away', $money)->update(); } $modelscorelog->insert([ 'uid'=>$uid, 'type'=>$type, 'score'=>$money, 'create_at'=>sr_getcurtime(time()), 'state'=>$state=='more'?1:2, 'before_score'=>$info['score_away'], 'after_score'=>($state=='more'?($info['score_away']+$money):($info['score_away']-$money)), 'from_id'=>$id, 'uid2'=>$uid2 ]); } // 锁定积分 function edit_user_scorelock1($type, $uid, $money, $id = 0, $uid2 = 0){ $state = ['more', 'less'][$type-1]; $modeluser = new \app\common\model\UserModel(); $modelscorelog = new \app\common\model\ScoreLock1LogModel(); $info = $modeluser->where('id', $uid)->find(); if (!$info){ return; } if ($state == 'more'){ $modeluser->where('id', $uid)->inc('score_lock', $money)->update(); }else{ $modeluser->where('id', $uid)->dec('score_lock', $money)->update(); } $modelscorelog->insert([ 'uid'=>$uid, 'type'=>$type, 'score'=>$money, 'create_at'=>sr_getcurtime(time()), 'state'=>$state=='more'?1:2, 'before_score'=>$info['score_lock'], 'after_score'=>($state=='more'?($info['score_lock']+$money):($info['score_lock']-$money)), 'from_id'=>$id, 'uid2'=>$uid2 ]); } function sr_getdianLen($num){ $pos = strpos($num, '.'); $ext = substr($num, $pos+1); $len = strlen($ext); return $len; } function sr_isdouble_xiaoshu($num) { if (is_float($num)){ if (preg_match('/^[0-9]+(.[0-9]{2})$/', $num)) { return true; }else{ return false; } } if (is_int($num)){ return true; } return false; } function removeEmojiChar($str){$mbLen = mb_strlen($str); $strArr = []; for ($i = 0; $i < $mbLen; $i++) { $mbSubstr = mb_substr($str, $i, 1, 'utf-8'); if (strlen($mbSubstr) >= 4) { continue; } $strArr[] = $mbSubstr; } return implode('', $strArr);} function edit_user_score($type, $uid, $money, $id = 0, $uid2 = 0){ $state = ['less', 'more', 'more', 'less'][$type-1]; $modeluser = new \app\common\model\UserModel(); $modelscorelog = new \app\common\model\ScoreLogModel(); $info = $modeluser->where('id', $uid)->find(); if (!$info || $money<=0){ return; } // if ($state == 'less' && $info['score']<$money ){ // $money = $info['score']; // } // 平级收益 10% // if ($state == 'more' && in_array($type, [9, 11])){ // $piduserinfo = $modeluser->where('id', $info['pid'])->where('is_auth', 1)->field('score, id,pid,is_auth,level')->find(); // if ($piduserinfo && $piduserinfo['level'] > 0 && $piduserinfo['level'] == $info['level']){ // $pj_score = number_format($money * env('coupon.COUPON_PINGJI_SCALE', 0)/100, 4, '.', ''); // if ($pj_score > 0){ // $modeluser->where('id', $info['pid'])->inc('score', $pj_score)->update(); // $modelscorelog->insert([ // 'uid'=>$info['pid'], // 'type'=>10, // 'score'=>$pj_score, // 'create_at'=>sr_getcurtime(time()), // 'state'=>$state=='more'?1:2, // 'before_score'=>$piduserinfo['score'], // 'after_score'=>$state=='more'?($piduserinfo['score']+$pj_score):($piduserinfo['score']-$pj_score), // 'from_id'=>0 // ]); // } // // } // } if ($money <= 0){ return; } if ($state == 'more'){ $modeluser->where('id', $uid)->inc('score', $money)->update(); }else{ $score = $modeluser->where('id', $uid)->value('score'); if($money>$score){ return; } $modeluser->where('id', $uid)->dec('score', $money)->update(); } $modelscorelog->insert([ 'uid'=>$uid, 'type'=>$type, 'score'=>$money, 'create_at'=>sr_getcurtime(time()), 'state'=>$state=='more'?1:2, 'before_score'=>$info['score'], 'after_score'=>$state=='more'?($info['score']+$money):($info['score']-$money), 'from_id'=>$id, 'uid2'=>$uid2 ]); } function edit_user_recyclecard($type, $uid, $money, $id = 0, $uid2 = 0){ $state = ['more', 'more', 'less', 'more'][$type-1]; $modeluser = new \app\common\model\UserModel(); $modelscorelog = new \app\common\model\RecyclecardLogModel(); $info = $modeluser->where('id', $uid)->find(); if (!$info || $money<=0){ return; } if ($money <= 0){ return; } if ($state == 'more'){ $modeluser->where('id', $uid)->inc('recycle_count', $money)->update(); }else{ $recycleCount = isset($info['recycle_count'])? intval($info['recycle_count']) : 0; if($recycleCount<$money){ return; } $modeluser->where('id', $uid)->dec('recycle_count', $money)->update(); } $modelscorelog->insert([ 'uid'=>$uid, 'type'=>$type, 'score'=>$money, 'create_at'=>sr_getcurtime(time()), 'state'=>$state=='more'?1:2, 'before_score'=>$info['recycle_count'], 'after_score'=>$state=='more'?($info['recycle_count']+$money):($info['recycle_count']-$money), 'from_id'=>$id, 'uid2'=>$uid2 ]); } function edit_user_tz($type, $uid, $money, $id = 0, $uid2 = 0){ $state = ['more', 'more', 'less', 'less', 'less', 'more', 'more', 'less', 'more', 'more','less', 'more', 'more', 'more'][$type-1]; $modeluser = new \app\common\model\UserModel(); $modelscorelog = new \app\common\model\TzLogModel(); $info = $modeluser->where('id', $uid)->find(); if (!$info){ return; } if ($money <= 0){ return; } if ($state == 'more'){ $modeluser->where('id', $uid)->inc('tz_num', $money)->update(); }else{ $modeluser->where('id', $uid)->dec('tz_num', $money)->update(); } $modelscorelog->insert([ 'uid'=>$uid, 'type'=>$type, 'score'=>$money, 'create_at'=>sr_getcurtime(time()), 'state'=>$state=='more'?1:2, 'before_score'=>$info['tz_num'], 'after_score'=>$state=='more'?($info['tz_num']+$money):($info['tz_num']-$money), 'from_id'=>$id, 'uid2'=>$uid2 ]); } function get_user_excharge_scale($uid){ $scale = 50; $user_info = \think\facade\Db::name('user')->where('id', $uid)->field('id, active_me,xz_type')->find(); if ($user_info['xz_type'] === 2){ return 0; } if ($user_info['active_me'] >=10 && $user_info['active_me'] <=49){ $scale = 35; } if ($user_info['active_me'] >=50 && $user_info['active_me'] <=99){ $scale = 30; } if ($user_info['active_me'] >=100 && $user_info['active_me'] <=499){ $scale = 28; } if ($user_info['active_me'] >=500){ $scale = 25; } $count = \think\facade\Db::name('user')->where('pid', $uid)->where('is_auth', 1)->count('id'); if ($count){ if ($scale > 35 && $count >= 3 && $count <= 10){ $scale = 35; } if ($scale > 30 && $count >= 11 && $count <= 30){ $scale = 30; } if ($scale > 28 && $count >= 31 && $count <= 99){ $scale = 28; } if ($scale > 25 && $count >= 100){ $scale = 25; } } return $scale; } function edit_user_renwusocre($type, $uid, $money){ $state = ['more', 'less'][$type-1]; $modeluser = new \app\common\model\UserModel(); $modelscorelog = new \app\common\model\RenwuscoreLogModel(); $info = $modeluser->where('id', $uid)->find(); if (!$info){ return; } // if ($state == 'less' && $info['renwu_score']<$money ){ // $money = $info['renwu_score']; // } if ($state == 'more'){ $modeluser->where('id', $uid)->inc('renwu_score', $money)->update(); }else{ $modeluser->where('id', $uid)->dec('renwu_score', $money)->update(); } $modelscorelog->insert([ 'uid'=>$uid, 'type'=>$type, 'score'=>$money, 'create_at'=>sr_getcurtime(time()), 'state'=>$state=='more'?1:2, 'before_score'=>$info['renwu_score'], 'after_score'=>$state=='more'?($info['renwu_score']+$money):($info['renwu_score']-$money) ]); } // cur_money 星钻价格 price 价值金额 function getXzPirceWithPrice($cur_money,$price){ // $cur_money = sysconfig('xzconfig', 'xz_cur_money'); // $cur_money = Db::name('system_config')->where('name', 'xz_cur_money')->where('group', 'xzconfig')->value('value'); return number_format(floatval($price)/$cur_money, 2, '.', ''); } function getUserDeny(\app\Request $request){ // if ($request->param('app_sources') == 'android'){ // 16号全天 // if (time() > 1655308800 && time() < 1655395200){ // 17号18号 两天 if (time() > 1655395201 && time() < 1655568000){ $tokenkey = $request->header('tokenkey', ''); if ($tokenkey != 'mkjw2022'){ if (!Db::name('deny_user')->where('uid', $request->uid)->find()){ Db::name('deny_user')->insert([ 'uid'=>$request->uid, 'create_time'=>sr_getcurtime(time()), 'reason'=>'刷机养号', 'sources'=>$request->param('app_sources'), 'ip'=>$request->ip(), 'req_header'=>json_encode($request->header()), 'req_body'=>($request->pathinfo().json_encode($request->param())) ]); } } }else{ $tokenkey = $request->header('tokenkey', ''); if (!empty($tokenkey)){ if (!Db::name('deny_user')->where('uid', $request->uid)->find()){ Db::name('deny_user')->insert([ 'uid'=>$request->uid, 'create_time'=>sr_getcurtime(time()), 'reason'=>'刷机养号', 'sources'=>$request->param('app_sources'), 'ip'=>$request->ip(), 'req_header'=>json_encode($request->header()), 'req_body'=>($request->pathinfo().json_encode($request->param())), 'type'=>3 ]); } } } // } } function edit_user_xz($type, $uid, $money, $uid2 = 0, $shouxu = 0){ $state = ['less', 'less', 'more', 'more', 'less', 'more', 'more', 'more', 'less', 'less', 'more', 'more','less','less','more', 'less', 'less', 'more', 'more'][$type-1]; $modeluser = new \app\common\model\UserModel(); $modelscorelog = new \app\common\model\XzLogModel(); $info = $modeluser->where('id', $uid)->find(); if (!$info){ return; } // if ($state == 'less' && $info['xz_num']<$money ){ // $money = $info['xz_num']; // } if ($state == 'more'){ $modeluser->where('id', $uid)->inc('xz_num', $money)->update(); }else{ $modeluser->where('id', $uid)->dec('xz_num', $money)->update(); } $modelscorelog->insert([ 'uid'=>$uid, 'type'=>$type, 'score'=>$money, 'create_at'=>sr_getcurtime(time()), 'state'=>($state=='more'?1:2), 'before_score'=>$info['xz_num'], 'after_score'=>($state=='more'?($info['xz_num']+$money):($info['xz_num']-$money)), 'uid2'=>$uid2, 'shouxu_num'=>$shouxu ]); } // 获得用户手续费 返回 50,代表 50%,返回 25 代表 25% function get_user_shouxufei($uid){ $user = Db::name('user')->where('id', $uid)->field('id,active_me')->find(); $zt_num = Db::name('user')->where('pid', $uid)->where('is_auth', 1)->count('id'); if (!$user){ return 50; } //直推 0-2 50 // 3-10 35 // 11-30 30 // 31-99 28 // >=100 25 $zt_scale = 50; if ($zt_num >= 100){ $zt_scale = 25; }elseif ($zt_num > 30 && $zt_num < 100){ $zt_scale = 28; }elseif ($zt_num > 10 && $zt_num < 31){ $zt_scale = 30; }elseif ($zt_num > 2 && $zt_num < 11){ $zt_scale = 35; }elseif ($zt_num >= 0 && $zt_num < 3){ $zt_scale = 50; } //个人活跃度 // 1-9 50 // 10-49 35 // 50-99 30 // 100-499 28 // >=500 25 $active_scale = 50; if ($user['active_me'] >= 500){ $active_scale = 25; }elseif ($user['active_me'] > 99 && $user['active_me'] < 500){ $active_scale = 28; }elseif ($user['active_me'] > 49 && $user['active_me'] < 100){ $active_scale = 30; }elseif ($user['active_me'] > 9 && $user['active_me'] < 50){ $active_scale = 35; }elseif ($user['active_me'] >= 0 && $user['active_me'] < 10){ $active_scale = 50; } return ($zt_scale<$active_scale?$zt_scale:$active_scale); } // 编辑用户红包积分 function edit_user_redscore($type, $uid, $money){ $state = ['more', 'less'][$type-1]; $modeluser = new \app\common\model\UserModel(); $modelscorelog = new \app\common\model\RedScoreLogModel(); $info = $modeluser->where('id', $uid)->find(); if (!$info){ throw new \think\Exception('用户查询失败'); } // if ($state == 'less' && $info['red_score']<$money ){ // $money = $info['red_score']; // } if ($state == 'more'){ $modeluser->where('id', $uid)->inc('red_score', $money)->update(); }else{ $modeluser->where('id', $uid)->dec('red_score', $money)->update(); } $modelscorelog->insert([ 'uid'=>$uid, 'type'=>$type, 'score'=>$money, 'create_at'=>sr_getcurtime(time()), 'state'=>$state=='more'?1:2, 'before_score'=>$info['red_score'], 'after_score'=>$state=='more'?($info['red_score']+$money):($info['red_score']-$money) ]); } /** * 获取随机字符串 */ if (!function_exists('nonce_str')) { function nonce_str (int $length = 20) { return substr(md5(microtime(true) . mt_rand(1, 1e9)), 5, $length); } } // type =1欢迎注册 2 香好友转赠余额 3 购买商城商品 4收到好友转赠余额 5向好友转赠jh 6收到好友的jh function addUserMessage($uid, $type, $title, $desc){ Db::name('user_message')->insert([ 'uid'=>$uid, 'title'=>$title, 'type'=>$type, 'banner_desc'=>$desc, 'create_time'=>sr_getcurtime(time()) ]); } function str_is_int($str) { return 0 === strcmp($str , (int)$str); } function edit_user_money($type, $uid, $money, $id = 0, $uid2 = 0, $free_type = ''){ $state = ['less', 'more', 'more', 'none', 'none', 'more', 'none', 'more', 'less', 'more', 'less', 'more', 'more', 'less'][$type-1]; $modeluser = new \app\common\model\UserModel(); $modelscorelog = new \app\common\model\MoneyLogModel(); $info = $modeluser->where('id', $uid)->find(); if (!$info){ return; } if ($money <= 0){ return; } if ($state == 'more'){ $res = $modeluser->where('id', $uid)->inc('money', $money)->update(); } if ($state == 'less'){ $userMoney = $modeluser->where('id', $uid)->value('money'); if($money>$userMoney){ return; } $res = $modeluser->where('id', $uid)->dec('money', $money)->update(); } if ($state == 'none'){ $res = false; // $res = $modeluser->where('id', $uid)->dec('money', $money)->update(); } $modelscorelog->insert([ 'uid'=>$uid, 'type'=>$type, 'money'=>$money, 'create_at'=>sr_getcurtime(time()), 'state'=>$state=='none'?0:($state=='more'?1:2), 'before_money'=>$info['money'], 'after_money'=>($state=='none'?$info['money']:($state=='more'?($info['money']+$money):($info['money']-$money))), 'from_id'=>$id, 'uid2'=>$uid2, 'free_type'=>$free_type ]); return $res; } // 购物券 function edit_user_lock_score($type, $uid, $money){ $state = ['more', 'less', 'more'][$type-1]; $modeluser = new \app\common\model\UserModel(); $modelscorelog = new \app\common\model\ScorelockLogModel(); $info = $modeluser->where('id', $uid)->find(); if (!$info){ return; } // if ($state == 'less' && $info['lock_score']<$money ){ // $money = $info['lock_score']; // } if ($state == 'more'){ $modeluser->where('id', $uid)->inc('lock_score', $money)->update(); }else{ $modeluser->where('id', $uid)->dec('lock_score', $money)->update(); } $modelscorelog->insert([ 'uid'=>$uid, 'type'=>$type, 'score'=>$money, 'create_at'=>sr_getcurtime(time()), 'state'=>$state=='more'?1:2, 'before_score'=>$info['lock_score'], 'after_score'=>$state=='more'?($info['lock_score']+$money):($info['lock_score']-$money) ]); } //增加团队静态数据 uid 当前产生的uid type 1 粉丝量 2有效粉丝量 用户的path if (!function_exists('incTeamStatic')) { function incTeamStatic (int $uid, int $type = 1, string $path = '', int $inc = 1) { switch ($type) { case 1: $field = 'total_number'; break; case 2: $field = 'total_number_real'; break; default: throw new \think\Exception('系统错误~'); } if (empty($path)) $path = \think\facade\Db::name('user')->where('id', $uid)->value('path'); \think\facade\Db::name('user')->where('id', 'in', $path)->inc($field, $inc)->update(); } } //增加团队今天静态数据 uid 当前产生的uid type 1 粉丝量 2有效粉丝量 用户的path if (!function_exists('incTodayTeamStatic')) { function incTodayTeamStatic (int $uid, int $type = 1, string $path = '', int $inc = 1) { if ($type == 1){ return; } switch ($type) { case 1: $field = 'total_number'; break; case 2: $field = 'today_number_real'; break; default: throw new \think\Exception('系统错误~'); } if (empty($path)) $path = \think\facade\Db::name('user')->where('id', $uid)->value('path'); \think\facade\Db::name('user')->where('id', 'in', $path)->inc($field, $inc)->update(); // $arr = explode(',', $path); // foreach ($arr as $key=>$val){ // \think\facade\Db::name('userteam_log')->insert([ // 'uid'=>$val, // 'create_time'=>sr_getcurtime(time()), // 'day'=>sr_getcurtime(time(), 'Y-m-d'), // 'num'=>$inc, // 'type'=>1 // ]); // } } } //增加用户业绩 if (!function_exists('incUserPerformance')) { function incUserPerformance (int $uid, $money) { $path = \think\facade\Db::name('user')->where('id', $uid)->value('path'); \think\facade\Db::name('user')->where('id', $uid)->inc('performance_me', $money)->inc('total_performance', $money)->update(); if (!empty($path)){ \think\facade\Db::name('user')->where('id', 'in', $path)->inc('total_performance', $money)->update(); } } } ////增加用户活跃度 //if (!function_exists('incUserActive')) { // // type 对于type。php里面的类型 // function incUserActive (int $uid, $active, $type) // { // $path = \think\facade\Db::name('user')->where('id', $uid)->value('path'); //// \think\facade\Db::name('user')->where('id', $uid)->inc('active_me', $active)->update(); // edit_user_active($type, $uid, $active); // if (!empty($path)){ // \think\facade\Db::name('user')->where('id', 'in', $path)->inc('total_active', $active)->update(); // } // // } //} function putArr($arr){ $out = '['; foreach ($arr as $key=>$value){ $out .= ($value.','); } $out = $out . ']'; return $out; } // 领取奖励 0获取星钻奖励 1参加众筹 2提现申请 3分红任务包领取 4话费兑换 5电费兑换 6奖金领取 function getActionBefore($type){ $time_arr = [['02:00',"23:55"],['08:00',"22:00"],['10:00',"18:00"], ['02:00',"23:55"], ['08:00',"18:00"], ['08:00',"18:00"], ['22:00','23:30']]; $Day = date('Y-m-d ',time()); $timeBegin = strtotime($Day.$time_arr[$type][0].":00"); $timeEnd = strtotime($Day.$time_arr[$type][1].":00"); $curr_time = time(); if($curr_time >= $timeBegin && $curr_time <= $timeEnd){ return; } throw new \think\Exception(('暂未开放,开放时间每天'.$time_arr[$type][0].'到'.$time_arr[$type][1])); } // 极光推送 //isall 是否广播 function JPushServicePushOneMsg($isall, $reg_id, $message, $extral){ if (empty($reg_id)){ return; } $receiver['registration_id'] = $isall?'all':[ $reg_id ];//指定用户 //$receiver='all';//全部 $title = '云德商城'; $content = $message; //发送类 return push($receiver,$content,$title, $extral); // $client = new JPush(env('APP.JPUSHAPPKEY'), env('APP.JPUSHAPPKEYMasterSecret')); // $client->push() // ->setPlatform('all') // ->addAlias($udid) // ->setNotificationAlert('hello,push') // ->send(); // $client->push() // ->setPlatform('all') // ->addAllAudience() // ->setNotificationAlert('Hello, JPush') // ->send(); // $udid = 'c4a971fb86c1ab2354e281cc256d31be325d78ab'; // $push = $client->push(); // $push->setPlatform('all'); // $push->addTag('ac986491e02f03aee20815c50abfda618087e07d'); // $push->addAlias('59572f480ed999abf6430f20de56a375d65ac388'); // $pusher = $client->push(); // $pusher->setPlatform('all'); // $pusher->addAllAudience(); // $pusher->setNotificationAlert('你好,你有'); // $pusher->custom(['extras'=>['type'=>2,'yg_id'=>333]]); // $pusher->options(['type'=>2,'yg_id'=>333]); // $pusher->addAlias($udid); // try { // $pusher->send(); // } catch (\JPush\Exceptions\JPushException $e) { // // try something else here // print $e; // return $e->getMessage(); // } } #发送类 function push($receiver='all',$content='',$title='',$extras=array(),$m_time= 86400 ){ $app_key = env('APP.JPUSHAPPKEY'); $master_secret = env('APP.JPUSHAPPKEYMasterSecret'); $url = "https://api.jpush.cn/v3/push"; $base64 = base64_encode("{$app_key}:{$master_secret}"); $header = array("Authorization:Basic {$base64}","Content-Type:application/json"); $data = array(); // $data['platform'] = 'android'; //目标用户终端手机的平台类型android,ios,winphone $data['platform'] = 'all'; //目标用户终端手机的平台类型android,ios,winphone $data['audience'] = $receiver; //目标用户 // print_r($data);exit; $data['notification'] = array( //统一的模式--标准模式 "alert"=>$content, //安卓自定义 "android"=>array( "alert"=>$content, "title"=>$title, "builder_id"=>1, "extras"=>array("data"=>$extras) ), //ios的自定义 "ios"=>array( "alert"=>$content, "badge" => "1", "sound" => "default", "content-available" => true, "extras" => array("data" => $extras) ), ); //附加选项 $data['options'] = array( "sendno"=>time(), "time_to_live"=>$m_time, //保存离线时间的秒数默认为一天 "apns_production"=>false, //指定 APNS 通知发送环境:0开发环境,1生产环境。 ); $param = json_encode($data); //dump($param);exit; $res = push_curl($param,$header,$url); sr_log(json_encode($res)); if($res){ //得到返回值--成功已否后面判断 sr_log(json_encode($res)); return $res; }else{ //未得到返回值--返回失败 sr_log('fasle'); return false; } } function time2string($second){ $day = floor($second/(3600*24)); $second = $second%(3600*24); // 除去整天之后剩余的时间 $hour = floor($second/3600); $second = $second%3600;//除去整小时之后剩余的时间 $minute = floor($second/60); $second = $second%60; //除去整分钟之后剩余的时间 //返回字串 return $day.'天'.$hour.'小时'.$minute.'分'.$second.'秒'; } //推送的Curl方法 function push_curl($param="",$header="",$url="") { if (empty($param)) { return false; } $postUrl = $url; $curlPost = $param; $ch = curl_init(); //初始化curl curl_setopt($ch, CURLOPT_URL,$postUrl); //抓取指定网页 curl_setopt($ch, CURLOPT_HEADER, 0); //设置header curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上 curl_setopt($ch, CURLOPT_POST, 1); //post提交方式 curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost); curl_setopt($ch, CURLOPT_HTTPHEADER,$header); // 增加 HTTP Header(头)里的字段 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 终止从服务端进行验证 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); $data = curl_exec($ch); //运行curl curl_close($ch); return $data; } // 是否可以做任务时间段 return true可以 return false 不可以 function getServiceTop(){ $time_arr = env('app.NOT_GET_XINGZUAN_TIME', []); $time_arr1 = explode('|', $time_arr); foreach ($time_arr1 as $key=>$val){ $time_days = explode('-', $val); $Day = date('Y-m-d ',time()); $timeBegin = strtotime($Day.$time_days[0].":00"); $timeEnd = strtotime($Day.$time_days[1].":00"); $curr_time = time(); if($curr_time >= $timeBegin && $curr_time <= $timeEnd){ return false; } } return true; } function getActionSecury($uid, $security_pass){ $user = Db::name('user')->where('id', $uid)->field('id,pay_pass')->find(); if ($user){ if (empty($user['pay_pass'])){ throw new \think\Exception('还未设置安全密码或安全密码错误', 500); } if (md5($security_pass) != $user['pay_pass']){ throw new \think\Exception('安全密码错误', 500); } }else{ throw new \think\Exception('用户信息错误'); } } // 判断时间是否交叉 true|没有交叉 false|交叉 function compareDate($arr): bool { array_multisort(array_column($arr, 'start_time'), SORT_ASC, $arr); foreach ($arr as $k => $v){ if ($v['start_time'] >= $v['end_time']) return false; if ($k > 0 && $arr[$k]['start_time'] < $arr[$k-1]['end_time']) return false; } return true; } if (!function_exists('createdGoodsSn')) { function createdGoodsSn () { return '6' . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))) . str_pad(mt_rand(1, 9999999), 7, '0', STR_PAD_LEFT), 0, 11); } } if (!function_exists('creathfOrderSn')) { function creathfOrderSn ($uid) { return 'HF'.$uid. substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))) . str_pad(mt_rand(1, 9999999), 7, '0', STR_PAD_LEFT), 0, 11); } } if (!function_exists('createdOrderWithdrawSn')) { function createdOrderWithdrawSn ($uid) { return 'WD'.$uid. substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))) . str_pad(mt_rand(1, 9999999), 7, '0', STR_PAD_LEFT), 0, 11); } } /** * curl POST * * @param string url * @param array 数据 * @param int 请求超时时间 * @param bool HTTPS时是否进行严格认证 * @return string */ function curlPost($url, $data = array(), $timeout = 30, $CA = true) { // $cacert = ROOT_PATH . '/Epay/cacert.pem'; //CA根证书 // $SSL = substr($url, 0, 8) == "https://" ? true : false; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout - 2); // if ($SSL && $CA) { // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); // 只信任CA颁布的证书 // curl_setopt($ch, CURLOPT_CAINFO, $cacert); // CA根证书(用来验证的网站证书是否是CA颁布) // curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 检查证书中是否设置域名,并且是否与提供的主机名匹配 // } else if ($SSL && !$CA) { // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书 // curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1); // 检查证书中是否设置域名 // } curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:')); //避免data数据过长问题 curl_setopt($ch, CURLOPT_POST, true); // curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); //data with URLEncode $ret = curl_exec($ch); // var_dump(curl_error($ch)); //查看报错信息 curl_close($ch); return $ret; } if (!function_exists('creatBankSignOrderSn')) { function creatBankSignOrderSn ($uid) { return 'signbank'.$uid. substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))) . str_pad(mt_rand(1, 9999999), 7, '0', STR_PAD_LEFT), 0, 11); } } if (!function_exists('creatJhOrderSn')) { function creatJhOrderSn ($uid) { return 'JH'.$uid. substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))) . str_pad(mt_rand(1, 9999999), 7, '0', STR_PAD_LEFT), 0, 11); } } if (!function_exists('getUserPayWay')) { function getUserPayWay ($uid) { return Db::name('user_data')->where('uid', $uid)->field('wx_img,wx_pay,wx_pay_name,ali_img,ali_pay,ali_pay_name,bank_no,bank_subname')->withAttr('wx_img', function ($val, $data){ return empty($val)?'':getWebUrl().'/'.$val; })->withAttr('ali_img', function ($val, $data){ return empty($val)?'':getWebUrl().'/'.$val; })->find(); } } if (!function_exists('createdMachineID')) { function createdMachineID () { return 'MA-' . md5('4dr'.substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))) . str_pad(mt_rand(1, 9999999), 7, '0', STR_PAD_LEFT), 0, 11).'DF'); } } if (!function_exists('multi_minmax_inarray')) { function multi_minmax_inarray ($arr, $key) { $disArr = array(); foreach ($arr as $value) { $disArr[] = floatval($value[$key]); } sort($disArr); $resArr = !empty($disArr) ? array($disArr[0], $disArr[count($disArr) - 1]) : array(10, 10); unset($disArr); return ['min' => $resArr[0], 'max' => $resArr[1]]; } } if (!function_exists('multi_array_sum')) { function multi_array_sum ($arr, $key) { if ($arr) { $sum_no = 0; foreach ($arr as $v) { $sum_no += $v[$key]; } return $sum_no; } else { return 0; } } } // 验证用户是否需要验证码登录 return true 需要 ,return false 不需要 function checkUserNeedsSecuritLogin($uid){ // if (in_array($uid, [7493266, 7493267, 7493487])){ // // } return false; $start = date('Y-m-d H:i:s',mktime(0,0,0,date('m'),date('d'),date('Y'))); $w = date('w',strtotime($start)); // $last_week_mon = date('Y-m-d H:i:s',mktime(0,0,0,date('m'),date('d')-$w+1-7,date('Y'))); $old_start = date('Y-m-d H:i:s',mktime(0,0,0,date('m'),date('d')-7,date('Y'))); $end_time = date('Y-m-d H:i:s',mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1); // 用户在上一周的抢购数据总和 $buy_num = Db::name('coupon_plan_log')->where('uid', $uid)->where('create_time', '>', $old_start)->sum('buy_num'); if ($buy_num < 1000){ return true; } return false; } function sr_hidtel($phone){ $IsWhat = preg_match('/(0[0-9]{2,3}[\-]?[2-9][0-9]{6,7}[\-]?[0-9]?)/i',$phone); //固定电话 if($IsWhat == 1){ return preg_replace('/(0[0-9]{2,3}[\-]?[2-9])[0-9]{3,4}([0-9]{3}[\-]?[0-9]?)/i','$1****$2',$phone); }else{ return preg_replace('/(1[358]{1}[0-9])[0-9]{4}([0-9]{4})/i','$1****$2',$phone); } } /** * 打印log日志 * @param 文件名 第几行 日志内容 */ function sr_log($msg=null){ if(is_array($msg)){ $msg = json_encode($msg,JSON_UNESCAPED_UNICODE); } $msg = '['.date("Y-m-d H:i:s").']'.'日志内容:'.$msg; $rootpath = ROOT_PATH.DS.'runtime'. DS .'sr_logs'. DS; makedir($rootpath); // 日志文件名:日期.txt $path = $rootpath.date("Ymd").'.txt'; file_put_contents($path, $msg.PHP_EOL,FILE_APPEND); } /** * [makedir 迭代创建级联目录] * @param [type] $path [目录路径] * @return [type] [Boolean] */ function makedir($path){ $arr=array(); while(!is_dir($path)){ array_push($arr,$path);//把路径中的各级父目录压入到数组中去,直接有父目录存在为止(即上面一行is_dir判断出来有目录,条件为假退出while循环) $path=dirname($path);//父目录 } if(empty($arr)){//arr为空证明上面的while循环没有执行,即目录已经存在 // echo $path,'已经存在'; return true; } while(count($arr)){ $parentdir=array_pop($arr);//弹出最后一个数组单元 mkdir($parentdir);//从父目录往下创建 } } function sr_testDb($msg , $type = 1){ \think\facade\Db::name('test')->insert(['msg'=>$msg, 'type'=>$type, 'time'=>sr_getcurtime(time())]); } function sr_getLastSql(){ return \think\facade\Db::getLastSql(); } /** * 图片地址替换 */ if (!function_exists('imageSrcReplace')) { function imageSrcReplace ($str) { $pattern = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png|\.jpeg]))[\'|\"].*?[\/]?>/i"; $content = preg_replace_callback($pattern, function ($ma) { $src = env('qiniu.domain') . $ma[1]; return str_replace($ma[1], $src, $ma[0]); }, $str); return $content; } } function sr_imgcodeconfig(){ return [ 'fontSize'=>40, 'codeSet'=>'0123456789', 'useCurve'=>true, 'useNoise'=>false ]; } /* * 生成签名 * @param array $args 数据 * @param string $key 私钥 */ function thirdPayGetSign($args, $key){ if(isset($args['sign'])) { unset($args['sign']); } ksort($args); $requestString = ''; foreach($args as $k => $v) { if($v==null || $v==''){ continue; } $requestString .= $k . '=' . urlencode($v).'&'; } $requestString .= 'key=' . $key; $newSign=strtoupper(md5($requestString)); return $newSign; } /** * 验证签名 * @param array $args 数据 * @param string $key 私钥 */ function thirdPayCheckSign($args, $key){ $sign = strtolower($args['sign']); $tenpaySign=strtolower(getSign($args,$key)); return $sign == $tenpaySign; } /* * 生成签名 畅联 * @param array $args 数据 * @param string $key 私钥 */ function thirdPayGetSignCL($secret, $data) { // 去空 $data = array_filter($data); //签名步骤一:按字典序排序参数 ksort($data); if (isset($data['pay_type'])){ if($data['pay_type']=='AliRoyalty'){ foreach ($data['royalty_parameters'] as $k=>$v){ ksort($data['royalty_parameters'][$k]); } } } // var_dump($data); $string_a = http_build_query($data); $string_a = urldecode($string_a); //签名步骤二:在string后加入mch_key $string_sign_temp = $string_a . "&key=" . $secret; // var_dump($string_sign_temp); //签名步骤三:MD5加密 $sign = md5($string_sign_temp); // 签名步骤四:所有字符转为大写 $result = strtoupper($sign); // var_dump($result); return $result; } /** * 验证签名 畅联 * @param array $args 数据 * @param string $key 私钥 */ function thirdPayCheckSignCL($data, $secret) { // 验证参数中是否有签名 if (!isset($data['sign']) || !$data['sign']) { return false; } // 要验证的签名串 $sign = $data['sign']; unset($data['sign']); // 生成新的签名、验证传过来的签名 $sign2 = thirdPayGetSignCL($secret, $data); return $sign2; } // 验证图形验证码 function sr_captcha_check($vercode, $uuid){ $text = CacheServices::get('catch'.$uuid); if (strtoupper($text) == strtoupper($vercode)){ CacheServices::set('catch'.$uuid, ''); return true; } return false; } if (!function_exists('createdOrderSn')) { function createdOrderSn () { return date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999)); } } if (!function_exists('createUserNickname')) { function createUserNickname () { return 'duobao'.date('His', time()) . rand(0, 999); } } if (!function_exists('createdHandleOrderSn')) { function createdHandleOrderSn () { return 'h'.date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999)); } } if (!function_exists('createdFDOrderSn')) { function createdFDOrderSn () { return 'fd-'.date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999)); } } if (!function_exists('createdRechargeOrderSn')) { function createdRechargeOrderSn () { return date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999)); } } if (!function_exists('getExportHeader')) { function getExportHeader ($name,$noExportFields) { $tableName = $name; $tableName = CommonTool::humpToLine(lcfirst($tableName)); $prefix = config('database.connections.mysql.prefix'); $dbList = Db::query("show full columns from {$prefix}{$tableName}"); $header = []; foreach ($dbList as $vo) { $comment = !empty($vo['Comment']) ? $vo['Comment'] : $vo['Field']; if (!in_array($vo['Field'], $noExportFields)) { $header[] = [$comment, $vo['Field']]; } } return $header; } } /** * RSA数据加密解密 * @param type $data * @param type $type encode加密 decode解密 */ function RSA_openssl($data,$type='encode'){ if (empty($data)) { return 'data参数不能为空'; } if (is_array($data)) { return 'data参数不能是数组形式'; } $rsa = new RsaClient(); // 生成的私钥 $privatePEMKey = env('api.PAY_FUYOU_PRIVATE_KEY'); // 生成的公钥 $publicPEMKey = env('api.PAY_FUYOU_PUBLIC_KEY'); $rsa->rsaPublicKey =$publicPEMKey; $rsa->rsaPrivateKey = $privatePEMKey; //私钥解密 if ($type=='decode') { $decrypted = $rsa->privateDecryptRsa($data); sr_log('4444444444'.'---'.$decrypted); return $decrypted; } //公钥加密 if ($type=='encode') { $decrypted = $rsa->publicEncryptRsa($data); return $decrypted; } }