<?php<liu21st@gmail.com>
use think\facade\Env;
function dbg($input, $filepath = '', $clean = false) {
if(is_array($input)) {
$input = var_export($input, true);
}
if(is_object($input)) {
$input = var_export((array)$input, true);
}
if(empty($filepath)) {
$filepath = Env::get('RUNTIME_PATH') .'dbg' . DIRECTORY_SEPARATOR . date("Y-m-d") . '.txt';
}
if(!file_exists(dirname($filepath))) {
mkdir(dirname($filepath), 0644, true);
}
if($clean) {
file_put_contents($filepath, $input . PHP_EOL);
} else {
file_put_contents($filepath, $input . PHP_EOL, FILE_APPEND);
}
}
function get_client_ip($type = 0) {
$type = $type ? 1 : 0;
$ip = NULL;
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'];
}
$long = sprintf("%u", ip2long($ip));
$ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
return $ip[$type];
}
function slog($data) {
if(is_array($data) || is_object($data)) {
$data = var_export($data, true);
}
$request = think\Facade\Request::instance();
think\facade\Log::record($request->domain().': '.$data);
}
function generateCode( $nums,$exist_array=[],$code_length = 6,$prefix = '' ) {
$characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$promotion_codes = array()
for($j = 0 ; $j < $nums; $j++) {
$code = '';
for ($i = 0; $i < $code_length; $i++) {
$code .= $characters[mt_rand(0, strlen($characters)-1)];
}
if( !in_array($code,$promotion_codes) ) {
if( is_array($exist_array) ) {
if( !in_array($code,$exist_array) ) $promotion_codes[$j] = $prefix.$code; } else {
$j--;
}
} else {
$promotion_codes[$j] = $prefix.$code }
} else {
$j--;
}
}
return $promotion_codes;
}
function qr($content='', $qr='', $logo='', $level='L', $size='6') {
if(empty($content)) {
return 'content is not empty';
}
\think\Loader::import('phpqrcode.phpqrcode', EXTEND_PATH);
if(empty($qr)) {
$path = Env::get('ROOT_PATH') . "public/static/"; if(!file_exists($path)) {
mkdir($path, 0777, true);
}
$qr = $path . time() . '.png';
}
QRcode::png($content, $qr, $level, $size, 2);
if($logo) {
if(file_exists($logo)) {
$logo_resource = imagecreatefromstring(file_get_contents($logo));
$qrcode_resource = imagecreatefromstring(file_get_contents($qr));
$logo_w = imagesx($logo_resource); $logo_h = imagesy($logo_resource); $qrcode_w = imagesx($qrcode_resource); $logo_qr_width = $qrcode_w / 5;
$scale = $logo_w / $logo_qr_width;
$logo_qr_height = $logo_h / $scale;
$from_width = ($qrcode_w - $logo_qr_width) / 2;
imagecopyresampled($qrcode_resource, $logo_resource, $from_width, $from_width, 0, 0, $logo_qr_width, $logo_qr_height, $logo_w, $logo_h);
imagepng($qrcode_resource, $qr);
} else {
return 'logo file is not exist';
}
}
return $qr;
}
function base64_en($str) {
$str = base64_encode($str);
$str .= randStr(5);
$str = base64_encode($str);
$str = randStr(3) . $str;
return $str;
}
function base64_de($str) {
$len = strlen($str);
$str = substr($str, 3, $len - 2);
$str = base64_decode($str);
$str = substr($str, 0, -5);
$str = base64_decode($str);
return $str;
}
function randStr($len) {
$str = "ABCDEFGHIJKLMNOPQRSTUVWSYZabcdefghijklmnopqrstuvwsyz0123456789";
return substr(str_shuffle($str), 0, $len);
}
function create_xls($data,$filename='simple.xls'){
ini_set('max_execution_time', '0');
Vendor('PHPExcel.PHPExcel');
$filename=str_replace('.xls', '', $filename).'.xls';
$phpexcel = new PHPExcel();
$phpexcel->getProperties()
->setCreator("Maarten Balliauw")
->setLastModifiedBy("Maarten Balliauw")
->setTitle("Office 2007 XLSX Test Document")
->setSubject("Office 2007 XLSX Test Document")
->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
->setKeywords("office 2007 openxml php")
->setCategory("Test result file");
$phpexcel->getActiveSheet()->fromArray($data);
$phpexcel->getActiveSheet()->setTitle('Sheet1');
$phpexcel->setActiveSheetIndex(0);
header('Content-Type: application/vnd.ms-excel');
header("Content-Disposition: attachment;filename=$filename");
header('Cache-Control: max-age=0');
header('Cache-Control: max-age=1');
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); header ('Cache-Control: cache, must-revalidate'); header ('Pragma: public'); $objwriter = PHPExcel_IOFactory::createWriter($phpexcel, 'Excel5');
$objwriter->save('php://output');
exit;
}
function create_csv($data,$header=null,$filename='simple.csv'){
if (!is_null($header)) {
array_unshift($data, $header);
}
$filename=str_replace('.csv', '', $filename).'.csv';
ob_clean();
Header( "Content-type: application/octet-stream ");
Header( "Accept-Ranges: bytes ");
Header( "Content-Disposition: attachment; filename=".$filename);
foreach( $data as $k => $v){
if (is_array($v)) {
$v=implode(',', $v);
}
$v=preg_replace('/\s*/', '', $v);
$v=str_replace(',', "\t,", $v);
echo iconv('UTF-8','GBK',$v)."\t\r\n";
}
}
function import_excel($file){
$type = pathinfo($file);
$type = strtolower($type["extension"]);
if ($type=='xlsx') {
$type='Excel2007';
}elseif($type=='xls') {
$type = 'Excel5';
}
ini_set('max_execution_time', '0');
Vendor('PHPExcel.PHPExcel');
$objReader = PHPExcel_IOFactory::createReader($type);
$objPHPExcel = $objReader->load($file);
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
$numHighestColum = PHPExcel_Cell::columnIndexFromString("$highestColumn");
$data=array();
for($j=1;$j<=$highestRow;$j++){
for($k=0;$k<=$numHighestColum;$k++){
$columnIndex = PHPExcel_Cell::stringFromColumnIndex($k);
$data[$j][]=$objPHPExcel->getActiveSheet()->getCell("$columnIndex$j")->getValue();
}
}
return $data;
}
function shuffle_assoc($array) {
if (!is_array($array) || empty($array)) return $array;
$keys = array_keys($array);
shuffle($keys);
$random = array();
foreach ($keys as $key){
$random[$key] = $array[$key];
}
return $random;
}
function phoneNumMosaic($num) {
if(!preg_match('/\d{11}/', $num)) {
return $num;
}
$resstr = substr_replace($num,'****',3,4);
return $resstr;
}
function curl_request($url, $data = array(), $method='post', $headers = [], $timeout = 10, $CA = false) {
$cacert = getcwd() . '/cacert.pem'; $SSL = substr($url, 0, 8) == "https://" ? true : false;
if(strtolower($method) == 'get') {
$url .= http_build_query($data);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout-2);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36');
if(!empty($headers)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
if ($SSL && $CA) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); curl_setopt($ch, CURLOPT_CAINFO, $cacert); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); } else if ($SSL && !$CA) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); }
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:')); if(strtolower($method) == 'post') {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
$ret = curl_exec($ch); curl_close($ch);
return $ret;
}
function time_tran($the_time) {
$now_time = date("Y-m-d H:i:s", time());
$now_time = strtotime($now_time);
$show_time = strtotime($the_time);
$dur = $now_time - $show_time;
if ($dur < 0) {
return $the_time;
} else {
if ($dur < 60) {
return $dur . '秒前';
}
if ($dur < 3600) {
return floor($dur / 60) . '分钟前';
}
if ($dur < 86400) {
return floor($dur / 3600) . '小时前';
}
if ($dur < 2592000) {
return floor($dur / 86400) . '天前';
}
if ($dur < 31536000) {
return floor($dur / 2592000) . '月前';
}
if ($dur > 31536000) {
return floor($dur / 31536000) . '年前';
}
}
}
function oss_init() {
$config = config('common.aliyun_oss');
$ossClient = new OssClient($config['keyid'], $config['keysecret'], $config['endpoint'], true);
return $ossClient;
}
function uploadFileToOss($object, $path, $bucket = '') {
try {
$ossClient = oss_init();
if (empty($bucket)) {
$bucket = config('common.aliyun_oss')['bucket'];
}
return $ossClient->uploadFile($bucket, $object, $path);
} catch (OssException $e) {
return $e->getMessage();
}
}
function deleteFileFromOss($object, $bucket = '') {
try {
$ossClient = oss_init();
if (empty($bucket)) {
$bucket = config('common.aliyun_oss')['bucket'];
}
$ossClient->deleteObject($bucket, $object);
} catch (OssException $e) {
return $e->getMessage();
}
}
function format_bytes($size, $delimiter = '') {
$units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
for ($i = 0; $size >= 1024 && $i < 5; $i++)
$size /= 1024;
return round($size, 2) . $delimiter . $units[$i];
}
function countSmscodeMaxTimes($phoneNum, $type, $db='sms') {
$ip = get_client_ip();
$where = [
'phone' => $phoneNum,
'type' => $type,
'create_time' => ['between', [strtotime('today'), strtotime('tomorrow')]], ];
$sendTimes = db($db)->where($where)->count();
$maxSendTimes = config('common.cl_sms')['max'];
if ($sendTimes >= $maxSendTimes) {
return '$_126';
}
return '$_128';
}
function addSmscodeInDb($data = [], $db="sms") {
if (countSmscodeMaxTimes($data['phoneNum'], $data['type']) == '$_126') {
return '$_126';
}
$where = [
'phone' => $data['phoneNum'],
'type' => $data['type'],
];
$update = ['status' => 0];
db($db)->where($where)->update($update);
$data = [
'phone' => $data['phoneNum'],
'code' => $data['code'],
'type' => $data['type'],
'content' => $data['content'],
'create_time' => time(),
'ip' => get_client_ip(),
];
$res = db($db)->insert($data);
if ($res !== false) {
return '$_0';
}
return '$_1';
}
function checkSmscode($code, $phoneNum, $type, $db='sms') {
$where = [
'phone' => $phoneNum,
'type' => $type,
];
$res = db($db)->where($where)->order('id','DESC')->find();
if (empty($res)) {
return '$_129';
}
if ($res['status'] == 0) {
return '$_130';
}
$lifecycle = config('common.cl_sms')['lifecycle'];
if ((time() - $res['create_time']) > $lifecycle * 60) {
return '$_130';
}
if ($code != $res['code']) {
return '$_131';
}
if ($code == $res['code']) {
db($db)->where($where)->update(['status' => 0]);
return '$_132';
}
}