diff --git a/application/admin/common.php b/application/admin/common.php index 72e20ed3..03af2679 100644 --- a/application/admin/common.php +++ b/application/admin/common.php @@ -24,19 +24,19 @@ * ) * */ -function int_to_string(&$data,$map=array('status'=>array(1=>'正常',-1=>'删除',0=>'禁用',2=>'未审核',3=>'草稿'))) { - if($data === false || $data === null ){ - return $data; - } - $data = (array)$data; - foreach ($data as $key => $row){ - foreach ($map as $col=>$pair){ - if(isset($row[$col]) && isset($pair[$row[$col]])){ - $data[$key][$col.'_text'] = $pair[$row[$col]]; - } - } - } - return $data; +function intToString(&$data, $map = array('status' => array(1 => '正常', -1 => '删除', 0 => '禁用', 2 => '未审核', 3 => '草稿'))) { + if ($data === false || $data === null) { + return $data; + } + $data = (array) $data; + foreach ($data as $key => $row) { + foreach ($map as $col => $pair) { + if (isset($row[$col]) && isset($pair[$row[$col]])) { + $data[$key][$col . '_text'] = $pair[$row[$col]]; + } + } + } + return $data; } /** @@ -45,27 +45,36 @@ function int_to_string(&$data,$map=array('status'=>array(1=>'正常',-1=>'删除 * @return string 状态文字 ,false 未获取到 * @author huajie */ -function get_status_title($status = null){ - if(!isset($status)){ - return false; - } - switch ($status){ - case -1 : return '已删除'; break; - case 0 : return '禁用'; break; - case 1 : return '正常'; break; - case 2 : return '待审核'; break; - default : return false; break; - } +function getStatusTitle($status = null) { + if (!isset($status)) { + return false; + } + switch ($status) { + case -1:return '已删除'; + break; + case 0:return '禁用'; + break; + case 1:return '正常'; + break; + case 2:return '待审核'; + break; + default:return false; + break; + } } // 获取数据的状态操作 -function show_status_op($status) { - switch ($status){ - case 0 : return '启用'; break; - case 1 : return '禁用'; break; - case 2 : return '审核'; break; - default : return false; break; - } +function showStatusOp($status) { + switch ($status) { + case 0:return '启用'; + break; + case 1:return '禁用'; + break; + case 2:return '审核'; + break; + default:return false; + break; + } } /** @@ -74,15 +83,15 @@ function show_status_op($status) { * @param bool $all 是否返回全部类型 * @author huajie */ -function get_action_type($type, $all = false){ - $list = array( - 1=>'系统', - 2=>'用户', - ); - if($all){ - return $list; - } - return $list[$type]; +function getActionType($type, $all = false) { + $list = array( + 1 => '系统', + 2 => '用户', + ); + if ($all) { + return $list; + } + return $list[$type]; } /** @@ -91,16 +100,16 @@ function get_action_type($type, $all = false){ * @param string $field 需要获取的字段 * @author huajie */ -function get_action($id = null, $field = null){ - if(empty($id) && !is_numeric($id)){ - return false; - } - $list = cache('action_list'); - if(empty($list[$id])){ - $map = array('status'=>array('gt', -1), 'id'=>$id); - $list[$id] = db('Action')->where($map)->field(true)->find(); - } - return empty($field) ? $list[$id] : $list[$id][$field]; +function getAction($id = null, $field = null) { + if (empty($id) && !is_numeric($id)) { + return false; + } + $list = cache('action_list'); + if (empty($list[$id])) { + $map = array('status' => array('gt', -1), 'id' => $id); + $list[$id] = db('Action')->where($map)->field(true)->find(); + } + return empty($field) ? $list[$id] : $list[$id][$field]; } /** @@ -110,18 +119,18 @@ function get_action($id = null, $field = null){ * @param string $field 需要返回的字段,不传则返回整个数据 * @author huajie */ -function get_document_field($value = null, $condition = 'id', $field = null){ - if(empty($value)){ - return false; - } +function getDocumentField($value = null, $condition = 'id', $field = null) { + if (empty($value)) { + return false; + } - //拼接参数 - $map[$condition] = $value; - $info = db('Model')->where($map); - if(empty($field)){ - $info = $info->field(true)->find(); - }else{ - $info = $info->value($field); - } - return $info; +//拼接参数 + $map[$condition] = $value; + $info = db('Model')->where($map); + if (empty($field)) { + $info = $info->field(true)->find(); + } else { + $info = $info->value($field); + } + return $info; } diff --git a/application/admin/controller/Addons.php b/application/admin/controller/Addons.php index 47777b6f..4ef1736b 100644 --- a/application/admin/controller/Addons.php +++ b/application/admin/controller/Addons.php @@ -14,27 +14,27 @@ class Addons extends Admin { protected $addons; - public function _initialize(){ + public function _initialize() { parent::_initialize(); //加入菜单 $this->getAddonsMenu(); $this->addons = model('Addons'); - $this->hooks = db('Hooks'); + $this->hooks = db('Hooks'); } /** - * 插件列表 - */ - public function index($refresh = 0){ + * 插件列表 + */ + public function index($refresh = 0) { if ($refresh) { $this->addons->refresh(); } - $list = $this->addons->order('id desc')->paginate(25); + $list = $this->addons->order('id desc')->paginate(25); // 记录当前列表页的cookie - Cookie('__forward__',$_SERVER['REQUEST_URI']); + Cookie('__forward__', $_SERVER['REQUEST_URI']); $data = array( - 'list' => $list, - 'page' => $list->render() + 'list' => $list, + 'page' => $list->render(), ); $this->setMeta("插件管理"); $this->assign($data); @@ -42,27 +42,27 @@ class Addons extends Admin { } //创建向导首页 - public function add(){ + public function add() { if (IS_POST) { $data = $this->addons->create(); if ($data) { if ($result) { - return $this->success("创建成功!",url('admin/addons/index')); - }else{ + return $this->success("创建成功!", url('admin/addons/index')); + } else { return $this->error("创建失败!"); } - }else{ + } else { return $this->error($this->addons->getError()); } - }else{ + } else { $hooks = db('Hooks')->field('name,description')->select(); - $this->assign('Hooks',$hooks); + $this->assign('Hooks', $hooks); $hook = db('Hooks')->field(true)->select(); - foreach($hook as $key => $value){ + foreach ($hook as $key => $value) { $addons_opt[$value['name']] = $value['name']; } - $addons_opt = array(array('type'=>'select','opt'=>$addons_opt)); - if(!is_writable(SENT_ADDON_PATH)){ + $addons_opt = array(array('type' => 'select', 'opt' => $addons_opt)); + if (!is_writable(SENT_ADDON_PATH)) { return $this->error('您没有创建目录写入权限,无法使用此功能'); } $this->setMeta("添加插件"); @@ -71,35 +71,35 @@ class Addons extends Admin { } //预览 - public function preview($output = true){ + public function preview($output = true) { } /** * 安装插件 */ - public function install(){ - $addon_name = input('addon_name','','trim,ucfirst'); - $class = get_addon_class($addon_name); - if(class_exists($class)){ - $addons = new $class; - $info = $addons->info; - if(!$info || !$addons->checkInfo()){ + public function install() { + $addon_name = input('addon_name', '', 'trim,ucfirst'); + $class = get_addon_class($addon_name); + if (class_exists($class)) { + $addons = new $class; + $info = $addons->info; + if (!$info || !$addons->checkInfo()) { //检测信息的正确性 return $this->error('插件信息缺失'); } - session('addons_install_error',null); - $install_flag = $addons->install(); - if(!$install_flag){ - return $this->error('执行插件预安装操作失败'.session('addons_install_error')); + session('addons_install_error', null); + $install_flag = $addons->install(); + if (!$install_flag) { + return $this->error('执行插件预安装操作失败' . session('addons_install_error')); } $result = $this->addons->install($info); - if($result){ + if ($result) { cache('hooks', null); return $this->success('安装成功'); - }else{ + } else { return $this->error($this->addons->getError()); } - }else{ + } else { return $this->error('插件不存在'); } } @@ -107,11 +107,11 @@ class Addons extends Admin { /** * 卸载插件 */ - public function uninstall($id){ + public function uninstall($id) { $result = $this->addons->uninstall($id); - if($result === false){ - return $this->error($this->addons->getError(),''); - }else{ + if ($result === false) { + return $this->error($this->addons->getError(), ''); + } else { return $this->success('卸载成功!'); } } @@ -119,14 +119,14 @@ class Addons extends Admin { /** * 启用插件 */ - public function enable(){ - $id = input('id'); + public function enable() { + $id = input('id'); cache('hooks', null); - $model = model('Addons'); - $result = $model::where(array('id'=>$id))->update(array('status'=>1)); + $model = model('Addons'); + $result = $model::where(array('id' => $id))->update(array('status' => 1)); if ($result) { return $this->success('启用成功'); - }else{ + } else { return $this->error("启用失败!"); } } @@ -134,14 +134,14 @@ class Addons extends Admin { /** * 禁用插件 */ - public function disable(){ - $id = input('id'); + public function disable() { + $id = input('id'); cache('hooks', null); - $model = model('Addons'); - $result = $model::where(array('id'=>$id))->update(array('status'=>0)); + $model = model('Addons'); + $result = $model::where(array('id' => $id))->update(array('status' => 0)); if ($result) { return $this->success('禁用成功'); - }else{ + } else { return $this->error("禁用失败!"); } } @@ -149,11 +149,11 @@ class Addons extends Admin { /** * 设置插件页面 */ - public function config(){ + public function config() { if (IS_POST) { # code... - }else{ - $id = input('id','','trim,intval'); + } else { + $id = input('id', '', 'trim,intval'); if (!$id) { return $this->error("非法操作!"); } @@ -162,13 +162,13 @@ class Addons extends Admin { $class = get_addon_class($info['name']); $keyList = array(); - $data = array( - 'keyList' => $keyList + $data = array( + 'keyList' => $keyList, ); $this->assign($data); $this->setMeta($info['title'] . " - 设置"); return $this->fetch('public/edit'); - }else{ + } else { return $this->error("未安装此插件!"); } } @@ -180,17 +180,17 @@ class Addons extends Admin { * @param string $addons 插件名称 * @param string $addons 插件简介 */ - public function existHook($str, $addons, $msg=''){ - $hook_mod = db('Hooks'); + public function existHook($str, $addons, $msg = '') { + $hook_mod = db('Hooks'); $where['name'] = $str; - $gethook = $hook_mod->where($where)->find(); - if(!$gethook || empty($gethook) || !is_array($gethook)){ - $data['name'] = $str; + $gethook = $hook_mod->where($where)->find(); + if (!$gethook || empty($gethook) || !is_array($gethook)) { + $data['name'] = $str; $data['description'] = $msg; - $data['type'] = 1; + $data['type'] = 1; $data['update_time'] = time(); - $data['addons'] = $addons; - if( false !== $hook_mod->create($data) ){ + $data['addons'] = $addons; + if (false !== $hook_mod->create($data)) { $hook_mod->add(); } } @@ -200,8 +200,8 @@ class Addons extends Admin { * 删除钩子 * @param string $hook 钩子名称 */ - public function deleteHook($hook){ - $model = db('hooks'); + public function deleteHook($hook) { + $model = db('hooks'); $condition = array( 'name' => $hook, ); @@ -212,36 +212,36 @@ class Addons extends Admin { /** * 钩子列表 */ - public function hooks(){ + public function hooks() { - $map = array(); + $map = array(); $order = "id desc"; - $list = model('Hooks')->where($map)->order($order)->paginate(10); - + $list = model('Hooks')->where($map)->order($order)->paginate(10); + // 记录当前列表页的cookie - Cookie('__forward__',$_SERVER['REQUEST_URI']); + Cookie('__forward__', $_SERVER['REQUEST_URI']); $data = array( - 'list' => $list, - 'page' => $list->render() + 'list' => $list, + 'page' => $list->render(), ); $this->setMeta("钩子管理"); $this->assign($data); return $this->fetch(); } - public function addhook(){ + public function addhook() { $hooks = model('Hooks'); if (IS_POST) { $result = $hooks->change(); if ($result !== false) { return $this->success("修改成功"); - }else{ + } else { return $this->error($hooks->getError()); } - }else{ + } else { $keylist = $hooks->getaddons(); - $data = array( + $data = array( 'keyList' => $keylist, ); $this->assign($data); @@ -251,20 +251,20 @@ class Addons extends Admin { } //钩子出编辑挂载插件页面 - public function edithook($id){ + public function edithook($id) { $hooks = model('Hooks'); if (IS_POST) { $result = $hooks->change(); if ($result !== false) { return $this->success("修改成功"); - }else{ + } else { return $this->error($hooks->getError()); } - }else{ - $info = db('Hooks')->find($id); + } else { + $info = db('Hooks')->find($id); $keylist = $hooks->getaddons($info['addons']); - $data = array( - 'info' => $info, + $data = array( + 'info' => $info, 'keyList' => $keylist, ); $this->assign($data); @@ -274,41 +274,41 @@ class Addons extends Admin { } //超级管理员删除钩子 - public function delhook(){ - $id = input('id','','trim,intval'); - $ids = input('post.ids/a',array()); + public function delhook() { + $id = input('id', '', 'trim,intval'); + $ids = input('post.ids/a', array()); array_push($ids, $id); - $map['id'] = array('IN',$ids); - $result = $this->hooks->where($map)->delete(); - if($result !== false){ + $map['id'] = array('IN', $ids); + $result = $this->hooks->where($map)->delete(); + if ($result !== false) { return $this->success('删除成功'); - }else{ + } else { return $this->error('删除失败'); } } - public function updateHook(){ - $hookModel = D('Hooks'); - $data = $hookModel->create(); - if($data){ - if($data['id']){ + public function updateHook() { + $hookModel = D('Hooks'); + $data = $hookModel->create(); + if ($data) { + if ($data['id']) { $flag = $hookModel->save($data); - if($flag !== false){ + if ($flag !== false) { S('hooks', null); $this->success('更新成功', Cookie('__forward__')); - }else{ + } else { $this->error('更新失败'); } - }else{ + } else { $flag = $hookModel->add($data); - if($flag){ + if ($flag) { S('hooks', null); $this->success('新增成功', Cookie('__forward__')); - }else{ + } else { $this->error('新增失败'); } } - }else{ + } else { $this->error($hookModel->getError()); } } diff --git a/application/common.php b/application/common.php index 7fa6a06d..56e58e90 100644 --- a/application/common.php +++ b/application/common.php @@ -13,104 +13,105 @@ define('SENT_ADDON_PATH', ROOT_PATH . DS . 'addons' . DS); //字符串解密加密 function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) { - $ckey_length = 4; // 随机密钥长度 取值 0-32; - // 加入随机密钥,可以令密文无任何规律,即便是原文和密钥完全相同,加密结果也会每次不同,增大破解难度。 - // 取值越大,密文变动规律越大,密文变化 = 16 的 $ckey_length 次方 - // 当此值为 0 时,则不产生随机密钥 - $uc_key = config('data_auth_key') ? config('data_auth_key') : 'sentcms'; - $key = md5($key ? $key : $uc_key); - $keya = md5(substr($key, 0, 16)); - $keyb = md5(substr($key, 16, 16)); - $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : ''; + $ckey_length = 4; // 随机密钥长度 取值 0-32; + // 加入随机密钥,可以令密文无任何规律,即便是原文和密钥完全相同,加密结果也会每次不同,增大破解难度。 + // 取值越大,密文变动规律越大,密文变化 = 16 的 $ckey_length 次方 + // 当此值为 0 时,则不产生随机密钥 + $uc_key = config('data_auth_key') ? config('data_auth_key') : 'sentcms'; + $key = md5($key ? $key : $uc_key); + $keya = md5(substr($key, 0, 16)); + $keyb = md5(substr($key, 16, 16)); + $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : ''; - $cryptkey = $keya.md5($keya.$keyc); - $key_length = strlen($cryptkey); + $cryptkey = $keya . md5($keya . $keyc); + $key_length = strlen($cryptkey); - $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string; + $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string; - $string_length = strlen($string); - $result = ''; - $box = range(0, 255); - $rndkey = array(); - for($i = 0; $i <= 255; $i++) { - $rndkey[$i] = ord($cryptkey[$i % $key_length]); - } + $string_length = strlen($string); + $result = ''; + $box = range(0, 255); + $rndkey = array(); + for ($i = 0; $i <= 255; $i++) { + $rndkey[$i] = ord($cryptkey[$i % $key_length]); + } - for($j = $i = 0; $i < 256; $i++) { - $j = ($j + $box[$i] + $rndkey[$i]) % 256; - $tmp = $box[$i]; - $box[$i] = $box[$j]; - $box[$j] = $tmp; - } + for ($j = $i = 0; $i < 256; $i++) { + $j = ($j + $box[$i] + $rndkey[$i]) % 256; + $tmp = $box[$i]; + $box[$i] = $box[$j]; + $box[$j] = $tmp; + } - for($a = $j = $i = 0; $i < $string_length; $i++) { - $a = ($a + 1) % 256; - $j = ($j + $box[$a]) % 256; - $tmp = $box[$a]; - $box[$a] = $box[$j]; - $box[$j] = $tmp; - $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256])); - } + for ($a = $j = $i = 0; $i < $string_length; $i++) { + $a = ($a + 1) % 256; + $j = ($j + $box[$a]) % 256; + $tmp = $box[$a]; + $box[$a] = $box[$j]; + $box[$j] = $tmp; + $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256])); + } - if($operation == 'DECODE') { - if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) { - return substr($result, 26); - } else { - return ''; - } - } else { - return $keyc.str_replace('=', '', base64_encode($result)); - } + if ($operation == 'DECODE') { + if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) { + return substr($result, 26); + } else { + return ''; + } + } else { + return $keyc . str_replace('=', '', base64_encode($result)); + } } /** - +---------------------------------------------------------- ++---------------------------------------------------------- * 产生随机字串,可用来自动生成密码 默认长度6位 字母和数字混合 - +---------------------------------------------------------- ++---------------------------------------------------------- * @param string $len 长度 * @param string $type 字串类型 * 0 字母 1 数字 其它 混合 * @param string $addChars 额外字符 - +---------------------------------------------------------- ++---------------------------------------------------------- * @return string - +---------------------------------------------------------- ++---------------------------------------------------------- */ -function rand_string($len=6,$type='',$addChars='') { - $str =''; - switch($type) { - case 0: - $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.$addChars; - break; - case 1: - $chars= str_repeat('0123456789',3); - break; - case 2: - $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZ'.$addChars; - break; - case 3: - $chars='abcdefghijklmnopqrstuvwxyz'.$addChars; - break; - case 4: - $chars = "们以我到他会作时要动国产的一是工就年阶义发成部民可出能方进在了不和有大这主中人上为来分生对于学下级地个用同行面说种过命度革而多子后自社加小机也经力线本电高量长党得实家定深法表着水理化争现所二起政三好十战无农使性前等反体合斗路图把结第里正新开论之物从当两些还天资事队批点育重其思与间内去因件日利相由压员气业代全组数果期导平各基或月毛然如应形想制心样干都向变关问比展那它最及外没看治提五解系林者米群头意只明四道马认次文通但条较克又公孔领军流入接席位情运器并飞原油放立题质指建区验活众很教决特此常石强极土少已根共直团统式转别造切九你取西持总料连任志观调七么山程百报更见必真保热委手改管处己将修支识病象几先老光专什六型具示复安带每东增则完风回南广劳轮科北打积车计给节做务被整联步类集号列温装即毫知轴研单色坚据速防史拉世设达尔场织历花受求传口断况采精金界品判参层止边清至万确究书术状厂须离再目海交权且儿青才证低越际八试规斯近注办布门铁需走议县兵固除般引齿千胜细影济白格效置推空配刀叶率述今选养德话查差半敌始片施响收华觉备名红续均药标记难存测士身紧液派准斤角降维板许破述技消底床田势端感往神便贺村构照容非搞亚磨族火段算适讲按值美态黄易彪服早班麦削信排台声该击素张密害侯草何树肥继右属市严径螺检左页抗苏显苦英快称坏移约巴材省黑武培著河帝仅针怎植京助升王眼她抓含苗副杂普谈围食射源例致酸旧却充足短划剂宣环落首尺波承粉践府鱼随考刻靠够满夫失包住促枝局菌杆周护岩师举曲春元超负砂封换太模贫减阳扬江析亩木言球朝医校古呢稻宋听唯输滑站另卫字鼓刚写刘微略范供阿块某功套友限项余倒卷创律雨让骨远帮初皮播优占死毒圈伟季训控激找叫云互跟裂粮粒母练塞钢顶策双留误础吸阻故寸盾晚丝女散焊功株亲院冷彻弹错散商视艺灭版烈零室轻血倍缺厘泵察绝富城冲喷壤简否柱李望盘磁雄似困巩益洲脱投送奴侧润盖挥距触星松送获兴独官混纪依未突架宽冬章湿偏纹吃执阀矿寨责熟稳夺硬价努翻奇甲预职评读背协损棉侵灰虽矛厚罗泥辟告卵箱掌氧恩爱停曾溶营终纲孟钱待尽俄缩沙退陈讨奋械载胞幼哪剥迫旋征槽倒握担仍呀鲜吧卡粗介钻逐弱脚怕盐末阴丰雾冠丙街莱贝辐肠付吉渗瑞惊顿挤秒悬姆烂森糖圣凹陶词迟蚕亿矩康遵牧遭幅园腔订香肉弟屋敏恢忘编印蜂急拿扩伤飞露核缘游振操央伍域甚迅辉异序免纸夜乡久隶缸夹念兰映沟乙吗儒杀汽磷艰晶插埃燃欢铁补咱芽永瓦倾阵碳演威附牙芽永瓦斜灌欧献顺猪洋腐请透司危括脉宜笑若尾束壮暴企菜穗楚汉愈绿拖牛份染既秋遍锻玉夏疗尖殖井费州访吹荣铜沿替滚客召旱悟刺脑措贯藏敢令隙炉壳硫煤迎铸粘探临薄旬善福纵择礼愿伏残雷延烟句纯渐耕跑泽慢栽鲁赤繁境潮横掉锥希池败船假亮谓托伙哲怀割摆贡呈劲财仪沉炼麻罪祖息车穿货销齐鼠抽画饲龙库守筑房歌寒喜哥洗蚀废纳腹乎录镜妇恶脂庄擦险赞钟摇典柄辩竹谷卖乱虚桥奥伯赶垂途额壁网截野遗静谋弄挂课镇妄盛耐援扎虑键归符庆聚绕摩忙舞遇索顾胶羊湖钉仁音迹碎伸灯避泛亡答勇频皇柳哈揭甘诺概宪浓岛袭谁洪谢炮浇斑讯懂灵蛋闭孩释乳巨徒私银伊景坦累匀霉杜乐勒隔弯绩招绍胡呼痛峰零柴簧午跳居尚丁秦稍追梁折耗碱殊岗挖氏刃剧堆赫荷胸衡勤膜篇登驻案刊秧缓凸役剪川雪链渔啦脸户洛孢勃盟买杨宗焦赛旗滤硅炭股坐蒸凝竟陷枪黎救冒暗洞犯筒您宋弧爆谬涂味津臂障褐陆啊健尊豆拔莫抵桑坡缝警挑污冰柬嘴啥饭塑寄赵喊垫丹渡耳刨虎笔稀昆浪萨茶滴浅拥穴覆伦娘吨浸袖珠雌妈紫戏塔锤震岁貌洁剖牢锋疑霸闪埔猛诉刷狠忽灾闹乔唐漏闻沈熔氯荒茎男凡抢像浆旁玻亦忠唱蒙予纷捕锁尤乘乌智淡允叛畜俘摸锈扫毕璃宝芯爷鉴秘净蒋钙肩腾枯抛轨堂拌爸循诱祝励肯酒绳穷塘燥泡袋朗喂铝软渠颗惯贸粪综墙趋彼届墨碍启逆卸航衣孙龄岭骗休借".$addChars; - break; - default : - // 默认去掉了容易混淆的字符oOLl和数字01,要添加请使用addChars参数 - $chars='ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789'.$addChars; - break; - } - if($len>10 ) {//位数过长重复字符串一定次数 - $chars= $type==1? str_repeat($chars,$len) : str_repeat($chars,5); - } - if($type!=4) { - $chars = str_shuffle($chars); - $str = substr($chars,0,$len); - }else{ - // 中文随机字 - for($i=0;$i<$len;$i++){ - $str.= msubstr($chars, floor(mt_rand(0,mb_strlen($chars,'utf-8')-1)),1); - } - } - return $str; +function randString($len = 6, $type = '', $addChars = '') { + $str = ''; + switch ($type) { + case 0: + $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' . $addChars; + break; + case 1: + $chars = str_repeat('0123456789', 3); + break; + case 2: + $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' . $addChars; + break; + case 3: + $chars = 'abcdefghijklmnopqrstuvwxyz' . $addChars; + break; + case 4: + $chars = "们以我到他会作时要动国产的一是工就年阶义发成部民可出能方进在了不和有大这主中人上为来分生对于学下级地个用同行面说种过命度革而多子后自社加小机也经力线本电高量长党得实家定深法表着水理化争现所二起政三好十战无农使性前等反体合斗路图把结第里正新开论之物从当两些还天资事队批点育重其思与间内去因件日利相由压员气业代全组数果期导平各基或月毛然如应形想制心样干都向变关问比展那它最及外没看治提五解系林者米群头意只明四道马认次文通但条较克又公孔领军流入接席位情运器并飞原油放立题质指建区验活众很教决特此常石强极土少已根共直团统式转别造切九你取西持总料连任志观调七么山程百报更见必真保热委手改管处己将修支识病象几先老光专什六型具示复安带每东增则完风回南广劳轮科北打积车计给节做务被整联步类集号列温装即毫知轴研单色坚据速防史拉世设达尔场织历花受求传口断况采精金界品判参层止边清至万确究书术状厂须离再目海交权且儿青才证低越际八试规斯近注办布门铁需走议县兵固除般引齿千胜细影济白格效置推空配刀叶率述今选养德话查差半敌始片施响收华觉备名红续均药标记难存测士身紧液派准斤角降维板许破述技消底床田势端感往神便贺村构照容非搞亚磨族火段算适讲按值美态黄易彪服早班麦削信排台声该击素张密害侯草何树肥继右属市严径螺检左页抗苏显苦英快称坏移约巴材省黑武培著河帝仅针怎植京助升王眼她抓含苗副杂普谈围食射源例致酸旧却充足短划剂宣环落首尺波承粉践府鱼随考刻靠够满夫失包住促枝局菌杆周护岩师举曲春元超负砂封换太模贫减阳扬江析亩木言球朝医校古呢稻宋听唯输滑站另卫字鼓刚写刘微略范供阿块某功套友限项余倒卷创律雨让骨远帮初皮播优占死毒圈伟季训控激找叫云互跟裂粮粒母练塞钢顶策双留误础吸阻故寸盾晚丝女散焊功株亲院冷彻弹错散商视艺灭版烈零室轻血倍缺厘泵察绝富城冲喷壤简否柱李望盘磁雄似困巩益洲脱投送奴侧润盖挥距触星松送获兴独官混纪依未突架宽冬章湿偏纹吃执阀矿寨责熟稳夺硬价努翻奇甲预职评读背协损棉侵灰虽矛厚罗泥辟告卵箱掌氧恩爱停曾溶营终纲孟钱待尽俄缩沙退陈讨奋械载胞幼哪剥迫旋征槽倒握担仍呀鲜吧卡粗介钻逐弱脚怕盐末阴丰雾冠丙街莱贝辐肠付吉渗瑞惊顿挤秒悬姆烂森糖圣凹陶词迟蚕亿矩康遵牧遭幅园腔订香肉弟屋敏恢忘编印蜂急拿扩伤飞露核缘游振操央伍域甚迅辉异序免纸夜乡久隶缸夹念兰映沟乙吗儒杀汽磷艰晶插埃燃欢铁补咱芽永瓦倾阵碳演威附牙芽永瓦斜灌欧献顺猪洋腐请透司危括脉宜笑若尾束壮暴企菜穗楚汉愈绿拖牛份染既秋遍锻玉夏疗尖殖井费州访吹荣铜沿替滚客召旱悟刺脑措贯藏敢令隙炉壳硫煤迎铸粘探临薄旬善福纵择礼愿伏残雷延烟句纯渐耕跑泽慢栽鲁赤繁境潮横掉锥希池败船假亮谓托伙哲怀割摆贡呈劲财仪沉炼麻罪祖息车穿货销齐鼠抽画饲龙库守筑房歌寒喜哥洗蚀废纳腹乎录镜妇恶脂庄擦险赞钟摇典柄辩竹谷卖乱虚桥奥伯赶垂途额壁网截野遗静谋弄挂课镇妄盛耐援扎虑键归符庆聚绕摩忙舞遇索顾胶羊湖钉仁音迹碎伸灯避泛亡答勇频皇柳哈揭甘诺概宪浓岛袭谁洪谢炮浇斑讯懂灵蛋闭孩释乳巨徒私银伊景坦累匀霉杜乐勒隔弯绩招绍胡呼痛峰零柴簧午跳居尚丁秦稍追梁折耗碱殊岗挖氏刃剧堆赫荷胸衡勤膜篇登驻案刊秧缓凸役剪川雪链渔啦脸户洛孢勃盟买杨宗焦赛旗滤硅炭股坐蒸凝竟陷枪黎救冒暗洞犯筒您宋弧爆谬涂味津臂障褐陆啊健尊豆拔莫抵桑坡缝警挑污冰柬嘴啥饭塑寄赵喊垫丹渡耳刨虎笔稀昆浪萨茶滴浅拥穴覆伦娘吨浸袖珠雌妈紫戏塔锤震岁貌洁剖牢锋疑霸闪埔猛诉刷狠忽灾闹乔唐漏闻沈熔氯荒茎男凡抢像浆旁玻亦忠唱蒙予纷捕锁尤乘乌智淡允叛畜俘摸锈扫毕璃宝芯爷鉴秘净蒋钙肩腾枯抛轨堂拌爸循诱祝励肯酒绳穷塘燥泡袋朗喂铝软渠颗惯贸粪综墙趋彼届墨碍启逆卸航衣孙龄岭骗休借" . $addChars; + break; + default: + // 默认去掉了容易混淆的字符oOLl和数字01,要添加请使用addChars参数 + $chars = 'ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789' . $addChars; + break; + } + if ($len > 10) { + //位数过长重复字符串一定次数 + $chars = $type == 1 ? str_repeat($chars, $len) : str_repeat($chars, 5); + } + if ($type != 4) { + $chars = str_shuffle($chars); + $str = substr($chars, 0, $len); + } else { + // 中文随机字 + for ($i = 0; $i < $len; $i++) { + $str .= msubstr($chars, floor(mt_rand(0, mb_strlen($chars, 'utf-8') - 1)), 1); + } + } + return $str; } /** @@ -124,27 +125,27 @@ function rand_string($len=6,$type='',$addChars='') { * @param string $suffix 截断显示字符 * @return string */ -function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true) { - if(function_exists("mb_substr")){ - $slice = mb_substr($str, $start, $length, $charset); - }elseif(function_exists('iconv_substr')) { - $slice = iconv_substr($str,$start,$length,$charset); - if(false === $slice) { - $slice = ''; - } - }else{ - $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/"; - $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/"; - $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/"; - $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/"; - preg_match_all($re[$charset], $str, $match); - $slice = join("",array_slice($match[0], $start, $length)); - } - if (strlen($slice) == strlen($str)) { - return $slice; - }else{ - return $suffix ? $slice.'...' : $slice; - } +function msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = true) { + if (function_exists("mb_substr")) { + $slice = mb_substr($str, $start, $length, $charset); + } elseif (function_exists('iconv_substr')) { + $slice = iconv_substr($str, $start, $length, $charset); + if (false === $slice) { + $slice = ''; + } + } else { + $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/"; + $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/"; + $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/"; + $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/"; + preg_match_all($re[$charset], $str, $match); + $slice = join("", array_slice($match[0], $start, $length)); + } + if (strlen($slice) == strlen($str)) { + return $slice; + } else { + return $suffix ? $slice . '...' : $slice; + } } /** @@ -153,8 +154,8 @@ function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true) { * @param mixed $params 传入参数 * @return void */ -function hook($hook,$params=array()){ - \think\Hook::listen($hook,$params); +function hook($hook, $params = array()) { + \think\Hook::listen($hook, $params); } /** @@ -163,31 +164,31 @@ function hook($hook,$params=array()){ * @param mixed $params 传入参数 * @return html */ -function ad($name, $param = array()){ - return widget('common/Ad/run',array('name'=>$name)); +function ad($name, $param = array()) { + return widget('common/Ad/run', array('name' => $name)); } /** * 获取插件类的类名 * @param strng $name 插件名 */ -function get_addon_class($name){ - $class = "\\addons\\".strtolower($name)."\\{$name}"; - return $class; +function getAddonClass($name) { + $class = "\\addons\\" . strtolower($name) . "\\{$name}"; + return $class; } /** * 获取插件类的配置文件数组 * @param string $name 插件名 */ -function get_addon_config($name){ - $class = get_addon_class($name); - if(class_exists($class)) { - $addon = new $class(); - return $addon->getConfig(); - }else { - return array(); - } +function getAddonConfig($name) { + $class = getAddonClass($name); + if (class_exists($class)) { + $addon = new $class(); + return $addon->getConfig(); + } else { + return array(); + } } /** @@ -196,28 +197,28 @@ function get_addon_config($name){ * @param array $param 参数 * @author 麦当苗儿 */ -function addons_url($url, $param = array()){ - $url = parse_url($url); - $case = config('URL_CASE_INSENSITIVE'); - $addons = $case ? parse_name($url['scheme']) : $url['scheme']; - $controller = $case ? parse_name($url['host']) : $url['host']; - $action = trim($case ? strtolower($url['path']) : $url['path'], '/'); +function addonsUrl($url, $param = array()) { + $url = parse_url($url); + $case = config('URL_CASE_INSENSITIVE'); + $addons = $case ? parseName($url['scheme']) : $url['scheme']; + $controller = $case ? parseName($url['host']) : $url['host']; + $action = trim($case ? strtolower($url['path']) : $url['path'], '/'); - /* 解析URL带的参数 */ - if(isset($url['query'])){ - parse_str($url['query'], $query); - $param = array_merge($query, $param); - } + /* 解析URL带的参数 */ + if (isset($url['query'])) { + parse_str($url['query'], $query); + $param = array_merge($query, $param); + } - /* 基础参数 */ - $params = array( - 'mc' => $addons, - 'op' => $controller, - 'ac' => $action, - ); - $params = array_merge($params, $param); //添加额外参数 + /* 基础参数 */ + $params = array( + 'mc' => $addons, + 'op' => $controller, + 'ac' => $action, + ); + $params = array_merge($params, $param); //添加额外参数 - return \think\Url::build('index/addons/execute', $params); + return \think\Url::build('index/addons/execute', $params); } /** @@ -226,19 +227,18 @@ function addons_url($url, $param = array()){ * @return string 解析或的url * @author 麦当苗儿 */ -function get_nav_url($url){ - switch ($url) { - case 'http://' === substr($url, 0, 7): - case '#' === substr($url, 0, 1): - break; - default: - $url = \think\Url::build($url); - break; - } - return $url; +function getNavUrl($url) { + switch ($url) { + case 'http://' === substr($url, 0, 7): + case '#' === substr($url, 0, 1): + break; + default: + $url = \think\Url::build($url); + break; + } + return $url; } - /** * 获取文档封面图片 * @param int $cover_id @@ -246,19 +246,19 @@ function get_nav_url($url){ * @return 完整的数据 或者 指定的$field字段值 * @author huajie */ -function get_cover($cover_id, $field = null){ - if(empty($cover_id)){ - return BASE_PATH.'/public/images/default.png'; - } - $picture = db('Picture')->where(array('status'=>1,'id'=>$cover_id))->find(); - if($field == 'path'){ - if(!empty($picture['url'])){ - $picture['path'] = $picture['url'] ? BASE_PATH . $picture['url'] : BASE_PATH . '/public/images/default.png'; - }else{ - $picture['path'] = $picture['path'] ? BASE_PATH . $picture['path'] : BASE_PATH . '/public/images/default.png'; - } - } - return empty($field) ? $picture : $picture[$field]; +function getCover($cover_id, $field = null) { + if (empty($cover_id)) { + return BASE_PATH . '/public/images/default.png'; + } + $picture = db('Picture')->where(array('status' => 1, 'id' => $cover_id))->find(); + if ($field == 'path') { + if (!empty($picture['url'])) { + $picture['path'] = $picture['url'] ? BASE_PATH . $picture['url'] : BASE_PATH . '/public/images/default.png'; + } else { + $picture['path'] = $picture['path'] ? BASE_PATH . $picture['path'] : BASE_PATH . '/public/images/default.png'; + } + } + return empty($field) ? $picture : $picture[$field]; } /** @@ -267,15 +267,15 @@ function get_cover($cover_id, $field = null){ * @return 返回图片列表 * @author molong */ -function get_cover_list($covers){ - if ($covers == '') { - return false; - } - $cover_list = explode(',', $covers); - foreach ($cover_list as $item) { - $list[] = get_cover($item, 'path'); - } - return $list; +function getCoverList($covers) { + if ($covers == '') { + return false; + } + $cover_list = explode(',', $covers); + foreach ($cover_list as $item) { + $list[] = getCover($item, 'path'); + } + return $list; } /** @@ -285,17 +285,17 @@ function get_cover_list($covers){ * @param integer $type 转换类型 * @return string */ -function parse_name($name, $type=0) { - if ($type) { - return ucfirst(preg_replace_callback('/_([a-zA-Z])/', function($match){return strtoupper($match[1]);}, $name)); - } else { - return strtolower(trim(preg_replace("/[A-Z]/", "_\\0", $name), "_")); - } +function parseName($name, $type = 0) { + if ($type) { + return ucfirst(preg_replace_callback('/_([a-zA-Z])/', function ($match) {return strtoupper($match[1]);}, $name)); + } else { + return strtolower(trim(preg_replace("/[A-Z]/", "_\\0", $name), "_")); + } } // 不区分大小写的in_array实现 -function in_array_case($value,$array){ - return in_array(strtolower($value),array_map('strtolower',$array)); +function inArrayCase($value, $array) { + return in_array(strtolower($value), array_map('strtolower', $array)); } /** @@ -304,15 +304,15 @@ function in_array_case($value,$array){ * @return string 签名 * @author 麦当苗儿 */ -function data_auth_sign($data) { - //数据类型检测 - if(!is_array($data)){ - $data = (array)$data; - } - ksort($data); //排序 - $code = http_build_query($data); //url编码并生成query字符串 - $sign = sha1($code); //生成签名 - return $sign; +function dataAuthSign($data) { + //数据类型检测 + if (!is_array($data)) { + $data = (array) $data; + } + ksort($data); //排序 + $code = http_build_query($data); //url编码并生成query字符串 + $sign = sha1($code); //生成签名 + return $sign; } /** @@ -320,13 +320,13 @@ function data_auth_sign($data) { * @return integer 0-未登录,大于0-当前登录用户ID * @author 麦当苗儿 */ -function is_login(){ - $user = session('user_auth'); - if (empty($user)) { - return 0; - } else { - return session('user_auth_sign') == data_auth_sign($user) ? $user['uid'] : 0; - } +function isLogin() { + $user = session('user_auth'); + if (empty($user)) { + return 0; + } else { + return session('user_auth_sign') == dataAuthSign($user) ? $user['uid'] : 0; + } } /** @@ -334,39 +334,45 @@ function is_login(){ * @return boolean true-管理员,false-非管理员 * @author 麦当苗儿 */ -function is_administrator($uid = null){ - $uid = is_null($uid) ? is_login() : $uid; - return $uid && (intval($uid) === config('user_administrator')); +function isAdministrator($uid = null) { + $uid = is_null($uid) ? isLogin() : $uid; + return $uid && (intval($uid) === config('user_administrator')); } /** * 获取客户端IP地址 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字 - * @param boolean $adv 是否进行高级模式获取(有可能被伪装) + * @param boolean $adv 是否进行高级模式获取(有可能被伪装) * @return mixed */ -function get_client_ip($type = 0,$adv=false) { - $type = $type ? 1 : 0; - static $ip = NULL; - if ($ip !== NULL) return $ip[$type]; - if($adv){ - if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { - $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); - $pos = array_search('unknown',$arr); - if(false !== $pos) unset($arr[$pos]); - $ip = trim($arr[0]); - }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) { - $ip = $_SERVER['HTTP_CLIENT_IP']; - }elseif (isset($_SERVER['REMOTE_ADDR'])) { - $ip = $_SERVER['REMOTE_ADDR']; - } - }elseif (isset($_SERVER['REMOTE_ADDR'])) { - $ip = $_SERVER['REMOTE_ADDR']; - } - // IP地址合法验证 - $long = sprintf("%u",ip2long($ip)); - $ip = $long ? array($ip, $long) : array('0.0.0.0', 0); - return $ip[$type]; +function getClientIp($type = 0, $adv = false) { + $type = $type ? 1 : 0; + static $ip = NULL; + if ($ip !== NULL) { + return $ip[$type]; + } + + if ($adv) { + if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { + $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); + $pos = array_search('unknown', $arr); + if (false !== $pos) { + unset($arr[$pos]); + } + + $ip = trim($arr[0]); + } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) { + $ip = $_SERVER['HTTP_CLIENT_IP']; + } elseif (isset($_SERVER['REMOTE_ADDR'])) { + $ip = $_SERVER['REMOTE_ADDR']; + } + } elseif (isset($_SERVER['REMOTE_ADDR'])) { + $ip = $_SERVER['REMOTE_ADDR']; + } + // IP地址合法验证 + $long = sprintf("%u", ip2long($ip)); + $ip = $long ? array($ip, $long) : array('0.0.0.0', 0); + return $ip[$type]; } /** @@ -375,9 +381,9 @@ function get_client_ip($type = 0,$adv=false) { * @return string 完整的时间显示 * @author huajie */ -function time_format($time = NULL,$format='Y-m-d H:i'){ - $time = $time === NULL ? time() : intval($time); - return date($format, $time); +function timeFormat($time = NULL, $format = 'Y-m-d H:i') { + $time = $time === NULL ? time() : intval($time); + return date($format, $time); } /** @@ -385,85 +391,92 @@ function time_format($time = NULL,$format='Y-m-d H:i'){ * @param integer $uid 用户ID * @return string 用户名 */ -function get_username($uid = 0){ - static $list; - if(!($uid && is_numeric($uid))){ //获取当前登录用户名 - return session('user_auth.username'); - } - $name = db('member')->where(array('uid'=>$uid))->value('username'); - return $name; +function getUsername($uid = 0) { + static $list; + if (!($uid && is_numeric($uid))) { + //获取当前登录用户名 + return session('user_auth.username'); + } + $name = db('member')->where(array('uid' => $uid))->value('username'); + return $name; } - /** * 根据用户ID获取用户昵称 * @param integer $uid 用户ID * @return string 用户昵称 */ -function get_nickname($uid = 0){ - static $list; - if(!($uid && is_numeric($uid))){ //获取当前登录用户名 - return session('user_auth.username'); - } +function getNickname($uid = 0) { + static $list; + if (!($uid && is_numeric($uid))) { + //获取当前登录用户名 + return session('user_auth.username'); + } - /* 获取缓存数据 */ - if(empty($list)){ - $list = cache('sys_user_nickname_list'); - } + /* 获取缓存数据 */ + if (empty($list)) { + $list = cache('sys_user_nickname_list'); + } - /* 查找用户信息 */ - $key = "u{$uid}"; - if(isset($list[$key])){ //已缓存,直接使用 - $name = $list[$key]; - } else { //调用接口获取用户信息 - $info = db('Member')->field('nickname')->find($uid); - if($info !== false && $info['nickname'] ){ - $nickname = $info['nickname']; - $name = $list[$key] = $nickname; - /* 缓存用户 */ - $count = count($list); - $max = config('USER_MAX_CACHE'); - while ($count-- > $max) { - array_shift($list); - } - cache('sys_user_nickname_list', $list); - } else { - $name = ''; - } - } - return $name; + /* 查找用户信息 */ + $key = "u{$uid}"; + if (isset($list[$key])) { + //已缓存,直接使用 + $name = $list[$key]; + } else { + //调用接口获取用户信息 + $info = db('Member')->field('nickname')->find($uid); + if ($info !== false && $info['nickname']) { + $nickname = $info['nickname']; + $name = $list[$key] = $nickname; + /* 缓存用户 */ + $count = count($list); + $max = config('USER_MAX_CACHE'); + while ($count-- > $max) { + array_shift($list); + } + cache('sys_user_nickname_list', $list); + } else { + $name = ''; + } + } + return $name; } /** -* 对查询结果集进行排序 -* @access public -* @param array $list 查询结果 -* @param string $field 排序的字段名 -* @param array $sortby 排序类型 -* asc正向排序 desc逆向排序 nat自然排序 -* @return array -*/ -function list_sort_by($list,$field, $sortby='asc') { - if(is_array($list)){ - $refer = $resultSet = array(); - foreach ($list as $i => $data) - $refer[$i] = &$data[$field]; - switch ($sortby) { - case 'asc': // 正向排序 - asort($refer); - break; - case 'desc':// 逆向排序 - arsort($refer); - break; - case 'nat': // 自然排序 - natcasesort($refer); - break; - } - foreach ( $refer as $key=> $val) - $resultSet[] = &$list[$key]; - return $resultSet; - } - return false; + * 对查询结果集进行排序 + * @access public + * @param array $list 查询结果 + * @param string $field 排序的字段名 + * @param array $sortby 排序类型 + * asc正向排序 desc逆向排序 nat自然排序 + * @return array + */ +function listSortBy($list, $field, $sortby = 'asc') { + if (is_array($list)) { + $refer = $resultSet = array(); + foreach ($list as $i => $data) { + $refer[$i] = &$data[$field]; + } + + switch ($sortby) { + case 'asc': // 正向排序 + asort($refer); + break; + case 'desc': // 逆向排序 + arsort($refer); + break; + case 'nat': // 自然排序 + natcasesort($refer); + break; + } + foreach ($refer as $key => $val) { + $resultSet[] = &$list[$key]; + } + + return $resultSet; + } + return false; } /** @@ -474,30 +487,30 @@ function list_sort_by($list,$field, $sortby='asc') { * @return array * @author 麦当苗儿 */ -function list_to_tree($list, $pk='id', $pid = 'pid', $child = '_child', $root = 0) { - // 创建Tree - $tree = array(); - if(is_array($list) && !is_object($list)) { - // 创建基于主键的数组引用 - $refer = array(); - foreach ($list as $key => $data) { - $refer[$data[$pk]] =& $list[$key]; - } - foreach ($list as $key => $data) { - // 判断是否存在parent - $parentId = $data[$pid]; - if ($root == $parentId) { - $tree[] =& $list[$key]; - }else{ - if (isset($refer[$parentId])) { - $parent =& $refer[$parentId]; - $parent['childs'][] = $data['id']; - $parent[$child][] =& $list[$key]; - } - } - } - } - return $tree; +function listToTree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0) { + // 创建Tree + $tree = array(); + if (is_array($list) && !is_object($list)) { + // 创建基于主键的数组引用 + $refer = array(); + foreach ($list as $key => $data) { + $refer[$data[$pk]] = &$list[$key]; + } + foreach ($list as $key => $data) { + // 判断是否存在parent + $parentId = $data[$pid]; + if ($root == $parentId) { + $tree[] = &$list[$key]; + } else { + if (isset($refer[$parentId])) { + $parent = &$refer[$parentId]; + $parent['childs'][] = $data['id']; + $parent[$child][] = &$list[$key]; + } + } + } + } + return $tree; } /** @@ -509,83 +522,83 @@ function list_to_tree($list, $pk='id', $pid = 'pid', $child = '_child', $root = * @return array 返回排过序的列表数组 * @author yangweijie */ -function tree_to_list($tree, $child = '_child', $order='id', &$list = array()){ - if(is_array($tree)) { - foreach ($tree as $key => $value) { - $reffer = $value; - if(isset($reffer[$child])){ - unset($reffer[$child]); - tree_to_list($value[$child], $child, $order, $list); - } - $list[] = $reffer; - } - $list = list_sort_by($list, $order, $sortby='asc'); - } - return $list; +function treeToList($tree, $child = '_child', $order = 'id', &$list = array()) { + if (is_array($tree)) { + foreach ($tree as $key => $value) { + $reffer = $value; + if (isset($reffer[$child])) { + unset($reffer[$child]); + treeToList($value[$child], $child, $order, $list); + } + $list[] = $reffer; + } + $list = listSortBy($list, $order, $sortby = 'asc'); + } + return $list; } - // 分析枚举类型字段值 格式 a:名称1,b:名称2 - // 暂时和 parse_config_attr功能相同 - // 但请不要互相使用,后期会调整 -function parse_field_attr($string) { - if(0 === strpos($string,':')){ - // 采用函数定义 - return eval('return '.substr($string,1).';'); - }elseif(0 === strpos($string,'[')){ - // 支持读取配置参数(必须是数组类型) - return \think\Config::get(substr($string,1,-1)); - } - - $array = preg_split('/[,;\r\n]+/', trim($string, ",;\r\n")); - if(strpos($string,':')){ - $value = array(); - foreach ($array as $val) { - list($k, $v) = explode(':', $val); - $value[$k] = $v; - } - }else{ - $value = $array; - } - return $value; +// 分析枚举类型字段值 格式 a:名称1,b:名称2 +// 暂时和 parse_config_attr功能相同 +// 但请不要互相使用,后期会调整 +function parseFieldAttr($string) { + if (0 === strpos($string, ':')) { + // 采用函数定义 + return eval('return ' . substr($string, 1) . ';'); + } elseif (0 === strpos($string, '[')) { + // 支持读取配置参数(必须是数组类型) + return \think\Config::get(substr($string, 1, -1)); + } + + $array = preg_split('/[,;\r\n]+/', trim($string, ",;\r\n")); + if (strpos($string, ':')) { + $value = array(); + foreach ($array as $val) { + list($k, $v) = explode(':', $val); + $value[$k] = $v; + } + } else { + $value = $array; + } + return $value; } -function parse_field_bind($table,$selected = '',$model = 0) { - if ($table) { - $select = db($table); - $res = $select->select(); - foreach ($res as $key => $value) { - if ($model && $value['model']) { - $models = explode(',', $value['model']); - if (in_array($model, $models)) { - $list[] = $value; - } - }else{ - $list[] = $value; - } - } - if (!empty($list)) { - $tree = new \com\Tree(); - $list = $tree->toFormatTree($list); - } - }else{ - $list = array(); - } - return $list; +function parseFieldBind($table, $selected = '', $model = 0) { + if ($table) { + $select = db($table); + $res = $select->select(); + foreach ($res as $key => $value) { + if ($model && $value['model']) { + $models = explode(',', $value['model']); + if (in_array($model, $models)) { + $list[] = $value; + } + } else { + $list[] = $value; + } + } + if (!empty($list)) { + $tree = new \com\Tree(); + $list = $tree->toFormatTree($list); + } + } else { + $list = array(); + } + return $list; } - // 分析枚举类型配置值 格式 a:名称1,b:名称2 -function parse_config_attr($string) { - $array = preg_split('/[,;\r\n]+/', trim($string, ",;\r\n")); - if(strpos($string,':')){ - $value = array(); - foreach ($array as $val) { - list($k, $v) = explode(':', $val); - $value[$k] = $v; - } - }else{ - $value = $array; - } - return $value; +// 分析枚举类型配置值 格式 a:名称1,b:名称2 +function parseConfigAttr($string) { + $array = preg_split('/[,;\r\n]+/', trim($string, ",;\r\n")); + if (strpos($string, ':')) { + $value = array(); + foreach ($array as $val) { + list($k, $v) = explode(':', $val); + $value[$k] = $v; + } + } else { + $value = $array; + } + return $value; } /** @@ -597,64 +610,64 @@ function parse_config_attr($string) { * @return boolean * @author huajie */ -function action_log($action = null, $model = null, $record_id = null, $user_id = null){ +function actionLog($action = null, $model = null, $record_id = null, $user_id = null) { - //参数检查 - if(empty($action) || empty($model) || empty($record_id)){ - return '参数不能为空'; - } - if(empty($user_id)){ - $user_id = is_login(); - } + //参数检查 + if (empty($action) || empty($model) || empty($record_id)) { + return '参数不能为空'; + } + if (empty($user_id)) { + $user_id = isLogin(); + } - //查询行为,判断是否执行 - $action_info = db('Action')->getByName($action); - if($action_info['status'] != 1){ - return '该行为被禁用或删除'; - } + //查询行为,判断是否执行 + $action_info = db('Action')->getByName($action); + if ($action_info['status'] != 1) { + return '该行为被禁用或删除'; + } - //插入行为日志 - $data['action_id'] = $action_info['id']; - $data['user_id'] = $user_id; - $data['action_ip'] = ip2long(get_client_ip()); - $data['model'] = $model; - $data['record_id'] = $record_id; - $data['create_time'] = time(); + //插入行为日志 + $data['action_id'] = $action_info['id']; + $data['user_id'] = $user_id; + $data['action_ip'] = ip2long(getClientIp()); + $data['model'] = $model; + $data['record_id'] = $record_id; + $data['create_time'] = time(); - //解析日志规则,生成日志备注 - if(!empty($action_info['log'])){ - if(preg_match_all('/\[(\S+?)\]/', $action_info['log'], $match)){ - $log['user'] = $user_id; - $log['record'] = $record_id; - $log['model'] = $model; - $log['time'] = time(); - $log['data'] = array('user'=>$user_id,'model'=>$model,'record'=>$record_id,'time'=>time()); - foreach ($match[1] as $value){ - $param = explode('|', $value); - if(isset($param[1])){ - $replace[] = call_user_func($param[1],$log[$param[0]]); - }else{ - $replace[] = $log[$param[0]]; - } - } - $data['remark'] = str_replace($match[0], $replace, $action_info['log']); - }else{ - $data['remark'] = $action_info['log']; - } - }else{ - //未定义日志规则,记录操作url - $data['remark'] = '操作url:'.$_SERVER['REQUEST_URI']; - } + //解析日志规则,生成日志备注 + if (!empty($action_info['log'])) { + if (preg_match_all('/\[(\S+?)\]/', $action_info['log'], $match)) { + $log['user'] = $user_id; + $log['record'] = $record_id; + $log['model'] = $model; + $log['time'] = time(); + $log['data'] = array('user' => $user_id, 'model' => $model, 'record' => $record_id, 'time' => time()); + foreach ($match[1] as $value) { + $param = explode('|', $value); + if (isset($param[1])) { + $replace[] = call_user_func($param[1], $log[$param[0]]); + } else { + $replace[] = $log[$param[0]]; + } + } + $data['remark'] = str_replace($match[0], $replace, $action_info['log']); + } else { + $data['remark'] = $action_info['log']; + } + } else { + //未定义日志规则,记录操作url + $data['remark'] = '操作url:' . $_SERVER['REQUEST_URI']; + } - db('ActionLog')->insert($data); + db('ActionLog')->insert($data); - if(!empty($action_info['rule'])){ - //解析行为 - $rules = parse_action($action, $user_id); + if (!empty($action_info['rule'])) { + //解析行为 + $rules = parseAction($action, $user_id); - //执行行为 - $res = execute_action($rules, $action_info['id'], $user_id); - } + //执行行为 + $res = executeAction($rules, $action_info['id'], $user_id); + } } /** @@ -672,44 +685,44 @@ function action_log($action = null, $model = null, $record_id = null, $user_id = * @return boolean|array: false解析出错 , 成功返回规则数组 * @author huajie */ -function parse_action($action = null, $self){ - if(empty($action)){ - return false; - } +function parseAction($action = null, $self) { + if (empty($action)) { + return false; + } - //参数支持id或者name - if(is_numeric($action)){ - $map = array('id'=>$action); - }else{ - $map = array('name'=>$action); - } + //参数支持id或者name + if (is_numeric($action)) { + $map = array('id' => $action); + } else { + $map = array('name' => $action); + } - //查询行为信息 - $info = db('Action')->where($map)->find(); - if(!$info || $info['status'] != 1){ - return false; - } + //查询行为信息 + $info = db('Action')->where($map)->find(); + if (!$info || $info['status'] != 1) { + return false; + } - //解析规则:table:$table|field:$field|condition:$condition|rule:$rule[|cycle:$cycle|max:$max][;......] - $rules = $info['rule']; - $rules = str_replace('{$self}', $self, $rules); - $rules = explode(';', $rules); - $return = array(); - foreach ($rules as $key=>&$rule){ - $rule = explode('|', $rule); - foreach ($rule as $k=>$fields){ - $field = empty($fields) ? array() : explode(':', $fields); - if(!empty($field)){ - $return[$key][$field[0]] = $field[1]; - } - } - //cycle(检查周期)和max(周期内最大执行次数)必须同时存在,否则去掉这两个条件 - if(!array_key_exists('cycle', $return[$key]) || !array_key_exists('max', $return[$key])){ - unset($return[$key]['cycle'],$return[$key]['max']); - } - } + //解析规则:table:$table|field:$field|condition:$condition|rule:$rule[|cycle:$cycle|max:$max][;......] + $rules = $info['rule']; + $rules = str_replace('{$self}', $self, $rules); + $rules = explode(';', $rules); + $return = array(); + foreach ($rules as $key => &$rule) { + $rule = explode('|', $rule); + foreach ($rule as $k => $fields) { + $field = empty($fields) ? array() : explode(':', $fields); + if (!empty($field)) { + $return[$key][$field[0]] = $field[1]; + } + } + //cycle(检查周期)和max(周期内最大执行次数)必须同时存在,否则去掉这两个条件 + if (!array_key_exists('cycle', $return[$key]) || !array_key_exists('max', $return[$key])) { + unset($return[$key]['cycle'], $return[$key]['max']); + } + } - return $return; + return $return; } /** @@ -720,64 +733,68 @@ function parse_action($action = null, $self){ * @return boolean false 失败 , true 成功 * @author huajie */ -function execute_action($rules = false, $action_id = null, $user_id = null){ - if(!$rules || empty($action_id) || empty($user_id)){ - return false; - } +function executeAction($rules = false, $action_id = null, $user_id = null) { + if (!$rules || empty($action_id) || empty($user_id)) { + return false; + } - $return = true; - foreach ($rules as $rule){ + $return = true; + foreach ($rules as $rule) { - //检查执行周期 - $map = array('action_id'=>$action_id, 'user_id'=>$user_id); - $map['create_time'] = array('gt', NOW_TIME - intval($rule['cycle']) * 3600); - $exec_count = db('ActionLog')->where($map)->count(); - if($exec_count > $rule['max']){ - continue; - } + //检查执行周期 + $map = array('action_id' => $action_id, 'user_id' => $user_id); + $map['create_time'] = array('gt', NOW_TIME - intval($rule['cycle']) * 3600); + $exec_count = db('ActionLog')->where($map)->count(); + if ($exec_count > $rule['max']) { + continue; + } - //执行数据库操作 - $Model = db(ucfirst($rule['table'])); - $field = $rule['field']; - $res = $Model->where($rule['condition'])->setField($field, array('exp', $rule['rule'])); + //执行数据库操作 + $field = $rule['field']; + $res = db(ucfirst($rule['table']))->where($rule['condition'])->setField($field, array('exp', $rule['rule'])); - if(!$res){ - $return = false; - } - } - return $return; + if (!$res) { + $return = false; + } + } + return $return; } - function avatar($uid, $size = 'middle') { - $size = in_array($size, array('big', 'middle', 'small','real')) ? $size : 'middle'; - $dir = setavatardir($uid); - $file = BASE_PATH . '/uploads/avatar/'.$dir.'avatar_'.$size.'.png'; - if (!file_exists('.'.$file)) { - $file = BASE_PATH . '/public/images/default_avatar_'.$size.'.jpg'; - } - return $file; + $size = in_array($size, array('big', 'middle', 'small', 'real')) ? $size : 'middle'; + $dir = setavatardir($uid); + $file = BASE_PATH . '/uploads/avatar/' . $dir . 'avatar_' . $size . '.png'; + if (!file_exists('.' . $file)) { + $file = BASE_PATH . '/public/images/default_avatar_' . $size . '.jpg'; + } + return $file; } -function setavatardir($uid){ - $uid = abs(intval($uid)); - $uid = sprintf("%09d", $uid); - $dir1 = substr($uid, 0, 3); - $dir2 = substr($uid, 3, 2); - $dir3 = substr($uid, 5, 2); - $dir4 = substr($uid, 7, 2); - $dir = $dir1.'/'.$dir2.'/'.$dir3.'/'.$dir4.'/'; - if (!is_dir("./uploads/avatar/$dir")) { - mk_dir("./uploads/avatar/".$dir); - } - return $dir; +function setavatardir($uid) { + $uid = abs(intval($uid)); + $uid = sprintf("%09d", $uid); + $dir1 = substr($uid, 0, 3); + $dir2 = substr($uid, 3, 2); + $dir3 = substr($uid, 5, 2); + $dir4 = substr($uid, 7, 2); + $dir = $dir1 . '/' . $dir2 . '/' . $dir3 . '/' . $dir4 . '/'; + if (!is_dir("./uploads/avatar/$dir")) { + mkDir("./uploads/avatar/" . $dir); + } + return $dir; } -function mk_dir($dir, $mode = 0755){ - if (is_dir($dir) || @mkdir($dir,$mode,true)) return true; - if (!mk_dir(dirname($dir),$mode,true)) return false; - return @mkdir($dir,$mode,true); -} +function mkDir($dir, $mode = 0755) { + if (is_dir($dir) || @mkdir($dir, $mode, true)) { + return true; + } + + if (!mkDir(dirname($dir), $mode, true)) { + return false; + } + + return @mkdir($dir, $mode, true); +} /** * 字符串转换为数组,主要用于把分隔符调整到第二个参数 @@ -786,12 +803,12 @@ function mk_dir($dir, $mode = 0755){ * @return array * @author 麦当苗儿 */ -function str2arr($str = '', $glue = ','){ - if ($str) { - return explode($glue, $str); - }else{ - return array(); - } +function str2arr($str = '', $glue = ',') { + if ($str) { + return explode($glue, $str); + } else { + return array(); + } } /** @@ -801,12 +818,12 @@ function str2arr($str = '', $glue = ','){ * @return string * @author 麦当苗儿 */ -function arr2str($arr = array(), $glue = ','){ - if (empty($arr)) { - return ''; - }else{ - return implode($glue, $arr); - } +function arr2str($arr = array(), $glue = ',') { + if (empty($arr)) { + return ''; + } else { + return implode($glue, $arr); + } } /** @@ -816,238 +833,313 @@ function arr2str($arr = array(), $glue = ','){ * @return string 格式化后的带单位的大小 * @author 麦当苗儿 */ -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 formatBytes($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 get_grid_list($list_grids){ - $grids = preg_split('/[;\r\n]+/s', trim($list_grids)); - foreach ($grids as &$value) { - // 字段:标题:链接 - $val = explode(':', $value); - // 支持多个字段显示 - $field = explode(',', $val[0]); - $value = array('field' => $field, 'title' => $val[1]); - if(isset($val[2])){ - // 链接信息 - $value['href'] = $val[2]; - // 搜索链接信息中的字段信息 - preg_replace_callback('/\[([a-z_]+)\]/', function($match) use(&$fields){$fields[]=$match[1];}, $value['href']); - } - if(strpos($val[1],'|')){ - // 显示格式定义 - list($value['title'],$value['format']) = explode('|',$val[1]); - } - foreach($field as $val){ - $array = explode('|',$val); - $fields[] = $array[0]; - } - } - $data = array('grids'=>$grids,'fields'=>$fields); - return $data; +function getGridList($list_grids) { + $grids = preg_split('/[;\r\n]+/s', trim($list_grids)); + foreach ($grids as &$value) { + // 字段:标题:链接 + $val = explode(':', $value); + // 支持多个字段显示 + $field = explode(',', $val[0]); + $value = array('field' => $field, 'title' => $val[1]); + if (isset($val[2])) { + // 链接信息 + $value['href'] = $val[2]; + // 搜索链接信息中的字段信息 + preg_replace_callback('/\[([a-z_]+)\]/', function ($match) use (&$fields) {$fields[] = $match[1];}, $value['href']); + } + if (strpos($val[1], '|')) { + // 显示格式定义 + list($value['title'], $value['format']) = explode('|', $val[1]); + } + foreach ($field as $val) { + $array = explode('|', $val); + $fields[] = $array[0]; + } + } + $data = array('grids' => $grids, 'fields' => $fields); + return $data; } -// 获取属性类型信息 -function get_attribute_type($type = ''){ - // TODO 可以加入系统配置 - $type_array = config('config_type_list'); - static $type_list = array(); - foreach ($type_array as $key => $value) { - $type_list[$key] = explode(',',$value); - } - return $type ? $type_list[$type][0] : $type_list; +/** + * 获取字段类型 + */ +function getAttributeType($type = '') { + // TODO 可以加入系统配置 + $type_array = config('config_type_list'); + static $type_list = array(); + foreach ($type_array as $key => $value) { + $type_list[$key] = explode(',', $value); + } + return $type ? $type_list[$type][0] : $type_list; } - /** * 获取文档模型信息 * @param integer $id 模型ID * @param string $field 模型字段 * @return array */ -function get_document_model($id = null, $field = null){ - static $list; +function getDocumentModel($id = null, $field = null) { + static $list; - /* 非法分类ID */ - if(!(is_numeric($id) || is_null($id))){ - return ''; - } + /* 非法分类ID */ + if (!(is_numeric($id) || is_null($id))) { + return ''; + } - /* 读取缓存数据 */ - if(empty($list)){ - $list = cache('document_model_list'); - } + /* 读取缓存数据 */ + if (empty($list)) { + $list = cache('document_model_list'); + } - /* 获取模型名称 */ - if(empty($list)){ - $map = array('status' => 1,'is_bind_category'=>1); - $model = db('Model')->where($map)->field(true)->select(); - foreach ($model as $value) { - $list[$value['id']] = $value; - } - cache('document_model_list', $list); //更新缓存 - } + /* 获取模型名称 */ + if (empty($list)) { + $map = array('status' => 1, 'is_bind_category' => 1); + $model = db('Model')->where($map)->field(true)->select(); + foreach ($model as $value) { + $list[$value['id']] = $value; + } + cache('document_model_list', $list); //更新缓存 + } - /* 根据条件返回数据 */ - if(is_null($id)){ - return $list; - } elseif(is_null($field)){ - return $list[$id]; - } else { - return $list[$id][$field]; - } + /* 根据条件返回数据 */ + if (is_null($id)) { + return $list; + } elseif (is_null($field)) { + return $list[$id]; + } else { + return $list[$id][$field]; + } } -function get_content_status($status){ - $text = array( - '-1' => '删除', - '0' => '禁用', - '1' => '正常', - '2' => '待审核' - ); - return $text[$status]; +function getContentStatus($status) { + $text = array( + '-1' => '删除', + '0' => '禁用', + '1' => '正常', + '2' => '待审核', + ); + return $text[$status]; } - /** * 获取分类信息并缓存分类 * @param integer $id 分类ID * @param string $field 要获取的字段名 * @return string 分类信息 */ -function get_category($id, $field = null){ - /* 非法分类ID */ - if(empty($id) || !is_numeric($id)){ - return ''; - } +function getCategory($id, $field = null) { + /* 非法分类ID */ + if (empty($id) || !is_numeric($id)) { + return ''; + } - $list = db('Category')->find($id); - return is_null($field) ? $list : $list[$field]; + $list = db('Category')->find($id); + return is_null($field) ? $list : $list[$field]; } /* 根据ID获取分类标识 */ -function get_category_name($id){ - return get_category($id, 'title'); +function getCategoryName($id) { + return getCategory($id, 'title'); } /* 根据ID获取分类名称 */ -function get_category_title($id){ - return get_category($id, 'title'); +function getCategoryTitle($id) { + return getCategory($id, 'title'); } //分类分组 -function get_category_list_tree($model){ - $list = cache('sys_category_list'); +function getCategoryListTree($model) { + $list = cache('sys_category_list'); - /* 读取缓存数据 */ - if(empty($list)){ - $list = D('category')->select(); - cache('sys_category_list',$list); - } - foreach ($list as $key => $value) { - if ($model) { - $models = explode(',', $value['model']); - if (in_array($model, $models)) { - $res[] = $value; - } - }else{ - $res[] = $value; - } - } - $res = list_unique($res); - $tree = list_to_tree($res); - if ($limit) { - $tree = array_slice($tree,0,$limit); - } - return $tree; + /* 读取缓存数据 */ + if (empty($list)) { + $list = D('category')->select(); + cache('sys_category_list', $list); + } + foreach ($list as $key => $value) { + if ($model) { + $models = explode(',', $value['model']); + if (in_array($model, $models)) { + $res[] = $value; + } + } else { + $res[] = $value; + } + } + $res = list_unique($res); + $tree = listToTree($res); + if ($limit) { + $tree = array_slice($tree, 0, $limit); + } + return $tree; } //获取栏目子ID -function get_category_child($id){ - $list = cache('sys_category_list'); +function getCategoryChild($id) { + $list = cache('sys_category_list'); - /* 读取缓存数据 */ - if(empty($list)){ - $list = db('category')->select(); - cache('sys_category_list',$list); - } - $ids[] = $id; - foreach ($list as $key => $value) { - if ($value['pid'] == $id) { - $ids[] = $value['id']; - $ids = array_merge($ids,get_category_child($value['id'])); - } - } - return array_unique($ids); + /* 读取缓存数据 */ + if (empty($list)) { + $list = db('category')->select(); + cache('sys_category_list', $list); + } + $ids[] = $id; + foreach ($list as $key => $value) { + if ($value['pid'] == $id) { + $ids[] = $value['id']; + $ids = array_merge($ids, getCategoryChild($value['id'])); + } + } + return array_unique($ids); } -function send_email($to, $subject, $message){ - $config = array( - 'protocol' => 'smtp', - 'smtp_host' => \think\Config::get('mail_host'), - 'smtp_user' => \think\Config::get('mail_username'), - 'smtp_pass' => \think\Config::get('mail_password') - ); - $email = new \com\Email($config); - $email->from(\think\Config::get('mail_fromname'), \think\Config::get('web_site_title')); - $email->to($to); +function sendEmail($to, $subject, $message) { + $config = array( + 'protocol' => 'smtp', + 'smtp_host' => \think\Config::get('mail_host'), + 'smtp_user' => \think\Config::get('mail_username'), + 'smtp_pass' => \think\Config::get('mail_password'), + ); + $email = new \com\Email($config); + $email->from(\think\Config::get('mail_fromname'), \think\Config::get('web_site_title')); + $email->to($to); - $email->subject($subject); - $email->message($message); + $email->subject($subject); + $email->message($message); - return $email->send(); + return $email->send(); } //php获取中文字符拼音首字母 -function getFirstCharter($s0){ - $fchar = ord($s0{0}); - if($fchar >= ord("A") and $fchar <= ord("z") )return strtoupper($s0{0}); - $s1 = \iconv("UTF-8","gb2312", $s0); - $s2 = \iconv("gb2312","UTF-8", $s1); - if($s2 == $s0){$s = $s1;}else{$s = $s0;} - $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; +function getFirstCharter($s0) { + $fchar = ord($s0{0}); + if ($fchar >= ord("A") and $fchar <= ord("z")) { + return strtoupper($s0{0}); + } + + $s1 = iconv("UTF-8", "gb2312", $s0); + $s2 = iconv("gb2312", "UTF-8", $s1); + if ($s2 == $s0) {$s = $s1;} else { $s = $s0;} + $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; } -function PyFirst($zh){ - $ret = ""; - $s1 = \iconv("UTF-8","gb2312", $zh); - $s2 = \iconv("gb2312","UTF-8", $s1); - if($s2 == $zh){$zh = $s1;} - for($i = 0; $i < strlen($zh); $i++){ - $s1 = substr($zh,$i,1); - $p = ord($s1); - if($p > 160){ - $s2 = substr($zh,$i++,2); - $ret .= getFirstCharter($s2); - }else{ - $ret .= $s1; - } - } - return $ret; +function PyFirst($zh) { + $ret = ""; + $s1 = iconv("UTF-8", "gb2312", $zh); + $s2 = iconv("gb2312", "UTF-8", $s1); + if ($s2 == $zh) {$zh = $s1;} + for ($i = 0; $i < strlen($zh); $i++) { + $s1 = substr($zh, $i, 1); + $p = ord($s1); + if ($p > 160) { + $s2 = substr($zh, $i++, 2); + $ret .= getFirstCharter($s2); + } else { + $ret .= $s1; + } + } + return $ret; } \ No newline at end of file diff --git a/application/config.php b/application/config.php index 9b572750..6af1e968 100644 --- a/application/config.php +++ b/application/config.php @@ -10,96 +10,96 @@ return array( // 调试模式 - 'app_debug' => true, + 'app_debug' => true, - 'charset' => 'UTF-8', - 'lang_switch_on' => true, // 开启语言包功能 - 'lang_list' => ['zh-cn'], // 支持的语言列表 + 'charset' => 'UTF-8', + 'lang_switch_on' => true, // 开启语言包功能 + 'lang_list' => ['zh-cn'], // 支持的语言列表 - 'data_auth_key' => 'sent', + 'data_auth_key' => 'sent', - 'base_url' => BASE_PATH, - 'url_route_on' => true, - 'url_common_param' => false, + 'base_url' => BASE_PATH, + 'url_route_on' => true, + 'url_common_param' => false, - 'template' => array( - 'taglib_build_in' => 'cx,com\Sent' + 'template' => array( + 'taglib_build_in' => 'cx,com\Sent', ), // 'dispatch_success_tmpl' => APP_PATH . 'common/view/default/jump.html', // 'dispatch_error_tmpl' => APP_PATH . 'common/view/default/jump.html', - 'attachment_upload' => array( + 'attachment_upload' => array( // 允许上传的文件MiMe类型 - 'mimes' => [], + 'mimes' => [], // 上传的文件大小限制 (0-不做限制) - 'maxSize' => 0, + 'maxSize' => 0, // 允许上传的文件后缀 - 'exts' => [], + 'exts' => [], // 子目录创建方式,[0]-函数名,[1]-参数,多个参数使用数组 - 'subName' => ['date', 'Ymd'], + 'subName' => ['date', 'Ymd'], //保存根路径 - 'rootPath' => './uploads/attachment', + 'rootPath' => './uploads/attachment', // 保存路径 - 'savePath' => '', + 'savePath' => '', // 上传文件命名规则,[0]-函数名,[1]-参数,多个参数使用数组 - 'saveName' => ['uniqid', ''], + 'saveName' => ['uniqid', ''], // 文件上传驱动e, - 'driver' => 'Local', + 'driver' => 'Local', ), - 'editor_upload' => array( + 'editor_upload' => array( // 允许上传的文件MiMe类型 - 'mimes' => [], + 'mimes' => [], // 上传的文件大小限制 (0-不做限制) - 'maxSize' => 0, + 'maxSize' => 0, // 允许上传的文件后缀 - 'exts' => [], + 'exts' => [], // 子目录创建方式,[0]-函数名,[1]-参数,多个参数使用数组 - 'subName' => ['date', 'Ymd'], + 'subName' => ['date', 'Ymd'], //保存根路径 - 'rootPath' => './uploads/editor', + 'rootPath' => './uploads/editor', // 保存路径 - 'savePath' => '', + 'savePath' => '', // 上传文件命名规则,[0]-函数名,[1]-参数,多个参数使用数组 - 'saveName' => ['uniqid', ''], + 'saveName' => ['uniqid', ''], // 文件上传驱动e, - 'driver' => 'Local', + 'driver' => 'Local', ), 'picture_upload' => array( // 允许上传的文件MiMe类型 - 'mimes' => [], + 'mimes' => [], // 上传的文件大小限制 (0-不做限制) - 'maxSize' => 0, + 'maxSize' => 0, // 允许上传的文件后缀 - 'exts' => [], + 'exts' => [], // 子目录创建方式,[0]-函数名,[1]-参数,多个参数使用数组 - 'subName' => ['date', 'Ymd'], + 'subName' => ['date', 'Ymd'], //保存根路径 - 'rootPath' => './uploads/picture', + 'rootPath' => './uploads/picture', // 保存路径 - 'savePath' => '', + 'savePath' => '', // 上传文件命名规则,[0]-函数名,[1]-参数,多个参数使用数组 - 'saveName' => ['uniqid', ''], + 'saveName' => ['uniqid', ''], // 文件上传驱动e, - 'driver' => 'Local', + 'driver' => 'Local', ), - 'session' => array( - 'prefix' => 'sent', - 'type' => '', - 'auto_start' => true, + 'session' => array( + 'prefix' => 'sent', + 'type' => '', + 'auto_start' => true, ), - 'log' => array( + 'log' => array( // 日志记录方式,支持 file sae 'type' => 'file', // 日志保存目录 'path' => LOG_PATH, ), // 页面Trace信息 - 'trace' =>array( + 'trace' => array( //支持Html,Console 设为false则不显示 - 'type' => 'Html', + 'type' => 'Html', ) ); \ No newline at end of file diff --git a/application/route.php b/application/route.php index ab01f048..1cc787f5 100644 --- a/application/route.php +++ b/application/route.php @@ -8,34 +8,34 @@ // +---------------------------------------------------------------------- return array( - '__pattern__' => array( + '__pattern__' => array( 'name' => '\w+', ), - '/' => 'index/index/index', // 首页访问路由 - 'search' => 'index/search/index', // 首页访问路由 + '/' => 'index/index/index', // 首页访问路由 + 'search' => 'index/search/index', // 首页访问路由 - 'cart/index' => 'index/cart/index', - 'cart/add' => 'index/cart/add', - 'cart/count' => 'index/cart/count', + 'cart/index' => 'index/cart/index', + 'cart/add' => 'index/cart/add', + 'cart/count' => 'index/cart/count', - 'login' => 'user/login/index', - 'register' => 'user/login/register', - 'logout' => 'user/login/logout', - 'uc' => 'user/index/index', + 'login' => 'user/login/index', + 'register' => 'user/login/register', + 'logout' => 'user/login/logout', + 'uc' => 'user/index/index', - 'order/index' => 'user/order/index', - 'order/list' => 'user/order/lists', + 'order/index' => 'user/order/index', + 'order/list' => 'user/order/lists', - 'admin/login' => 'admin/index/login', - 'admin/logout' => 'admin/index/logout', + 'admin/login' => 'admin/index/login', + 'admin/logout' => 'admin/index/logout', // 变量传入index模块的控制器和操作方法 'addons/:mc/:ac' => 'index/addons/execute', // 静态地址和动态地址结合 - 'usera/:mc/:ac' => 'user/addons/execute', // 静态地址和动态地址结合 + 'usera/:mc/:ac' => 'user/addons/execute', // 静态地址和动态地址结合 'admina/:mc/:ac' => 'admin/addons/execute', // 静态地址和动态地址结合 'book/list' => 'index/book/index', - 'book/search' => 'index/book/search', - 'book/detail/:id' => 'index/book/detail', + 'book/search' => 'index/book/search', + 'book/detail/:id' => 'index/book/detail', ); \ No newline at end of file diff --git a/application/tags.php b/application/tags.php index f18dcf68..b272c7c4 100644 --- a/application/tags.php +++ b/application/tags.php @@ -1,4 +1,4 @@ array('app\\common\\behavior\\InitHook'), + 'app_init' => array('app\\common\\behavior\\InitHook'), ); \ No newline at end of file diff --git a/application/user/controller/Content.php b/application/user/controller/Content.php index c046692f..9872f06b 100644 --- a/application/user/controller/Content.php +++ b/application/user/controller/Content.php @@ -10,51 +10,51 @@ namespace app\user\controller; use app\common\controller\User; -class Content extends User{ +class Content extends User { - public function _initialize(){ + public function _initialize() { parent::_initialize(); $this->getContentMenu(); $model_id = $this->request->param('model_id'); - $row = db('Model')->select(); + $row = db('Model')->select(); foreach ($row as $key => $value) { - $list[$value['id']] = $value; + $list[$value['id']] = $value; } if (empty($list[$model_id])) { return $this->error("无此模型!"); - }else { + } else { $this->modelInfo = $list[$model_id]; if ($this->modelInfo['extend'] > 1) { $this->model = model($this->modelInfo['name']); - }else{ + } else { $this->model = model('Document')->extend($this->modelInfo['name']); } } - $this->assign('model_id',$model_id); - $this->assign('model_list',$list); - $this->assign('model_info',$this->modelInfo); + $this->assign('model_id', $model_id); + $this->assign('model_list', $list); + $this->assign('model_info', $this->modelInfo); } - public function index(){ + public function index() { if ($this->modelInfo['list_grid'] == '') { - return $this->error("列表定义不正确!", url('admin/model/edit',array('id'=>$this->modelInfo['id']))); + return $this->error("列表定义不正确!", url('admin/model/edit', array('id' => $this->modelInfo['id']))); } - $grid_list = get_grid_list($this->modelInfo['list_grid']); - $order = "id desc"; + $grid_list = get_grid_list($this->modelInfo['list_grid']); + $order = "id desc"; $map['uid'] = session('user_auth.uid'); if ($this->modelInfo['extend'] == 1) { $map['model_id'] = $this->modelInfo['id']; } $field = array_filter($grid_list['fields']); - $list = $this->model->where($map)->field($field)->order($order)->paginate(15); + $list = $this->model->where($map)->field($field)->order($order)->paginate(15); $data = array( - 'grid' => $grid_list, - 'list' => $list, - 'page' => $list->render() + 'grid' => $grid_list, + 'list' => $list, + 'page' => $list->render(), ); $this->assign($data); return $this->fetch(); @@ -64,21 +64,21 @@ class Content extends User{ * 内容添加 * @author molong */ - public function add(){ + public function add() { if (IS_POST) { $result = $this->model->change(); if ($result) { - return $this->success("添加成功!",url('admin/content/index',array('model_id'=>$this->modelInfo['id']))); - }else{ - return $this->error($this->model->getError(),''); + return $this->success("添加成功!", url('admin/content/index', array('model_id' => $this->modelInfo['id']))); + } else { + return $this->error($this->model->getError(), ''); } - }else{ + } else { $info = array( - 'model_id' => $this->modelInfo['id'] + 'model_id' => $this->modelInfo['id'], ); $data = array( - 'info' => $info, - 'fieldGroup' => $this->getField($this->modelInfo) + 'info' => $info, + 'fieldGroup' => $this->getField($this->modelInfo), ); $this->assign($data); return $this->fetch('public/edit'); @@ -89,15 +89,15 @@ class Content extends User{ * 内容修改 * @author molong */ - public function edit($id){ + public function edit($id) { if (IS_POST) { $result = $this->model->change(); if ($result !== false) { - return $this->success("更新成功!",url('admin/content/index',array('model_id'=>$this->modelInfo['id']))); - }else{ - return $this->error($this->model->getError(),''); + return $this->success("更新成功!", url('admin/content/index', array('model_id' => $this->modelInfo['id']))); + } else { + return $this->error($this->model->getError(), ''); } - }else{ + } else { if (!$id) { return $this->error("非法操作!"); } @@ -106,9 +106,9 @@ class Content extends User{ return $this->error($this->model->getError()); } $info['model_id'] = $this->modelInfo['id']; - $data = array( - 'info' => $info, - 'fieldGroup' => $this->getField($this->modelInfo) + $data = array( + 'info' => $info, + 'fieldGroup' => $this->getField($this->modelInfo), ); $this->assign($data); return $this->fetch('public/edit'); @@ -119,44 +119,44 @@ class Content extends User{ * 内容删除 * @author molong */ - public function del(){ - $id = input('get.id','','trim'); - $ids = input('post.ids/a',array()); + public function del() { + $id = input('get.id', '', 'trim'); + $ids = input('post.ids/a', array()); array_push($ids, $id); if (empty($ids)) { return $this->error("非法操作!"); } - $map['id'] = array('IN',$ids); - $result = $this->model->del($map); + $map['id'] = array('IN', $ids); + $result = $this->model->del($map); if ($result) { return $this->success("删除成功!"); - }else{ + } else { return $this->error("删除失败!", '', ""); } } - protected function getField(){ + protected function getField() { $field_group = parse_config_attr($this->modelInfo['field_group']); - $field_sort = json_decode($this->modelInfo['field_sort'],true); + $field_sort = json_decode($this->modelInfo['field_sort'], true); if ($this->modelInfo['extend'] > 1) { $map['model_id'] = $this->modelInfo['id']; - }else{ - $model_id[] = $this->modelInfo['id']; - $model_id[] = 1; - $map['model_id'] = array('IN',$model_id); + } else { + $model_id[] = $this->modelInfo['id']; + $model_id[] = 1; + $map['model_id'] = array('IN', $model_id); } if (ACTION_NAME == 'add') { - $map['is_show'] = array('in',array('1','2')); - }elseif(ACTION_NAME == 'edit'){ - $map['is_show'] = array('in',array('1','3')); + $map['is_show'] = array('in', array('1', '2')); + } elseif (ACTION_NAME == 'edit') { + $map['is_show'] = array('in', array('1', '3')); } //获得数组的第一条数组 $first_key = array_keys($field_group); - $fields = model('Attribute')->getFieldlist($map); + $fields = model('Attribute')->getFieldlist($map); if (!empty($field_sort)) { foreach ($field_sort as $key => $value) { foreach ($value as $index) { @@ -168,8 +168,8 @@ class Content extends User{ } } //未进行排序的放入第一组中 - $fields[] = array('name'=>'model_id','type'=>'hidden'); //加入模型ID值 - $fields[] = array('name'=>'id','type'=>'hidden'); //加入模型ID值 + $fields[] = array('name' => 'model_id', 'type' => 'hidden'); //加入模型ID值 + $fields[] = array('name' => 'id', 'type' => 'hidden'); //加入模型ID值 foreach ($fields as $key => $value) { $groupfield[$first_key[0]][] = $value; } diff --git a/application/user/controller/Index.php b/application/user/controller/Index.php index 3bd1d35a..5350a254 100644 --- a/application/user/controller/Index.php +++ b/application/user/controller/Index.php @@ -10,9 +10,9 @@ namespace app\user\controller; use app\common\controller\User; -class Index extends User{ +class Index extends User { - public function index(){ + public function index() { return $this->fetch(); } } diff --git a/core/helper.php b/core/helper.php index 16f3f0ed..57b8ae49 100644 --- a/core/helper.php +++ b/core/helper.php @@ -115,7 +115,7 @@ if (!function_exists('input')) { * @param string $filter 过滤方法 * @return mixed */ - function input($key, $default = null, $filter = null) + function input($key = '', $default = null, $filter = null) { if (0 === strpos($key, '?')) { $key = substr($key, 1); @@ -124,7 +124,7 @@ if (!function_exists('input')) { if ($pos = strpos($key, '.')) { // 指定参数来源 $method = substr($key, 0, $pos); - if (in_array($method, ['get', 'post', 'put', 'delete', 'param', 'request', 'session', 'cookie', 'server', 'env', 'path', 'file'])) { + if (in_array($method, ['get', 'post', 'put', 'patch', 'delete', 'param', 'request', 'session', 'cookie', 'server', 'env', 'path', 'file'])) { $key = substr($key, $pos + 1); } else { $method = 'param'; @@ -191,7 +191,7 @@ if (!function_exists('db')) { */ function db($name = '', $config = []) { - return Db::connect($config)->name($name); + return Db::connect($config, true)->name($name); } } @@ -421,12 +421,13 @@ if (!function_exists('view')) { * 渲染模板输出 * @param string $template 模板文件 * @param array $vars 模板变量 + * @param array $replace 模板替换 * @param integer $code 状态码 * @return \think\response\View */ - function view($template = '', $vars = [], $code = 200) + function view($template = '', $vars = [], $replace = [], $code = 200) { - return Response::create($template, 'view', $code)->vars($vars); + return Response::create($template, 'view', $code)->replace($replace)->assign($vars); } } diff --git a/core/library/think/App.php b/core/library/think/App.php index 24163372..ebc3a776 100644 --- a/core/library/think/App.php +++ b/core/library/think/App.php @@ -337,9 +337,9 @@ class App } catch (\ReflectionException $e) { // 操作不存在 if (method_exists($instance, '_empty')) { - $method = new \ReflectionMethod($instance, '_empty'); - $data = $method->invokeArgs($instance, [$action, '']); - self::$debug && Log::record('[ RUN ] ' . $method->__toString(), 'info'); + $reflect = new \ReflectionMethod($instance, '_empty'); + $data = $reflect->invokeArgs($instance, [$action]); + self::$debug && Log::record('[ RUN ] ' . $reflect->__toString(), 'info'); } else { throw new HttpException(404, 'method not exists:' . (new \ReflectionClass($instance))->getName() . '->' . $action); } diff --git a/core/library/think/File.php b/core/library/think/File.php index 54c2b138..21e8c9dd 100644 --- a/core/library/think/File.php +++ b/core/library/think/File.php @@ -195,11 +195,8 @@ class File extends SplFileObject { $extension = strtolower(pathinfo($this->getInfo('name'), PATHINFO_EXTENSION)); /* 对图像文件进行严格检测 */ - if (in_array($extension, array('gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf'))) { - $imginfo = getimagesize($this->filename); - if (empty($imginfo) || ('gif' == $extension && empty($imginfo['bits']))) { - return false; - } + if (in_array($extension, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf']) && !in_array(exif_imagetype($this->filename), [1, 2, 3, 4, 6])) { + return false; } return true; } diff --git a/core/library/think/Model.php b/core/library/think/Model.php index 47d422e5..16db8797 100644 --- a/core/library/think/Model.php +++ b/core/library/think/Model.php @@ -756,7 +756,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess $value = null; } if (!in_array($field, $this->change)) { - $this->setAttr($field, isset($this->data[$field]) ? $this->data[$field] : $value); + $this->setAttr($field, !is_null($value) ? $value : (isset($this->data[$field]) ? $this->data[$field] : $value)); } } } diff --git a/core/library/think/Request.php b/core/library/think/Request.php index 798575d9..c19cd9ee 100644 --- a/core/library/think/Request.php +++ b/core/library/think/Request.php @@ -83,7 +83,6 @@ class Request protected $request = []; protected $route = []; protected $put; - protected $delete; protected $session = []; protected $file = []; protected $cookie = []; @@ -490,6 +489,7 @@ class Request } elseif (!$this->method) { if (isset($_POST[Config::get('var_method')])) { $this->method = strtoupper($_POST[Config::get('var_method')]); + $this->{$this->method}($_POST); } elseif (isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'])) { $this->method = strtoupper($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']); } else { @@ -612,10 +612,9 @@ class Request $vars = $this->post(false); break; case 'PUT': - $vars = $this->put(false); - break; case 'DELETE': - $vars = $this->delete(false); + case 'PATCH': + $vars = $this->put(false); break; default: $vars = []; @@ -718,13 +717,20 @@ class Request */ public function delete($name = '', $default = null, $filter = null) { - if (is_array($name)) { - return $this->delete = is_null($this->delete) ? $name : array_merge($this->delete, $name); - } - if (is_null($this->delete)) { - parse_str(file_get_contents('php://input'), $this->delete); - } - return $this->input($this->delete, $name, $default, $filter); + return $this->put($name, $default, $filter); + } + + /** + * 设置获取获取PATCH参数 + * @access public + * @param string|array $name 变量名 + * @param mixed $default 默认值 + * @param string|array $filter 过滤方法 + * @return mixed + */ + public function patch($name = '', $default = null, $filter = null) + { + return $this->put($name, $default, $filter); } /** diff --git a/core/library/think/Route.php b/core/library/think/Route.php index ad3b603b..eee061f9 100644 --- a/core/library/think/Route.php +++ b/core/library/think/Route.php @@ -26,6 +26,7 @@ class Route 'POST' => [], 'PUT' => [], 'DELETE' => [], + 'PATCH' => [], 'HEAD' => [], 'OPTIONS' => [], '*' => [], @@ -59,7 +60,7 @@ class Route // 域名绑定 private static $bind = []; // 当前分组 - private static $group; + private static $group = ''; // 当前参数 private static $option = []; @@ -242,7 +243,7 @@ class Route self::$rules[$type][$rule] = ['rule' => $rule, 'route' => $route, 'var' => $vars, 'option' => $option, 'pattern' => $pattern]; if ('*' == $type) { // 注册路由快捷方式 - foreach (['GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'OPTIONS'] as $method) { + foreach (['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'] as $method) { self::$rules[$method][$rule] = true; } } @@ -257,7 +258,11 @@ class Route */ public static function setGroup($name) { - self::$group = $name; + if (self::$group) { + self::$group = self::$group . '/' . ltrim($name, '/'); + } else { + self::$group = $name; + } } /** @@ -291,9 +296,11 @@ class Route if (!empty($name)) { // 分组 if ($routes instanceof \Closure) { + $curentGroup = self::$group; self::setGroup($name); call_user_func_array($routes, []); - self::setGroup(null); + self::$group = $curentGroup; + self::$rules[$type][$name]['route'] = ''; self::$rules[$type][$name]['var'] = self::parseVar($name); self::$rules[$type][$name]['option'] = $option; @@ -317,7 +324,7 @@ class Route self::$rules[$type][$name] = ['rule' => $item, 'route' => '', 'var' => [], 'option' => $option, 'pattern' => $pattern]; } if ('*' == $type) { - foreach (['GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'OPTIONS'] as $method) { + foreach (['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'] as $method) { if (!isset(self::$rules[$method][$name])) { self::$rules[$method][$name] = true; } else { @@ -408,6 +415,20 @@ class Route self::rule($rule, $route, 'DELETE', $option, $pattern); } + /** + * 注册PATCH路由 + * @access public + * @param string $rule 路由规则 + * @param string $route 路由地址 + * @param array $option 路由参数 + * @param array $pattern 变量规则 + * @return void + */ + public static function patch($rule, $route = '', $option = [], $pattern = []) + { + self::rule($rule, $route, 'PATCH', $option, $pattern); + } + /** * 注册资源路由 * @access public diff --git a/core/library/think/Url.php b/core/library/think/Url.php index cf570af0..a5190d7b 100644 --- a/core/library/think/Url.php +++ b/core/library/think/Url.php @@ -19,9 +19,6 @@ use think\Route; class Url { - // 生成URL地址的root - protected static $root; - /** * URL生成 支持路由反射 * @param string $url URL表达式, @@ -116,7 +113,7 @@ class Url // 检测域名 $domain = self::parseDomain($url, $domain); // URL组装 - $url = $domain . (self::$root ?: Request::instance()->root()) . '/' . ltrim($url, '/'); + $url = $domain . Request::instance()->root() . '/' . ltrim($url, '/'); return $url; } @@ -319,11 +316,4 @@ class Url { Cache::rm('think_route_map'); } - - // 指定当前生成URL地址的root - public static function root($root) - { - self::$root = $root; - Request::instance()->root($root); - } -} +} \ No newline at end of file diff --git a/core/library/think/Validate.php b/core/library/think/Validate.php index 1c43f80c..a88043a2 100644 --- a/core/library/think/Validate.php +++ b/core/library/think/Validate.php @@ -68,6 +68,7 @@ class Validate 'allowIp' => '不允许的IP访问', 'denyIp' => '禁止的IP访问', 'confirm' => ':attribute和字段 :rule 不一致', + 'different' => ':attribute和字段 :rule 不能相同', 'egt' => ':attribute必须大于等于 :rule', 'gt' => ':attribute必须大于 :rule', 'elt' => ':attribute必须小于等于 :rule', @@ -400,6 +401,19 @@ class Validate return $this->getDataValue($data, $rule) == $value; } + /** + * 验证是否和某个字段的值是否不同 + * @access protected + * @param mixed $value 字段值 + * @param mixed $rule 验证规则 + * @param array $data 数据 + * @return bool + */ + protected function different($value, $rule, $data) + { + return $this->getDataValue($data, $rule) != $value; + } + /** * 验证是否大于等于某个值 * @access protected diff --git a/core/library/think/controller/Rest.php b/core/library/think/controller/Rest.php index a58743b3..a75cfd37 100644 --- a/core/library/think/controller/Rest.php +++ b/core/library/think/controller/Rest.php @@ -11,8 +11,9 @@ namespace think\controller; -use think\Response; +use think\App; use think\Request; +use think\Response; abstract class Rest { @@ -38,7 +39,7 @@ abstract class Rest { // 资源类型检测 $request = Request::instance(); - $ext = $request->ext(); + $ext = $request->ext(); if ('' == $ext) { // 自动检测资源类型 $this->type = $request->type(); @@ -61,11 +62,10 @@ abstract class Rest * REST 调用 * @access public * @param string $method 方法名 - * @param array $args 参数 * @return mixed * @throws \Exception */ - public function _empty($method, $args) + public function _empty($method) { if (method_exists($this, $method . '_' . $this->method . '_' . $this->type)) { // RESTFul方法支持 @@ -76,7 +76,7 @@ abstract class Rest $fun = $method . '_' . $this->method; } if (isset($fun)) { - return $this->$fun(); + return App::invokeMethod([$this, $fun]); } else { // 抛出异常 throw new \Exception('error action :' . $method); diff --git a/core/library/think/db/Query.php b/core/library/think/db/Query.php index b1451de8..f380b563 100644 --- a/core/library/think/db/Query.php +++ b/core/library/think/db/Query.php @@ -357,7 +357,7 @@ class Query protected function builder() { static $builder = []; - $driver = $this->driver; + $driver = $this->driver; if (!isset($builder[$driver])) { $class = '\\think\\db\\builder\\' . ucfirst($driver); $builder[$driver] = new $class($this->connection); @@ -660,7 +660,7 @@ class Query } if (count($join)) { // 有设置第二个元素则把第二元素作为表前缀 - $table = (string)current($join) . $table; + $table = (string) current($join) . $table; } elseif (false === strpos($table, '.')) { // 加上默认的表前缀 $table = $prefix . $table; @@ -975,7 +975,7 @@ class Query /** @var Paginator $class */ $class = false !== strpos($config['type'], '\\') ? $config['type'] : '\\think\\paginator\\driver\\' . ucwords($config['type']); - $page = isset($config['page']) ? (int)$config['page'] : call_user_func([ + $page = isset($config['page']) ? (int) $config['page'] : call_user_func([ $class, 'getCurrentPage', ], $config['var_page']); @@ -983,7 +983,7 @@ class Query $page = $page < 1 ? 1 : $page; $config['path'] = isset($config['path']) ? $config['path'] : call_user_func([$class, 'getCurrentPath']); - + if (!$simple) { $options = $this->getOptions(); $total = $this->count(); @@ -1326,7 +1326,7 @@ class Query if (!isset($this->info[$guid])) { $info = $this->connection->getFields($tableName); $fields = array_keys($info); - $bind = $type = []; + $bind = $type = []; foreach ($info as $key => $val) { // 记录字段类型 $type[$key] = $val['type']; @@ -1444,7 +1444,7 @@ class Query $relation = $key; $with[$key] = $key; } elseif (is_string($relation) && strpos($relation, '.')) { - $with[$key] = $relation; + $with[$key] = $relation; list($relation, $subRelation) = explode('.', $relation, 2); } @@ -1479,7 +1479,7 @@ class Query if ($closure) { // 执行闭包查询 - call_user_func_array($closure, [& $this]); + call_user_func_array($closure, [ & $this]); //指定获取关联的字段 //需要在 回调中 调方法 withField 方法,如 // $query->where(['id'=>1])->withField('id,name'); @@ -1599,13 +1599,15 @@ class Query $options = $this->parseExpress(); // 生成SQL语句 $sql = $this->builder()->insert($data, $options, $replace); + // 获取参数绑定 + $bind = $this->getBind(); if ($options['fetch_sql']) { // 获取实际执行的SQL语句 - return $this->connection->getRealSql($sql, $this->bind); + return $this->connection->getRealSql($sql, $bind); } $sequence = $sequence ?: (isset($options['sequence']) ? $options['sequence'] : null); // 执行操作 - return $this->execute($sql, $this->getBind(), $getLastInsID, $sequence); + return $this->execute($sql, $bind, $getLastInsID, $sequence); } /** @@ -1636,12 +1638,14 @@ class Query } // 生成SQL语句 $sql = $this->builder()->insertAll($dataSet, $options); + // 获取参数绑定 + $bind = $this->getBind(); if ($options['fetch_sql']) { // 获取实际执行的SQL语句 - return $this->connection->getRealSql($sql, $this->bind); + return $this->connection->getRealSql($sql, $bind); } else { // 执行操作 - return $this->execute($sql, $this->getBind()); + return $this->execute($sql, $bind); } } @@ -1660,12 +1664,14 @@ class Query // 生成SQL语句 $table = $this->parseSqlTable($table); $sql = $this->builder()->selectInsert($fields, $table, $options); + // 获取参数绑定 + $bind = $this->getBind(); if ($options['fetch_sql']) { // 获取实际执行的SQL语句 - return $this->connection->getRealSql($sql, $this->bind); + return $this->connection->getRealSql($sql, $bind); } else { // 执行操作 - return $this->execute($sql, $this->getBind()); + return $this->execute($sql, $bind); } } @@ -1708,9 +1714,11 @@ class Query } // 生成UPDATE SQL语句 $sql = $this->builder()->update($data, $options); + // 获取参数绑定 + $bind = $this->getBind(); if ($options['fetch_sql']) { // 获取实际执行的SQL语句 - return $this->connection->getRealSql($sql, $this->bind); + return $this->connection->getRealSql($sql, $bind); } else { // 检测缓存 if (isset($key) && Cache::get($key)) { @@ -1718,7 +1726,7 @@ class Query Cache::rm($key); } // 执行操作 - return '' == $sql ? 0 : $this->execute($sql, $this->getBind()); + return '' == $sql ? 0 : $this->execute($sql, $bind); } } @@ -1736,7 +1744,7 @@ class Query if ($data instanceof Query) { return $data->select(); } elseif ($data instanceof \Closure) { - call_user_func_array($data, [& $this]); + call_user_func_array($data, [ & $this]); $data = null; } // 分析查询表达式 @@ -1760,12 +1768,14 @@ class Query if (!$resultSet) { // 生成查询SQL $sql = $this->builder()->select($options); + // 获取参数绑定 + $bind = $this->getBind(); if ($options['fetch_sql']) { // 获取实际执行的SQL语句 - return $this->connection->getRealSql($sql, $this->bind); + return $this->connection->getRealSql($sql, $bind); } // 执行查询操作 - $resultSet = $this->query($sql, $this->getBind(), $options['master'], $options['fetch_class']); + $resultSet = $this->query($sql, $bind, $options['master'], $options['fetch_class']); if ($resultSet instanceof \PDOStatement) { // 返回PDOStatement对象 @@ -1819,7 +1829,7 @@ class Query if ($data instanceof Query) { return $data->find(); } elseif ($data instanceof \Closure) { - call_user_func_array($data, [& $this]); + call_user_func_array($data, [ & $this]); $data = null; } // 分析查询表达式 @@ -1845,12 +1855,14 @@ class Query if (!$result) { // 生成查询SQL $sql = $this->builder()->select($options); + // 获取参数绑定 + $bind = $this->getBind(); if ($options['fetch_sql']) { // 获取实际执行的SQL语句 - return $this->connection->getRealSql($sql, $this->bind); + return $this->connection->getRealSql($sql, $bind); } // 执行查询 - $result = $this->query($sql, $this->getBind(), $options['master'], $options['fetch_class']); + $result = $this->query($sql, $bind, $options['master'], $options['fetch_class']); if ($result instanceof \PDOStatement) { // 返回PDOStatement对象 @@ -2015,10 +2027,11 @@ class Query } // 生成删除SQL语句 $sql = $this->builder()->delete($options); - + // 获取参数绑定 + $bind = $this->getBind(); if ($options['fetch_sql']) { // 获取实际执行的SQL语句 - return $this->connection->getRealSql($sql, $this->bind); + return $this->connection->getRealSql($sql, $bind); } // 检测缓存 @@ -2027,7 +2040,7 @@ class Query Cache::rm($key); } // 执行操作 - return $this->execute($sql, $this->getBind()); + return $this->execute($sql, $bind); } /** @@ -2112,10 +2125,10 @@ class Query if (isset($options['page'])) { // 根据页数计算limit list($page, $listRows) = $options['page']; - $page = $page > 0 ? $page : 1; - $listRows = $listRows > 0 ? $listRows : (is_numeric($options['limit']) ? $options['limit'] : 20); - $offset = $listRows * ($page - 1); - $options['limit'] = $offset . ',' . $listRows; + $page = $page > 0 ? $page : 1; + $listRows = $listRows > 0 ? $listRows : (is_numeric($options['limit']) ? $options['limit'] : 20); + $offset = $listRows * ($page - 1); + $options['limit'] = $offset . ',' . $listRows; } $this->options = []; diff --git a/core/library/think/exception/Handle.php b/core/library/think/exception/Handle.php index a598df8c..7b3d0ff1 100644 --- a/core/library/think/exception/Handle.php +++ b/core/library/think/exception/Handle.php @@ -44,13 +44,13 @@ class Handle 'message' => $this->getMessage($exception), 'code' => $this->getCode($exception), ]; - $log = "[{$data['code']}]{$data['message']}[{$data['file']}:{$data['line']}]"; + $log = "[{$data['code']}]{$data['message']}[{$data['file']}:{$data['line']}]"; } else { $data = [ 'code' => $this->getCode($exception), 'message' => $this->getMessage($exception), ]; - $log = "[{$data['code']}]{$data['message']}"; + $log = "[{$data['code']}]{$data['message']}"; } Log::record($log, 'error'); @@ -103,7 +103,7 @@ class Handle $status = $e->getStatusCode(); $template = Config::get('http_exception_template'); if (!App::$debug && !empty($template[$status])) { - return Response::create($template[$status], 'view')->vars(['e' => $e]); + return Response::create($template[$status], 'view', $status)->assign(['e' => $e]); } else { return $this->convertExceptionToResponse($e); } @@ -155,9 +155,9 @@ class Handle while (ob_get_level() > 1) { ob_end_clean(); } - + $data['echo'] = ob_get_clean(); - + ob_start(); extract($data); include Config::get('exception_tmpl'); diff --git a/core/library/think/response/View.php b/core/library/think/response/View.php index 224e3b60..3a5f3660 100644 --- a/core/library/think/response/View.php +++ b/core/library/think/response/View.php @@ -36,18 +36,6 @@ class View extends Response ->fetch($data, $this->vars, $this->replace); } - /** - * 视图变量赋值 - * @access public - * @param array $vars 模板变量 - * @return $this - */ - public function vars($vars = []) - { - $this->vars = $vars; - return $this; - } - /** * 获取视图变量 * @access public @@ -56,11 +44,11 @@ class View extends Response */ public function getVars($name = null) { - if(is_null($name)){ + if (is_null($name)) { return $this->vars; - }else{ + } else { return isset($this->vars[$name]) ? $this->vars[$name] : null; - } + } } /**