Commit 062ac947 by mushishixian

优化

parent fbf63ae9
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
\ No newline at end of file
...@@ -36,7 +36,7 @@ class CheckLogin ...@@ -36,7 +36,7 @@ class CheckLogin
$cookie = 'oa_user_id=' . $userId . '; oa_skey=' . $skey; $cookie = 'oa_user_id=' . $userId . '; oa_skey=' . $skey;
$rsp=curls($login['check'],'',false,false,$cookie); $rsp=curl($login['check'],'',false,false,$cookie);
if (!$rsp) { if (!$rsp) {
......
<?php <?php
function apiReturn($errcode=0,$errmsg='ok',$datas=[]){ function apiReturn($errCode = 0, $errMsg = 'ok', $data = [])
{
$data = [ $data = [
'errcode' => $errcode, 'err_code' => $errCode,
'errmsg' => $errmsg, 'err_msg' => $errMsg,
'code' => $errcode, 'code' => $errCode,
'msg' => $errmsg, 'msg' => $errMsg,
]; ];
if(!empty($datas['total'])){ if (!empty($data['total'])) {
$data['count'] = $datas['total']; $data['count'] = $data['total'];
} }
if(!empty($datas)){ if (!empty($data)) {
foreach ($datas as $k=>$v){ foreach ($data as $k => $v) {
$data[$k] = $v; $data[$k] = $v;
} }
} }
return response()->json($data,200); return response()->json($data, 200);
} }
function curls($url, $params = false, $ispost = 0, $https = 0,$cookie='',$timeout=1000) function curl($url, $params = false, $isPost = 0, $https = 0, $cookie = '', $timeout = 1000)
{ {
$httpInfo = array();
$ch = curl_init(); $ch = curl_init();
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36'); curl_setopt($ch, CURLOPT_USERAGENT,
'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch,CURLOPT_REFERER,Config('website.data')); curl_setopt($ch, CURLOPT_REFERER, Config('website.data'));
curl_setopt($ch, CURLOPT_COOKIE, $cookie); curl_setopt($ch, CURLOPT_COOKIE, $cookie);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
if ($ispost) { if ($isPost) {
curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params); curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_URL, $url);
...@@ -48,102 +49,109 @@ function curls($url, $params = false, $ispost = 0, $https = 0,$cookie='',$timeou ...@@ -48,102 +49,109 @@ function curls($url, $params = false, $ispost = 0, $https = 0,$cookie='',$timeou
} }
$response = curl_exec($ch); $response = curl_exec($ch);
if ($response === FALSE) { if ($response === false) {
echo "cURL Error: " . curl_error($ch); echo "cURL Error: " . curl_error($ch);
return false; return false;
} }
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$httpInfo = array_merge($httpInfo, curl_getinfo($ch));
curl_close($ch); curl_close($ch);
return $response; return $response;
} }
//检查权限,仅支持验证单个权限 //检查权限,仅支持验证单个权限
function perm($userId,$perm1=''){ function perm($userId, $perm1 = '')
$permArr=config('perm.perm'); {
$NotAuth=$permArr['notAuth']; $permArr = config('perm.perm');
$AdminID=$permArr['adminGroup']; $NotAuth = $permArr['notAuth'];
if((!in_array($perm1,$NotAuth)) && !in_array($userId,$AdminID)) {//过滤不用鉴权的方法与用户 $AdminID = $permArr['adminGroup'];
if ((!in_array($perm1, $NotAuth)) && !in_array($userId, $AdminID)) {//过滤不用鉴权的方法与用户
$permID = $permArr['id']; $permID = $permArr['id'];
$url = $permArr['url'] . '/' . $userId . '/' . $permID . '?perms=' . $perm1; $url = $permArr['url'] . '/' . $userId . '/' . $permID . '?perms=' . $perm1;
$result = json_decode(curl($url, '', 0),true); $result = json_decode(curl($url, '', 0), true);
if(!isset($result['retcode']) || $result['retcode']!==0 || $result['data']['perms'][$perm1]==false){ if (!isset($result['retcode']) || $result['retcode'] !== 0 || $result['data']['perms'][$perm1] == false) {
return false; return false;
}else{ } else {
return true; return true;
} }
}else{ } else {
return true; return true;
} }
} }
//根据权限生成菜单 //根据权限生成菜单
function menu($menu,$user){ function menu($menu, $user)
$perm=chils($menu); {
$perm1=implode(',',$perm); $perm = chils($menu);
$permArr=config('perm.perm'); $perm1 = implode(',', $perm);
$perm=$permArr['id']; $permArr = config('perm.perm');
$perm = $permArr['id'];
$url=$permArr['url'].'/'.$user.'/'.$perm.'?perms='.$perm1; $url = $permArr['url'] . '/' . $user . '/' . $perm . '?perms=' . $perm1;
$result=json_decode(curl($url,'',false),true); $result = json_decode(curl($url, '', false), true);
if($result['retcode']===0){ if ($result['retcode'] === 0) {
$find=$result['data']['perms']; $find = $result['data']['perms'];
$menu=DeleteMenu($menu,$find); $menu = DeleteMenu($menu, $find);
if(!empty($menu) && is_array($menu)){ if (!empty($menu) && is_array($menu)) {
foreach ($menu as $k=>$v){ foreach ($menu as $k => $v) {
$v=(array)$v; $v = (array)$v;
if($v['title']!='Dashboard' && count($v['childs'])==0 && empty($v['href'])) if ($v['title'] != 'Dashboard' && count($v['childs']) == 0 && empty($v['href'])) {
unset($menu[$k]); unset($menu[$k]);
}
} }
} }
return array_merge($menu); return array_merge($menu);
}else{ } else {
return false; return false;
} }
} }
//提取菜单 //提取菜单
function chils($chils){ function chils($chils)
$perms=[]; {
foreach ($chils as $k=>$v){ $perms = [];
$perm_a=[]; foreach ($chils as $k => $v) {
$perm=[]; $perm_a = [];
if(strlen($v['href'])>2){ $perm = [];
$action=explode('/',$v['href']); if (strlen($v['href']) > 2) {
$perm[]=end($action); $action = explode('/', $v['href']);
$perm[] = end($action);
} }
if(count($v['childs'])>0){ if (count($v['childs']) > 0) {
$perm_a=chils($v['childs']); $perm_a = chils($v['childs']);
} }
$perms=array_merge($perms,array_merge($perm,$perm_a)); $perms = array_merge($perms, array_merge($perm, $perm_a));
} }
return $perms; return $perms;
} }
//删除没有权限的菜单 //删除没有权限的菜单
function DeleteMenu($menu,$find){ function DeleteMenu($menu, $find)
foreach ($menu as $k=>$v){ {
if(strlen($v['href'])>2){ foreach ($menu as $k => $v) {
$action=explode('/',$v['href']); if (strlen($v['href']) > 2) {
$key=end($action); $action = explode('/', $v['href']);
if(empty($find[$key]) || $find[$key]==false) $key = end($action);
if (empty($find[$key]) || $find[$key] == false) {
unset($menu[$k]); unset($menu[$k]);
}else{
if(count($v['childs'])>0){
$menu[$k]['childs'] = array_values(DeleteMenu($v['childs'],$find));
} }
if(!count($v['childs'])>0 && $v['title'] != '首页') unset($menu[$k]);//为了删除没有下级的目录 } else {
if (count($v['childs']) > 0) {
$menu[$k]['childs'] = array_values(DeleteMenu($v['childs'], $find));
}
if (!count($v['childs']) > 0 && $v['title'] != '首页') {
unset($menu[$k]);
}//为了删除没有下级的目录
} }
} }
return array_values($menu); return array_values($menu);
} }
//处理iframe的Url //处理iframe的Url
function iframeUrl($Url){ function iframeUrl($Url)
if(strstr($Url, '?') === false){ {
if (strstr($Url, '?') === false) {
$Url .= '?view=iframe'; $Url .= '?view=iframe';
}else{ } else {
$Url .= '&view=iframe'; $Url .= '&view=iframe';
} }
return $Url; return $Url;
......
<?php
namespace Common\Exceptions;
use Exception;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Laravel\Lumen\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Response;
use PDOException;
use Predis\Connection\ConnectionException;
use Symfony\Component\Debug\Exception\FatalThrowableError;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
AuthorizationException::class,
HttpException::class,
ModelNotFoundException::class,
ValidationException::class,
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $e
* @return void
*/
public function report(Exception $e)
{
$trace = $e->getTrace();
$class = $trace[0]['class'] ?? '';
$func = $trace[0]['function'] ?? '';
$method = trim($class.'::'.$func, '::');
$report = [
'code' => $this->getCode($e),
'message' => toUtf8($e->getMessage()),
'file' => $e->getFile(),
'line' => $e->getLine(),
'method' => $method,
'request' => json_encode(Request::input()),
'apiUrl' => getUrl(),
'uniqid' => getUnique(true),
];
\LogReport::write(\LogReport::anlyError($report));
parent::report($e);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
$code = $this->getCode($e);
//自动区分错误编码返回内容
if (strlen($code) == 6 && substr($code, 0, 1) == 1) {
return Response()->json(['errcode' => $code, 'errmsg' => toUtf8($e->getMessage())]);
}
$msg = '系统错误,请联系客服处理';
$data = '';
if (env('APP_DEBUG', '') == 'true') {
$msg = toUtf8($e->getMessage());
$log = [toUtf8($e->getMessage()), $e->getFile(), $e->getLine()];
$data = implode(" ", $log);
}
$data .= '#'.Request::getMethod();
//return Response()->json(['errcode' => $code, 'errmsg' => $msg.' :'.$e->getMessage(), 'data' => $data]);
return Response()->json(['errcode' => $code, 'errmsg' => $msg.' #'.getUnique(true), 'data' => $data]);
// return parent::render($request, $e);
}
private function getCode($e)
{
$systemcode = config('website.SystemCode');
if ($e instanceof PDOException) {//数据库连接
$code = errCode(001, 9, $systemcode);
} elseif ($e instanceof ConnectionException) {//redis连接
$code = errCode(002, 9, $systemcode);
} elseif ($e instanceof FatalThrowableError) {//致命错误
$code = errCode(003, 9, $systemcode);
} elseif ($e instanceof NotFoundHttpException || $e instanceof MethodNotAllowedHttpException) {//404
$code = 404;
} else {
$code = $e->getCode() ? $e->getCode() : 500;
}
return $code;
}
}
<?php
//日志目录位置
defined('REPORT_LOG_PATH') or define('REPORT_LOG_PATH', $_SERVER['DOCUMENT_ROOT'].'/Application/Runtime/LogReport/');
//项目名
defined('REPORT_APP_NAME') or define('REPORT_APP_NAME', 'api');
//单日志文件大小限制
defined('LOG_FILE_SIZE') or define('LOG_FILE_SIZE', 2097152); //2MB
//旧日志清理天数差
defined('REPORT_CLEAR_DAY_DIFF') or define('REPORT_CLEAR_DAY_DIFF', 7); //7天前
//旧数据触发清空时间条件
defined('REPORT_CLEAR_TIME') or define('REPORT_CLEAR_TIME', '9,10,11'); //9-11点
// 设定错误和异常处理
error_reporting(0);
LogReport::auto();
class LogReport
{
static $logtime = null;
static $handler = [
'finally_except' => ['Think\Think', 'appException'],
'finally_error' => ['Think\Think', 'appError'],
];
static $suffix = '';
static $log_path = '';
static $app_name = '';
static $local_ip = '';
static $data = [
'msg' => '',// 错误信息
'msgCode' => '',// 自定义错误码 六位数字字符串 etc "100000"
'ts' => '',// 10位整形 时间戳
'dateStr' => '',// 日期 2018-06-28 21:24:09
'app' => '',// 应用名称
'serverIp' => '',// 服务器ip
'fileName' => '',// 文件名
'lineNo' => '',// 行数
'method' => '',// 函数名
'apiUrl' => '',// 请求地址
'unique' => '',// 唯一追踪值
'request' => '',// 请求原数据
'response' => '',// 响应原数据
'useTime' => '',// 耗时ms
];
/**
* 自动注册
* @return [type] [description]
*/
static function auto()
{
if (defined('APP_PATH')) {
self::register();
self::set();
} else {
self::$handler = array_map(function($v){
return [];
}, self::$handler);
}
}
/**
* 注册致命错误
* @return [type] [description]
*/
static function register()
{
register_shutdown_function('LogReport::fatalError');
}
/**
* 设置处理方法
*/
static function set()
{
set_error_handler('LogReport::appError');
set_exception_handler('LogReport::exception');
}
/**
* 记录耗时ms
* @param boolean $end true返回耗时 false记录起始记录值
*/
static function LogTime($end = false)
{
if (!$end) {
$time = true;
self::$logtime = microtime(true);
} else {
$time = (microtime(true) - self::$logtime) * 1000;
self::$logtime = null;
}
return $time;
}
/**
* 错误数据格式
* @param string|array $e 错误内容|'message','file','line','code','method',~~
* @param string $file 错误文件
* @param string $line 错误行数
* @param string $code 错误码
* @param string $method 错误函数
* @param string $ip IP
* @param string $unique 追踪唯一值
* @param string $apiUrl 请求地址
* @param string $request 请求值
* @param string $response 响应值
* @param string $useTime 耗时ms
* @return [type] [description]
*/
static function anlyError($e, $file = null, $line = null, $code = null, $method = null, $ip = null, $unique = null,
$apiUrl = null, $request = null, $response = null, $useTime = null)
{
//默认获取本地内网IP
if (!empty(self::$local_ip)) {
$remote_ip = self::$local_ip;
} elseif (function_exists('swoole_get_local_ip')) {
$ips = swoole_get_local_ip();
$remote_ip = empty($ips['eth0']) ? '' : $ips['eth0'];
} elseif (isset($_SERVER['SERVER_ADDR'])) {
$remote_ip = $_SERVER['SERVER_ADDR'];
} else {
$remote_ip = '0.0.0.0';
}
$default_usetime = !is_null(self::$logtime) ? self::LogTime(true) : '';
$default_unique = isset($_REQUEST['unique']) ? $_REQUEST['unique'] : md5(microtime().rand());
if (!is_array($e)) {
$e = [
'message' => $e,
'file' => $file,
'line' => $line,
'code' => $code,
'method' => $method,
'apiUrl' => $apiUrl,
'request' => $request,
'response' => $response,
'useTime' => !is_null($useTime) ? $useTime : $default_usetime,
'ip' => !is_null($ip) ? $ip : $remote_ip,
'unique' => !is_null($unique) ? $unique : $default_unique,
];
}
$app_name = !empty(self::$app_name) ? self::$app_name : REPORT_APP_NAME;
$data = self::$data;
$data['msg'] = !empty($e['message']) ? $e['message'] : '';
$data['msgCode'] = isset($e['code']) ? $e['code'] : '';//str_pad($e['code'], 6, '0', STR_PAD_LEFT);
$data['ts'] = time();
$data['dateStr'] = date('Y-m-d H:i:s');
$data['app'] = $app_name.self::$suffix;
$data['serverIp'] = isset($e['ip']) && !empty($e['ip']) ? $e['ip'] : $remote_ip;
$data['fileName'] = isset($e['file']) && !empty($e['file']) ? $e['file'] : '';
$data['lineNo'] = isset($e['line']) && !empty($e['line']) ? $e['line'] : '';
$data['method'] = isset($e['method']) && !empty($e['method']) ? $e['method'] : '';
$data['unique'] = isset($e['unique']) && !empty($e['unique']) ? $e['unique'] : $default_unique;
$data['apiUrl'] = isset($e['apiUrl']) && !empty($e['apiUrl']) ? $e['apiUrl'] : '';
$data['request'] = isset($e['request']) && !empty($e['request']) && $e['request'] != '[]' ? $e['request'] : '';
$data['response'] = isset($e['response']) && !empty($e['response']) ? $e['response'] : '';
$data['useTime'] = isset($e['useTime']) && !empty($e['useTime']) ? $e['useTime'] : $default_usetime;
return $data;
}
/**
* 致命错误处理
* @return [type] [description]
*/
static function fatalError()
{
if ($e = error_get_last()) {
switch ($e['type']) {
case E_ERROR:
case E_PARSE:
case E_CORE_ERROR:
case E_COMPILE_ERROR:
case E_USER_ERROR:
ob_end_clean();
$e['code'] = 500;
$e['method'] = 'fatal';
$e['apiUrl'] = '';
$e['request'] = !empty($_REQUEST) ? json_encode($_REQUEST) : '';
self::write(self::anlyError($e));
break;
}
}
// exit();
}
/**
* 用户错误处理使用user_error()触发
* @param [type] $errno [description]
* @param [type] $errstr [description]
* @param [type] $errfile [description]
* @param [type] $errline [description]
* @return [type] [description]
*/
static function appError($errno, $errstr, $errfile, $errline)
{
switch ($errno) {
case E_ERROR:
case E_PARSE:
case E_CORE_ERROR:
case E_COMPILE_ERROR:
case E_USER_ERROR:
$near_trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
$backtrace = array_pop($near_trace);
$class = isset($backtrace['class']) ? $backtrace['class'] : '';
$func = isset($backtrace['function']) ? $backtrace['function'] : '';
$method = trim($class . '::' . $func, '::');
$request_url = '';
$request = !empty($_REQUEST) ? json_encode($_REQUEST) : '';
self::write(self::anlyError($errstr , $errfile, $errline));
break;
}
if (!empty(self::$handler['finally_error'])) {
call_user_func(self::$handler['finally_error'], $errno, $errstr, $errfile, $errline);
}
}
/**
* 异常处理
* @return [type] [description]
*/
static function exception($e)
{
$trace = $e->getTrace();
$class = isset($trace[0]['class']) ? $trace[0]['class'] : '';
$func = isset($trace[0]['function']) ? $trace[0]['function'] : '';
$method = trim($class . '::' . $func, '::');
$request_url = '';
$request = !empty($_REQUEST) ? json_encode($_REQUEST) : '';
$code = !empty($e->getCode()) ? $e->getCode() : 500;
self::write(self::anlyError($e->getMessage() , $e->getFile(), $e->getLine(), $code, $method, null, null, $request_url, $request));
if (!empty(self::$handler['finally_except'])) {
call_user_func(self::$handler['finally_except'], $e);
}
}
/**
* 日志记录
* @param string $log 日志内容
* @return [type] [description]
*/
static function write($log)
{
if (is_array($log)) {
$log = json_encode($log);
}
if (empty($log)) {
return false;
}
$report_log_path = !empty(self::$log_path) ? self::$log_path : REPORT_LOG_PATH;
// 自动创建日志目录
if (!is_dir($report_log_path)) {
mkdir($report_log_path, 0755, true);
}
if (in_array(intval(date('H')), explode(',', REPORT_CLEAR_TIME))) { //9-11点触发清空旧数据条件
$dir = scandir($report_log_path);
$clear_day = (int)date_sub(date_create(date('Ymd')), date_interval_create_from_date_string(REPORT_CLEAR_DAY_DIFF. ' days'))->format('Ymd');
if (!empty($dir)) {
array_walk($dir, function($file) use ($clear_day){
$file_arr = explode('-', strchr($file, '.', true), 2);
if ($file_arr[0] != '' && $file_arr[0] <= $clear_day) {
@unlink($report_log_path.$file);
}
});
}
}
$name = date('Ymd');
$filename = $report_log_path.$name.'.log';
//检测日志文件大小,超过配置大小则备份日志文件重新生成
if (is_file($filename) && floor(LOG_FILE_SIZE) <= filesize($filename)) {
rename($filename, dirname($filename) . '/' . $name. '-' . time() . '.log');
}
$log .= PHP_EOL;
return file_put_contents($filename, $log, FILE_APPEND);
}
}
<?php
namespace Common\Model;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Redis;
class RedisModel extends Model
{
const WRITE_CONNECT_METHOD = ['set', 'del', 'rpush','lpush', 'expire', 'hset', 'hmset', 'hdel','hsetnx','hincrby'];
const WANRING_LEVEL = 1;
const INGORE_LEVEL = 0;
private $read = [];
private $write = [];
private $level = self::WANRING_LEVEL;
public function __construct($level = self::WANRING_LEVEL, $ConnectWrite = 'default', $ConnectRead = 'read')
{
parent::__construct();
$this->level = $level;
$this->read = Redis::connection($ConnectRead);
$this->write = Redis::connection($ConnectWrite);
}
public function __call($method, $args)
{
$cls = &$this;
$tmp = function($method, $args) use ($cls) {
if (strpos($method, 'pipeline_')) {//使用管道
$method = substr($method, 9);
if (in_array($method, $cls::WRITE_CONNECT_METHOD)) {
return $cls->write->pipeline(function ($pipe) use ($args) {
foreach ($args as $arg) {
$pipe->$method(...$arg);
}
});
} else {
try {
return $cls->read->pipeline(function ($pipe) use ($args) {
foreach ($args as $arg) {
$pipe->$method(...$arg);
}
});
} catch (ConnectionException $e) {
return $cls->write->pipeline(function ($pipe) use ($args) {
foreach ($args as $arg) {
$pipe->$method(...$arg);
}
});
}
}
} else {
if (in_array($method, $cls::WRITE_CONNECT_METHOD)) {
return $cls->write->$method(...$args);
} else {
try {
return $cls->read->$method(...$args);
} catch (ConnectionException $e) {
return $cls->write->$method(...$args);
}
}
}
};
if ($this->level == self::WANRING_LEVEL) {//默认告警级别,抛出异常
if (strpos($method, 'catch_') === 0) {
$method = substr($method, 6);
try {
return $tmp($method, $args);
} catch (\Exception $e) {
return null;
}
} else {
return $tmp($method, $args);
}
} else {
try {
return $tmp($method, $args);
} catch (\Exception $e) {
return null;
}
}
}
//管道
public function pipeline_to_hset($data){
return $this->write->pipeline(function ($pipe) use ($data) {
foreach ($data['data'] as $k => $v) {
$pipe->hset($data['key'],$k,$v);
}
});
}
}
<?php
namespace Rpc\Msg;
/**
* Autogenerated by Thrift Compiler (0.11.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
use Thrift\Base\TBase;
use Thrift\Type\TType;
use Thrift\Type\TMessageType;
use Thrift\Exception\TException;
use Thrift\Exception\TProtocolException;
use Thrift\Protocol\TProtocol;
use Thrift\Protocol\TBinaryProtocolAccelerated;
use Thrift\Exception\TApplicationException;
interface MessageIf {
/**
* @param string $str
* @return string
*/
public function MessageApiAction($str);
}
class MessageClient implements \Rpc\Msg\MessageIf {
protected $input_ = null;
protected $output_ = null;
protected $seqid_ = 0;
public function __construct($input, $output=null) {
$this->input_ = $input;
$this->output_ = $output ? $output : $input;
}
public function MessageApiAction($str)
{
$this->send_MessageApiAction($str);
return $this->recv_MessageApiAction();
}
public function send_MessageApiAction($str)
{
$args = new \Rpc\Msg\Message_MessageApiAction_args();
$args->str = $str;
$bin_accel = ($this->output_ instanceof TBinaryProtocolAccelerated) && function_exists('thrift_protocol_write_binary');
if ($bin_accel)
{
thrift_protocol_write_binary($this->output_, 'MessageApiAction', TMessageType::CALL, $args, $this->seqid_, $this->output_->isStrictWrite());
}
else
{
$this->output_->writeMessageBegin('MessageApiAction', TMessageType::CALL, $this->seqid_);
$args->write($this->output_);
$this->output_->writeMessageEnd();
$this->output_->getTransport()->flush();
}
}
public function recv_MessageApiAction()
{
$bin_accel = ($this->input_ instanceof TBinaryProtocolAccelerated) && function_exists('thrift_protocol_read_binary');
if ($bin_accel) $result = thrift_protocol_read_binary($this->input_, '\Rpc\Msg\Message_MessageApiAction_result', $this->input_->isStrictRead());
else
{
$rseqid = 0;
$fname = null;
$mtype = 0;
$this->input_->readMessageBegin($fname, $mtype, $rseqid);
if ($mtype == TMessageType::EXCEPTION) {
$x = new TApplicationException();
$x->read($this->input_);
$this->input_->readMessageEnd();
throw $x;
}
$result = new \Rpc\Msg\Message_MessageApiAction_result();
$result->read($this->input_);
$this->input_->readMessageEnd();
}
if ($result->success !== null) {
return $result->success;
}
throw new \Exception("MessageApiAction failed: unknown result");
}
}
// HELPER FUNCTIONS AND STRUCTURES
class Message_MessageApiAction_args {
static $isValidate = false;
static $_TSPEC = array(
1 => array(
'var' => 'str',
'isRequired' => false,
'type' => TType::STRING,
),
);
/**
* @var string
*/
public $str = null;
public function __construct($vals=null) {
if (is_array($vals)) {
if (isset($vals['str'])) {
$this->str = $vals['str'];
}
}
}
public function getName() {
return 'Message_MessageApiAction_args';
}
public function read($input)
{
$xfer = 0;
$fname = null;
$ftype = 0;
$fid = 0;
$xfer += $input->readStructBegin($fname);
while (true)
{
$xfer += $input->readFieldBegin($fname, $ftype, $fid);
if ($ftype == TType::STOP) {
break;
}
switch ($fid)
{
case 1:
if ($ftype == TType::STRING) {
$xfer += $input->readString($this->str);
} else {
$xfer += $input->skip($ftype);
}
break;
default:
$xfer += $input->skip($ftype);
break;
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
public function write($output) {
$xfer = 0;
$xfer += $output->writeStructBegin('Message_MessageApiAction_args');
if ($this->str !== null) {
$xfer += $output->writeFieldBegin('str', TType::STRING, 1);
$xfer += $output->writeString($this->str);
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
}
class Message_MessageApiAction_result {
static $isValidate = false;
static $_TSPEC = array(
0 => array(
'var' => 'success',
'isRequired' => false,
'type' => TType::STRING,
),
);
/**
* @var string
*/
public $success = null;
public function __construct($vals=null) {
if (is_array($vals)) {
if (isset($vals['success'])) {
$this->success = $vals['success'];
}
}
}
public function getName() {
return 'Message_MessageApiAction_result';
}
public function read($input)
{
$xfer = 0;
$fname = null;
$ftype = 0;
$fid = 0;
$xfer += $input->readStructBegin($fname);
while (true)
{
$xfer += $input->readFieldBegin($fname, $ftype, $fid);
if ($ftype == TType::STOP) {
break;
}
switch ($fid)
{
case 0:
if ($ftype == TType::STRING) {
$xfer += $input->readString($this->success);
} else {
$xfer += $input->skip($ftype);
}
break;
default:
$xfer += $input->skip($ftype);
break;
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
public function write($output) {
$xfer = 0;
$xfer += $output->writeStructBegin('Message_MessageApiAction_result');
if ($this->success !== null) {
$xfer += $output->writeFieldBegin('success', TType::STRING, 0);
$xfer += $output->writeString($this->success);
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
}
<?php
namespace Rpc\Msg;
/**
* Autogenerated by Thrift Compiler (0.11.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
use Thrift\Base\TBase;
use Thrift\Type\TType;
use Thrift\Type\TMessageType;
use Thrift\Exception\TException;
use Thrift\Exception\TProtocolException;
use Thrift\Protocol\TProtocol;
use Thrift\Protocol\TBinaryProtocolAccelerated;
use Thrift\Exception\TApplicationException;
interface SendMsgIf {
/**
* @param string $str
* @return string
*/
public function sendMsg($str);
}
class SendMsgClient implements \Rpc\Msg\SendMsgIf {
protected $input_ = null;
protected $output_ = null;
protected $seqid_ = 0;
public function __construct($input, $output=null) {
$this->input_ = $input;
$this->output_ = $output ? $output : $input;
}
public function sendMsg($str)
{
$this->send_sendMsg($str);
return $this->recv_sendMsg();
}
public function send_sendMsg($str)
{
$args = new \Rpc\Msg\SendMsg_sendMsg_args();
$args->str = $str;
$bin_accel = ($this->output_ instanceof TBinaryProtocolAccelerated) && function_exists('thrift_protocol_write_binary');
if ($bin_accel)
{
thrift_protocol_write_binary($this->output_, 'sendMsg', TMessageType::CALL, $args, $this->seqid_, $this->output_->isStrictWrite());
}
else
{
$this->output_->writeMessageBegin('sendMsg', TMessageType::CALL, $this->seqid_);
$args->write($this->output_);
$this->output_->writeMessageEnd();
$this->output_->getTransport()->flush();
}
}
public function recv_sendMsg()
{
$bin_accel = ($this->input_ instanceof TBinaryProtocolAccelerated) && function_exists('thrift_protocol_read_binary');
if ($bin_accel) $result = thrift_protocol_read_binary($this->input_, '\Rpc\Msg\SendMsg_sendMsg_result', $this->input_->isStrictRead());
else
{
$rseqid = 0;
$fname = null;
$mtype = 0;
$this->input_->readMessageBegin($fname, $mtype, $rseqid);
if ($mtype == TMessageType::EXCEPTION) {
$x = new TApplicationException();
$x->read($this->input_);
$this->input_->readMessageEnd();
throw $x;
}
$result = new \Rpc\Msg\SendMsg_sendMsg_result();
$result->read($this->input_);
$this->input_->readMessageEnd();
}
if ($result->success !== null) {
return $result->success;
}
throw new \Exception("sendMsg failed: unknown result");
}
}
// HELPER FUNCTIONS AND STRUCTURES
class SendMsg_sendMsg_args {
static $isValidate = false;
static $_TSPEC = array(
1 => array(
'var' => 'str',
'isRequired' => false,
'type' => TType::STRING,
),
);
/**
* @var string
*/
public $str = null;
public function __construct($vals=null) {
if (is_array($vals)) {
if (isset($vals['str'])) {
$this->str = $vals['str'];
}
}
}
public function getName() {
return 'SendMsg_sendMsg_args';
}
public function read($input)
{
$xfer = 0;
$fname = null;
$ftype = 0;
$fid = 0;
$xfer += $input->readStructBegin($fname);
while (true)
{
$xfer += $input->readFieldBegin($fname, $ftype, $fid);
if ($ftype == TType::STOP) {
break;
}
switch ($fid)
{
case 1:
if ($ftype == TType::STRING) {
$xfer += $input->readString($this->str);
} else {
$xfer += $input->skip($ftype);
}
break;
default:
$xfer += $input->skip($ftype);
break;
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
public function write($output) {
$xfer = 0;
$xfer += $output->writeStructBegin('SendMsg_sendMsg_args');
if ($this->str !== null) {
$xfer += $output->writeFieldBegin('str', TType::STRING, 1);
$xfer += $output->writeString($this->str);
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
}
class SendMsg_sendMsg_result {
static $isValidate = false;
static $_TSPEC = array(
0 => array(
'var' => 'success',
'isRequired' => false,
'type' => TType::STRING,
),
);
/**
* @var string
*/
public $success = null;
public function __construct($vals=null) {
if (is_array($vals)) {
if (isset($vals['success'])) {
$this->success = $vals['success'];
}
}
}
public function getName() {
return 'SendMsg_sendMsg_result';
}
public function read($input)
{
$xfer = 0;
$fname = null;
$ftype = 0;
$fid = 0;
$xfer += $input->readStructBegin($fname);
while (true)
{
$xfer += $input->readFieldBegin($fname, $ftype, $fid);
if ($ftype == TType::STOP) {
break;
}
switch ($fid)
{
case 0:
if ($ftype == TType::STRING) {
$xfer += $input->readString($this->success);
} else {
$xfer += $input->skip($ftype);
}
break;
default:
$xfer += $input->skip($ftype);
break;
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
public function write($output) {
$xfer = 0;
$xfer += $output->writeStructBegin('SendMsg_sendMsg_result');
if ($this->success !== null) {
$xfer += $output->writeFieldBegin('success', TType::STRING, 0);
$xfer += $output->writeString($this->success);
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
}
<?php
namespace Rpc\Msg;
/**
* Autogenerated by Thrift Compiler (0.11.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
use Thrift\Base\TBase;
use Thrift\Type\TType;
use Thrift\Type\TMessageType;
use Thrift\Exception\TException;
use Thrift\Exception\TProtocolException;
use Thrift\Protocol\TProtocol;
use Thrift\Protocol\TBinaryProtocolAccelerated;
use Thrift\Exception\TApplicationException;
<?php
namespace Rpc;
use Thrift\Exception\TException;
use Thrift\Protocol\TBinaryProtocol;
use Thrift\Transport\TBufferedTransport;
use Thrift\Transport\THttpClient;
use Thrift\Transport\TPhpStream;
use Thrift\TMultiplexedProcessor;
use Thrift\Protocol\TMultiplexedProtocol;
use Thrift\Factory\TBinaryProtocolFactory;
use Thrift\Factory\TTransportFactory;
use Thrift\Server\TServerSocket;
use Thrift\Server\TSimpleServer;
use Thrift\Server\TForkingServer;
use Thrift\Transport\TSocket;
class MsgRpcClient {
public function sendMsg($data){
try {
ini_set('memory_limit', '1024M');
$socket = new TSocket('192.168.2.245', '9988');
$socket->setRecvTimeout(50000);
$socket->setDebug(true);
$transport = new TBufferedTransport($socket, 1024, 1024);
$protocol = new TBinaryProtocol($transport);
$client = new \Rpc\Msg\SendMsgClient(new TMultiplexedProtocol($protocol, "sendMsg"));
$transport->open();
$result = $client->sendMsg(json_encode($data));
print_r($result);
$transport->close();
} catch (TException $tx) {
print_r($tx->getMessage());
}
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: ICHUNT
* Date: 2019-03-28
* Time: 18:51
*/
/**
* 二维数组根据字段进行排序testing123
* @params array $array 需要排序的数组
* @params string $field 排序的字段
* @params string $sort 排序顺序标志 SORT_DESC 降序;SORT_ASC 升序
*/
function arraySequence($array, $field, $sort = 'SORT_DESC')
{
$arrSort = array();
foreach ($array as $uniqid => $row) {
foreach ($row as $key => $value) {
$arrSort[$key][$uniqid] = $value;
}
}
array_multisort($arrSort[$field], constant($sort), $array);
return $array;
}
/**
* 钉钉发送请求curl方法
*/
function SendAlarm($e,$webhook='',$at=false,$SystemName=''){
if(stripos($e->getFile(),'RouteCollection.php')) return false;
$message='时间:'.date('Y-m-d H:i:s')."\r\n".'任务:'.$e->getFile()."\r\n".'错误信息:'.$e->getMessage()."\r\n".'行号:'.$e->getLine();
SendRobot($webhook,$message,$at,$SystemName);
}
/**
* @param string $webhook 机器人地址
* @param string $message 消息内容
* @param bool|array $at 需要@的人
* @param string $sign 系统标记
* @return mixed
*/
function SendRobot($webhook='',$message,$at=false,$sign='未设置系统')
{
if(empty($webhook)) $webhook = "https://oapi.dingtalk.com/robot/send?access_token=d1e3ec2e48d250721276accbadb8defcf28ba8e6fd8644ee3f4c3ea4cf417bca";
$data = array ('msgtype' => 'text','text' => array ('content' => $message."\r\n系统:".$sign));
if($at!==true && is_array($at)) $data['at']=['atMobiles'=>$at];
$data_string = json_encode($data);
$result = dtcurl($webhook, $data_string,true);
return $result;
}
/**
* 钉钉发送请求curl方法
*/
function dtcurl($url,$data=null){
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
if (!empty($data)){
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_HTTPHEADER,array('Content-Type: application/json;charset=UTF-8'));
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return json_decode($output,true);
}
/**
* @param 错误码 $ErrCode
* @param 错误描述 $ErrMsg
* @return bool
*/
function ErrorLog($ErrCode=null,$ErrMsg=null){
$Route = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
$ErrFile = !empty($Route[1]['file']) ? $Route[1]['file'] : '';
$line = !empty($Route[1]['line']) ? $Route[1]['line'] : '';
$Action = !empty($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : '';
if(empty($ErrCode)) return true;
$ErrInfo=\LogReport::anlyError($ErrMsg,$ErrFile,$line,$ErrCode,$Action);//错误内容, 错误文件, 错误行数, 错误码, 错误方法名); 返回固定格式字符串,第一个参数可传数组
\LogReport::write($ErrInfo); //将anlyError返回的数据作参数传入
return true;
}
/**
* @param array|bool $arr 指定收集的字段
* @param bool $empty 是否过滤空值
* @param array $data 需要过滤数据,不指定从get、post拿指定字段
* @return array|string
*/
function TrimX($arr = false, $empty = true, $data = [])
{
if (empty($data)) $data = \Illuminate\Support\Facades\Request::only($arr);
if (is_array($data)) {
foreach ($data as $k => &$v) {
if (!empty($v) && $v != '0' && is_string($v)) {
$v = input_xxs($v);
} elseif (is_array($v)) {
array_walk_recursive($v, function(&$i){
if (is_string($i)) {
$i = input_xxs($i);
}
});
}
if ($empty == true) if ((empty($v) && $v != 0) || $v == 'undefined' || $v == null) unset($data[$k]);
if (is_array($arr) && count($arr) > 0 && count($data) > 0) {
if (!in_array($k, $arr)) unset($data[$k]);
}
}
} else {
$data = input_xxs($data, true);
}
return $data;
}
/**
* 输入参数安全处理
* @param [type] $data [description]
* @param [type] $simple [description]
* @return [type] [description]
*/
function input_xxs($data, $simple = false)
{
if (!is_string($data)) {
return $data;
}
if ($simple) {
$data = trim($data);
} else {
$data = addslashes(htmlspecialchars(trim($data)));
}
return $data;
}
/**
* @param string $url
* @param array|bool $params
* @param int|bool $ispost
* @param array $header
* @return bool|mixed
*/
function curl($url, $params = false, $ispost = 0, $header=[], &$httpInfo = [])
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在
if(!empty($header)){
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
}
if (is_array($params)) {
$result = array_filter($params, function($v){
return is_object($v) && get_class($v) == 'CURLFile';
});
if (empty($result)) {
$params = http_build_query($params);
}
}
if ($ispost) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_URL, $url);
} else {
if ($params) {
curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
} else {
curl_setopt($ch, CURLOPT_URL, $url);
}
}
$response = curl_exec($ch);
$httpInfo = curl_getinfo($ch);
if ($response === FALSE) {
// echo "cURL Error: " . curl_error($ch);
return false;
}
curl_close($ch);
return $response;
}
/**
* 质量上报http请求
* @param [type] $url [description]
* @param [type] $param [description]
* @return [type] [description]
*/
function reportCurl($url, $param = [], $is_post = 1, $header = [])
{
$httpinfo = [];
\LogReport::LogTime();
if (is_array($param) && !isset($param['unique'])) {
$param['unique'] = getUnique(true);
}
$body = curl($url, $param, $is_post, $header, $httpinfo);
//保留请求主体不带参数
$url_arr = parse_url($url);
$url_arr['scheme'] = isset($url_arr['scheme']) ? $url_arr['scheme'].'://' : '';
$url_arr['port'] = isset($url_arr['port']) ? ':'.$url_arr['port'] : '';
$url_arr['query'] = empty($url_arr['query']) ? '' : $url_arr['query'];
parse_str($url_arr['query'], $get);
unset($url_arr['user'], $url_arr['pass'], $url_arr['query'], $url_arr['fragment']);
$url = implode('', $url_arr);
$param = array_merge($get, $param);
$report = [
'method' => empty($url_arr['path']) ? '' : $url_arr['path'],
'apiUrl' => $url,
'code' => $httpinfo['http_code'] == 0 ? 500 : $httpinfo['http_code'],
'message' => $httpinfo['http_code'] == 0 ? '请求失败' : '',
'request' => is_array($param) ? json_encode($param) : $param,
'response' => $httpinfo['http_code'] == 404 ? '' : $body,
];
\LogReport::write(\LogReport::anlyError($report));
return $body;
}
/**
* @param array $data
* @param string $key
* @return mixed
*/
function ApiRequest($data,$key){
$data['k1']=time();
$data['k2']=MD5(MD5($data['k1']).$key);
return $data;
}
/**
* 获取唯一追踪值
* @return [type] [description]
*/
function getUnique($request = false)
{
$unique = '';
if ($request) {
try {
$unique = \Illuminate\Support\Facades\Request::input('unique', '');
} catch (\Exception $e) {
$unique = $_REQUEST['unique'];
}
}
if (empty($unique)) {
$unique = md5(microtime().rand());
}
return $unique;
}
/**
* 获取当前完整地址
* @return [type] [description]
*/
function getUrl($full = false)
{
$http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
if (class_exists('\Illuminate\Support\Facades\Request')) {
try {
$url = \Illuminate\Support\Facades\Request::url();
} catch (\Exception $e) {
$url = $http_type.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
}
if (!$full) {
$url_split = parse_url($url);
$url_split['scheme'] = isset($url_split['scheme']) ? $url_split['scheme'].'://' : $http_type;
unset($url_split['query'], $url_split['fragment']);
$url = implode('', $url_split);
}
} else {
if ($full) {
$url = $http_type.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
} else {
$url_split = parse_url($_SERVER['REQUEST_URI']);
$url = $http_type.$_SERVER['HTTP_HOST'].$url_split['path'];
}
}
return $url;
}
/**
* 判断是否不是UTF-8编码,如果不是UTF-8编码,则转换为UTF-8编码
* @param [type] $str [description]
* @return [type] [description]
*/
function toUtf8($str)
{
if (mb_detect_encoding($str,'UTF-8, ISO-8859-1, GBK') != 'UTF-8') {
return iconv('gbk', 'utf-8', $str);
} else {
return $str;
}
}
/**
* @param int $code 错误码
* @param int $level 错误级别 1普通错误 5需关注错误 9致命错误,急需解决
* @return int
*/
function errCode($code = 0, $level = 1, $systemcode = ''){
if (intval($code) == 0) {
return 0;
} else {
$code = str_pad($code, 3, '0', STR_PAD_LEFT);
}
return intval($level.$systemcode.$code);
}
/**
* 生成随机数
*
* @param $length int 随机数长度
* @param $numeric boolean 是否为纯数字
* @return string 随机数
*/
function random($length, $numeric = 0) {
$seed = base_convert(md5(microtime().$_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
$seed = $numeric ? (str_replace('0', '', $seed).'012340567890') : ($seed.'zZ'.strtoupper($seed));
if($numeric) {
$hash = '';
} else {
$hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
$length--;
}
$max = strlen($seed) - 1;
for($i = 0; $i < $length; $i++) {
$hash .= $seed{mt_rand(0, $max)};
}
return $hash;
}
/**
* 价格格式化
* @param [type] $price [description]
* @param integer $sign [description]
* @param integer $num [description]
* @return [type] [description]
*/
function price_format($price, $sign = 0, $num = 2, $sep = '')
{
$minus = $price < 0 ? '-' : '';
$price = number_format(abs($price), $num, '.', $sep);
switch ($sign) {
case 1: $sign = '¥'; break;
case 2: $sign = '$'; break;
default: $sign = ''; break;
}
if (!empty($sign)) {
$price = $sign . $price;
}
return $minus . $price;
}
/**
* 获取客户端IP
* @return [type] [description]
*/
function get_client_ip()
{
try {
$ip = \Illuminate\Support\Facades\Request::getClientIp();
} catch (\Exception $e) {
static $ip = null;
if (null !== $ip) {
return $ip;
}
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'];
}
}
return $ip;
}
/**
* 捕获json解析失败的数据
* @param [type] $data json数据
* @param [type] $errcode 错误时错误码
* @param boolean $raw 是否原数据返回
* @return [type] [description]
*/
function catch_json_decode($data, $errcode, $raw = false)
{
if ($raw) {
return $data;
}
$arr = json_decode($data, true);
if (empty($arr)) {
$debug = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
$msg = '文件:'.$debug[0]['file'].',行数:'.$debug[0]['line'];
throw new \Exception('无法解析数据:'.$msg, $errcode);
}
return $arr;
}
/**
* laravel兼容wherein
* @param [type] &$query [description]
* @param [type] $where [description]
* @return [type] [description]
*/
function laravel_where(&$query, $where)
{
if (is_array($where) && isset($where[0])) {
$args = $where;
foreach ($args as $k => $v) {
if (strtolower($v[1]) == 'in') {
$value = is_string($v[2]) ? explode(',', $v[2]) : $v[2];
$query->whereIn($v[0], $value);
unset($where[$k]);
} elseif (strtolower($v[1]) == 'not in') {
$value = is_string($v[2]) ? explode(',', $v[2]) : $v[2];
$query->whereNotIn($v[0], $value);
unset($where[$k]);
}
}
$query->where($where);
}
}
/**
* 加密明文
* $data 需要加密的明文 string
* $key 加密用的秘钥 string 32位
*/
function Encryption($data,$key){
$data = openssl_encrypt(json_encode($data), 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
$data = strtolower(bin2hex($data));
return $data;
}
/**
* 解密
* $plain_text 需要解密的密文 string
* $key 解密秘钥 string 32位
*/
function Deciphering($plain_text,$key){
$decrypted = openssl_decrypt(hex2bin($plain_text), 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
return $decrypted;
}
/**
* 加密
* $info 需要加密的数据 array
* $key 密钥
*/
function ExcessEncryption($info, $key){
$info['random_string'] = random(32);//添加随机值
$data['data'] = Encryption($info,$key);
$data['timestamp'] = time();
$data['token'] = md5($data['data'].$data['timestamp'].$key.$info['random_string']);
return $data;
}
/**
* 解密
*/
function ExcessDecrypt($data,$key){
if(empty($data['data']) || empty($data['timestamp']) || empty($data['token'])) return false;
$info = json_decode(Deciphering($data['data'],$key),true);
if(!$info) return false;
if($data['token']!== md5($data['data'].$data['timestamp'].$key.$info['random_string'])) return false;
return $info;
}
\ No newline at end of file
...@@ -6,7 +6,9 @@ ...@@ -6,7 +6,9 @@
"type": "project", "type": "project",
"require": { "require": {
"php": ">=5.5.9", "php": ">=5.5.9",
"laravel/framework": "5.2.*" "laravel/framework": "5.2.*",
"ext-json": "*",
"ext-curl": "*"
}, },
"require-dev": { "require-dev": {
"fzaninotto/faker": "~1.4", "fzaninotto/faker": "~1.4",
...@@ -23,8 +25,7 @@ ...@@ -23,8 +25,7 @@
"App\\": "app/" "App\\": "app/"
}, },
"files": [ "files": [
"app/Http/function.php", "app/Http/function.php"
"common/function.php"
] ]
}, },
"autoload-dev": { "autoload-dev": {
......
<?php
namespace ScmWmsCommon;
use Closure;
class CheckLogin
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$login = config('website.verification_token');
$token = $request->input('token');
if(!$token){
return response()->json(["errcode" => 502, "errmsg" => "no token"]);
}
$rsp = curl($login,['token' => $token],true);
if(!$rsp){
return response()->json(["errcode" => 503, "errmsg" => "登录验证失败"]);
}
$ret = json_decode($rsp);
if ($ret->errcode != 0) {
return response()->json(["errcode" => $ret->errcode, "errmsg" => $ret->errmsg]);
}
$user = $ret->data;
$request->user = $user;
//还需要处理仓库
$request->store_id = 1;
return $next($request);
}
}
<?php
namespace ScmWmsCommon;
use Illuminate\Database\Eloquent\Model;
use DB;
class SnModel extends Model
{
protected $table = 'numbering_rules';
public $timestamps = false;
public function __construct($connection = false)
{
parent::__construct();
if($connection){
$this->connection= $connection;
}
}
//单号
public function sn($ruleCode)
{
$str = DB::connection($this->connection)->transaction(function() use($ruleCode){
$data = $this->where('rule_code', $ruleCode)->first();
if (!empty($data)) {
$data = $data->toArray();
}
$str = $data['rule_prefix'];
$str_middle = '';
$number = $data['rule_suffix_number'] + 1;
if (!empty($data['rule_mask'])) {
$str_middle = date($data['rule_mask']);
}
$str .= $str_middle;
if ($str_middle != $data['rule_mask_str']) {//重置
$number = $data['rule_suffix'];
$save['rule_mask_str'] = $str_middle;
}
if ($data['rule_suffix_len'] > 0) {
$str .= $this->fillNum($data['rule_suffix_len'], $number);
if ($number != $data['rule_suffix_number']) {
$save['rule_suffix_number'] = $number;
}
if (isset($save)) {
$this->where('rule_id', $data['rule_id'])->update($save);
}
}
return $str;
});
return $str;
}
private function fillNum($len, $num)
{
$str = '';
if ($len > 0) {
$str = str_pad($num, $len, '0', 0);
}
return $str;
}
//生成单号
public function generateNumber($codeId)
{
return $this->sn($codeId);
}
}
...@@ -17,5 +17,4 @@ return array( ...@@ -17,5 +17,4 @@ return array(
'f0906e6318348a765ffb6eb24e0d0938' => $vendorDir . '/laravel/framework/src/Illuminate/Foundation/helpers.php', 'f0906e6318348a765ffb6eb24e0d0938' => $vendorDir . '/laravel/framework/src/Illuminate/Foundation/helpers.php',
'58571171fd5812e6e447dce228f52f4d' => $vendorDir . '/laravel/framework/src/Illuminate/Support/helpers.php', '58571171fd5812e6e447dce228f52f4d' => $vendorDir . '/laravel/framework/src/Illuminate/Support/helpers.php',
'cdab8ec77ae0402ce2cb2fdd82a8a401' => $baseDir . '/app/Http/function.php', 'cdab8ec77ae0402ce2cb2fdd82a8a401' => $baseDir . '/app/Http/function.php',
'a259deb85a47aeb259b02ded2ed1ff28' => $baseDir . '/common/function.php',
); );
...@@ -18,7 +18,6 @@ class ComposerStaticInit2a46e5674e69fd121680370ab820bf2e ...@@ -18,7 +18,6 @@ class ComposerStaticInit2a46e5674e69fd121680370ab820bf2e
'f0906e6318348a765ffb6eb24e0d0938' => __DIR__ . '/..' . '/laravel/framework/src/Illuminate/Foundation/helpers.php', 'f0906e6318348a765ffb6eb24e0d0938' => __DIR__ . '/..' . '/laravel/framework/src/Illuminate/Foundation/helpers.php',
'58571171fd5812e6e447dce228f52f4d' => __DIR__ . '/..' . '/laravel/framework/src/Illuminate/Support/helpers.php', '58571171fd5812e6e447dce228f52f4d' => __DIR__ . '/..' . '/laravel/framework/src/Illuminate/Support/helpers.php',
'cdab8ec77ae0402ce2cb2fdd82a8a401' => __DIR__ . '/../..' . '/app/Http/function.php', 'cdab8ec77ae0402ce2cb2fdd82a8a401' => __DIR__ . '/../..' . '/app/Http/function.php',
'a259deb85a47aeb259b02ded2ed1ff28' => __DIR__ . '/../..' . '/common/function.php',
); );
public static $prefixLengthsPsr4 = array ( public static $prefixLengthsPsr4 = array (
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment