This commit is contained in:
Gitea
2022-01-24 10:43:35 +08:00
commit 15dfc6576b
786 changed files with 219240 additions and 0 deletions

626
core/function/file.php Normal file
View File

@@ -0,0 +1,626 @@
<?php
/**
* @copyright (C)2016-2099 Hnaoyun Inc.
* @author XingMeng
* @email hnxsh@foxmail.com
* @date 2017年8月3日
* 数据处理函数库
*/
use core\basic\Config;
// 检测目录是否存在
function check_dir($path, $create = false)
{
if (is_dir($path)) {
return true;
} elseif ($create) {
return create_dir($path);
}
}
// 创建目录
function create_dir($path)
{
if (! file_exists($path)) {
if (mkdir($path, 0777, true)) {
return true;
}
}
return false;
}
// 检查文件是否存在
function check_file($path, $create = false, $content = null)
{
if (file_exists($path)) {
return true;
} elseif ($create) {
return create_file($path, $content);
}
}
// 创建文件
function create_file($path, $content = null, $over = false)
{
if (file_exists($path) && ! $over) {
return false;
} elseif (file_exists($path)) {
@unlink($path);
}
check_dir(dirname($path), true);
$handle = fopen($path, 'w') or error('创建文件失败,请检查目录权限!');
fwrite($handle, $content);
return fclose($handle);
}
// 目录文件夹列表
function dir_list($path)
{
$list = array();
if (! is_dir($path) || ! $filename = scandir($path)) {
return $list;
}
$files = count($filename);
for ($i = 0; $i < $files; $i ++) {
$dir = $path . '/' . $filename[$i];
if (is_dir($dir) && $filename[$i] != '.' && $filename[$i] != '..') {
$list[] = $filename[$i];
}
}
return $list;
}
// 目录文件列表
function file_list($path)
{
$list = array();
if (! is_dir($path) || ! $filename = scandir($path)) {
return $list;
}
$files = count($filename);
for ($i = 0; $i < $files; $i ++) {
$dir = $path . '/' . $filename[$i];
if (is_file($dir)) {
$list[] = $filename[$i];
}
}
return $list;
}
// 目录下文件及文件夹列表
function path_list($path)
{
$list = array();
if (! is_dir($path) || ! $filename = scandir($path)) {
return $list;
}
$files = count($filename);
for ($i = 0; $i < $files; $i ++) {
$dir = $path . '/' . $filename[$i];
if (is_file($dir) || (is_dir($dir) && $filename[$i] != '.' && $filename[$i] != '..')) {
$list[] = $filename[$i];
}
}
return $list;
}
/**
* 删除目录及目录下所有文件或删除指定文件
*
* @param str $path
* 待删除目录路径
* @param int $delDir
* 是否删除目录true删除目录false则只删除文件保留目录
* @return bool 返回删除状态
*/
function path_delete($path, $delDir = false)
{
$result = true; // 对于空目录直接返回true状态
if (! file_exists($path)) {
return $result;
}
if (is_dir($path)) {
if (! ! $dirs = scandir($path)) {
foreach ($dirs as $value) {
if ($value != "." && $value != "..") {
$dir = $path . '/' . $value;
$result = is_dir($dir) ? path_delete($dir, $delDir) : unlink($dir);
}
}
if ($result && $delDir) {
return rmdir($path);
} else {
return $result;
}
} else {
return false;
}
} else {
return unlink($path);
}
}
// 拷贝文件夹
function dir_copy($src, $des, $son = 1)
{
if (! is_dir($src)) {
return false;
}
if (! is_dir($des)) {
create_dir($des);
}
$handle = dir($src);
while (! ! $path = $handle->read()) {
if (($path != ".") && ($path != "..")) {
if (is_dir($src . "/" . $path)) {
if ($son)
dir_copy($src . "/" . $path, $des . "/" . $path, $son);
} else {
copy($src . "/" . $path, $des . "/" . $path);
}
}
}
return true;
}
// 判断文件是否是图片
function is_image($path)
{
$types = '.gif|.jpeg|.png|.bmp'; // 定义检查的图片类型
if (file_exists($path)) {
$info = getimagesize($path);
$ext = image_type_to_extension($info['2']);
if (stripos($types, $ext) !== false)
return true;
}
return false;
}
/**
* 文件上传
*
* @param string $input_name表单名称
* @param string $file_ext允许的扩展名
* @param number $max_width最大宽度
* @param number $max_height最大高度
* @return string 返回成功上传文件的路径数组
*/
function upload($input_name, $file_ext = null, $max_width = null, $max_height = null, $watermark = false)
{
// 未选择文件返回空
if (! isset($_FILES[$input_name])) {
return '文件超过PHP环境允许的大小';
} else {
$files = $_FILES[$input_name];
}
// 定义允许上传的扩展
if (! $file_ext) {
$array_ext_allow = Config::get('upload.format', true);
} else {
$array_ext_allow = explode(',', $file_ext);
}
// 未直接传递函数参数,且具有地址参数,则打水印
if (! $watermark && get('watermark', 'int')) {
$watermark = true;
}
$array_save_file = array();
if (is_array($files['tmp_name'])) { // 多文件情况
$file_count = count($files['tmp_name']);
for ($i = 0; $i < $file_count; $i ++) {
if (! $files['error'][$i]) {
$upfile = handle_upload($files['name'][$i], $files['tmp_name'][$i], $array_ext_allow, $max_width, $max_height, $watermark);
if (strrpos($upfile, '/') > 0) {
$array_save_file[] = $upfile;
} else {
$err = $upfile;
}
} else {
$err = '错误代码' . $files['error'][$i];
}
}
} else { // 单文件情况
if (! $files['error']) {
$upfile = handle_upload($files['name'], $files['tmp_name'], $array_ext_allow, $max_width, $max_height, $watermark);
if (strrpos($upfile, '/') > 0) {
$array_save_file[] = $upfile;
} else {
$err = $upfile;
}
} else {
$err = '错误代码' . $files['error'];
}
}
if (isset($err)) {
return $err;
} else {
return $array_save_file;
}
}
// 处理并移动上传文件
function handle_upload($file, $temp, $array_ext_allow, $max_width, $max_height, $watermark)
{
// 定义主存储路径
$save_path = DOC_PATH . STATIC_DIR . '/upload';
$file = explode('.', $file); // 分离文件名及扩展
$file_ext = strtolower(end($file)); // 获取扩展
if (! in_array($file_ext, $array_ext_allow)) {
return $file_ext . '格式的文件不允许上传!';
}
$image = array(
'png',
'jpg',
'gif',
'bmp'
);
$file = array(
'ppt',
'pptx',
'xls',
'xlsx',
'doc',
'docx',
'pdf',
'txt'
);
if (in_array($file_ext, $image)) {
$file_type = 'image';
} elseif (in_array($file_ext, $file)) {
$file_type = 'file';
} else {
$file_type = 'other';
}
// 检查文件存储路径
if (! check_dir($save_path . '/' . $file_type . '/' . date('Ymd'), true)) {
return '存储目录创建失败!';
}
$file_path = $save_path . '/' . $file_type . '/' . date('Ymd') . '/' . time() . mt_rand(100000, 999999) . '.' . $file_ext;
if (! move_uploaded_file($temp, $file_path)) { // 从缓存中转存
return '从缓存中转存失败!';
}
$save_file = str_replace(ROOT_PATH, '', $file_path); // 获取文件站点路径
// 如果是图片
if (is_image($file_path)) {
// 进行等比例缩放
if (($reset = resize_img($file_path, $file_path, $max_width, $max_height)) !== true) {
return $reset;
}
// 图片打水印
if ($watermark) {
watermark_img($file_path);
}
}
return $save_file;
}
/**
* *
* 等比缩放图片
*
* @param string $src_image源图片路径
* @param string $out_image输出图像路径
* @param number $max_width最大宽
* @param number $max_height最大高
* @param number $img_quality图片质量
* @return boolean 返回是否成功
*/
function resize_img($src_image, $out_image = null, $max_width = null, $max_height = null, $img_quality = 90)
{
// 输出地址
if (! $out_image)
$out_image = $src_image;
// 读取配置文件设置
if (! $max_width)
$max_width = Config::get('upload.max_width') ?: 999999999;
if (! $max_height)
$max_height = Config::get('upload.max_height') ?: 999999999;
// 获取图片属性
list ($width, $height, $type, $attr) = getimagesize($src_image);
// 检查输出目录
check_dir(dirname($out_image), true);
// 无需缩放的图片
if ($width <= $max_width && $height <= $max_height) {
if ($src_image != $out_image) { // 存储地址不一致时进行拷贝
if (! copy($src_image, $out_image)) {
return '缩放图片时拷贝到目的地址失败!';
}
}
return true;
}
// 求缩放比例
if ($max_width && $max_height) {
$scale = min($max_width / $width, $max_height / $height);
} elseif ($max_width) {
$scale = $max_width / $width;
} elseif ($max_height) {
$scale = $max_height / $height;
}
if ($scale < 1) {
switch ($type) {
case 1:
$img = imagecreatefromgif($src_image);
break;
case 2:
$img = imagecreatefromjpeg($src_image);
break;
case 3:
$img = imagecreatefrompng($src_image);
break;
}
$new_width = floor($scale * $width);
$new_height = floor($scale * $height);
$new_img = imagecreatetruecolor($new_width, $new_height); // 创建画布
// 创建透明画布,避免黑色
if ($type == 1 || $type == 3) {
$color = imagecolorallocate($new_img, 255, 255, 255);
imagefill($new_img, 0, 0, $color);
imagecolortransparent($new_img, $color);
}
imagecopyresized($new_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
switch ($type) {
case 1:
imagegif($new_img, $out_image, $img_quality);
break;
case 2:
imagejpeg($new_img, $out_image, $img_quality);
break;
case 3:
imagepng($new_img, $out_image, $img_quality / 10); // $quality参数取值范围0-99 在php 5.1.2之后变更为0-9
break;
default:
imagejpeg($new_img, $out_image, $img_quality);
}
imagedestroy($new_img);
imagedestroy($img);
}
return true;
}
// 剪切图片
function cut_img($src_image, $out_image = null, $new_width = null, $new_height = null, $img_quality = 90)
{
// 输出地址
if (! $out_image)
$out_image = $src_image;
// 读取配置文件设置
if (! $new_width && ! $new_height)
return;
// 获取图片属性
list ($width, $height, $type, $attr) = getimagesize($src_image);
switch ($type) {
case 1:
$img = imagecreatefromgif($src_image);
break;
case 2:
$img = imagecreatefromjpeg($src_image);
break;
case 3:
$img = imagecreatefrompng($src_image);
break;
}
// 不限定是等比例缩放
if (! $new_width) {
$new_width = floor($width * ($new_height / $height));
}
if (! $new_height) {
$new_height = floor($height * ($new_width / $width));
}
// 计算裁剪是变大缩小方式
if ($width >= $new_width && $height >= $new_height) { // 长宽均满足
$cut_width = $new_width;
$cut_height = $new_height;
} else { // 有一边不满足
$scale1 = $width / $new_width;
$scale2 = $height / $new_height;
if ($scale1 < $scale2) { // 变化越多的一边取全值,其余一边等比例缩放
$cut_width = $width;
$cut_height = floor($height * ($width / $new_width));
} else {
$cut_width = floor($new_width * ($height / $new_height));
$cut_height = $height;
}
}
// 创建画布
$new_img = imagecreatetruecolor($new_width, $new_height);
// 创建透明画布,避免黑色
if ($type == 1 || $type == 3) {
$color = imagecolorallocate($new_img, 255, 255, 255);
imagefill($new_img, 0, 0, $color);
imagecolortransparent($new_img, $color);
}
imagecopyresized($new_img, $img, 0, 0, 0, 0, $new_width, $new_height, $cut_width, $cut_height);
check_dir(dirname($out_image), true); // 检查输出目录
switch ($type) {
case 1:
imagegif($new_img, $out_image, $img_quality);
break;
case 2:
imagejpeg($new_img, $out_image, $img_quality);
break;
case 3:
imagepng($new_img, $out_image, $img_quality / 10); // $quality参数取值范围0-99 在php 5.1.2之后变更为0-9
break;
default:
imagejpeg($new_img, $out_image, $img_quality);
}
imagedestroy($new_img);
imagedestroy($img);
return true;
}
// 图片水印
function watermark_img($src_image, $out_image = null, $position = null, $watermark_image = null, $watermark_text = '', $watermark_text_size = null, $watermark_text_color = null)
{
if (! Config::get('watermark_open')) {
return;
}
// 输出地址
if (! $out_image)
$out_image = $src_image;
// 如果不存在文字及图片则直接返回
if (! $watermark_text) {
$watermark_text = Config::get('watermark_text') ?: 'PbootCMS';
}
$watermark_image = $watermark_image ?: Config::get('watermark_pic');
if (! $watermark_text && ! $watermark_image) {
return;
}
// 获取图片属性
list ($width1, $height1, $type1, $attr1) = getimagesize($src_image);
switch ($type1) {
case 1:
$img1 = imagecreatefromgif($src_image);
break;
case 2:
$img1 = imagecreatefromjpeg($src_image);
break;
case 3:
$img1 = imagecreatefrompng($src_image);
break;
}
if ($watermark_image) {
$watermark_image = ROOT_PATH . $watermark_image;
// 获取水印图片
list ($width2, $height2, $type2, $attr2) = getimagesize($watermark_image);
switch ($type2) {
case 1:
$img2 = imagecreatefromgif($watermark_image);
break;
case 2:
$img2 = imagecreatefromjpeg($watermark_image);
break;
case 3:
$img2 = imagecreatefrompng($watermark_image);
break;
}
} else {
if (! $watermark_text_size) {
$watermark_text_size = Config::get('watermark_text_size') ?: 16;
}
if (! $watermark_text_color) {
$watermark_text_color = Config::get('watermark_text_color') ?: '100,100,100';
}
$colors = explode(',', $watermark_text_color);
if (Config::get('watermark_text_font')) {
$font = ROOT_PATH . Config::get('watermark_text_font');
} else {
return;
}
// 手动创建水印图像
$fontsize = $watermark_text_size;
$width2 = mb_strlen($watermark_text, 'UTF-8') * ($fontsize + 10) + 20;
$height2 = $fontsize + 10;
$img2 = imagecreatetruecolor($width2, $height2);
$color = imagecolorallocate($img2, 255, 255, 255);
imagefill($img2, 0, 0, $color);
imagecolortransparent($img2, $color); // 创建透明图
$textcolor = imagecolorallocate($img2, $colors[0], $colors[1], $colors[2]);
imagettftext($img2, $fontsize, 0, 5, $fontsize + 5, $textcolor, $font, $watermark_text);
}
// 现对图片太大时,自动缩放水印
if ($width1 < $width2 * 3 || $height1 < $height2) {
$scale = min(($width1 / 3) / $width2, ($height1 / 2) / $height2); // 求缩放比例
$new_width = floor($scale * $width2);
$new_height = floor($scale * $height2);
} else {
$new_width = $width2;
$new_height = $height2;
}
// 水印位置
if (! $position) {
$position = Config::get('watermark_position') ?: 4;
}
switch ($position) {
case '1':
$x = 15;
$y = 15;
break;
case '2':
$x = $width1 - $new_width - 15;
$y = 20;
break;
case '3':
$x = 20;
$y = $height1 - $new_height - 15;
break;
case '5':
$x = ($width1 - $new_width) / 2;
$y = ($height1 - $new_height) / 2;
break;
default:
$x = $width1 - $new_width - 15;
$y = $height1 - $new_height - 15;
break;
}
// 创建透明画布,避免黑色
if ($type1 == 1 || $type1 == 3) {
$out = imagecreatetruecolor($width1, $height1);
$color = imagecolorallocate($out, 255, 255, 255);
imagefill($out, 0, 0, $color);
imagecolortransparent($out, $color);
imagecopy($out, $img1, 0, 0, 0, 0, $width1, $height1);
} else {
$out = $img1;
}
// 打上水印
imagecopyresized($out, $img2, $x, $y - 10, 0, 0, $new_width, $new_height, $width2, $height2);
check_dir(dirname($out_image), true); // 检查输出目录
// 输出图片
switch ($type1) {
case 1:
imagegif($out, $out_image, 90);
break;
case 2:
imagejpeg($out, $out_image, 90);
break;
case 3:
imagepng($out, $out_image, 90 / 10); // $quality参数取值范围0-99 在php 5.1.2之后变更为0-9
break;
default:
imagejpeg($out, $out_image, 90);
}
imagedestroy($img1);
imagedestroy($img2);
return true;
}

976
core/function/handle.php Normal file
View File

@@ -0,0 +1,976 @@
<?php
/**
* @copyright (C)2016-2099 Hnaoyun Inc.
* @author XingMeng
* @email hnxsh@foxmail.com
* @date 2017年11月5日
*
*/
use core\basic\Config;
// 获取用户浏览器类型
function get_user_bs($bs = null)
{
if (isset($_SERVER["HTTP_USER_AGENT"])) {
$user_agent = strtolower($_SERVER["HTTP_USER_AGENT"]);
} else {
return null;
}
// 直接检测传递的值
if ($bs) {
if (strpos($user_agent, strtolower($bs))) {
return true;
} else {
return false;
}
}
// 固定检测
if (strpos($user_agent, 'micromessenger')) {
$user_bs = 'Weixin';
} elseif (strpos($user_agent, 'qq')) {
$user_bs = 'QQ';
} elseif (strpos($user_agent, 'weibo')) {
$user_bs = 'Weibo';
} elseif (strpos($user_agent, 'alipayclient')) {
$user_bs = 'Alipay';
} elseif (strpos($user_agent, 'trident/7.0')) {
$user_bs = 'IE11'; // 新版本IE优先避免360等浏览器的兼容模式检测错误
} elseif (strpos($user_agent, 'trident/6.0')) {
$user_bs = 'IE10';
} elseif (strpos($user_agent, 'trident/5.0')) {
$user_bs = 'IE9';
} elseif (strpos($user_agent, 'trident/4.0')) {
$user_bs = 'IE8';
} elseif (strpos($user_agent, 'msie 7.0')) {
$user_bs = 'IE7';
} elseif (strpos($user_agent, 'msie 6.0')) {
$user_bs = 'IE6';
} elseif (strpos($user_agent, 'edge')) {
$user_bs = 'Edge';
} elseif (strpos($user_agent, 'firefox')) {
$user_bs = 'Firefox';
} elseif (strpos($user_agent, 'chrome') || strpos($user_agent, 'android')) {
$user_bs = 'Chrome';
} elseif (strpos($user_agent, 'safari')) {
$user_bs = 'Safari';
} elseif (strpos($user_agent, 'mj12bot')) {
$user_bs = 'MJ12bot';
} else {
$user_bs = 'Other';
}
return $user_bs;
}
// 获取用户操作系统类型
function get_user_os($osstr = null)
{
if (isset($_SERVER["HTTP_USER_AGENT"])) {
$user_agent = strtolower($_SERVER["HTTP_USER_AGENT"]);
} else {
return null;
}
// 直接检测传递的值
if ($osstr) {
if (strpos($user_agent, strtolower($osstr))) {
return true;
} else {
return false;
}
}
if (strpos($user_agent, 'windows nt 5.0')) {
$user_os = 'Windows 2000';
} elseif (strpos($user_agent, 'windows nt 9')) {
$user_os = 'Windows 9X';
} elseif (strpos($user_agent, 'windows nt 5.1')) {
$user_os = 'Windows XP';
} elseif (strpos($user_agent, 'windows nt 5.2')) {
$user_os = 'Windows 2003';
} elseif (strpos($user_agent, 'windows nt 6.0')) {
$user_os = 'Windows Vista';
} elseif (strpos($user_agent, 'windows nt 6.1')) {
$user_os = 'Windows 7';
} elseif (strpos($user_agent, 'windows nt 6.2')) {
$user_os = 'Windows 8';
} elseif (strpos($user_agent, 'windows nt 6.3')) {
$user_os = 'Windows 8.1';
} elseif (strpos($user_agent, 'windows nt 10')) {
$user_os = 'Windows 10';
} elseif (strpos($user_agent, 'windows phone')) {
$user_os = 'Windows Phone';
} elseif (strpos($user_agent, 'android')) {
$user_os = 'Android';
} elseif (strpos($user_agent, 'iphone')) {
$user_os = 'iPhone';
} elseif (strpos($user_agent, 'ipad')) {
$user_os = 'iPad';
} elseif (strpos($user_agent, 'mac')) {
$user_os = 'Mac';
} elseif (strpos($user_agent, 'sunos')) {
$user_os = 'Sun OS';
} elseif (strpos($user_agent, 'bsd')) {
$user_os = 'BSD';
} elseif (strpos($user_agent, 'ubuntu')) {
$user_os = 'Ubuntu';
} elseif (strpos($user_agent, 'linux')) {
$user_os = 'Linux';
} elseif (strpos($user_agent, 'unix')) {
$user_os = 'Unix';
} else {
$user_os = 'Other';
}
return $user_os;
}
// 获取用户IP
function get_user_ip()
{
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$cip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
$cip = $_SERVER['HTTP_CLIENT_IP'];
} else {
$cip = $_SERVER['REMOTE_ADDR'];
}
if ($cip == '::1') { // 使用localhost时
$cip = '127.0.0.1';
}
if (! preg_match('/^[0-9\.]+$/', $cip)) { // 非标准的IP
$cip = '0.0.0.0';
}
return htmlspecialchars($cip);
}
// 执行URL请求并返回数据
function get_url($url, $fields = array(), $UserAgent = null, $vfSSL = false)
{
$SSL = substr($url, 0, 8) == "https://" ? true : false;
$ch = curl_init();
if ($UserAgent) { // 在HTTP请求中包含一个"User-Agent: "头的字符串。
curl_setopt($ch, CURLOPT_USERAGENT, $UserAgent);
} else {
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]);
}
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60); // 在发起连接前等待的时间如果设置为0则无限等待
curl_setopt($ch, CURLOPT_TIMEOUT, 90); // 设置cURL允许执行的最长秒数
curl_setopt($ch, CURLOPT_URL, $url); // 设置请求地址
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 设置cURL 参数,要求结果保存到字符串中还是输出到屏幕上。
// SSL验证
if ($SSL) {
if ($vfSSL) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_CAINFO, CORE_PATH . '/cacert.pem');
} else {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 不检查证书中是否设置域名
}
}
// 数据字段
if ($fields) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
}
$output = curl_exec($ch);
if (curl_errno($ch)) {
error('请求远程地址错误:' . curl_error($ch));
}
curl_close($ch);
return $output;
}
// 返回时间戳格式化日期时间,默认当前
function get_datetime($timestamp = null)
{
if (! $timestamp)
$timestamp = time();
return date('Y-m-d H:i:s', $timestamp);
}
// 返回时间戳格式化日期,默认当前
function get_date($timestamp = null)
{
if (! $timestamp)
$timestamp = time();
return date('Y-m-d', $timestamp);
}
// 返回时间戳差值部分,年、月、日
function get_date_diff($startstamp, $endstamp, $return = 'm')
{
$y = date('Y', $endstamp) - date('Y', $startstamp);
$m = date('m', $endstamp) - date('m', $startstamp);
switch ($return) {
case 'y':
if ($y <= 1) {
$y = $m / 12;
}
$string = $y;
break;
case 'm':
$string = $y * 12 + $m;
break;
case 'd':
$string = ($endstamp - $startstamp) / 86400;
break;
}
return $string;
}
// 生成无限极树,$data为二维数组数据
function get_tree($data, $tid, $idField, $pidField, $sonName = 'son')
{
$tree = array();
foreach ($data as $key => $value) {
if (is_array($value)) {
if ($value[$pidField] == "$tid") { // 父亲找到儿子
$value[$sonName] = get_tree($data, $value[$idField], $idField, $pidField, $sonName);
$tree[] = $value;
}
} else {
if ($value->$pidField == "$tid") { // 父亲找到儿子
$temp = clone $value;
$temp->$sonName = get_tree($data, $value->$idField, $idField, $pidField, $sonName);
$tree[] = $temp;
}
}
}
return $tree;
}
// 获取数据数组的映射数组
function get_mapping($array, $vValue, $vKey = null)
{
if (! $array)
return array();
foreach ($array as $key => $value) {
if (is_array($value)) {
if ($vKey) {
$result[$value[$vKey]] = $value[$vValue];
} else {
$result[] = $value[$vValue];
}
} elseif (is_object($value)) {
if ($vKey) {
$result[$value->$vKey] = $value->$vValue;
} else {
$result[] = $value->$vValue;
}
} else {
return $array;
}
}
return $result;
}
// 页码赋值异常返回1
function get_page()
{
if (isset($_GET['page'])) {
$value = trim($_GET['page']);
if (preg_match('/^[0-9]+$/', $value)) {
return $value;
}
}
return 1;
}
// 返回请求类型
function get_request_method()
{
return $_SERVER['REQUEST_METHOD'];
}
// 获取当前完整URL地址
function get_current_url()
{
$http_type = is_https() ? 'https://' : 'http://';
return $http_type . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
}
// 获取字符串第N次出现位置
function get_strpos($string, $find, $n)
{
$pos = strpos($string, $find);
for ($i = 2; $i <= $n; $i ++) {
$pos = strpos($string, $find, $pos + 1);
}
return $pos;
}
// array_column向下兼容低版本PHP
if (! function_exists('array_column')) {
function array_column($input, $columnKey, $indexKey = null)
{
$columnKeyIsNumber = (is_numeric($columnKey)) ? true : false;
$indexKeyIsNull = (is_null($indexKey)) ? true : false;
$indexKeyIsNumber = (is_numeric($indexKey)) ? true : false;
$result = array();
foreach ((array) $input as $key => $row) {
if ($columnKeyIsNumber) {
$tmp = array_slice($row, $columnKey, 1);
$tmp = (is_array($tmp) && ! empty($tmp)) ? current($tmp) : null;
} else {
$tmp = isset($row[$columnKey]) ? $row[$columnKey] : null;
}
if (! $indexKeyIsNull) {
if ($indexKeyIsNumber) {
$key = array_slice($row, $indexKey, 1);
$key = (is_array($key) && ! empty($key)) ? current($key) : null;
$key = is_null($key) ? 0 : $key;
} else {
$key = isset($row[$indexKey]) ? $row[$indexKey] : 0;
}
}
$result[$key] = $tmp;
}
return $result;
}
}
/**
* 系统信息弹出解析函数
*
* @param string $info_tpl模板
* @param string $string内容
* @param string $jump_url跳转地址
* @param number $time时间
*/
function parse_info_tpl($info_tpl, $string, $jump_url = null, $time = 0)
{
if (file_exists($info_tpl)) {
$tpl_content = file_get_contents($info_tpl);
if ($jump_url) {
$timeout_js = "<script>var timeout = {time};var showbox = document.getElementById('time');show();function show(){showbox.innerHTML = timeout+ ' 秒后自动跳转';timeout--;if (timeout == 0) {window.location.href = '{url}';}else {setTimeout(function(){show();}, 1000);}}</script>";
} else {
$timeout_js = '';
}
$tpl_content = str_replace('{js}', $timeout_js, $tpl_content);
$tpl_content = str_replace('{info}', $string, $tpl_content);
$tpl_content = str_replace('{url}', $jump_url, $tpl_content);
$tpl_content = str_replace('{time}', $time, $tpl_content);
$tpl_content = str_replace('{sitedir}', SITE_DIR, $tpl_content);
$tpl_content = str_replace('{coredir}', CORE_DIR, $tpl_content);
$tpl_content = str_replace('{appversion}', APP_VERSION . '-' . RELEASE_TIME, $tpl_content);
$tpl_content = str_replace('{serveros}', PHP_OS, $tpl_content);
$tpl_content = str_replace('{serversoft}', $_SERVER['SERVER_SOFTWARE'], $tpl_content);
return $tpl_content;
} else {
exit('<div style="font-size:50px;">:(</div>提示信息的模板文件不存在!');
}
}
// 获取转义数据,支持字符串、数组、对象
function escape_string($string)
{
if (! $string)
return $string;
if (is_array($string)) { // 数组处理
foreach ($string as $key => $value) {
$string[$key] = escape_string($value);
}
} elseif (is_object($string)) { // 对象处理
foreach ($string as $key => $value) {
$string->$key = escape_string($value);
}
} else { // 字符串处理
$string = htmlspecialchars(trim($string), ENT_QUOTES, 'UTF-8');
$string = addslashes($string);
}
return $string;
}
// 字符反转义html实体及斜杠支持字符串、数组、对象
function decode_string($string)
{
if (! $string)
return $string;
if (is_array($string)) { // 数组处理
foreach ($string as $key => $value) {
$string[$key] = decode_string($value);
}
} elseif (is_object($string)) { // 对象处理
foreach ($string as $key => $value) {
$string->$key = decode_string($value);
}
} else { // 字符串处理
$string = stripcslashes($string);
$string = htmlspecialchars_decode($string, ENT_QUOTES);
}
$string = preg_replace_r('/pboot:if/i', 'pboot@if', $string); // 避免解码绕过问题
return $string;
}
// 字符反转义斜杠,支持字符串、数组、对象
function decode_slashes($string)
{
if (! $string)
return $string;
if (is_array($string)) { // 数组处理
foreach ($string as $key => $value) {
$string[$key] = decode_slashes($value);
}
} elseif (is_object($string)) { // 对象处理
foreach ($string as $key => $value) {
$string->$key = decode_slashes($value);
}
} else { // 字符串处理
$string = stripcslashes($string);
}
return $string;
}
// 字符串双层MD5加密
function encrypt_string($string)
{
return md5(md5($string));
}
// 生成唯一标识符
function get_uniqid()
{
return encrypt_string(uniqid(mt_rand(), true));
}
// 清洗html代码的空白符号
function clear_html_blank($string)
{
$string = str_replace("\r\n", '', $string); // 清除换行符
$string = str_replace("\n", '', $string); // 清除换行符
$string = str_replace("\t", '', $string); // 清除制表符
$string = str_replace(' ', '', $string); // 清除大空格
$string = str_replace('&nbsp;', '', $string); // 清除 &nbsp;
$string = preg_replace('/\s+/', ' ', $string); // 清除空格
return $string;
}
// 去除字符串两端斜线
function trim_slash($string)
{
return trim($string, '/');
}
// 驼峰转换下划线加小写字母
function hump_to_underline($string)
{
return strtolower(preg_replace('/(?<=[a-z])([A-Z])/', '_$1', $string));
}
// 转换对象为数组
function object_to_array($object)
{
return json_decode(json_encode($object), true);
}
// 转换数组为对象
function array_to_object($array)
{
return json_decode(json_encode($array));
}
// 值是否在对象中
function in_object($needle, $object)
{
foreach ($object as $value) {
if ($needle == $value)
return true;
}
}
// 结果集中查找指定字段父节点是否存在
function result_value_search($needle, $result, $skey)
{
foreach ($result as $key => $value) {
if ($value->$skey == $needle) {
return $key;
}
}
return false;
}
// 多维数组合并
function mult_array_merge($array1, $array2)
{
if (is_array($array2)) {
foreach ($array2 as $key => $value) {
if (is_array($value)) {
if (array_key_exists($key, $array1)) {
$array1[$key] = mult_array_merge($array1[$key], $value);
} else {
$array1[$key] = $value;
}
} else {
$array1[$key] = $value;
}
}
}
return $array1;
}
// 数组转换为带引号字符串
function implode_quot($glue, array $pieces, $diffnum = false)
{
if (! $pieces)
return "''";
foreach ($pieces as $key => $value) {
if ($diffnum && ! is_numeric($value)) {
$value = "'$value'";
} elseif (! $diffnum) {
$value = "'$value'";
}
if (isset($string)) {
$string .= $glue . $value;
} else {
$string = $value;
}
}
return $string;
}
// 是否为多维数组,是返回true
function is_multi_array($array)
{
if (is_array($array)) {
return (count($array) != count($array, 1));
} else {
return false;
}
}
// 是否为移动设备
function is_mobile()
{
$os = get_user_os();
if ($os == 'Android' || $os == 'iPhone' || $os == 'Windows Phone' || $os == 'iPad') {
return true;
}
}
// 是否为POST请求
function is_post()
{
if ($_POST) {
return true;
} else {
return false;
}
}
// 是否为GET请求
function is_get()
{
if ($_GET) {
return true;
} else {
return false;
}
}
// 是否为PUT请求
function is_put()
{
if ($_SERVER['REQUEST_METHOD'] == 'PUT') {
return true;
} else {
return false;
}
}
// 是否为PATCH请求
function is_patch()
{
if ($_SERVER['REQUEST_METHOD'] == 'PATCH') {
return true;
} else {
return false;
}
}
// 是否为DELETE请求
function is_delete()
{
if ($_SERVER['REQUEST_METHOD'] == 'DELETE') {
return true;
} else {
return false;
}
}
// 是否为AJAX请求
function is_ajax()
{
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
return true;
} else {
return false;
}
}
// 判断当前是否为https
function is_https()
{
if ((isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on')) {
return true;
} elseif (isset($_SERVER['REQUEST_SCHEME']) && strtolower($_SERVER['REQUEST_SCHEME']) == 'https') {
return true;
} elseif (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https') {
return true;
} elseif (isset($_SERVER['HTTP_X_CLIENT_SCHEME']) && strtolower($_SERVER['HTTP_X_CLIENT_SCHEME']) == 'https') {
return true;
} else {
return false;
}
}
// 获取当前访问地址
function get_http_url($noport = false)
{
if (is_https()) {
$url = 'https://' . $_SERVER['HTTP_HOST'];
} else {
$url = 'http://' . $_SERVER['HTTP_HOST'];
}
if ($noport) {
$url = str_replace(':' . $_SERVER['SERVER_PORT'], '', $url);
}
return $url;
}
// 获取当前访问域名
function get_http_host($noport = true)
{
if ($noport) {
return str_replace(':' . $_SERVER['SERVER_PORT'], '', $_SERVER['HTTP_HOST']);
} else {
return $_SERVER['HTTP_HOST'];
}
}
// 服务器信息
function get_server_info()
{
// 定义输出常量
define('YES', 'Yes');
define('NO', '<span style="color:red">No</span>');
// 服务器系统
$data['php_os'] = PHP_OS;
// 服务器访问地址
$data['http_host'] = $_SERVER['HTTP_HOST'];
// 服务器名称
$data['server_name'] = $_SERVER['SERVER_NAME'];
// 服务器端口
$data['server_port'] = $_SERVER['SERVER_PORT'];
// 服务器地址
$data['server_addr'] = isset($_SERVER['LOCAL_ADDR']) ? $_SERVER['LOCAL_ADDR'] : $_SERVER['SERVER_ADDR'];
// 服务器软件
$data['server_software'] = $_SERVER['SERVER_SOFTWARE'];
// 站点目录
$data['document_root'] = isset($_SERVER['DOCUMENT_ROOT']) ? $_SERVER['DOCUMENT_ROOT'] : DOC_PATH;
// PHP版本
$data['php_version'] = PHP_VERSION;
// 数据库驱动
$data['db_driver'] = Config::get('database.type');
// php配置文件
$data['php_ini'] = @php_ini_loaded_file();
// 最大上传
$data['upload_max_filesize'] = ini_get('upload_max_filesize');
// 最大提交
$data['post_max_size'] = ini_get('post_max_size');
// 最大提交文件数
$data['max_file_uploads'] = ini_get('max_file_uploads');
// 内存限制
$data['memory_limit'] = ini_get('memory_limit');
// 检测gd扩展
$data['gd'] = extension_loaded('gd') ? YES : NO;
// 检测imap扩展
$data['imap'] = extension_loaded('imap') ? YES : NO;
// 检测socket扩展
$data['sockets'] = extension_loaded('sockets') ? YES : NO;
// 检测curl扩展
$data['curl'] = extension_loaded('curl') ? YES : NO;
// 会话保存路径
$data['session_save_path'] = session_save_path() ?: $_SERVER['TMP'];
// 检测standard库是否存在
$data['standard'] = extension_loaded('standard') ? YES : NO;
// 检测多线程支持
$data['pthreads'] = extension_loaded('pthreads') ? YES : NO;
// 检测XCache支持
$data['xcache'] = extension_loaded('XCache') ? YES : NO;
// 检测APC支持
$data['apc'] = extension_loaded('APC') ? YES : NO;
// 检测eAccelerator支持
$data['eaccelerator'] = extension_loaded('eAccelerator') ? YES : NO;
// 检测wincache支持
$data['wincache'] = extension_loaded('wincache') ? YES : NO;
// 检测ZendOPcache支持
$data['zendopcache'] = extension_loaded('Zend OPcache') ? YES : NO;
// 检测memcache支持
$data['memcache'] = extension_loaded('memcache') ? YES : NO;
// 检测memcached支持
$data['memcached'] = extension_loaded('memcached') ? YES : NO;
// 已经安装模块
$loaded_extensions = get_loaded_extensions();
$extensions = '';
foreach ($loaded_extensions as $key => $value) {
$extensions .= $value . ', ';
}
$data['extensions'] = $extensions;
return json_decode(json_encode($data));
}
// 获取数据库类型
function get_db_type()
{
switch (Config::get('database.type')) {
case 'mysqli':
case 'pdo_mysql':
$db = 'mysql';
break;
case 'sqlite':
case 'pdo_sqlite':
$db = 'sqlite';
break;
case 'pdo_pgsql':
$db = 'pgsql';
break;
default:
$db = null;
}
return $db;
}
// 获取间隔的月份的起始及结束日期
function get_month_days($date, $start = 0, $interval = 1, $retamp = false)
{
$timestamp = strtotime($date) ?: $date;
$first_day = strtotime(date('Y', $timestamp) . '-' . date('m', $timestamp) . '-01 +' . $start . ' month');
$last_day = strtotime(date('Y-m-d', $first_day) . ' +' . $interval . ' month -1 day');
if ($retamp) {
$return = array(
'first' => $first_day,
'last' => $last_day
);
} else {
$return = array(
'first' => date('Y-m-d', $first_day),
'last' => date('Y-m-d', $last_day)
);
}
return $return;
}
// 框架地址地址前缀
function url_index_path($indexfile = null)
{
$indexfile = $indexfile ?: $_SERVER["SCRIPT_NAME"];
if (Config::get('app_url_type') == 2 && strripos($indexfile, 'index.php') !== false) {
return SITE_DIR;
} elseif (Config::get('app_url_type') == 3 && strripos($indexfile, 'index.php') !== false) {
return SITE_DIR . '/?p=';
} elseif (Config::get('app_url_type') == 3 && strripos($indexfile, 'index.php') === false) {
return $indexfile . '?p=';
} else {
return $indexfile;
}
}
// 获取服务端web软件
function get_server_soft()
{
$soft = strtolower($_SERVER["SERVER_SOFTWARE"]);
if (strpos($soft, 'iis')) {
return 'iis';
} elseif (strpos($soft, 'apache')) {
return 'apache';
} elseif (strpos($soft, 'nginx')) {
return 'nginx';
} else {
return 'other';
}
}
// 创建会话层级目录
function create_session_dir($path, $depth)
{
if ($depth < 1) {
return;
} else {
$depth --;
}
$char = array(
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
'a',
'b',
'c',
'd',
'e',
'f',
'g',
'h',
'i',
'j',
'k',
'l',
'm',
'n',
'o',
'p',
'q',
'r',
's',
't',
'u',
'v'
);
foreach ($char as $value) {
if (! check_dir($path . '/' . $value, true)) {
error('会话目录写入权限不足!');
}
create_session_dir($path . '/' . $value, $depth);
}
}
// 中英混合的字符串截取,以一个汉字为一个单位长度,英文为半个
function substr_both($string, $strat, $length)
{
$s = 0; // 起始位置
$i = 0; // 实际Byte计数
$n = 0; // 字符串长度计数
$str_length = strlen($string); // 字符串的字节长度
while (($n < $length) and ($i < $str_length)) {
$ascnum = Ord(substr($string, $i, 1)); // 得到字符串中第$i位字符的ascii码
if ($ascnum >= 224) { // 根据UTF-8编码规范将3个连续的字符计为单个字符
$i += 3;
$n ++;
} elseif ($ascnum >= 192) { // 根据UTF-8编码规范将2个连续的字符计为单个字符
$i += 2;
$n ++;
} else {
$i += 1;
$n += 0.5;
}
if ($s == 0 && $strat > 0 && $n >= $strat) {
$s = $i; // 记录起始位置
}
}
if ($n < $strat) { // 起始位置大于字符串长度
return;
}
return substr($string, $s, $i);
}
// 中英混合的字符串长度,以一个汉字为一个单位长度,英文为半个
function strlen_both($string)
{
$i = 0; // 实际Byte计数
$n = 0; // 字符串长度计数
$str_length = strlen($string); // 字符串的字节长度
while ($i < $str_length) {
$ascnum = Ord(substr($string, $i, 1)); // 得到字符串中第$i位字符的ascii码
if ($ascnum >= 224) { // 根据UTF-8编码规范将3个连续的字符计为单个字符
$i += 3;
$n ++;
} elseif ($ascnum >= 192) { // 根据UTF-8编码规范将2个连续的字符计为单个字符
$i += 2;
$n ++;
} else {
$i += 1;
$n += 0.5;
}
}
return $n;
}
// 获取地址参数
function query_string($unset = null)
{
if (isset($_SERVER["QUERY_STRING"]) && ! ! $qs = $_SERVER["QUERY_STRING"]) {
parse_str($qs, $output);
unset($output['page']);
$unset = strpos($unset, ',') ? explode(',', $unset) : $unset;
if (is_array($unset)) {
foreach ($unset as $value) {
if (isset($output[$value])) {
unset($output[$value]);
}
}
} else {
if (isset($output[$unset])) {
unset($output[$unset]);
}
}
// 避免路径参数编码
if (isset($output['p'])) {
$p = 'p=' . $output['p'];
unset($output['p']);
$qs = $output ? $p . '&' . http_build_query($output) : $p;
} else {
$qs = http_build_query($output);
}
}
return $qs ? '?' . $qs : '';
}
// 判断是否在子网
function network_match($ip, $network)
{
if (strpos($network, '/') > 0) {
$network = explode('/', $network);
$move = 32 - $network[1];
if ($network[1] == 0) {
return true;
}
return ((ip2long($ip) >> $move) === (ip2long($network[0]) >> $move)) ? true : false;
} elseif ($network == $ip) {
return true;
} else {
return false;
}
}
// 递归替换
function preg_replace_r($search, $replace, $subject)
{
while (preg_match($search, $subject)) {
$subject = preg_replace($search, $replace, $subject);
}
return $subject;
}
// 生成随机验证码
function create_code($len = 4)
{
$charset = 'ABCDEFGHKMNPRTUVWXY23456789';
$charset = str_shuffle($charset);
$charlen = strlen($charset) - 1;
$code = '';
for ($i = 0; $i < $len; $i ++) {
$code .= $charset[mt_rand(0, $charlen)];
}
return $code;
}

733
core/function/helper.php Normal file
View File

@@ -0,0 +1,733 @@
<?php
/**
* @copyright (C)2016-2099 Hnaoyun Inc.
* @author XingMeng
* @email hnxsh@foxmail.com
* @date 2017年11月5日
* 助手函数
*/
use core\basic\Config;
use core\basic\Json;
use core\view\View;
use core\view\Paging;
use core\basic\Response;
use core\basic\Url;
use core\basic\Basic;
use core\basic\Smtp;
/**
* 生成实际跳转路径
*
* @param string $url
* 接收控制器方法访问完整路径,如:/home/index/index
* @return mixed
*/
function url($url, $suffix = false)
{
return Url::get($url, $suffix);
}
/**
* 生成前端路径
*
* @param string $url
* 前端地址参数
* @return mixed
*/
function homeurl($url, $suffix = null, $qs = null)
{
return Url::home($url, $suffix, $qs);
}
/**
* 自定义错误页面
*
* @param string $_string内容
* @param string $_url跳转地址
* @param number $_time时间
*/
function error($string, $jump_url = null, $time = 2)
{
@ob_clean();
http_response_code(404);
if (! $string)
$string = '未知错误!';
if ($jump_url == '-1' && isset($_SERVER['HTTP_REFERER'])) {
$jump_url = $_SERVER['HTTP_REFERER'];
if (strpos($jump_url, get_http_url()) !== 0) {
$jump_url = '/';
}
} elseif ($jump_url == '-1') {
$jump_url = null;
}
if (Config::get('return_data_type') == 'json' || is_ajax()) { // 接口模型返回格式数据
Response::json(0, strip_tags($string), $jump_url);
} else {
$err_tpl = CORE_PATH . '/template/error.html';
echo parse_info_tpl($err_tpl, $string, $jump_url, $time);
}
exit();
}
/**
* 自定义错误页面
*
* @param string $_string内容
* @param string $_url跳转地址
* @param number $_time时间
*/
function success($string, $jump_url = null, $time = 2)
{
if ($jump_url == '-1' && isset($_SERVER['HTTP_REFERER'])) {
$jump_url = $_SERVER['HTTP_REFERER'];
if (strpos($jump_url, get_http_url()) !== 0) {
$jump_url = '/';
}
} elseif ($jump_url == '-1') {
$jump_url = null;
}
if (Config::get('return_data_type') == 'json' || is_ajax()) { // 接口模型返回格式数据
Response::json(1, strip_tags($string), $jump_url);
} else {
$err_tpl = CORE_PATH . '/template/success.html';
echo parse_info_tpl($err_tpl, $string, $jump_url, $time);
}
exit();
}
/**
* 弹窗
*
* @param string $info信息
*/
function alert($info, $status = 0)
{
if (Config::get('return_data_type') == 'json' || is_ajax()) { // 接口模型返回格式数据
Response::json($status, strip_tags($info));
} else {
echo '<script type="text/javascript">alert("' . clear_html_blank($info) . '");</script>';
}
}
/**
* 弹窗并返回前页
*
* @param string $info信息
*/
function alert_back($info, $status = 0)
{
if (Config::get('return_data_type') == 'json' || is_ajax()) { // 接口模型返回格式数据
Response::json($status, strip_tags($info));
} else {
echo '<script type="text/javascript">alert("' . clear_html_blank($info) . '");window.history.go(-1);</script>';
exit();
}
}
/**
* 跳转
*
* @param string $url跳转地址
*/
function location($url)
{
if ($url == '-1' && isset($_SERVER['HTTP_REFERER'])) {
$url = $_SERVER['HTTP_REFERER'];
if (strpos($url, get_http_url()) !== 0) {
$url = '/';
}
}
header('Location:' . $url);
exit();
}
/**
* 弹窗并跳转
*
* @param string $info信息
* @param string $url跳转地址
*/
function alert_location($info, $url, $status = 0)
{
if ($url == '-1' && isset($_SERVER['HTTP_REFERER'])) {
$url = $_SERVER['HTTP_REFERER'];
if (strpos($url, get_http_url()) !== 0) {
$url = '/';
}
}
if (Config::get('return_data_type') == 'json' || is_ajax()) { // 接口模型返回格式数据
Response::json($status, strip_tags($info), $url);
} else {
echo '<script type="text/javascript">alert("' . clear_html_blank($info) . '");location.href="' . $url . '";</script>';
exit();
}
}
/**
* 弹窗并关闭
*
* @param string $info信息
*/
function alert_close($info, $status = 0)
{
if (Config::get('return_data_type') == 'json' || is_ajax()) { // 接口模型返回格式数据
Response::json($status, strip_tags($info));
} else {
echo '<script type="text/javascript">alert("' . clear_html_blank($info) . '");window.close();</script>';
exit();
}
}
/**
* 实例化模型对象助手
*
* @param string $name
* 需要实力化的模型名称
* @param string $new
* 是否强制新建对象
* @return mixed
*/
function model($name = null, $new = false)
{
return Basic::createModel($name, $new);
}
/**
* api读取数据
*
* @param string $name
* 接口名称add或 admin.user.addd
* @param array $param
* 参数
* @param string $rsOriginal
* 结果不处理直接返回
* @param string $jsonRsArray
* 返回Json数组方式
* @return mixed
*/
function api($args = null)
{
return Basic::createApi(func_get_args());
}
// 输出模板内容
function display($tpl)
{
$view = View::getInstance();
echo $view->parser($tpl);
}
// 解析模板内容
function parser($tpl)
{
$view = View::getInstance();
return $view->parser($tpl);
}
// 设置模板
function set_theme($theme_name)
{
$view = View::getInstance();
$view->assign('theme', $theme_name);
}
// 注入模板变量
function assign($var, $value)
{
$view = View::getInstance();
$view->assign($var, $value);
}
// 变量获取接口
function get_var($var)
{
$view = View::getInstance();
return $view->getVar($var);
}
// 手动生成分页信息,返回限制语句
function page($tatal, $morePageStr = false)
{
$page = Paging::getInstance();
return $page->limit($tatal, $morePageStr);
}
// 内容输出助手函数
function response($data)
{
return core\basic\Response::handle($data);
}
// Json内容输出助手函数
function json($code, $data, $tourl = null)
{
return core\basic\Response::json($code, $data, $tourl);
}
/**
* 数据过滤
*
* @param mixed $varname
* 字符串或参数名称
* @param array $condition
* array('d_source'=>'post','d_none'=>true,'d_require'=>true,'d_type'=>'int','d_max'=>5,'d_min'=2,'d_default'=>'')
* 字段名称:$varname,用字段名称做key传递文本
* 数据源:d_source[post、get、cookie、session、both、string]
* 是否允许空d_none[true、false],如果为false接受的收据为空则直接报错
* 是否必须d_require[true、false],如果为true意味着如果数据不满足要求直接报错否则返回null
* 数据类型d_type[int、float、num、letter、var、bool、date、array、object]
* 正则表达d_regular接受正则表达式
* 最大值|最大长度d_max
* 最小值|最小长度d_min
* 默认值d_default
* @return mixed
*/
function filter($varname, $condition)
{
// 变量名称文本
if (array_key_exists($varname, $condition) && $condition[$varname]) {
$vartext = $condition[$varname];
} else {
$vartext = $varname;
}
// 数据源
if (array_key_exists('d_source', $condition)) {
switch ($condition['d_source']) {
case 'post':
$data = @$_POST[$varname];
break;
case 'get':
$data = @$_GET[$varname];
break;
case 'cookie':
$data = @$_COOKIE[$varname];
break;
case 'session':
$data = session($varname);
break;
case 'both':
$data = @$_POST[$varname] ?: @$_GET[$varname];
break;
case 'string':
$data = $varname;
default:
error($vartext . '数据获取方式设置错误!');
}
// 去空格
if (is_string($data))
$data = trim($data);
} else {
$data = $varname; // 没有数据源指定时直接按照字符串过滤处理
}
// 数据为空时,进行是否允许空检测
if (! $data && array_key_exists('d_none', $condition) && $condition['d_none'] === false) {
error($vartext . '不能为空!');
}
// 判断是否强制检测为true时意味着如果数据不满足要求直接报错否则返回null
if (array_key_exists('d_require', $condition) && $condition['d_require'] == true) {
$require = true;
} else {
$require = false;
}
// 数据类型检测
if (array_key_exists('d_type', $condition)) {
switch ($condition['d_type']) {
case 'int':
if (! preg_match('/^[0-9]+$/', $data)) {
$err = '必须为整数!';
}
break;
case 'float':
if (! is_float($data)) {
$err = '必须为浮点数!';
}
break;
case 'num':
if (! is_numeric($data)) {
$err = '必须为数字!';
}
break;
case 'letter':
if (! preg_match('/^[a-zA-Z]+$/', $data)) {
$err = '只能包含字母!';
}
break;
case 'var':
if (! preg_match('/^[\w\-\.]+$/', $data)) {
$err = '只能包含字母、数字、划线、点!';
}
break;
case 'bool':
if (! is_bool($data)) {
$err = '必须为布尔类型!';
}
break;
case 'date':
if (! strtotime($data)) {
$err = '必须为日期类型!';
}
break;
case 'array':
if (! is_array($data)) {
$err = '必须为数组类型!';
}
break;
case 'object':
if (! is_object($data)) {
$err = '必须为对象类型!';
}
break;
case 'vars':
if (! preg_match('/^[\x{4e00}-\x{9fa5}\w\-\.,\s]+$/u', $data)) {
$err = '只能包含中文、字母、数字、横线、点、逗号、空格!';
}
break;
default:
if ($condition['d_type'])
error($vartext . '数据类型设置错误!');
}
}
// 非必须或必须但无错误时执行
if ((! $require || ($require && ! isset($err)))) {
// 正则匹配
if (array_key_exists('d_regular', $condition)) {
if (! preg_match($condition['d_regular'], $data)) {
$err = '不符合正则表达式规则!';
}
}
// 最大值匹配
if (array_key_exists('d_max', $condition)) {
if (is_numeric($data)) {
if ($data > $condition['d_max']) {
$err = '不能大于' . $condition['d_max'];
}
} else {
if (mb_strlen($data) > $condition['d_max']) {
$err = '长度不能大于' . $condition['d_max'];
}
}
}
// 最小值匹配
if (array_key_exists('d_min', $condition)) {
if (is_numeric($data)) {
if ($data < $condition['d_min']) {
$err = '不能小于' . $condition['d_min'];
}
} else {
if (mb_strlen($data) < $condition['d_min']) {
$err = '长度不能小于' . $condition['d_min'];
}
}
}
}
// 如果为必须且有错误,则显示错误,如果非必须但有错误则设置数据为null
if ($require && isset($err)) {
error($vartext . $err);
} elseif (isset($err)) {
$data = null;
}
// 如果设置有默认值,默认值
if (array_key_exists('d_default', $condition)) {
$data = (! is_null($data)) ? $data : $condition['d_default'];
}
if (is_string($data)) {
$data = trim($data); // 去空格
$data = preg_replace_r('/(x3c)|(x3e)/', '', $data); // 去十六进制括号
$data = preg_replace_r('/pboot:if/i', 'pboot@if', $data); // 过滤插入cms条件语句
$data = preg_replace_r('/pboot:sql/i', 'pboot@sql', $data); // 过滤插入cms条件语句
$data = preg_replace_r('/GET\[/i', 'GET@[', $data);
$data = preg_replace_r('/POST\[/i', 'POST@[', $data);
}
// 销毁错误
unset($err);
// 返回收据
return escape_string($data);
}
/**
* 获取GET参数
*
* @param string $name
* 参数名称
* @param mixed $type
* 数据类型
* @param string $require
* 是否为必须为true是如果不满足条件直接错误
* @param string $vartext
* 变量描述文本
* @param string $default
* 在非必需情况下默认值
* @return mixed
*/
function get($name, $type = null, $require = false, $vartext = null, $default = null)
{
$condition = array(
'd_source' => 'get',
'd_type' => $type,
'd_require' => $require,
$name => $vartext,
'd_default' => $default
);
return filter($name, $condition);
}
/**
* * 获取POST参数
*
* @param string $name
* 参数名称
* @param mixed $type
* 数据类型
* @param string $require
* 是否为必须为true是如果不满足条件直接错误
* @param string $vartext
* 变量描述文本
* @param string $default
* 在非必需情况下默认值
* @return mixed
*/
function post($name, $type = null, $require = false, $vartext = null, $default = null)
{
$condition = array(
'd_source' => 'post',
'd_type' => $type,
'd_require' => $require,
$name => $vartext,
'd_default' => $default
);
return filter($name, $condition);
}
/**
* * 获取参数post或get
*
* @param string $name
* 参数名称
* @param mixed $type
* 数据类型
* @param string $require
* 是否为必须为true是如果不满足条件直接错误
* @param string $vartext
* 变量描述文本
* @param string $default
* 在非必需情况下默认值
* @return mixed
*/
function request($name, $type = null, $require = false, $vartext = null, $default = null)
{
if (isset($_POST[$name])) {
$d_source = 'post';
} else {
$d_source = 'get';
}
$condition = array(
'd_source' => $d_source,
'd_type' => $type,
'd_require' => $require,
$name => $vartext,
'd_default' => $default
);
return filter($name, $condition);
}
/**
* 读取或写入Cookie信息
*
* @param string $name
* 名称
* @param string $value
* 值
* @param int $expire
* 秒数
* @param string $path
* 路径,默认站点目录
*/
function cookie($name, $value = null, $expire = null, $path = null, $domain = null, $secure = null, $httponly = true)
{
if (! is_null($value)) {
$path = SITE_DIR . '/';
if (is_string($value))
$value = trim($value);
$_COOKIE[$name] = $value; // 让cookie立即生效
if (! is_null($expire)) {
return setcookie($name, $value, time() + $expire, $path, $domain, $secure, $httponly);
} else {
return setcookie($name, $value, 0, $path, $domain, $secure, $httponly);
}
} else {
if (isset($_COOKIE[$name])) {
return escape_string($_COOKIE[$name]);
} else {
return null;
}
}
}
/**
* 读取或写入session信息
*
* @param string $name
* 支持点分多级获取
* @param mixed $value
* 设置值
* @return string|NULL|unknown
*/
function session($name, $value = null)
{
if (! isset($_SESSION)) {
session_start(); // 自动启动会话
}
if (! is_null($value)) {
if (isset($_SESSION[$name])) {
if ($_SESSION[$name] != $value) {
$_SESSION[$name] = $value;
}
} else {
$_SESSION[$name] = $value;
}
return $value;
} else {
if (strpos($name, '.')) {
if (isset($_SESSION[$name])) {
return $_SESSION[$name];
}
$names = explode('.', $name);
if (! isset($_SESSION[$names[0]])) {
return null;
}
$var = $_SESSION[$names[0]];
$len = count($names);
for ($i = 1; $i < $len; $i ++) {
if (is_array($var)) {
if (isset($var[$names[$i]])) {
$var = $var[$names[$i]];
} else {
return null;
}
} elseif (is_object($var)) {
if (isset($var->{$names[$i]})) {
$var = $var->{$names[$i]};
} else {
return null;
}
} else {
break;
}
}
return $var;
} else {
if (isset($_SESSION[$name])) {
return $_SESSION[$name];
} else {
return null;
}
}
}
}
// 检查会话参数是否存在
function issetSession($name)
{
if (! isset($_SESSION)) {
session_start(); // 自动启动会话
}
return isset($_SESSION[$name]);
}
/**
* 快速发送邮件函数
*
* @param array $config
* 邮件服务器连接数组,需包含 smtp_server、smtp_username、smtp_password、smtp_port、smtp_port
* @param string $to
* 邮件接收人
* @param string $subject
* 邮件主题
* @param string $body
* 邮件正文
*/
function sendmail(array $config, $to, $subject, $body)
{
$smtp = new Smtp($config['smtp_server'], $config['smtp_username'], $config['smtp_password'], $config['smtp_port'], $config['smtp_ssl']);
if ($smtp->sendMail($to, $subject, $body)) {
return true;
} else {
return $smtp->error();
}
}
// 发送短信
function sendsms(array $config, $to, $content)
{
if (! $to || ! $content) {
return false;
}
if (! isset($config['sms_account']) || ! isset($config['sms_pwd']) || ! isset($config['sms_signid'])) {
alert_back('短信发送参数配置有误');
}
$data['Account'] = $config['sms_account'];
$data['Pwd'] = $config['sms_pwd'];
$data['SignId'] = $config['sms_signid'];
$data['Content'] = $content;
$to = str_replace("\r\n", ",", $to); // 替换回车
$to = str_replace("", ",", $to); // 替换中文逗号分割符
$data['Mobile'] = str_replace(" ", "", $to); // 替换空格
$url = "http://api.feige.ee/SmsService/Send";
if (! ! $res = get_url($url, $data)) {
$result = json_decode($res);
if (! ($result->Code === 0)) {
error('短信发送失败,' . $result->Message);
} else {
return true;
}
}
}
// 查询短信余额
function get_sms_balance(array $config)
{
$data['Account'] = $config['sms_account'];
$data['Pwd'] = $config['sms_pwd'];
$url = "http://api.feige.ee/Account/Balance";
if (! ! $res = get_url($url, $data)) {
$result = json_decode($res);
if (! ($result->Code === 0)) {
error('查询失败,' . $result->Message);
} else {
return $result->Balance;
}
}
}
// 返回404页面,文件中可使用{info}替换提示信息
function _404($string, $jump_url = null, $time = 2)
{
http_response_code(404);
$file_404 = ROOT_PATH . '/404.html';
if (file_exists($file_404)) {
echo parse_info_tpl($file_404, $string, $jump_url, $time);
exit();
} else {
error($string, $jump_url, $time);
}
}