这是之前老框架的一些类文件,具体逻辑已经不是很清晰,不过用起来应该很容易上手吧
现在吧一些类代码贴在这里了,可能不适合您,不过一些函数还是可以独立拿出来使用的
一、工具类,主要处理数组数据和字符串,包括验证和切串等
<?php
/**
* 归属于:Common
* 本类名:Tools
* 创建者:IntelliJ IDEA
* 创建时:2021/10/17 16:07:03
* 职责集:工具类
*/
namespace Common\Controller;
class ToolsController extends LogsController
{
public function __construct()
{
parent::__construct();
}
public function index()
{
}
/**
* 检查数据
* @param $arrData
* @param $mKey
* @return array
*/
public static function checkPar($arrData, $mKey)
{
$map = [];
$arrAllKeys = [];
if (is_array($mKey)) {
$arrAllKeys = $mKey;
} else if (is_string($mKey)) {
if (strpos($mKey, ',') > 0) {
foreach (explode(',', $mKey) as $key) {
$strKey = trim($key);
if (!empty($key)) {
$arrAllKeys[] = $key;
}
}
} else {
$arrAllKeys[] = $mKey;
}
}
foreach ($arrAllKeys as $mKey) {
if (isset($arrData[$mKey])) {
$bId = $arrData[$mKey];
if (is_numeric($bId)) {
$map [$mKey] = intval($arrData[$mKey]);
} else {
//echo strpos($mKey,'_id');exit;
if (strpos($mKey, '_id') > 0) {
//echo $mKey;exit;
FeedbackController::feedback(13, [$mKey]);
} else {
$map [$mKey] = strval($arrData[$mKey]);
}
}
} else {
FeedbackController::feedback(12, [$mKey]);
}
}
return $map;
}
/**
* 获取域
* @return mixed|string
*/
public static function getDomain()
{
$strDomain = C('DOMAIN_AND_PORT');
if (empty($strDomain)) {
$strDomain = $_SERVER['REQUEST_SCHEME'] . "://" . $_SERVER['HTTP_HOST'];
}
return $strDomain;
}
/**
* $url = 'http://www.baidu.com/index.php?m=content&c=index&a=lists&catid=6&area=0&author=0&h=0®ion=0&s=1&page=1';
* $arr = parse_url($url);
* var_dump($arr);
* $arr_query = convertUrlQuery($arr['query']);
* var_dump($arr_query);
* var_dump(getUrlQuery($arr_query));
* 将字符串参数变为数组
* @param $query
* @return array array (size=10)
* 'm' => string 'content' (length=7)
* 'c' => string 'index' (length=5)
* 'a' => string 'lists' (length=5)
* 'catid' => string '6' (length=1)
* 'area' => string '0' (length=1)
* 'author' => string '0' (length=1)
* 'h' => string '0' (length=1)
* 'region' => string '0' (length=1)
* 's' => string '1' (length=1)
* 'page' => string '1' (length=1)
*/
public static function convertUrlQuery($query)
{
$queryParts = explode('&', $query);
$params = array();
foreach ($queryParts as $param) {
$item = explode('=', $param);
$params[$item[0]] = $item[1];
}
return $params;
}
/**
* 将参数变为字符串
* @param $array_query
* @return string string 'm=content&c=index&a=lists&catid=6&area=0&author=0&h=0®ion=0&s=1&page=1' (length=73)
*/
public static function getUrlQuery($array_query)
{
$tmp = array();
foreach ($array_query as $k => $param) {
$tmp[] = $k . '=' . $param;
}
$params = implode('&', $tmp);
return $params;
}
public static function uriSort($uri)
{
$queryParts = explode('&', $uri);
$params = array();
$uriNew = '';
foreach ($queryParts as $param) {
$item = explode('=', $param);
$params[$item[0]] = $item[1];
}
ksort($params);
foreach ($params as $key => $value) {
$uriNew .= '&' . $key . '=' . $value;
}
return substr($uriNew, 1);
}
/**
* 有条件的合并和过滤参数数据
* @param array $arrScreen
* @param array $arr1
* @param array $arr2
* @return array
*/
public static function arrayMerge($arrScreen = [], $arr1 = [], $arr2 = [])
{
$arrR = [];
if (empty($arr1)) {
if (empty($arr2)) {
return [];
} else {
$arrR = $arr2;
}
} else {
if (empty($arr2)) {
$arrR = $arr1;
} else {
$arrR = array_merge($arr1, $arr2);
}
}
//增补必要字段
$arrR['project_name_short'] = $arrR['ps'];
$arrScreen[] = 'ps';
$arrScreen[] = 'pre';
//过滤字段
foreach ($arrScreen as $item) {
if (isset($arrR[$item])) {
unset($arrR[$item]);
}
}
return $arrR;
}
/** 检查区划码正确性,返回相应级别 */
public static function checkAreaCode($code, $level = 3)
{
$codeNew = '';
for ($i = 2; $i <= $level * 2; $i += 2) {
$levelCode = substr($code, -$i, 2);
if ($levelCode != '00') {
$codeNew = substr($code, 0, ($level * 2 - $i + 2));
$i = $level * 2 + 2;
}
}
return [$code, $codeNew];
}
/**
* 检查数据归属,是否有权操作
* @param $mdlObj
* @param $mapData
* @param $rowData
* @return mixed
*/
public static function checkBelong($mdlObj, $mapData, $rowData)
{
$strKey = 'project_name_short';
$rowResult = $mdlObj->where($mapData)->find();
//var_dump($rowResult);exit;
if ($rowResult == null) {
FeedbackController::feedback(2);
}
if (@strlen($rowResult[$strKey]) == 0) {
FeedbackController::feedback(16, ['']);
} else {
if (isset($rowData[$strKey])) {
if ($rowData[$strKey] != $rowResult[$strKey]) {
FeedbackController::feedback(17, ['']);
}
}
}
return $rowData;
}
public static function curl($strUrl, $parBody = [], $type = "post", $timeout = 30)
{
if ($strUrl == '' || $parBody == [] || $timeout <= 0) {
return false;
}
$byType = strtolower($type) == 'get' ? false : true;//true:post;false:get
$con = curl_init((string)$strUrl);
curl_setopt($con, CURLOPT_HEADER, false);
curl_setopt($con, CURLOPT_POSTFIELDS, $parBody);
curl_setopt($con, CURLOPT_POST, $byType);
curl_setopt($con, CURLOPT_RETURNTRANSFER, true);
curl_setopt($con, CURLOPT_TIMEOUT, (int)$timeout);
return curl_exec($con);
}
public static function curlByBody($strUrl, $parBody = [])
{
if ($strUrl == '') {
return false;
}
$ch = curl_init((string)$strUrl);
curl_setopt($ch, CURLOPT_HEADER, false);
// curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($parBody));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)');
curl_setopt($ch, CURLOPT_HTTPHEADER,
"aaa:ffff"
);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
return curl_exec($ch);
}
public static function cutBody($result)
{
$pattern = '/<body>(.+?)<\/body>/is';
preg_match($pattern, $result, $match);
$match[0] = str_replace("<body>", "", $match[0]);
$match[0] = str_replace("</body>", "", $match[0]);
$match[0] = trim(htmlspecialchars_decode($match[0]));
return $match[0];
}
public static function getIP()
{
global $ip;
if (getenv("HTTP_CLIENT_IP"))
$ip = getenv("HTTP_CLIENT_IP");
else if (getenv("HTTP_X_FORWARDED_FOR"))
$ip = getenv("HTTP_X_FORWARDED_FOR");
else if (getenv("REMOTE_ADDR"))
$ip = getenv("REMOTE_ADDR");
else $ip = "";
$arrLocal = ['192.168.', '127.0.0.1', 'localhost', ''];
if (in_array($ip, $arrLocal) || strstr($ip, $arrLocal[0])) {
$res = @file_get_contents("http://tool.huixiang360.com/zhanzhang/ipaddress.php");
$indexB = strpos($res, '[') + 1;
$indexE = strpos($res, ']');
$ip = substr($res, $indexB, $indexE - $indexB);
}
return $ip;
}
/**
* 返回当前的毫秒时间戳
* @return float
*/
public static function msectime()
{
list($msec, $sec) = explode(' ', microtime());
$msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
return $msectime;
}
public static function getIPInfo($ip)
{
$res = @file_get_contents("http://ip.taobao.com/service/getIpInfo.php?ip=$ip");
self::drew($res);
$res = json_decode($res, true);
$data = $res['data'];
return @$data['country'] . ' ' . @$data['region'] . ' ' . @$data['city'] . ' ' . @$data['county'] . ' ' . @$data['isp'];
}
public static function convertIP($ip) {
//IP数据文件路径
$dat_path = 'assets/qqwry.dat';
//检查IP地址
//if(!preg_match("/^d{1,3}.d{1,3}.d{1,3}.d{1,3}$/", $ip)) {
// return 'IP Address Error';
//}
// echo $dat_path;exit;
//打开IP数据文件
if(!$fd = @fopen($dat_path, 'rb')){
return 'IP date file not exists or access denied';
}
//分解IP进行运算,得出整形数
$ip = explode('.', $ip);
$ipNum = $ip[0] * 16777216 + $ip[1] * 65536 + $ip[2] * 256 + $ip[3];
//获取IP数据索引开始和结束位置
$DataBegin = fread($fd, 4);
$DataEnd = fread($fd, 4);
$ipbegin = implode('', unpack('L', $DataBegin));
if($ipbegin < 0) $ipbegin += pow(2, 32);
$ipend = implode('', unpack('L', $DataEnd));
if($ipend < 0) $ipend += pow(2, 32);
$ipAllNum = ($ipend - $ipbegin) / 7 + 1;
$BeginNum = 0;
$EndNum = $ipAllNum;
//使用二分查找法从索引记录中搜索匹配的IP记录
while($ip1num>$ipNum || $ip2num<$ipNum) {
$Middle= intval(($EndNum + $BeginNum) / 2);
//偏移指针到索引位置读取4个字节
fseek($fd, $ipbegin + 7 * $Middle);
$ipData1 = fread($fd, 4);
if(strlen($ipData1) < 4) {
fclose($fd);
return 'System Error';
}
//提取出来的数据转换成长整形,如果数据是负数则加上2的32次幂
$ip1num = implode('', unpack('L', $ipData1));
if($ip1num < 0) $ip1num += pow(2, 32);
//提取的长整型数大于我们IP地址则修改结束位置进行下一次循环
if($ip1num > $ipNum) {
$EndNum = $Middle;
continue;
}
//取完上一个索引后取下一个索引
$DataSeek = fread($fd, 3);
if(strlen($DataSeek) < 3) {
fclose($fd);
return 'System Error';
}
$DataSeek = implode('', unpack('L', $DataSeek.chr(0)));
fseek($fd, $DataSeek);
$ipData2 = fread($fd, 4);
if(strlen($ipData2) < 4) {
fclose($fd);
return 'System Error';
}
$ip2num = implode('', unpack('L', $ipData2));
if($ip2num < 0) $ip2num += pow(2, 32);
//没找到提示未知
if($ip2num < $ipNum) {
if($Middle == $BeginNum) {
fclose($fd);
return 'Unknown';
}
$BeginNum = $Middle;
}
}
$ipFlag = fread($fd, 1);
if($ipFlag == chr(1)) {
$ipSeek = fread($fd, 3);
if(strlen($ipSeek) < 3) {
fclose($fd);
return 'System Error';
}
$ipSeek = implode('', unpack('L', $ipSeek.chr(0)));
fseek($fd, $ipSeek);
$ipFlag = fread($fd, 1);
}
if($ipFlag == chr(2)) {
$AddrSeek = fread($fd, 3);
if(strlen($AddrSeek) < 3) {
fclose($fd);
return 'System Error';
}
$ipFlag = fread($fd, 1);
if($ipFlag == chr(2)) {
$AddrSeek2 = fread($fd, 3);
if(strlen($AddrSeek2) < 3) {
fclose($fd);
return 'System Error';
}
$AddrSeek2 = implode('', unpack('L', $AddrSeek2.chr(0)));
fseek($fd, $AddrSeek2);
} else {
fseek($fd, -1, SEEK_CUR);
}
while(($char = fread($fd, 1)) != chr(0))
$ipAddr2 .= $char;
$AddrSeek = implode('', unpack('L', $AddrSeek.chr(0)));
fseek($fd, $AddrSeek);
while(($char = fread($fd, 1)) != chr(0))
$ipAddr1 .= $char;
} else {
fseek($fd, -1, SEEK_CUR);
while(($char = fread($fd, 1)) != chr(0))
$ipAddr1 .= $char;
$ipFlag = fread($fd, 1);
if($ipFlag == chr(2)) {
$AddrSeek2 = fread($fd, 3);
if(strlen($AddrSeek2) < 3) {
fclose($fd);
return 'System Error';
}
$AddrSeek2 = implode('', unpack('L', $AddrSeek2.chr(0)));
fseek($fd, $AddrSeek2);
} else {
fseek($fd, -1, SEEK_CUR);
}
while(($char = fread($fd, 1)) != chr(0)){
$ipAddr2 .= $char;
}
}
fclose($fd);
//最后做相应的替换操作后返回结果
if(preg_match('/http/i', $ipAddr2)) {
$ipAddr2 = '';
}
$ipaddr = "$ipAddr1 $ipAddr2";
$ipaddr = preg_replace('/CZ88.Net/is', '', $ipaddr);
$ipaddr = preg_replace('/^s*/is', '', $ipaddr);
$ipaddr = preg_replace('/s*$/is', '', $ipaddr);
if(preg_match('/http/i', $ipaddr) || $ipaddr == '') {
$ipaddr = 'Unknown';
}
$ipaddr = iconv('gbk', 'utf-8//IGNORE', $ipaddr); //转换编码,如果网页的gbk可以删除此行
return $ipaddr;
}
/**
* 中文截取无乱码
* 下面自定义一个函数实现中文截取无乱码,由于中文字符是多字节编码实现的,所以
* 在截取的时候不仅要知道从哪里开始截取还要知道截取几个字节,在这一点上utf-8
* 实现的比较好,这种编码可以通过最高位字节来区分该字符占几个字节的编码
*
* UTF-8(8-bit Unicode Transformation Format)是一种针对Unicode的可变长度字符编码,由Ken Thompson于1992年创建。
*
* 通过查询相关资料可知:
* utf-8最高位字节与该字符所占字节数有以下对应关系
* 0xxx xxxx 占1字节
* 110x xxxx 占2字节
* 1110 xxxx 占3字节
* 一般三个字节能够表示所有汉字对应编码
*/
/**
* @param str $str 被截取的字符串
* @param int $length 需要截取长度,即需要截取的字符个数
*/
public static function mulSubStr($str, $length)
{
if ($length <= 0) { //截取字符为0或负数,返回空字符串
return '';
}
$offset = 0; //截取每个字符时最高位字节的偏移量(位置),开始的时候截取第一个字符,该字符最高位字节位置为0
$chars = 0; //已经截取到的字符,开始时为0
$returnstr = ''; //截取后返回的字符串
while ($chars < $length) { //只要已经截取到的字符没有达到需要截取的就继续截取
$highchar = decbin(ord(substr($str, $offset, 1))); //得到每个字符最高位字节编码字符,根据该编码字符判断向后截取几个字节
if (strlen($highchar) < 8) { //该字符占一个字节时,按照上面的规律,返回字符编码二进制为0xxx xxxx的字符串形式,转为二进制时开头的0会舍弃,该字节就只有7位了,
//若此处使用if(substr($highchar,0,2)=='01'),则该判断永远不会生效,因为在decbin时最高位字节为0会舍去,这样就可以使用最高位字节长度来判断了,这点需要重点理解。
$cutbyte = 1;//
} else if (substr($highchar, 0, 3) == '110') {
$cutbyte = 2;
} else if (substr($highchar, 0, 4) == '1110') {
$cutbyte = 3;
} else if (substr($highchar, 0, 5) == '11110') {
$cutbyte = 4;
}
//判断完对应字符编码所占字节后开始截取并拼接
$returnstr .= substr($str, $offset, $cutbyte);
$chars += 1; //继续截取下一个字符
$offset += $cutbyte; //下一个字符最高字节偏移量
}
return $returnstr; //返回需要截取的字符串
}
public static function createQrCode($url = "", $level = 3, $size = 4)
{
// include 'phpqrcode.php';
Vendor('phpqrcode.phpqrcode');
$value = 'http://www.cnblogs.com/txw1958/'; //二维码内容
$errorCorrectionLevel = 'L';//容错级别
$matrixPointSize = 6;//生成图片大小
//生成二维码图片
QRcode::png($value, 'qrcode.png', $errorCorrectionLevel, $matrixPointSize, 2);
$logo = 'logo.png';//准备好的logo图片
$QR = 'qrcode.png';//已经生成的原始二维码图
if ($logo !== FALSE) {
$QR = imagecreatefromstring(file_get_contents($QR));
$logo = imagecreatefromstring(file_get_contents($logo));
$QR_width = imagesx($QR);//二维码图片宽度
$QR_height = imagesy($QR);//二维码图片高度
$logo_width = imagesx($logo);//logo图片宽度
$logo_height = imagesy($logo);//logo图片高度
$logo_qr_width = $QR_width / 5;
$scale = $logo_width / $logo_qr_width;
$logo_qr_height = $logo_height / $scale;
$from_width = ($QR_width - $logo_qr_width) / 2;
//重新组合图片并调整大小
imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,
$logo_qr_height, $logo_width, $logo_height);
}
//输出图片
imagepng($QR, 'helloweixin.png');
echo '<img src="helloweixin.png">';
}
public static function createQrCodeEasy($url = "www.baidu.com", $level = 3, $size = 4)
{
Vendor('phpqrcode.phpqrcode');
$errorCorrectionLevel = intval($level);//容错级别
$matrixPointSize = intval($size);//生成图片大小
//生成二维码图片
$object = new \QRcode();
$object->png($url, false, $errorCorrectionLevel, $matrixPointSize, 2);
}
public static function makeCode($content, $name, $url, $qrcode_path = '', $matrixPointSize = 128, $matrixMarginSize = 1, $errorCorrectionLevel = 'L')
{
/** 参数详情:
* $qrcode_path:logo地址
* $content:需要生成二维码的内容
* $matrixPointSize:二维码尺寸大小
* $matrixMarginSize:生成二维码的边距
* $errorCorrectionLevel:容错级别(L,M,Q,H)
* $url:生成的带logo的二维码地址
* */
ob_clean();
Vendor('phpqrcode.phpqrcode');
$object = new \QRcode();
$qrcode_path_new = C('QR_CODE_PATH') . $name . '.png';//定义生成二维码的路径及名称
// echo $qrcode_path_new;exit;
$object::png($content, $qrcode_path_new, $errorCorrectionLevel, $matrixPointSize, $matrixMarginSize);
$QR = imagecreatefromstring(file_get_contents($qrcode_path_new));//imagecreatefromstring:创建一个图像资源从字符串中的图像流
$logo = imagecreatefromstring(file_get_contents($qrcode_path));
$QR_width = imagesx($QR);// 获取图像宽度函数
$QR_height = imagesy($QR);//获取图像高度函数
$logo_width = imagesx($logo);// 获取图像宽度函数
$logo_height = imagesy($logo);//获取图像高度函数
$logo_qr_width = $QR_width / 4;//logo的宽度
$scale = $logo_width / $logo_qr_width;//计算比例
$logo_qr_height = $logo_height / $scale;//计算logo高度
$from_width = ($QR_width - $logo_qr_width) / 2;//规定logo的坐标位置
imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height);
/** imagecopyresampled ( resource $dst_image , resource $src_image , int $dst_x , int $dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h )
* 参数详情:
* $dst_image:目标图象连接资源。
* $src_image:源图象连接资源。
* $dst_x:目标 X 坐标点。
* $dst_y:目标 Y 坐标点。
* $src_x:源的 X 坐标点。
* $src_y:源的 Y 坐标点。
* $dst_w:目标宽度。
* $dst_h:目标高度。
* $src_w:源图象的宽度。
* $src_h:源图象的高度。
* */
// Header("Content-type: image/png");
//$url:定义生成带logo的二维码的地址及名称
// imagepng($QR,$url);
}
public static function makecode_no_pic($content, $qrcode_path_new, $matrixPointSize, $matrixMarginSize, $errorCorrectionLevel)
{
ob_clean();
Vendor('phpqrcode.phpqrcode');
$object = new \QRcode();
$object::png($content, $qrcode_path_new, $errorCorrectionLevel, $matrixPointSize, $matrixMarginSize);
}
public static function packagingDir()
{
/*$file_template = FCPATH . 'canddata/cand_picture.zip';//在此之前你的项目目录中必须新建一个空的zip包(必须存在)
$downname = $card . '.zip';//你即将打包的zip文件名称
$file_name = FCPATH . 'canddata/' . $card . '.zip';//把你打包后zip所存放的目录
$result = copy($file_template, $file_name);//把原来项目目录存在的zip复制一份新的到另外一个目录并重命名(可以在原来的目录)
$zip = new ZipArchive();//新建一个对象
if ($zip->open($file_name, ZipArchive::CREATE) === TRUE) { //打开你复制过后空的zip包
$zip->addEmptyDir($card);//在zip压缩包中建一个空文件夹,成功时返回 TRUE, 或者在失败时返回 FALSE
//下面是我的场景业务处理,可根据自己的场景需要去处理(我的是将所有的图片打包)
$i = 1;
foreach ($cand_photo as $key3 => $value3) {
$file_ext = explode('.', $value3['cand_face']);//获取到图片的后缀名
$zip->addFromString($card . '/' . $card . '_' . $i . '.' . $file_ext[3], file_get_contents($value3['cand_face']));//(图片的重命名,获取到图片的二进制流)
$i++;
}
$zip->close();
$fp = fopen($file_name, "r");
$file_size = filesize($file_name);//获取文件的字节
//下载文件需要用到的头
Header("Content-type: application/octet-stream");
Header("Accept-Ranges: bytes");
Header("Accept-Length:" . $file_size);
Header("Content-Disposition: attachment; filename=$downname");
$buffer = 1024; //设置一次读取的字节数,每读取一次,就输出数据(即返回给浏览器)
$file_count = 0; //读取的总字节数
//向浏览器返回数据 如果下载完成就停止输出,如果未下载完成就一直在输出。根据文件的字节大小判断是否下载完成
while (!feof($fp) && $file_count < $file_size) {
$file_con = fread($fp, $buffer);
$file_count += $buffer;
echo $file_con;
}
fclose($fp);
//下载完成后删除压缩包,临时文件夹
if ($file_count >= $file_size) {
unlink($file_name);
}
}*/
}
public static function sendSMS($template, $mobile, $rowInfo)
{
$content = '';
$code = self::randStr(5, 1);
switch ($template) {
case 'change_binding':
$content = "尊敬的" . $rowInfo['member_name'] . ",您正在进行换绑手机操作,本次验证码:" . $code . ",请勿向他人出示";
//存储验证码&生成令牌
$token = self::token('user_sms');
break;
case 'binding':
$content = "尊敬的" . $rowInfo['member_name'] . ",您正在进行绑定手机操作,本次验证码:" . $code . ",请勿向他人出示";
//存储验证码&生成令牌
$token = self::token('user_sms');
break;
case 'unbound':
$content = "尊敬的" . $rowInfo['member_name'] . ",您已成功解绑本手机,祝您生活愉快";
//存储验证码&生成令牌
$token = self::token('user_sms');
break;
case 'bound':
$content = "尊敬的" . $rowInfo['member_name'] . ",您已成功绑定本手机号码,祝您生活愉快";
//存储验证码&生成令牌
$token = self::token('user_sms');
break;
case 'payment':
$content = "尊敬的" . $rowInfo['member_name'] . ",您正在进行支付密码更新,本次验证码:" . $code . ",祝您生活愉快";
//存储验证码&生成令牌
$token = self::token('user_sms');
break;
case 'password':
$content = "尊敬的" . $rowInfo['member_name'] . ",您正在进行登陆密码更新,本次验证码:" . $code . ",祝您生活愉快";
//存储验证码&生成令牌
$token = self::token('user_sms');
break;
default:
return false;
}
self::cache($token, array($mobile, $code));
//self::drew(array($mobile, $content));
$re = self::send($mobile, $content);
if ($re)
return $token;
return false;
}
/**
* 发送手机短信
* @param unknown $mobile 手机号
* @param unknown $content 短信内容
*/
public function send($mobile, $content)
{
$user_id = C('PLATFORM_USER');
$ts = time() * 1000;
$apikey = C('PLATFORM_KEY');
$sign = md5($user_id . $ts . $apikey);
if (strpos($content, "【") == -1 || strpos($content, "【") == '') {
$content = C('PLATFORM_SIGN') . $content;
}
$content = urlencode($content);
$url = "http://47.98.19.118:8081/api/sms/send?userid=$user_id&ts=$ts&sign=$sign&mobile=$mobile&msgcontent=$content";
//tools::feedback('00',[],'',$url);
//$res = self::https_request($url);
$res = file_get_contents($url);
$json = json_decode($res, true);
if (!is_null($json)) {
if ($json["code"] == "0") {
//为有据可查,记录发送日志
return true;
}
}
return false;
}
function curl_request($url)
{
$ch = curl_init();
//设置选项,包括URL
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//绕过ssl验证
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
//执行并获取HTML文档内容
$output = curl_exec($ch);
//释放curl句柄
curl_close($ch);
return $output;
}
/**
* 检测FORM是否提交
* @param bool $availability
* @return bool
*/
public static function isSubmit($availability = true)
{
//$submit = isset($_POST['form_token']) ? $_POST['form_token'] : $_GET['form_token'];
$submit = I('post.form_token');
if (self::cache($submit) && $availability) {
return true;
} else if ($submit && strlen($submit)) {
return true;
}
return false;
}
public static function isAjax()
{
$strAjax = I('request.ajax/d');
if ($strAjax) {
return true;
}
return false;
}
/**
* 生成token
* @param bool $destroy /传入则直接销毁,不传则返回一个32位长度的token,默认时长10分钟
* @return bool|string
*/
public static function formToken($destroy = false)
{
if ($destroy) {
self::cache($destroy, false);
return true;
}
$token = self::randStr();
self::cache($token, true);
return $token;
}
public static function randStr($length = 32, $number = 0, $md5 = false)
{
$str = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz123456789';
if ($number) $str = '1234567890';
$len = strlen($str) - 1;
$string = '';
for ($i = 0; $i < $length; $i++) {
$num = mt_rand(0, $len);
$string .= $str[$num];
}
return $md5 ? md5($string) : $string;
}
/**
* 缓存键值
* @param $key
* @param string $value
* @param int $times
* @return bool|int|mixed
*/
public static function cache($key, $value = '', $times = 6000)
{
return true;
$key = C('REDIS_PRE') . $key;
if (empty($key)) {
return false;
}
$redis = new \Redis();
$redis->connect(C('REDIS_HOST'), C('REDIS_PORT'));
//值为false,视为清除当前key
if ($value === false) {
return $redis->delete($key);
}
if (empty($value)) {
$data = $redis->get($key);
return empty($data) ? false : unserialize($data);
}
$redis->set($key, serialize($value), $times);
}
/**
* 正则验证
* @param $value
* @param string $rule
* @return bool
*/
public static function regex($value, $rule = 'require')
{
$validate = array(
'require' => '/\S+/',
'email' => '/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/',//PHP验证邮箱地址正则表达式代码
//'email' => '/^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@([a-zA-Z0-9]+[-.])+([a-z]{2,5})$/ims',//PHP验证邮箱地址正则表达式代码
'url' => '/^http(s?):\/\/(?:[A-za-z0-9-]+\.)+[A-za-z]{2,4}(?:[\/\?#][\/=\?%\-&~`@[\]\':+!\.#\w]*)?$/',
'currency' => '/^\d+(\.\d+)?$/',
'number' => '/^\d+$/',
'zip' => '/^\d{6}$/',
'integer' => '/^[-\+]?\d+$/',
'double' => '/^[-\+]?\d+(\.\d+)?$/',
'english' => '/^[A-Za-z]+$/',
'tel' => '/^(0\d{2,3})?(\d{7,8})$/ims',//PHP验证固定号码的正则表达式
'phone' => '/^1[345789]\d{9}$/ims',//PHP验证手机号正则表达式代码
'idcard' => '/^\d{15}$)|(^\d{17}([0-9]|X)$/isu',//PHP验证身份证号正则表达式代码
'qq' => '/^\d{5,12}$/isu',//PHP验证QQ号码的正则表达式代码
'wechat' => '/^[_a-zA-Z0-9]{5,19}+$/isu',//PHP验证是否微信号的正则表达式代码
'letter' => '/^[\x{4e00}-\x{9fa5}]{2,10}$|^[a-zA-Z\s]*[a-zA-Z\s]{2,20}$/isu',//PHP验证是否只包含中文或英文的正则表达式代码
);
// 检查是否有内置的正则表达式
if (isset($validate[strtolower($rule)]))
$rule = $validate[strtolower($rule)];
return preg_match($rule, $value) === 1;
}
public static function clearCookies($value = '', $name = null)
{
if (is_null($name)) {
if (empty($_COOKIE))
return;
// 要删除的cookie前缀,不指定则删除config设置的指定前缀
$prefix = empty($value) ? C('COOKIE_PREFIX') : $value;
if (!empty($prefix) || null == $name) {// 如果前缀为空字符串将不作处理直接返回//
//增加 null == $name 判断
foreach ($_COOKIE as $key => $val) {
if (0 === stripos($key, $prefix) || null == $name) {
//增加 null == $name 判断
self::cache($key, null);
setcookie($key, '', time() - 3600, C('COOKIE_PATH'), C('COOKIE_DOMAIN'));
unset($_COOKIE[$key]);
}
}
}
return;
}
}
private static $_outEncoding = "GB2312";
public static function getPinyin($str, $pix = ' ', $code = 'utf-8')
{
$_DataKey = "a|ai|an|ang|ao|ba|bai|ban|bang|bao|bei|ben|beng|bi|bian|biao|bie|bin|bing|bo|bu|ca|cai|can|cang|cao|ce|ceng|cha" . "|chai|chan|chang|chao|che|chen|cheng|chi|chong|chou|chu|chuai|chuan|chuang|chui|chun|chuo|ci|cong|cou|cu|" . "cuan|cui|cun|cuo|da|dai|dan|dang|dao|de|deng|di|dian|diao|die|ding|diu|dong|dou|du|duan|dui|dun|duo|e|en|er" . "|fa|fan|fang|fei|fen|feng|fo|fou|fu|ga|gai|gan|gang|gao|ge|gei|gen|geng|gong|gou|gu|gua|guai|guan|guang|gui" . "|gun|guo|ha|hai|han|hang|hao|he|hei|hen|heng|hong|hou|hu|hua|huai|huan|huang|hui|hun|huo|ji|jia|jian|jiang" . "|jiao|jie|jin|jing|jiong|jiu|ju|juan|jue|jun|ka|kai|kan|kang|kao|ke|ken|keng|kong|kou|ku|kua|kuai|kuan|kuang" . "|kui|kun|kuo|la|lai|lan|lang|lao|le|lei|leng|li|lia|lian|liang|liao|lie|lin|ling|liu|long|lou|lu|lv|luan|lue" . "|lun|luo|ma|mai|man|mang|mao|me|mei|men|meng|mi|mian|miao|mie|min|ming|miu|mo|mou|mu|na|nai|nan|nang|nao|ne" . "|nei|nen|neng|ni|nian|niang|niao|nie|nin|ning|niu|nong|nu|nv|nuan|nue|nuo|o|ou|pa|pai|pan|pang|pao|pei|pen" . "|peng|pi|pian|piao|pie|pin|ping|po|pu|qi|qia|qian|qiang|qiao|qie|qin|qing|qiong|qiu|qu|quan|que|qun|ran|rang" . "|rao|re|ren|reng|ri|rong|rou|ru|ruan|rui|run|ruo|sa|sai|san|sang|sao|se|sen|seng|sha|shai|shan|shang|shao|" . "she|shen|sheng|shi|shou|shu|shua|shuai|shuan|shuang|shui|shun|shuo|si|song|sou|su|suan|sui|sun|suo|ta|tai|" . "tan|tang|tao|te|teng|ti|tian|tiao|tie|ting|tong|tou|tu|tuan|tui|tun|tuo|wa|wai|wan|wang|wei|wen|weng|wo|wu" . "|xi|xia|xian|xiang|xiao|xie|xin|xing|xiong|xiu|xu|xuan|xue|xun|ya|yan|yang|yao|ye|yi|yin|ying|yo|yong|you" . "|yu|yuan|yue|yun|za|zai|zan|zang|zao|ze|zei|zen|zeng|zha|zhai|zhan|zhang|zhao|zhe|zhen|zheng|zhi|zhong|" . "zhou|zhu|zhua|zhuai|zhuan|zhuang|zhui|zhun|zhuo|zi|zong|zou|zu|zuan|zui|zun|zuo";
$_DataValue = "-20319|-20317|-20304|-20295|-20292|-20283|-20265|-20257|-20242|-20230|-20051|-20036|-20032|-20026|-20002|-19990" . "|-19986|-19982|-19976|-19805|-19784|-19775|-19774|-19763|-19756|-19751|-19746|-19741|-19739|-19728|-19725" . "|-19715|-19540|-19531|-19525|-19515|-19500|-19484|-19479|-19467|-19289|-19288|-19281|-19275|-19270|-19263" . "|-19261|-19249|-19243|-19242|-19238|-19235|-19227|-19224|-19218|-19212|-19038|-19023|-19018|-19006|-19003" . "|-18996|-18977|-18961|-18952|-18783|-18774|-18773|-18763|-18756|-18741|-18735|-18731|-18722|-18710|-18697" . "|-18696|-18526|-18518|-18501|-18490|-18478|-18463|-18448|-18447|-18446|-18239|-18237|-18231|-18220|-18211" . "|-18201|-18184|-18183|-18181|-18012|-17997|-17988|-17970|-17964|-17961|-17950|-17947|-17931|-17928|-17922" . "|-17759|-17752|-17733|-17730|-17721|-17703|-17701|-17697|-17692|-17683|-17676|-17496|-17487|-17482|-17468" . "|-17454|-17433|-17427|-17417|-17202|-17185|-16983|-16970|-16942|-16915|-16733|-16708|-16706|-16689|-16664" . "|-16657|-16647|-16474|-16470|-16465|-16459|-16452|-16448|-16433|-16429|-16427|-16423|-16419|-16412|-16407" . "|-16403|-16401|-16393|-16220|-16216|-16212|-16205|-16202|-16187|-16180|-16171|-16169|-16158|-16155|-15959" . "|-15958|-15944|-15933|-15920|-15915|-15903|-15889|-15878|-15707|-15701|-15681|-15667|-15661|-15659|-15652" . "|-15640|-15631|-15625|-15454|-15448|-15436|-15435|-15419|-15416|-15408|-15394|-15385|-15377|-15375|-15369" . "|-15363|-15362|-15183|-15180|-15165|-15158|-15153|-15150|-15149|-15144|-15143|-15141|-15140|-15139|-15128" . "|-15121|-15119|-15117|-15110|-15109|-14941|-14937|-14933|-14930|-14929|-14928|-14926|-14922|-14921|-14914" . "|-14908|-14902|-14894|-14889|-14882|-14873|-14871|-14857|-14678|-14674|-14670|-14668|-14663|-14654|-14645" . "|-14630|-14594|-14429|-14407|-14399|-14384|-14379|-14368|-14355|-14353|-14345|-14170|-14159|-14151|-14149" . "|-14145|-14140|-14137|-14135|-14125|-14123|-14122|-14112|-14109|-14099|-14097|-14094|-14092|-14090|-14087" . "|-14083|-13917|-13914|-13910|-13907|-13906|-13905|-13896|-13894|-13878|-13870|-13859|-13847|-13831|-13658" . "|-13611|-13601|-13406|-13404|-13400|-13398|-13395|-13391|-13387|-13383|-13367|-13359|-13356|-13343|-13340" . "|-13329|-13326|-13318|-13147|-13138|-13120|-13107|-13096|-13095|-13091|-13076|-13068|-13063|-13060|-12888" . "|-12875|-12871|-12860|-12858|-12852|-12849|-12838|-12831|-12829|-12812|-12802|-12607|-12597|-12594|-12585" . "|-12556|-12359|-12346|-12320|-12300|-12120|-12099|-12089|-12074|-12067|-12058|-12039|-11867|-11861|-11847" . "|-11831|-11798|-11781|-11604|-11589|-11536|-11358|-11340|-11339|-11324|-11303|-11097|-11077|-11067|-11055" . "|-11052|-11045|-11041|-11038|-11024|-11020|-11019|-11018|-11014|-10838|-10832|-10815|-10800|-10790|-10780" . "|-10764|-10587|-10544|-10533|-10519|-10331|-10329|-10328|-10322|-10315|-10309|-10307|-10296|-10281|-10274" . "|-10270|-10262|-10260|-10256|-10254";
$_TDataKey = explode('|', $_DataKey);
$_TDataValue = explode('|', $_DataValue);
$data = (PHP_VERSION >= '5.0') ? array_combine($_TDataKey, $_TDataValue) : self::_Array_Combine($_TDataKey, $_TDataValue);
arsort($data);
reset($data);
$str = self::safe_encoding($str);
$_Res = '';
for ($i = 0; $i < strlen($str); $i++) {
$_P = ord(substr($str, $i, 1));
if ($_P > 160) {
$_Q = ord(substr($str, ++$i, 1));
$_P = $_P * 256 + $_Q - 65536;
}
$_Res .= self::_Pinyin($_P, $data) . $pix;
}
return preg_replace("/[^a-z0-9" . $pix . "]*/", '', $_Res);
}
private static function _Pinyin($_Num, $_Data)
{
if ($_Num > 0 && $_Num < 160)
return chr($_Num);
elseif ($_Num < -20319 || $_Num > -10247)
return '';
else {
foreach ($_Data as $k => $v) {
if ($v <= $_Num)
break;
}
return $k;
}
}
public static function getFirstChar($str = '')
{
if (!$str) return null;
$fchar = ord($str{0});
if ($fchar >= ord("A") and $fchar <= ord("z")) return strtoupper($str{0});
$s = self::safe_encoding($str);
$asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
if ($asc >= -20319 and $asc <= -20284) return "A";
if ($asc >= -20283 and $asc <= -19776) return "B";
if ($asc >= -19775 and $asc <= -19219) return "C";
if ($asc >= -19218 and $asc <= -18711) return "D";
if ($asc >= -18710 and $asc <= -18527) return "E";
if ($asc >= -18526 and $asc <= -18240) return "F";
if ($asc >= -18239 and $asc <= -17923) return "G";
if ($asc >= -17922 and $asc <= -17418) return "H";
if ($asc >= -17417 and $asc <= -16475) return "J";
if ($asc >= -16474 and $asc <= -16213) return "K";
if ($asc >= -16212 and $asc <= -15641) return "L";
if ($asc >= -15640 and $asc <= -15166) return "M";
if ($asc >= -15165 and $asc <= -14923) return "N";
if ($asc >= -14922 and $asc <= -14915) return "O";
if ($asc >= -14914 and $asc <= -14631) return "P";
if ($asc >= -14630 and $asc <= -14150) return "Q";
if ($asc >= -14149 and $asc <= -14091) return "R";
if ($asc >= -14090 and $asc <= -13319) return "S";
if ($asc >= -13318 and $asc <= -12839) return "T";
if ($asc >= -12838 and $asc <= -12557) return "W";
if ($asc >= -12556 and $asc <= -11848) return "X";
if ($asc >= -11847 and $asc <= -11056) return "Y";
if ($asc >= -11055 and $asc <= -10247) return "Z";
return null;
}
private static function safe_encoding($string)
{
$encoding = "UTF-8";
for ($i = 0; $i < strlen($string); $i++) {
if (ord($string{$i}) < 128) continue;
if ((ord($string{$i}) & 224) == 224) { //第一个字节判断通过
$char = $string{++$i};
if ((ord($char) & 128) == 128) { //第二个字节判断通过
$char = $string{++$i};
if ((ord($char) & 128) == 128) {
$encoding = "UTF-8";
break;
}
}
}
if ((ord($string{$i}) & 192) == 192) { //第一个字节判断通过
$char = $string{++$i};
if ((ord($char) & 128) == 128) { //第二个字节判断通过
$encoding = "GB2312";
break;
}
}
}
if (strtoupper($encoding) == strtoupper(self::$_outEncoding))
return $string;
else
return iconv($encoding, self::$_outEncoding, $string);
}
private static function _Array_Combine($_Arr1, $_Arr2)
{
for ($i = 0; $i < count($_Arr1); $i++)
$_Res [$_Arr1 [$i]] = $_Arr2 [$i];
return $_Res;
}
/**
* 将字符串(中文同样实用)转为ascii
* 注意:我默认当前我们的php文件环境是UTF-8
* 如果是GBK的话mb_convert_encoding操作就不需要
* @param $str
* @return string
*/
public static function strToASCII($str)
{
$str = mb_convert_encoding($str, 'GB2312');
$change_after = '';
for ($i = 0; $i < strlen($str); $i++) {
$temp_str = dechex(ord($str[$i]));
$change_after .= $temp_str[1] . $temp_str[0];
}
return strtoupper($change_after);
}
/**
* 将ascii转为字符串(中文同样实用)
* 注意:我默认当前我们的php文件环境是UTF-8
* 如果是GBK的话mb_convert_encoding操作就不需要
* @param $SACII
* @return string
*/
public static function ASCIIToStr($SACII)
{
$asc_arr = str_split(strtolower($SACII), 2);
$str = '';
for ($i = 0; $i < count($asc_arr); $i++) {
$str .= chr(hexdec($asc_arr[$i][1] . $asc_arr[$i][0]));
}
return mb_convert_encoding($str, 'UTF-8', 'GB2312');
}
/**
* 字母转ASCII
* @param $str
* @return string
*/
public static function AZIncrement($str)
{
// 参数转换为大写
$str = strtoupper($str);
// 返回参数的 ASCII 值
$str = ord($str);
if ($str < 65 || $str > 90) {
// 参数不符合预期
return '你传过来的是什么鬼!';
}
if ($str == 90) {
// 参数已是末位英文字母Z,不可以递增
return '已经是 Z 啦!';
}
return chr($str + 1);
}
/**
* 返回字母索引
* 或
* 依据字母索引返回大写字母
* @param $letter
* @param bool $getUpper
* @return false|int|mixed|string
*/
public static function ZANumber($letter, $getUpper = false)
{
$chtLetter = strtoupper($letter);
$arrLetters = array(" ", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
if ($getUpper)
return $arrLetters[$letter];
else
return array_search($chtLetter, $arrLetters);
}
/**
* 毫秒时间戳
* @return float /毫秒时间戳
*/
public static function getMillisecond()
{
list($s1, $s2) = explode(' ', microtime());
return (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000);
}
/**
* 创建UUID
* @param string $prefix /前缀
* @param string $mark /连接符
* @return string /结果
*/
public static function UUID($prefix = '', $mark = '')
{
$chars = md5(uniqid(mt_rand(), true));
$uuid = substr($chars, 0, 8) . $mark;
$uuid .= substr($chars, 8, 4) . $mark;
$uuid .= substr($chars, 12, 4) . $mark;
$uuid .= substr($chars, 16, 4) . $mark;
$uuid .= substr($chars, 20, 12);
return $prefix . $uuid;
}
/**
* 中文字段需要decode解码,否则入库错误
* @param $arrParams
* @return array
*/
public static function fieldDecode($arrParams)
{
$arrNew = array();
foreach ($arrParams as $key => $field) {
$arrNew[$key] = urldecode($field);
}
return $arrNew;
}
public static function encryption($for, $data, $extend = '****')
{
switch ($for) {
case 'mobile':
return substr_replace($data, $extend, 3, 4);
break;
default:
return false;
}
}
/**
* 通用导出
* @param $data /导出数据
* @param $indexKey /导出数据键
* @param $headArr /表头
* @param $title /生成文件名
* 必须保持 $indexKey 和 $headArr 顺序对应才能保证导出数据准确
*/
public static function plainExportExcel($data, $indexKey, $headArr, $title)
{
//引入核心文件
vendor("PHPExcel");
vendor("PHPExcel.IOFactory");
$objPHPExcel = new \PHPExcel();
$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
// 设置excel文档的属性
$objPHPExcel->getProperties();
$fileName = $title . date("Y-m-d", time()) . ".xls";
//excel头
$letter = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH", "AI", "AJ", "AK", "AL", "AM", "AN", "AO");
//设置表头
$num = 0;
foreach ($headArr as $v) {
$objPHPExcel->setActiveSheetIndex(0)->setCellValue($letter[$num] . '1', $v);
$num++;
}
$column = 2;
$objActSheet = $objPHPExcel->getActiveSheet();
//写入内容
foreach ($data as $key => $rows) {
//行写入
$num = 0;
foreach ($indexKey as $ki => $vi) {
//列写入
$objActSheet->setCellValue($letter[$num] . $column, $rows[$vi]);
$num++;
}
$column++;
}
$fileName = iconv("utf-8", "gb2312", $fileName);
$objPHPExcel->setActiveSheetIndex(0);
ob_end_clean();
ob_start();
Header('content-Type:application/vnd.ms-excel;charset=utf-8');
header('Content-Type: application/vnd.ms-excel');
header("Content-Disposition: attachment;filename=\"$fileName\"");
header('Cache-Control: max-age=0');
header('content-type:application/octet-stream');
$objWriter->save('php://output'); //文件通过浏览器下载
}
/**
* 多sheet导出
* @param $configs
* @param string $fileName
*/
public static function plainExportExcelSheets($configs, $fileName = 'noname')
{
//引入核心文件
vendor("PHPExcel");
vendor("PHPExcel.IOFactory");
$objPHPExcel = new \PHPExcel();
$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
// 设置excel文档的属性
$objPHPExcel->getProperties();
$fileName = $fileName . date("Y-m-d", time()) . ".xls";
//excel头
$letter = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH", "AI", "AJ", "AK", "AL", "AM", "AN", "AO");
//$data, $indexKey, $headArr, $title
foreach ($configs as $sheetIndex => $config) {
if ($sheetIndex > 0) {
$objPHPExcel->createSheet();
}
$data = $config[0];
$headArr = $config[2];
$indexKey = $config[1];
$sheetName = isset($config[3]) ? $config[3] : 'Sheet' . $sheetIndex;
//$objPHPExcel->getActiveSheet()->setTitle($result[‘alias_name‘][$ca]);
//设置表头
$num = 0;
foreach ($headArr as $v) {
$objPHPExcel->setActiveSheetIndex($sheetIndex)->setCellValue($letter[$num] . '1', $v);
$num++;
}
$column = 2;
$objActSheet = $objPHPExcel->getActiveSheet()->setTitle($sheetName);
//写入内容
foreach ($data as $key => $rows) {
//行写入
$num = 0;
foreach ($indexKey as $ki => $vi) {
//列写入
$objActSheet->setCellValue($letter[$num] . $column, $rows[$vi]);
$num++;
}
$column++;
}
$fileName = iconv("utf-8", "gb2312", $fileName);
// $objPHPExcel->setActiveSheetIndex($sheetIndex);
}
$objPHPExcel->setActiveSheetIndex(0);
ob_end_clean();
ob_start();
Header('content-Type:application/vnd.ms-excel;charset=utf-8');
header('Content-Type: application/vnd.ms-excel');
header("Content-Disposition: attachment;filename=\"$fileName\"");
header('Cache-Control: max-age=0');
header('content-type:application/octet-stream');
$objWriter->save('php://output'); //文件通过浏览器下载
}
public function token($for = 'form', $token = '', $inter = 'lyj')
{
$tk = '';
$default = $for . $inter . date('YmdH');
switch ($for) {
case 'user_sms':
$cookiePre = C('COOKIE_PREFIX_USER');
$tk = md5($default . $_COOKIE[$cookiePre . 'key']);
break;
case 'form':
default:
$tk = md5($default . self::randStr());
}
if ($token) {
return $tk === $token ? true : false;
}
return $tk;
}
/**
* 获取当前网站是HTTPS还是HTTP
* @param bool $bool
* @return bool|string
*/
public function protocol($bool = false)
{
//获取当前网站是HTTPS还是HTTP:
$http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
if ($bool) {
return $http_type == 'https://' ? true : false;
}
return $http_type;
}
}
二、上传处理类,主要处理图片上传、文档上传、以及后续的移动和解析
<?php
/**
* 归属于:Common
* 本类名:Upload
* 创建者:IntelliJ IDEA
* 创建时:2021/10/17 16:42:42
* 职责集:上传处理类
*/
namespace Common\Controller;
class UploadController extends BaseController
{
public function index($subPath = '')
{
//var_dump($_FILES['file']);
if (isset($_FILES['file'])) {
$arrPars = $_REQUEST;
//解密base64
$strData = str_replace(" ", " +", @$_REQUEST['data']);
$arrData = json_decode(base64_decode($strData), true);
if (!empty($arrData)) {
$arrPars = array_merge($arrPars, $arrData);
}
$arrPars['subPath'] = $subPath;
self::entrance($arrPars);
}
}
public function file()
{
$file = $_FILES['file'];
//配置上传目录
$pathUploadConfig = C('UPLOAD_FOLDER');
if (empty($pathUploadConfig)) {
//目录不存在赋予默认根目录指定文件夹
$pathUploadConfig = "./Upload/";
}
//判断目录是否存在,不存在就递归创建
if (!is_dir($pathUploadConfig)) {
mkdir($pathUploadConfig, 0777, true);
}
$index = 0;
$dbPre = C('DB_PREFIX');
if ($file["error"] == 0) {
//未发生错误
if ($file["size"] != 0) {
$strName = $file['name'];
$strExt = substr($strName, strripos($strName, "."));
$strNameTrue = @date("YmdHis") . CustomerToolsController::getMillisecond() . rand(1000, 9999) . $strExt;
$strFull = $pathUploadConfig . $strNameTrue;
$boolResult = @move_uploaded_file($file['tmp_name'], $strFull);
$strDateTime = date("Y/m/d H:i:s");
if ($boolResult) {
//记录数据
$rowData = array(
"file_name" => $strName,
"file_path" => $strFull,
"file_time" => $strDateTime
);
$index = M("files", $dbPre)->add($rowData);
} else {
//$strErrorMsg .= $strName . "\n";
}
} else {
$boolCode = false;
//0大小文件
}
} else {
$boolCode = false;
//上传错误
}
if ($index == 0) {
FeedbackController::feedback(1, 0);
} else {
FeedbackController::feedback(0, $index);
}
}
/**
* 入口
* @param $arrPars
*/
public static function entrance($arrPars)
{
//配置上传目录
$pathUploadConfig = C('UPLOAD_IMAGES_FOLDER') . $arrPars['subPath'] . $arrPars['for'] . '/';
if (empty($pathUploadConfig)) {
//目录不存在赋予默认根目录指定文件夹
$pathUploadConfig = "./Upload/";
}
//判断目录是否存在,不存在就递归创建
if (!is_dir($pathUploadConfig)) {
mkdir($pathUploadConfig, 0777, true);
}
$arrConfig = array(
'savePath' => $pathUploadConfig,
);
if (!empty($arrPars)) {
$arrConfig = array_merge($arrConfig, $arrPars);
}
self::moveFiles($arrConfig);
}
/**
* 上传文件
* @param array $config
*/
public static function moveFiles($config = array())
{
/** @var /全部的文件 $files */
$arrFiles = isset($_FILES['files']) ? $_FILES['files'] : (isset($_FILES['file']) ? $_FILES['file'] : array());
//var_dump($arrFiles);
if (!isset($arrFiles[0])) {
$arrFiles = array($arrFiles);
}
//echo json_encode($arrFiles);exit;
$strError = "";
//多文件
foreach ($arrFiles as $i => $v) {
if ($v["error"][0] == 0) {
//未发生错误
if ($v["size"] != 0) {
$strName = $v['name'];
$strExt = substr($strName, strripos($strName, "."));
$strNameTrue = self::getMillisecond() . rand(1000, 9999) . $strExt;
$boolResult = @move_uploaded_file($v['tmp_name'], $config['savePath'] . $strNameTrue);
$thumb_size = self::createThunmbConfig();
/** @var /已更改缩略图的名称信息 */
$all_img_url = self::createMultiThumb($config['savePath'], $strNameTrue, $thumb_size);
if ($boolResult) {
$arrParas = array(
// "file_id" => CustomerToolsController::UUID(),
"file_by" => $config['token'],
"file_for" => $config['for'],
"file_name" => $strName,
"file_true" => $strNameTrue,
"file_path" => $config['savePath'],
"file_date" => @date(C('DATE_FORMAT_LONG')),
"file_size" => $v["size"],
"file_ext" => $strExt,
"config" => array(
"import" => intval(@$_REQUEST['import']),
"save" => intval(@$_REQUEST['save']),
"record" => 1,//intval(@$_REQUEST['record']),//限定为必存
"new" => @$_REQUEST['new'],
"suffix" => @$_REQUEST['suffix'],
"prefix" => @$_REQUEST['prefix'],
'initTable' => @$_REQUEST['initTable'],
)
);
//是否需要导入
if ($arrParas['config']['import'] > 0) {
ExcelController::import($arrParas);
}
//是否需要导入
if ($arrParas['config']['record'] > 0) {
M('files')->add($arrParas, array(
'file_by' => $config['token'],
'file_for' => $config['for'],
'file_name' => $strName
), true);
}
//返回结果
$arrResult = array(
'path' => str_replace('./','/',$config['savePath']),
'name' => $strName,
'token' => $config['token'],
'original' => $strNameTrue,
'thumbnail' => str_replace('.','_360x360.',$strNameTrue)
);
self::feedback(0, $arrResult);
} else {
//$strErrorMsg .= $strName . "\n";
}
} else {
$boolCode = false;
//0大小文件
}
} else {
$boolCode = false;
//上传错误
}
usleep(1500);//毫秒
self::feedback(4021);
}
}
#region 返回信息
/*public static function output($data = ['code' => 0, 'msg' => '成功', 'result' => []])
{
exit(json_encode($data));
}*/
#endregion
#region 新生成缩略图
private static function createThunmbConfig($type = 'goods')
{
//设置文件存放路径及缩放比例
switch ($type) {
case 'header':
$thumb_size = C('IMAGES_THUMB_SIZE_SETTING.USER_HEADER');
break;
case 'photos':
$thumb_size = C('IMAGES_THUMB_SIZE_SETTING.PHOTOS_HEADER');
break;
case 'emotions':
$thumb_size = C('IMAGES_THUMB_SIZE_SETTING.EMOTIONS_PHOTO');
break;
default:
$thumb_size = C('IMAGES_THUMB_SIZE_SETTING.GOODS_IMAGE');
}
return $thumb_size;
}
/**
* 批量生成不同尺寸缩略图
* @param $sourcePath
* @param $image
* @param $size_arr
* @param $strExt
* @return string
*/
private static function createMultiThumb($sourcePath, $image, $size_arr)
{
$all_img_url = '';
$img_url_arr = array();
//需要生成多个缩略图
if (is_array($size_arr)) {
foreach ($size_arr as $key => $value) {
$img_url_arr[$key] = self::thumbSave($sourcePath, $image, $value);
}
$all_img_url = json_encode($img_url_arr);
} else {
$all_img_url = self::thumbSave($sourcePath, $image, $size_arr);
}
return $all_img_url;
}
/**
* 批量生成不同尺寸缩略图
* @param $sourcePath
* @param $imageName
* @param $thumb_size
* @param $strExt
* @return string
*/
private static function thumbSave($sourcePath, $imageName, $thumb_size)
{
//$source = $path . $info['savepath'] . $info['savename'];
$image = new \Think\Image();
$image->open($sourcePath . $imageName);
$size = explode('*', $thumb_size);
$width = $size[0];
$height = $size[1];
//如果原始图片尺寸本来就小于缩略尺寸,那么不做压缩操作
if ($image->width() <= $width && $image->height() <= $height && false) {
$name = $sourcePath . $imageName;
} else {
$arrName = explode('.', $imageName);
// $name = $path . $info['savepath'] . $sha1 . '_' . $width . 'x' . $height . '_' . $file_name;
$name = $sourcePath . $arrName[0] . '_' . $width . 'x' . $height . '.' . $arrName[1];
// $image->thumb($width, $height, \Think\Image::IMAGE_THUMB_SCALE);
$image->thumb($width, $height, \Think\Image::IMAGE_THUMB_FIXED);
$image->save($name);
}
return $name;
}
#endregion
/**
* 文件上传方法,TP在此处有个坑,当图片名称命名不规范时,图片不能保存而且不会提示错误
* 成功返回图片保存路径
* 失败返回相关失败信息
*/
public function uploading()
{
/**
* file_put_contents('1.txt',var_export($_POST,true));
* file_put_contents('2.txt',var_export($GLOBALS['HTTP_RAW_POST_DATA'],true));
* $raw_post_data = file_get_contents('php://input', 'r');
* file_put_contents('3.txt',var_export($raw_post_data, true));
* file_put_contents('4.txt',var_export($_FILES, true));
*/
$type = I('post.type', 0, 'intval');//操作类型,0:商品图像,1:用户头像上传,2:图片上传,3:说说图片上传
$gid = I('post.gid', 0, 'intval');
$gnum = I('post.gnum', 0, 'intval');
$method = I('post.method', '', 'strval');
$data = array();
//设置文件存放路径及缩放比例
$folder = '';
$thumb_size = '';
switch ($type) {
case 1:
$folder = 'header';
$thumb_size = C('IMAGES_THUMB_SIZE_SETTING.USER_HEADER');
break;
case 2:
$folder = 'photos';
$thumb_size = C('IMAGES_THUMB_SIZE_SETTING.PHOTOS_HEADER');
break;
case 3:
$folder = 'emotions';
$thumb_size = C('IMAGES_THUMB_SIZE_SETTING.EMOTIONS_PHOTO');
break;
default:
$folder = 'goods';
$thumb_size = C('IMAGES_THUMB_SIZE_SETTING.GOODS_IMAGE');
}
$path = C('SOURCE_IMAGES_FOLDERS') . $folder . '/' . $gnum;
//echo $path;exit;
if (!file_exists($path)) {
mkdir($path);
chmod($path, 755);
}
$file_arr = explode('.', $_FILES['file']['name']);
$file_ext = $file_arr[1];
$file_name = $file_arr[0];
$file_name_new = @date('YmdHis') . mt_rand(1000, 9999);
$sha1 = sha1(time() . mt_rand());
$config = array();
$config['maxSize'] = 3145728;
$config['exts'] = array('jpg', 'gif', 'png', 'jpeg', 'JPG', 'GIF', 'PNG', 'JPEG');
$config['rootPath'] = $path;
$config['savePath'] = '/';
$config['subName'] = @date('Ym');
$config['saveName'] = $file_name_new;//$sha1.'-'.$file_name;
$upload = new \Think\Upload($config);
$info = $upload->uploadOne($_FILES['file']);
if (!$info) {
self::feedback(1, array(), $upload->getError());
} else {
//文件存放路径
$url = $path . $info['savepath'] . $info['savename'];
//生成缩略图
// $all_img_url = $this->_multi_thumb_save($path,$info,$sha1,$thumb_size,$_FILES['file']['name']);
/** @var /已更改缩略图的名称信息 */
$all_img_url = $this->_multi_thumb_save($path, $info, $file_name_new, $thumb_size, "." . $file_ext);
$data = array(
'url' => $url,
'thumb_url' => $all_img_url
);
if (method_exists(new DataController(), $method))
DataController::$method($all_img_url, array('goods_number' => $gnum));
self::feedback(0, $data);
}
// $this->ajaxReturn($data);
}
/**
* 批量生成不同尺寸缩略图
* @param $path 原始图片
* @param $info 图片上传后获得的object
* @param $sha1 sha1()后得到的值
* @param $size_arr 缩略尺寸数组
* @param $file_name 原始图片名称
* @return string 所有缩略图地址字串
*/
private function _multi_thumb_save($path, $info, $sha1, $size_arr, $file_name)
{
$all_img_url = '';
$img_url_arr = array();
//需要生成多个缩略图
if (is_array($size_arr)) {
foreach ($size_arr as $key => $value) {
$img_url_arr[$key] = $this->_thumb_save($path, $info, $sha1, $value, $file_name);
}
$all_img_url = json_encode($img_url_arr);
} else {
$all_img_url = $this->_thumb_save($path, $info, $sha1, $size_arr, $file_name);
}
return $all_img_url;
}
/**
* 批量生成不同尺寸缩略图
* @param $path 原始图片
* @param $info 图片上传后获得的object
* @param $sha1 sha1()后得到的值
* @param $thumb_size 缩略尺寸
* @param $file_name 原始图片名称
* @return string 所有缩略图地址字串
*/
private function _thumb_save($path, $info, $sha1, $thumb_size, $file_name)
{
$source = $path . $info['savepath'] . $info['savename'];
$image = new \Think\Image();
$image->open($source);
$size = explode('*', $thumb_size);
$width = $size[0];
$height = $size[1];
//如果原始图片尺寸本来就小于缩略尺寸,那么不做压缩操作
if ($image->width() <= $width && $image->height() <= $height) {
$name = $source;
} else {
$name = $path . $info['savepath'] . $sha1 . '_' . $width . 'x' . $height . '_' . $file_name;
$image->thumb($width, $height, \Think\Image::IMAGE_THUMB_SCALE);
$image->save($name);
}
return $name;
}
}
class ExcelController extends InterfaceController
{
public function index()
{
}
#region 导入检测
public static function import($config = array())
{
$arrConfig = C('UPLOAD_CONFIG');
//检查配置,防止出问题
$result = self::checkConfig($arrConfig, $config);
//获取本次要使用的配置
$configWant = $arrConfig['import'][@$config['config']['import']];
//echo json_encode($configWant);exit;
if ($result) {
if (!empty($configWant)) {
$objPHPExcel = self::loadExcelObject($config);
//多个sheet配置的循环导入
foreach ($configWant as $c => $conf) {
$sheet = $objPHPExcel->getSheet(intval(@$conf['sheet']));
$highestRow = $sheet->getHighestRow();//取得总行数
$highestColumn = $sheet->getHighestColumn(); //取得总列数
$dataAll = array();
for ($i = 2; $i <= $highestRow; $i++) {
$rowData = array();
//读取excel内容到数组
foreach ($conf['fields'] as $excelCol => $dbField) {
$rowData[$dbField] = $objPHPExcel->getActiveSheet()->getCell($excelCol . $i)->getValue();
}
//追加的cookie内容
foreach ($conf['cookies'] as $cookie => $cookies) {
$rowData[$cookies] = $_COOKIE[$cookie];
}
$dataAll[] = $rowData;
}
//echo json_encode($dataAll);
//具有清空原有数据的配置
//################待优化####################
if (isset($conf['clear'])) {
$map = '1=1';
if (!empty($conf['clear'])) {
foreach ($conf['clear'] as $k => $v) {
$map .= " AND {$v}='" . @$_COOKIE[$k] . "'";
}
}
M(@$conf['table'])->where($map)->delete();
}
//##################待优化##################
M(@$conf['table'])->addAll($dataAll);
}
// exit;
FeedbackController::feedback(0);
} else {
FeedbackController::feedback(33);
}
} else {
FeedbackController::feedback(33);
}
}
public static function checkConfig($arrConfig, $config)
{
$importCus = $config['config']['import'];
if (intval($importCus) > 0) {
if (!empty($arrConfig['import'][$importCus])) {
return $arrConfig['import'][$importCus];
}
}
return false;
}
#endregion
#region 载入Excel并返回操作对象
public static function loadExcelObject($arrPars)
{
vendor("PHPExcel");
$fileName = $arrPars['file_path'] . $arrPars['file_true'];
$extension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));//判断导入表格后缀格式
$objPHPExcel = '';
if ($extension == 'xlsx') {
$objReader = \PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = $objReader->load($fileName, $encode = 'utf-8');
} else if ($extension == 'xls') {
$objReader = \PHPExcel_IOFactory::createReader('Excel5');
$objPHPExcel = $objReader->load($fileName, $encode = 'utf-8');
}
return $objPHPExcel;
}
#endregion
public static function importNew($strDBName, $arrPars, $strTableName, $arrYet)
{
$objPHPExcel = self::loadExcelObject($arrPars);
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();//取得总行数
$highestColumn = $sheet->getHighestColumn(); //取得总列数
$mdlDB = M($strDBName . "." . $strTableName, null);
if (intval($arrPars['config']['initTable']) > 0) {
$mdlDB->execute("TRUNCATE {$strDBName}.{$strTableName}");
}
for ($i = 2; $i <= $highestRow; $i++) {
$rowData = array();
foreach ($arrYet as $excelCol => $dbField) {
$rowData[$dbField[1]] = $objPHPExcel->getActiveSheet()->getCell($dbField[0] . $i)->getValue();
}
$mdlDB->add($rowData);
usleep(100);
}
}
}
class CustomerToolsController
{
private static $_outEncoding = "GB2312";
public static function getPinyin($str, $pix = ' ', $code = 'utf-8')
{
$_DataKey = "a|ai|an|ang|ao|ba|bai|ban|bang|bao|bei|ben|beng|bi|bian|biao|bie|bin|bing|bo|bu|ca|cai|can|cang|cao|ce|ceng|cha" . "|chai|chan|chang|chao|che|chen|cheng|chi|chong|chou|chu|chuai|chuan|chuang|chui|chun|chuo|ci|cong|cou|cu|" . "cuan|cui|cun|cuo|da|dai|dan|dang|dao|de|deng|di|dian|diao|die|ding|diu|dong|dou|du|duan|dui|dun|duo|e|en|er" . "|fa|fan|fang|fei|fen|feng|fo|fou|fu|ga|gai|gan|gang|gao|ge|gei|gen|geng|gong|gou|gu|gua|guai|guan|guang|gui" . "|gun|guo|ha|hai|han|hang|hao|he|hei|hen|heng|hong|hou|hu|hua|huai|huan|huang|hui|hun|huo|ji|jia|jian|jiang" . "|jiao|jie|jin|jing|jiong|jiu|ju|juan|jue|jun|ka|kai|kan|kang|kao|ke|ken|keng|kong|kou|ku|kua|kuai|kuan|kuang" . "|kui|kun|kuo|la|lai|lan|lang|lao|le|lei|leng|li|lia|lian|liang|liao|lie|lin|ling|liu|long|lou|lu|lv|luan|lue" . "|lun|luo|ma|mai|man|mang|mao|me|mei|men|meng|mi|mian|miao|mie|min|ming|miu|mo|mou|mu|na|nai|nan|nang|nao|ne" . "|nei|nen|neng|ni|nian|niang|niao|nie|nin|ning|niu|nong|nu|nv|nuan|nue|nuo|o|ou|pa|pai|pan|pang|pao|pei|pen" . "|peng|pi|pian|piao|pie|pin|ping|po|pu|qi|qia|qian|qiang|qiao|qie|qin|qing|qiong|qiu|qu|quan|que|qun|ran|rang" . "|rao|re|ren|reng|ri|rong|rou|ru|ruan|rui|run|ruo|sa|sai|san|sang|sao|se|sen|seng|sha|shai|shan|shang|shao|" . "she|shen|sheng|shi|shou|shu|shua|shuai|shuan|shuang|shui|shun|shuo|si|song|sou|su|suan|sui|sun|suo|ta|tai|" . "tan|tang|tao|te|teng|ti|tian|tiao|tie|ting|tong|tou|tu|tuan|tui|tun|tuo|wa|wai|wan|wang|wei|wen|weng|wo|wu" . "|xi|xia|xian|xiang|xiao|xie|xin|xing|xiong|xiu|xu|xuan|xue|xun|ya|yan|yang|yao|ye|yi|yin|ying|yo|yong|you" . "|yu|yuan|yue|yun|za|zai|zan|zang|zao|ze|zei|zen|zeng|zha|zhai|zhan|zhang|zhao|zhe|zhen|zheng|zhi|zhong|" . "zhou|zhu|zhua|zhuai|zhuan|zhuang|zhui|zhun|zhuo|zi|zong|zou|zu|zuan|zui|zun|zuo";
$_DataValue = "-20319|-20317|-20304|-20295|-20292|-20283|-20265|-20257|-20242|-20230|-20051|-20036|-20032|-20026|-20002|-19990" . "|-19986|-19982|-19976|-19805|-19784|-19775|-19774|-19763|-19756|-19751|-19746|-19741|-19739|-19728|-19725" . "|-19715|-19540|-19531|-19525|-19515|-19500|-19484|-19479|-19467|-19289|-19288|-19281|-19275|-19270|-19263" . "|-19261|-19249|-19243|-19242|-19238|-19235|-19227|-19224|-19218|-19212|-19038|-19023|-19018|-19006|-19003" . "|-18996|-18977|-18961|-18952|-18783|-18774|-18773|-18763|-18756|-18741|-18735|-18731|-18722|-18710|-18697" . "|-18696|-18526|-18518|-18501|-18490|-18478|-18463|-18448|-18447|-18446|-18239|-18237|-18231|-18220|-18211" . "|-18201|-18184|-18183|-18181|-18012|-17997|-17988|-17970|-17964|-17961|-17950|-17947|-17931|-17928|-17922" . "|-17759|-17752|-17733|-17730|-17721|-17703|-17701|-17697|-17692|-17683|-17676|-17496|-17487|-17482|-17468" . "|-17454|-17433|-17427|-17417|-17202|-17185|-16983|-16970|-16942|-16915|-16733|-16708|-16706|-16689|-16664" . "|-16657|-16647|-16474|-16470|-16465|-16459|-16452|-16448|-16433|-16429|-16427|-16423|-16419|-16412|-16407" . "|-16403|-16401|-16393|-16220|-16216|-16212|-16205|-16202|-16187|-16180|-16171|-16169|-16158|-16155|-15959" . "|-15958|-15944|-15933|-15920|-15915|-15903|-15889|-15878|-15707|-15701|-15681|-15667|-15661|-15659|-15652" . "|-15640|-15631|-15625|-15454|-15448|-15436|-15435|-15419|-15416|-15408|-15394|-15385|-15377|-15375|-15369" . "|-15363|-15362|-15183|-15180|-15165|-15158|-15153|-15150|-15149|-15144|-15143|-15141|-15140|-15139|-15128" . "|-15121|-15119|-15117|-15110|-15109|-14941|-14937|-14933|-14930|-14929|-14928|-14926|-14922|-14921|-14914" . "|-14908|-14902|-14894|-14889|-14882|-14873|-14871|-14857|-14678|-14674|-14670|-14668|-14663|-14654|-14645" . "|-14630|-14594|-14429|-14407|-14399|-14384|-14379|-14368|-14355|-14353|-14345|-14170|-14159|-14151|-14149" . "|-14145|-14140|-14137|-14135|-14125|-14123|-14122|-14112|-14109|-14099|-14097|-14094|-14092|-14090|-14087" . "|-14083|-13917|-13914|-13910|-13907|-13906|-13905|-13896|-13894|-13878|-13870|-13859|-13847|-13831|-13658" . "|-13611|-13601|-13406|-13404|-13400|-13398|-13395|-13391|-13387|-13383|-13367|-13359|-13356|-13343|-13340" . "|-13329|-13326|-13318|-13147|-13138|-13120|-13107|-13096|-13095|-13091|-13076|-13068|-13063|-13060|-12888" . "|-12875|-12871|-12860|-12858|-12852|-12849|-12838|-12831|-12829|-12812|-12802|-12607|-12597|-12594|-12585" . "|-12556|-12359|-12346|-12320|-12300|-12120|-12099|-12089|-12074|-12067|-12058|-12039|-11867|-11861|-11847" . "|-11831|-11798|-11781|-11604|-11589|-11536|-11358|-11340|-11339|-11324|-11303|-11097|-11077|-11067|-11055" . "|-11052|-11045|-11041|-11038|-11024|-11020|-11019|-11018|-11014|-10838|-10832|-10815|-10800|-10790|-10780" . "|-10764|-10587|-10544|-10533|-10519|-10331|-10329|-10328|-10322|-10315|-10309|-10307|-10296|-10281|-10274" . "|-10270|-10262|-10260|-10256|-10254";
$_TDataKey = explode('|', $_DataKey);
$_TDataValue = explode('|', $_DataValue);
$data = (PHP_VERSION >= '5.0') ? array_combine($_TDataKey, $_TDataValue) : self::_Array_Combine($_TDataKey, $_TDataValue);
arsort($data);
reset($data);
$str = self::safe_encoding($str);
$_Res = '';
for ($i = 0; $i < strlen($str); $i++) {
$_P = ord(substr($str, $i, 1));
if ($_P > 160) {
$_Q = ord(substr($str, ++$i, 1));
$_P = $_P * 256 + $_Q - 65536;
}
$_Res .= self::_Pinyin($_P, $data) . $pix;
}
return preg_replace("/[^a-z0-9" . $pix . "]*/", '', $_Res);
}
private static function _Pinyin($_Num, $_Data)
{
if ($_Num > 0 && $_Num < 160)
return chr($_Num);
elseif ($_Num < -20319 || $_Num > -10247)
return '';
else {
foreach ($_Data as $k => $v) {
if ($v <= $_Num)
break;
}
return $k;
}
}
public static function getFirstChar($str = '')
{
if (!$str) return null;
$fchar = ord($str{0});
if ($fchar >= ord("A") and $fchar <= ord("z")) return strtoupper($str{0});
$s = self::safe_encoding($str);
$asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
if ($asc >= -20319 and $asc <= -20284) return "A";
if ($asc >= -20283 and $asc <= -19776) return "B";
if ($asc >= -19775 and $asc <= -19219) return "C";
if ($asc >= -19218 and $asc <= -18711) return "D";
if ($asc >= -18710 and $asc <= -18527) return "E";
if ($asc >= -18526 and $asc <= -18240) return "F";
if ($asc >= -18239 and $asc <= -17923) return "G";
if ($asc >= -17922 and $asc <= -17418) return "H";
if ($asc >= -17417 and $asc <= -16475) return "J";
if ($asc >= -16474 and $asc <= -16213) return "K";
if ($asc >= -16212 and $asc <= -15641) return "L";
if ($asc >= -15640 and $asc <= -15166) return "M";
if ($asc >= -15165 and $asc <= -14923) return "N";
if ($asc >= -14922 and $asc <= -14915) return "O";
if ($asc >= -14914 and $asc <= -14631) return "P";
if ($asc >= -14630 and $asc <= -14150) return "Q";
if ($asc >= -14149 and $asc <= -14091) return "R";
if ($asc >= -14090 and $asc <= -13319) return "S";
if ($asc >= -13318 and $asc <= -12839) return "T";
if ($asc >= -12838 and $asc <= -12557) return "W";
if ($asc >= -12556 and $asc <= -11848) return "X";
if ($asc >= -11847 and $asc <= -11056) return "Y";
if ($asc >= -11055 and $asc <= -10247) return "Z";
return null;
}
private static function safe_encoding($string)
{
$encoding = "UTF-8";
for ($i = 0; $i < strlen($string); $i++) {
if (ord($string{$i}) < 128) continue;
if ((ord($string{$i}) & 224) == 224) { //第一个字节判断通过
$char = $string{++$i};
if ((ord($char) & 128) == 128) { //第二个字节判断通过
$char = $string{++$i};
if ((ord($char) & 128) == 128) {
$encoding = "UTF-8";
break;
}
}
}
if ((ord($string{$i}) & 192) == 192) { //第一个字节判断通过
$char = $string{++$i};
if ((ord($char) & 128) == 128) { //第二个字节判断通过
$encoding = "GB2312";
break;
}
}
}
if (strtoupper($encoding) == strtoupper(self::$_outEncoding))
return $string;
else
return iconv($encoding, self::$_outEncoding, $string);
}
private static function _Array_Combine($_Arr1, $_Arr2)
{
for ($i = 0; $i < count($_Arr1); $i++)
$_Res [$_Arr1 [$i]] = $_Arr2 [$i];
return $_Res;
}
/**
* 将字符串(中文同样实用)转为ascii
* 注意:我默认当前我们的php文件环境是UTF-8
* 如果是GBK的话mb_convert_encoding操作就不需要
* @param $str
* @return string
*/
public static function strToASCII($str)
{
$str = mb_convert_encoding($str, 'GB2312');
$change_after = '';
for ($i = 0; $i < strlen($str); $i++) {
$temp_str = dechex(ord($str[$i]));
$change_after .= $temp_str[1] . $temp_str[0];
}
return strtoupper($change_after);
}
/**
* 将ascii转为字符串(中文同样实用)
* 注意:我默认当前我们的php文件环境是UTF-8
* 如果是GBK的话mb_convert_encoding操作就不需要
* @param $SACII
* @return string
*/
public static function ASCIIToStr($SACII)
{
$asc_arr = str_split(strtolower($SACII), 2);
$str = '';
for ($i = 0; $i < count($asc_arr); $i++) {
$str .= chr(hexdec($asc_arr[$i][1] . $asc_arr[$i][0]));
}
return mb_convert_encoding($str, 'UTF-8', 'GB2312');
}
/**
* 字母转ASCII
* @param $str
* @return string
*/
public static function AZIncrement($str)
{
// 参数转换为大写
$str = strtoupper($str);
// 返回参数的 ASCII 值
$str = ord($str);
if ($str < 65 || $str > 90) {
// 参数不符合预期
return '你传过来的是什么鬼!';
}
if ($str == 90) {
// 参数已是末位英文字母Z,不可以递增
return '已经是 Z 啦!';
}
return chr($str + 1);
}
/**
* 返回字母索引
* 或
* 依据字母索引返回大写字母
* @param $letter
* @param bool $getUpper
* @return false|int|mixed|string
*/
public static function ZANumber($letter, $getUpper = false)
{
$chtLetter = strtoupper($letter);
$arrLetters = array(" ", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
if ($getUpper)
return $arrLetters[$letter];
else
return array_search($chtLetter, $arrLetters);
}
/**
* 毫秒时间戳
* @return float /毫秒时间戳
*/
public static function getMillisecond()
{
list($s1, $s2) = explode(' ', microtime());
return (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000);
}
/**
* 创建UUID
* @param string $prefix /前缀
* @param string $mark /连接符
* @return string /结果
*/
public static function UUID($prefix = '', $mark = '')
{
$chars = md5(uniqid(mt_rand(), true));
$uuid = substr($chars, 0, 8) . $mark;
$uuid .= substr($chars, 8, 4) . $mark;
$uuid .= substr($chars, 12, 4) . $mark;
$uuid .= substr($chars, 16, 4) . $mark;
$uuid .= substr($chars, 20, 12);
return $prefix . $uuid;
}
}
三、异常信息枚举
<?php
/**
* 归属于:Admin
* 本类名:Goods
* 创建者:IntelliJ IDEA
* 创建时:2021/10/18 12:09:45
* 职责集:礼品数据处理
*/
namespace Common\Controller;
use Think\Controller;
class FeedbackController extends Controller
{
public function __construct()
{
parent::__construct();
//self::sysInfo();
$token = ToolsController::randStr();
ToolsController::cache($token, 'login');
$this->assign('token', $token);
}
private function sysInfo()
{
$strPre = self::$dbPre;
$rowConfig = $re = M()->table("{$strPre}config c")->join("LEFT JOIN {$strPre}files f ON f.file_id=c.sys_h5_bg")->find();
$this->assign('systemInfo', $rowConfig);
}
public static function output($arrData){
Controller::ajaxReturn($arrData);
}
/**
* 返回信息
* @param int $code
* @param array $result
* @param string $more
*/
public static function feedback($code = 1, $result = array(), $more = '')
{
$arrError = self::errors($code);
$arrData = array(
'code' => $code,
'msg' => $arrError['msg'] . ($more == '' ? '' : ',参考信息:' . $more),
'result' => $result,
'referrer' => $result['referrer']
);
Controller::ajaxReturn($arrData);
}
public static function logs($str, $filename = 'error')
{
$strTime = date('Y-m-d H:i:s') . "===================================\r\n";
file_put_contents(LOG_PATH . $filename . '_' . date('Y-m-d') . '.log', $strTime . $str . "\r\n\r\n", FILE_APPEND);
}
public static function getErrorInfo($code = 0)
{
return self::errors($code);
}
/**
* 预设错误
* @param $code
* @return mixed
*/
private static function errors($code)
{
$arrErrors = array(
0 => array('msg' => '成功'),
1 => array('msg' => '失败'),
//参数相关错误
10 => array('msg' => '不允许的appKey'),
1014 => array('msg' => '必要的参数无法识别'),
1044 => array('msg' => '缺少必要的参数'),
11 => array('msg' => '缺少必要的参数'),
12 => array('msg' => '必要的参数不可为空'),
13 => array('msg' => '自动登录失败'),
14 => array('msg' => '必要的参数无法识别'),
1401 => array('msg' => '验证码发送失败'),
1404 => array('msg' => '验证码错误'),
1405 => array('msg' => '验证码无效,请刷新再试'),
1444 => array('msg' => '无法验证请求来源,请刷新页面再试'),
1445 => array('msg' => '参数异常,可能存在非法注入,已阻止进一步操作'),
1446 => array('msg' => '状态未改变或者已为当前状态,请刷新页面再试(Ctrl+F5)'),
1700 => array('msg' => '表单验证未通过,已终止进一步操作。参考信息:'),
1701 => array('msg' => '表单验证配置为空,无法继续'),
//用户相关错误
2000 => array('msg' => '用户登录失败'),
2001 => array('msg' => '用户状态异常'),
2002 => array('msg' => '用户已被禁用'),
2003 => array('msg' => '账户或密码错误'),
2004 => array('msg' => '登陆已超时<br/>请重新登陆'),
2005 => array('msg' => '登陆信息不完整,请检查后再试'),
2006 => array('msg' => '验证码不正确,请重新输入'),
2011 => array('msg' => '您未设置支付密码<br/>请使用短信验证码<br/><br/>tips:如若手机号也未绑定,您可以到个人中心进行设置与绑定,在此之后再支付订单'),
2012 => array('msg' => '支付密码错误'),
2014 => array('msg' => '支付失败'),
2015 => array('msg' => '支付失败,用户余额不足'),
2016 => array('msg' => '支付失败,未成功完成扣款与订单状态变更'),
2020 => array('msg' => '手机号错误,检查后再试'),
2021 => array('msg' => '手机号已被另一账户绑定,请更换'),
2030 => array('msg' => '收件地址添加失败,请稍后再试'),
2031 => array('msg' => '默认收件地址设置失败,请刷新后再试'),
2032 => array('msg' => '收件地址删除失败,请刷新后再试'),
2040 => array('msg' => '原密码错误'),
2041 => array('msg' => '密码更新失败'),
2050 => array('msg' => '角色信息配置错误'),
2051 => array('msg' => '角色已被禁止使用'),
//30订单相关错误
3014 => array('msg' => '创建订单失败'),
3015 => array('msg' => '创建删除失败'),
//40商品相关
4010 => array('msg' => '拒绝删除,类目下存在礼品'),
4011 => array('msg' => '更新失败,请稍后再试'),
4021 => array('msg' => '图像上传失败,请刷新后再试'),
4022 => array('msg' => '插入主表信息失败,请刷新后再试'),
4023 => array('msg' => '插入从表信息失败,请刷新后再试'),
4024 => array('msg' => '插入礼品信息失败,请刷新后再试'),
//50企业相关
5001 => array('msg' => '新增失败,请刷新后再试'),
31 => array('msg' => '处理模板函数时发生异常,请检查模板'),
32 => array('msg' => '处理模板函数参数时发生异常,请检查参数设置'),
33 => array('msg' => '导入数据的相关配置为空\n无法正常导入数据至数据库\n请联系管理员进行配置的检查'),
70 => array('msg' => '系统支持年度范围配置项异常,请联系管理员调整,以确保网站正确运行'),
80 => array('msg' => '异常的参数内容'),
81 => array('msg' => '信息检测失败,请稍后再试'),
88 => array('msg' => '无效内容,请勿尝试'),
44 => array('msg' => '未知异常'),
);
if (isset($arrErrors[$code])) {
return $arrErrors[$code];
} else {
return $arrErrors[44];
}
}
#region 临时使用的
public static function drew($data)
{
if (is_array($data)) {
self::showArray($data);
}
echo $data;
exit;
}
public static function lastSql()
{
echo M()->getLastSql();
exit;
}
public static function showArray($array)
{
echo json_encode($array);
exit;
}
#endregion
}
这里都是一些老框架中的老类文件,也可能是不完整的,毕竟是在老项目里面拿出来的独立类,不过,这些类使用起来应该不会很麻烦