移除Auth.php类中的Ucenter

优化基类Backend.php中的逻辑
优化插件管理网络失败的逻辑
优化代码格式化
pull/117/MERGE v1.0.0.20190407_beta
Karson 2019-04-07 20:34:22 +08:00
parent 5298c52e47
commit 9d42f92c95
49 changed files with 1975 additions and 2172 deletions

View File

@ -23,10 +23,10 @@ FastAdmin是一款基于ThinkPHP5+Bootstrap的极速后台开发框架。
* 共用同一账号体系的Web端会员中心权限验证和API接口会员权限验证 * 共用同一账号体系的Web端会员中心权限验证和API接口会员权限验证
* 二级域名部署支持,同时域名支持绑定到插件 * 二级域名部署支持,同时域名支持绑定到插件
* 多语言支持,服务端及客户端支持 * 多语言支持,服务端及客户端支持
* 强大的第三方模块支持([CMS](https://www.fastadmin.net/store/cms.html)、[博客](https://www.fastadmin.net/store/blog.html)、[文档生成](https://www.fastadmin.net/store/docs.html)) * 强大的第三方模块支持([CMS](https://www.fastadmin.net/store/cms.html)、[博客](https://www.fastadmin.net/store/blog.html)、[知识付费问答](https://www.fastadmin.net/store/ask.html))
* 整合第三方短信接口(阿里云、腾讯云短信) * 整合第三方短信接口(阿里云、腾讯云短信)
* 无缝整合第三方云存储(七牛、阿里云OSS、又拍云)功能 * 无缝整合第三方云存储(七牛、阿里云OSS、又拍云)功能
* 第三方富文本编辑器支持(Summernote、Tinymce、百度编辑器) * 第三方富文本编辑器支持(Summernote、Kindeditor、百度编辑器)
* 第三方登录(QQ、微信、微博)整合 * 第三方登录(QQ、微信、微博)整合
* Ucenter整合第三方应用 * Ucenter整合第三方应用
@ -86,6 +86,6 @@ FastAdmin遵循Apache2开源协议发布并提供免费使用。
本项目包含的第三方源码和二进制文件之版权信息另行标注。 本项目包含的第三方源码和二进制文件之版权信息另行标注。
版权所有Copyright © 2017-2018 by FastAdmin (https://www.fastadmin.net) 版权所有Copyright © 2017-2019 by FastAdmin (https://www.fastadmin.net)
All rights reserved。 All rights reserved。

View File

@ -29,6 +29,9 @@ return [
'Not installed tips' => '请安装后再访问插件前台页面!', 'Not installed tips' => '请安装后再访问插件前台页面!',
'Not enabled tips' => '插件已经禁用,请启用后再访问插件前台页面!', 'Not enabled tips' => '插件已经禁用,请启用后再访问插件前台页面!',
'New version tips' => '发现新版本:%s 点击查看更新日志', 'New version tips' => '发现新版本:%s 点击查看更新日志',
'Store now available tips' => 'FastAdmin插件市场暂不可用是否切换到本地插件',
'Switch to the local' => '切换到本地插件',
'try to reload' => '重新尝试加载',
'Please disable addon first' => '请先禁用插件再进行升级', 'Please disable addon first' => '请先禁用插件再进行升级',
'Login now' => '立即登录', 'Login now' => '立即登录',
'Continue install' => '不登录,继续安装', 'Continue install' => '不登录,继续安装',

View File

@ -12,7 +12,6 @@ use think\Session;
class Auth extends \fast\Auth class Auth extends \fast\Auth
{ {
protected $_error = ''; protected $_error = '';
protected $requestUri = ''; protected $requestUri = '';
protected $breadcrumb = []; protected $breadcrumb = [];
@ -33,7 +32,7 @@ class Auth extends \fast\Auth
* *
* @param string $username 用户名 * @param string $username 用户名
* @param string $password 密码 * @param string $password 密码
* @param int $keeptime 有效时长 * @param int $keeptime 有效时长
* @return boolean * @return boolean
*/ */
public function login($username, $password, $keeptime = 0) public function login($username, $password, $keeptime = 0)
@ -146,17 +145,17 @@ class Auth extends \fast\Auth
$request = Request::instance(); $request = Request::instance();
$arr = is_array($arr) ? $arr : explode(',', $arr); $arr = is_array($arr) ? $arr : explode(',', $arr);
if (!$arr) { if (!$arr) {
return FALSE; return false;
} }
$arr = array_map('strtolower', $arr); $arr = array_map('strtolower', $arr);
// 是否存在 // 是否存在
if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) { if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) {
return TRUE; return true;
} }
// 没找到匹配 // 没找到匹配
return FALSE; return false;
} }
/** /**
@ -229,7 +228,7 @@ class Auth extends \fast\Auth
public function isSuperAdmin() public function isSuperAdmin()
{ {
return in_array('*', $this->getRuleIds()) ? TRUE : FALSE; return in_array('*', $this->getRuleIds()) ? true : false;
} }
/** /**
@ -322,8 +321,9 @@ class Auth extends \fast\Auth
*/ */
public function getBreadCrumb($path = '') public function getBreadCrumb($path = '')
{ {
if ($this->breadcrumb || !$path) if ($this->breadcrumb || !$path) {
return $this->breadcrumb; return $this->breadcrumb;
}
$path_rule_id = 0; $path_rule_id = 0;
foreach ($this->rules as $rule) { foreach ($this->rules as $rule) {
$path_rule_id = $rule['name'] == $path ? $rule['id'] : $path_rule_id; $path_rule_id = $rule['name'] == $path ? $rule['id'] : $path_rule_id;
@ -341,7 +341,7 @@ class Auth extends \fast\Auth
/** /**
* 获取左侧和顶部菜单栏 * 获取左侧和顶部菜单栏
* *
* @param array $params URL对应的badge数据 * @param array $params URL对应的badge数据
* @param string $fixedPage 默认页 * @param string $fixedPage 默认页
* @return array * @return array
*/ */
@ -455,5 +455,4 @@ class Auth extends \fast\Auth
{ {
return $this->_error ? __($this->_error) : ''; return $this->_error ? __($this->_error) : '';
} }
} }

View File

@ -7,7 +7,10 @@ use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx; use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls; use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv; use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\Db;
use think\Exception; use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
trait Backend trait Backend
{ {
@ -108,6 +111,8 @@ trait Backend
if ($this->dataLimit && $this->dataLimitFieldAutoFill) { if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
$params[$this->dataLimitField] = $this->auth->id; $params[$this->dataLimitField] = $this->auth->id;
} }
$result = false;
Db::startTrans();
try { try {
//是否采用模型验证 //是否采用模型验证
if ($this->modelValidate) { if ($this->modelValidate) {
@ -116,15 +121,21 @@ trait Backend
$this->model->validate($validate); $this->model->validate($validate);
} }
$result = $this->model->allowField(true)->save($params); $result = $this->model->allowField(true)->save($params);
if ($result !== false) { Db::commit();
$this->success(); } catch (ValidateException $e) {
} else { Db::rollback();
$this->error($this->model->getError());
}
} catch (\think\exception\PDOException $e) {
$this->error($e->getMessage()); $this->error($e->getMessage());
} catch (\think\Exception $e) { } catch (PDOException $e) {
Db::rollback();
$this->error($e->getMessage()); $this->error($e->getMessage());
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($result) {
$this->success();
} else {
$this->error();
} }
} }
$this->error(__('Parameter %s can not be empty', '')); $this->error(__('Parameter %s can not be empty', ''));
@ -151,7 +162,8 @@ trait Backend
$params = $this->request->post("row/a"); $params = $this->request->post("row/a");
if ($params) { if ($params) {
$params = $this->preExcludeFields($params); $params = $this->preExcludeFields($params);
$result = false;
Db::startTrans();
try { try {
//是否采用模型验证 //是否采用模型验证
if ($this->modelValidate) { if ($this->modelValidate) {
@ -160,15 +172,21 @@ trait Backend
$row->validate($validate); $row->validate($validate);
} }
$result = $row->allowField(true)->save($params); $result = $row->allowField(true)->save($params);
if ($result !== false) { Db::commit();
$this->success(); } catch (ValidateException $e) {
} else { Db::rollback();
$this->error($row->getError());
}
} catch (\think\exception\PDOException $e) {
$this->error($e->getMessage()); $this->error($e->getMessage());
} catch (\think\Exception $e) { } catch (PDOException $e) {
Db::rollback();
$this->error($e->getMessage()); $this->error($e->getMessage());
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($result) {
$this->success();
} else {
$this->error();
} }
} }
$this->error(__('Parameter %s can not be empty', '')); $this->error(__('Parameter %s can not be empty', ''));
@ -186,12 +204,23 @@ trait Backend
$pk = $this->model->getPk(); $pk = $this->model->getPk();
$adminIds = $this->getDataLimitAdminIds(); $adminIds = $this->getDataLimitAdminIds();
if (is_array($adminIds)) { if (is_array($adminIds)) {
$count = $this->model->where($this->dataLimitField, 'in', $adminIds); $this->model->where($this->dataLimitField, 'in', $adminIds);
} }
$list = $this->model->where($pk, 'in', $ids)->select(); $list = $this->model->where($pk, 'in', $ids)->select();
$count = 0; $count = 0;
foreach ($list as $k => $v) { Db::startTrans();
$count += $v->delete(); try {
foreach ($list as $k => $v) {
$count += $v->delete();
}
Db::commit();
} catch (PDOException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
} }
if ($count) { if ($count) {
$this->success(); $this->success();
@ -210,15 +239,25 @@ trait Backend
$pk = $this->model->getPk(); $pk = $this->model->getPk();
$adminIds = $this->getDataLimitAdminIds(); $adminIds = $this->getDataLimitAdminIds();
if (is_array($adminIds)) { if (is_array($adminIds)) {
$count = $this->model->where($this->dataLimitField, 'in', $adminIds); $this->model->where($this->dataLimitField, 'in', $adminIds);
} }
if ($ids) { if ($ids) {
$this->model->where($pk, 'in', $ids); $this->model->where($pk, 'in', $ids);
} }
$count = 0; $count = 0;
$list = $this->model->onlyTrashed()->select(); Db::startTrans();
foreach ($list as $k => $v) { try {
$count += $v->delete(true); $list = $this->model->onlyTrashed()->select();
foreach ($list as $k => $v) {
$count += $v->delete(true);
}
Db::commit();
} catch (PDOException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
} }
if ($count) { if ($count) {
$this->success(); $this->success();
@ -242,9 +281,19 @@ trait Backend
$this->model->where($pk, 'in', $ids); $this->model->where($pk, 'in', $ids);
} }
$count = 0; $count = 0;
$list = $this->model->onlyTrashed()->select(); Db::startTrans();
foreach ($list as $index => $item) { try {
$count += $item->restore(); $list = $this->model->onlyTrashed()->select();
foreach ($list as $index => $item) {
$count += $item->restore();
}
Db::commit();
} catch (PDOException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
} }
if ($count) { if ($count) {
$this->success(); $this->success();
@ -268,9 +317,19 @@ trait Backend
$this->model->where($this->dataLimitField, 'in', $adminIds); $this->model->where($this->dataLimitField, 'in', $adminIds);
} }
$count = 0; $count = 0;
$list = $this->model->where($this->model->getPk(), 'in', $ids)->select(); Db::startTrans();
foreach ($list as $index => $item) { try {
$count += $item->allowField(true)->isUpdate(true)->save($values); $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
foreach ($list as $index => $item) {
$count += $item->allowField(true)->isUpdate(true)->save($values);
}
Db::commit();
} catch (PDOException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
} }
if ($count) { if ($count) {
$this->success(); $this->success();
@ -405,7 +464,7 @@ trait Backend
} }
} }
$this->model->saveAll($insert); $this->model->saveAll($insert);
} catch (\think\exception\PDOException $exception) { } catch (PDOException $exception) {
$msg = $exception->getMessage(); $msg = $exception->getMessage();
if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) { if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
$msg = "导入失败,包含【{$matches[1]}】的记录已存在"; $msg = "导入失败,包含【{$matches[1]}】的记录已存在";

View File

@ -13,21 +13,15 @@ use think\Config;
*/ */
class Common extends Api class Common extends Api
{ {
protected $noNeedLogin = ['init']; protected $noNeedLogin = ['init'];
protected $noNeedRight = '*'; protected $noNeedRight = '*';
public function _initialize()
{
parent::_initialize();
}
/** /**
* 加载初始化 * 加载初始化
* *
* @param string $version 版本号 * @param string $version 版本号
* @param string $lng 经度 * @param string $lng 经度
* @param string $lat 纬度 * @param string $lat 纬度
*/ */
public function init() public function init()
{ {
@ -137,5 +131,4 @@ class Common extends Api
$this->error($file->getError()); $this->error($file->getError());
} }
} }
} }

View File

@ -1,123 +1,102 @@
<?php <?php
namespace app\api\controller; namespace app\api\controller;
use app\common\controller\Api; use app\common\controller\Api;
use app\common\library\Ems as Emslib; use app\common\library\Ems as Emslib;
use app\common\model\User; use app\common\model\User;
/** /**
* 邮箱验证码接口 * 邮箱验证码接口
*/ */
class Ems extends Api class Ems extends Api
{ {
protected $noNeedLogin = '*';
protected $noNeedLogin = '*'; protected $noNeedRight = '*';
protected $noNeedRight = '*';
public function _initialize()
public function _initialize() {
{ parent::_initialize();
parent::_initialize(); \think\Hook::add('ems_send', function ($params) {
\think\Hook::add('ems_send', function($params) { $obj = \app\common\library\Email::instance();
$obj = \app\common\library\Email::instance(); $result = $obj
$result = $obj ->to($params->email)
->to($params->email) ->subject('验证码')
->subject('验证码') ->message("你的验证码是:" . $params->code)
->message("你的验证码是:" . $params->code) ->send();
->send(); return $result;
return $result; });
}); }
}
/**
/** * 发送验证码
* 发送验证码 *
* * @param string $email 邮箱
* @param string $email 邮箱 * @param string $event 事件名称
* @param string $event 事件名称 */
*/ public function send()
public function send() {
{ $email = $this->request->request("email");
$email = $this->request->request("email"); $event = $this->request->request("event");
$event = $this->request->request("event"); $event = $event ? $event : 'register';
$event = $event ? $event : 'register';
$last = Emslib::get($email, $event);
$last = Emslib::get($email, $event); if ($last && time() - $last['createtime'] < 60) {
if ($last && time() - $last['createtime'] < 60) $this->error(__('发送频繁'));
{ }
$this->error(__('发送频繁')); if ($event) {
} $userinfo = User::getByEmail($email);
if ($event) if ($event == 'register' && $userinfo) {
{ //已被注册
$userinfo = User::getByEmail($email); $this->error(__('已被注册'));
if ($event == 'register' && $userinfo) } elseif (in_array($event, ['changeemail']) && $userinfo) {
{ //被占用
//已被注册 $this->error(__('已被占用'));
$this->error(__('已被注册')); } elseif (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
} //未注册
else if (in_array($event, ['changeemail']) && $userinfo) $this->error(__('未注册'));
{ }
//被占用 }
$this->error(__('已被占用')); $ret = Emslib::send($email, null, $event);
} if ($ret) {
else if (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) $this->success(__('发送成功'));
{ } else {
//未注册 $this->error(__('发送失败'));
$this->error(__('未注册')); }
} }
}
$ret = Emslib::send($email, NULL, $event); /**
if ($ret) * 检测验证码
{ *
$this->success(__('发送成功')); * @param string $email 邮箱
} * @param string $event 事件名称
else * @param string $captcha 验证码
{ */
$this->error(__('发送失败')); public function check()
} {
} $email = $this->request->request("email");
$event = $this->request->request("event");
/** $event = $event ? $event : 'register';
* 检测验证码 $captcha = $this->request->request("captcha");
*
* @param string $email 邮箱 if ($event) {
* @param string $event 事件名称 $userinfo = User::getByEmail($email);
* @param string $captcha 验证码 if ($event == 'register' && $userinfo) {
*/ //已被注册
public function check() $this->error(__('已被注册'));
{ } elseif (in_array($event, ['changeemail']) && $userinfo) {
$email = $this->request->request("email"); //被占用
$event = $this->request->request("event"); $this->error(__('已被占用'));
$event = $event ? $event : 'register'; } elseif (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
$captcha = $this->request->request("captcha"); //未注册
$this->error(__('未注册'));
if ($event) }
{ }
$userinfo = User::getByEmail($email); $ret = Emslib::check($email, $captcha, $event);
if ($event == 'register' && $userinfo) if ($ret) {
{ $this->success(__('成功'));
//已被注册 } else {
$this->error(__('已被注册')); $this->error(__('验证码不正确'));
} }
else if (in_array($event, ['changeemail']) && $userinfo) }
{ }
//被占用
$this->error(__('已被占用'));
}
else if (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo)
{
//未注册
$this->error(__('未注册'));
}
}
$ret = Emslib::check($email, $captcha, $event);
if ($ret)
{
$this->success(__('成功'));
}
else
{
$this->error(__('验证码不正确'));
}
}
}

View File

@ -9,17 +9,15 @@ use app\common\controller\Api;
*/ */
class Index extends Api class Index extends Api
{ {
protected $noNeedLogin = ['*']; protected $noNeedLogin = ['*'];
protected $noNeedRight = ['*']; protected $noNeedRight = ['*'];
/** /**
* 首页 * 首页
* *
*/ */
public function index() public function index()
{ {
$this->success('请求成功'); $this->success('请求成功');
} }
} }

View File

@ -1,105 +1,98 @@
<?php <?php
namespace app\api\controller; namespace app\api\controller;
use app\common\controller\Api; use app\common\controller\Api;
use app\common\library\Sms as Smslib; use app\common\library\Sms as Smslib;
use app\common\model\User; use app\common\model\User;
/** /**
* 手机短信接口 * 手机短信接口
*/ */
class Sms extends Api class Sms extends Api
{ {
protected $noNeedLogin = '*';
protected $noNeedLogin = '*'; protected $noNeedRight = '*';
protected $noNeedRight = '*';
/**
public function _initialize() * 发送验证码
{ *
parent::_initialize(); * @param string $mobile 手机号
} * @param string $event 事件名称
*/
/** public function send()
* 发送验证码 {
* $mobile = $this->request->request("mobile");
* @param string $mobile 手机号 $event = $this->request->request("event");
* @param string $event 事件名称 $event = $event ? $event : 'register';
*/
public function send() if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
{ $this->error(__('手机号不正确'));
$mobile = $this->request->request("mobile"); }
$event = $this->request->request("event"); $last = Smslib::get($mobile, $event);
$event = $event ? $event : 'register'; if ($last && time() - $last['createtime'] < 60) {
$this->error(__('发送频繁'));
if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) { }
$this->error(__('手机号不正确')); $ipSendTotal = \app\common\model\Sms::where(['ip' => $this->request->ip()])->whereTime('createtime', '-1 hours')->count();
} if ($ipSendTotal >= 5) {
$last = Smslib::get($mobile, $event); $this->error(__('发送频繁'));
if ($last && time() - $last['createtime'] < 60) { }
$this->error(__('发送频繁')); if ($event) {
} $userinfo = User::getByMobile($mobile);
$ipSendTotal = \app\common\model\Sms::where(['ip' => $this->request->ip()])->whereTime('createtime', '-1 hours')->count(); if ($event == 'register' && $userinfo) {
if ($ipSendTotal >= 5) { //已被注册
$this->error(__('发送频繁')); $this->error(__('已被注册'));
} } elseif (in_array($event, ['changemobile']) && $userinfo) {
if ($event) { //被占用
$userinfo = User::getByMobile($mobile); $this->error(__('已被占用'));
if ($event == 'register' && $userinfo) { } elseif (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
//已被注册 //未注册
$this->error(__('已被注册')); $this->error(__('未注册'));
} else if (in_array($event, ['changemobile']) && $userinfo) { }
//被占用 }
$this->error(__('已被占用')); $ret = Smslib::send($mobile, null, $event);
} else if (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) { if ($ret) {
//未注册 $this->success(__('发送成功'));
$this->error(__('未注册')); } else {
} $this->error(__('发送失败'));
} }
$ret = Smslib::send($mobile, NULL, $event); }
if ($ret) {
$this->success(__('发送成功')); /**
} else { * 检测验证码
$this->error(__('发送失败')); *
} * @param string $mobile 手机号
} * @param string $event 事件名称
* @param string $captcha 验证码
/** */
* 检测验证码 public function check()
* {
* @param string $mobile 手机号 $mobile = $this->request->request("mobile");
* @param string $event 事件名称 $event = $this->request->request("event");
* @param string $captcha 验证码 $event = $event ? $event : 'register';
*/ $captcha = $this->request->request("captcha");
public function check()
{ if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
$mobile = $this->request->request("mobile"); $this->error(__('手机号不正确'));
$event = $this->request->request("event"); }
$event = $event ? $event : 'register'; if ($event) {
$captcha = $this->request->request("captcha"); $userinfo = User::getByMobile($mobile);
if ($event == 'register' && $userinfo) {
if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) { //已被注册
$this->error(__('手机号不正确')); $this->error(__('已被注册'));
} } elseif (in_array($event, ['changemobile']) && $userinfo) {
if ($event) { //被占用
$userinfo = User::getByMobile($mobile); $this->error(__('已被占用'));
if ($event == 'register' && $userinfo) { } elseif (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
//已被注册 //未注册
$this->error(__('已被注册')); $this->error(__('未注册'));
} else if (in_array($event, ['changemobile']) && $userinfo) { }
//被占用 }
$this->error(__('已被占用')); $ret = Smslib::check($mobile, $captcha, $event);
} else if (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) { if ($ret) {
//未注册 $this->success(__('成功'));
$this->error(__('未注册')); } else {
} $this->error(__('验证码不正确'));
} }
$ret = Smslib::check($mobile, $captcha, $event); }
if ($ret) { }
$this->success(__('成功'));
} else {
$this->error(__('验证码不正确'));
}
}
}

View File

@ -1,49 +1,42 @@
<?php <?php
namespace app\api\controller; namespace app\api\controller;
use app\common\controller\Api; use app\common\controller\Api;
use fast\Random; use fast\Random;
/** /**
* Token接口 * Token接口
*/ */
class Token extends Api class Token extends Api
{ {
protected $noNeedLogin = [];
protected $noNeedLogin = []; protected $noNeedRight = '*';
protected $noNeedRight = '*';
/**
public function _initialize() * 检测Token是否过期
{ *
parent::_initialize(); */
} public function check()
{
/** $token = $this->auth->getToken();
* 检测Token是否过期 $tokenInfo = \app\common\library\Token::get($token);
* $this->success('', ['token' => $tokenInfo['token'], 'expires_in' => $tokenInfo['expires_in']]);
*/ }
public function check()
{ /**
$token = $this->auth->getToken(); * 刷新Token
$tokenInfo = \app\common\library\Token::get($token); *
$this->success('', ['token' => $tokenInfo['token'], 'expires_in' => $tokenInfo['expires_in']]); */
} public function refresh()
{
/** //删除源Token
* 刷新Token $token = $this->auth->getToken();
* \app\common\library\Token::delete($token);
*/ //创建新Token
public function refresh() $token = Random::uuid();
{ \app\common\library\Token::set($token, $this->auth->id, 2592000);
//删除源Token $tokenInfo = \app\common\library\Token::get($token);
$token = $this->auth->getToken(); $this->success('', ['token' => $tokenInfo['token'], 'expires_in' => $tokenInfo['expires_in']]);
\app\common\library\Token::delete($token); }
//创建新Token }
$token = Random::uuid();
\app\common\library\Token::set($token, $this->auth->id, 2592000);
$tokenInfo = \app\common\library\Token::get($token);
$this->success('', ['token' => $tokenInfo['token'], 'expires_in' => $tokenInfo['expires_in']]);
}
}

View File

@ -13,7 +13,6 @@ use think\Validate;
*/ */
class User extends Api class User extends Api
{ {
protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third']; protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third'];
protected $noNeedRight = '*'; protected $noNeedRight = '*';
@ -33,7 +32,7 @@ class User extends Api
/** /**
* 会员登录 * 会员登录
* *
* @param string $account 账号 * @param string $account 账号
* @param string $password 密码 * @param string $password 密码
*/ */
public function login() public function login()
@ -55,7 +54,7 @@ class User extends Api
/** /**
* 手机验证码登录 * 手机验证码登录
* *
* @param string $mobile 手机号 * @param string $mobile 手机号
* @param string $captcha 验证码 * @param string $captcha 验证码
*/ */
public function mobilelogin() public function mobilelogin()
@ -92,8 +91,8 @@ class User extends Api
* *
* @param string $username 用户名 * @param string $username 用户名
* @param string $password 密码 * @param string $password 密码
* @param string $email 邮箱 * @param string $email 邮箱
* @param string $mobile 手机号 * @param string $mobile 手机号
*/ */
public function register() public function register()
{ {
@ -131,10 +130,10 @@ class User extends Api
/** /**
* 修改会员个人信息 * 修改会员个人信息
* *
* @param string $avatar 头像地址 * @param string $avatar 头像地址
* @param string $username 用户名 * @param string $username 用户名
* @param string $nickname 昵称 * @param string $nickname 昵称
* @param string $bio 个人简介 * @param string $bio 个人简介
*/ */
public function profile() public function profile()
{ {
@ -142,7 +141,7 @@ class User extends Api
$username = $this->request->request('username'); $username = $this->request->request('username');
$nickname = $this->request->request('nickname'); $nickname = $this->request->request('nickname');
$bio = $this->request->request('bio'); $bio = $this->request->request('bio');
$avatar = $this->request->request('avatar'); $avatar = $this->request->request('avatar', '', 'trim,strip_tags,htmlspecialchars');
if ($username) { if ($username) {
$exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find(); $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
if ($exists) { if ($exists) {
@ -160,7 +159,7 @@ class User extends Api
/** /**
* 修改邮箱 * 修改邮箱
* *
* @param string $email 邮箱 * @param string $email 邮箱
* @param string $captcha 验证码 * @param string $captcha 验证码
*/ */
public function changeemail() public function changeemail()
@ -194,7 +193,7 @@ class User extends Api
/** /**
* 修改手机号 * 修改手机号
* *
* @param string $email 手机号 * @param string $email 手机号
* @param string $captcha 验证码 * @param string $captcha 验证码
*/ */
public function changemobile() public function changemobile()
@ -229,7 +228,7 @@ class User extends Api
* 第三方登录 * 第三方登录
* *
* @param string $platform 平台名称 * @param string $platform 平台名称
* @param string $code Code码 * @param string $code Code码
*/ */
public function third() public function third()
{ {
@ -259,9 +258,9 @@ class User extends Api
/** /**
* 重置密码 * 重置密码
* *
* @param string $mobile 手机号 * @param string $mobile 手机号
* @param string $newpassword 新密码 * @param string $newpassword 新密码
* @param string $captcha 验证码 * @param string $captcha 验证码
*/ */
public function resetpwd() public function resetpwd()
{ {
@ -309,5 +308,4 @@ class User extends Api
$this->error($this->auth->getError()); $this->error($this->auth->getError());
} }
} }
} }

View File

@ -1,147 +1,138 @@
<?php <?php
namespace app\api\controller; namespace app\api\controller;
use app\common\controller\Api; use app\common\controller\Api;
use app\common\model\User; use app\common\model\User;
/** /**
* 验证接口 * 验证接口
*/ */
class Validate extends Api class Validate extends Api
{ {
protected $noNeedLogin = '*';
protected $noNeedLogin = '*'; protected $layout = '';
protected $layout = ''; protected $error = null;
protected $error = null;
public function _initialize()
public function _initialize() {
{ parent::_initialize();
parent::_initialize(); }
}
/**
/** * 检测邮箱
* 检测邮箱 *
* * @param string $email 邮箱
* @param string $email 邮箱 * @param string $id 排除会员ID
* @param string $id 排除会员ID */
*/ public function check_email_available()
public function check_email_available() {
{ $email = $this->request->request('email');
$email = $this->request->request('email'); $id = (int)$this->request->request('id');
$id = (int) $this->request->request('id'); $count = User::where('email', '=', $email)->where('id', '<>', $id)->count();
$count = User::where('email', '=', $email)->where('id', '<>', $id)->count(); if ($count > 0) {
if ($count > 0) $this->error(__('邮箱已经被占用'));
{ }
$this->error(__('邮箱已经被占用')); $this->success();
} }
$this->success();
} /**
* 检测用户名
/** *
* 检测用户名 * @param string $username 用户名
* * @param string $id 排除会员ID
* @param string $username 用户名 */
* @param string $id 排除会员ID public function check_username_available()
*/ {
public function check_username_available() $email = $this->request->request('username');
{ $id = (int)$this->request->request('id');
$email = $this->request->request('username'); $count = User::where('username', '=', $email)->where('id', '<>', $id)->count();
$id = (int) $this->request->request('id'); if ($count > 0) {
$count = User::where('username', '=', $email)->where('id', '<>', $id)->count(); $this->error(__('用户名已经被占用'));
if ($count > 0) }
{ $this->success();
$this->error(__('用户名已经被占用')); }
}
$this->success(); /**
} * 检测手机
*
/** * @param string $mobile 手机号
* 检测手机 * @param string $id 排除会员ID
* */
* @param string $mobile 手机号 public function check_mobile_available()
* @param string $id 排除会员ID {
*/ $mobile = $this->request->request('mobile');
public function check_mobile_available() $id = (int)$this->request->request('id');
{ $count = User::where('mobile', '=', $mobile)->where('id', '<>', $id)->count();
$mobile = $this->request->request('mobile'); if ($count > 0) {
$id = (int) $this->request->request('id'); $this->error(__('该手机号已经占用'));
$count = User::where('mobile', '=', $mobile)->where('id', '<>', $id)->count(); }
if ($count > 0) $this->success();
{ }
$this->error(__('该手机号已经占用'));
} /**
$this->success(); * 检测手机
} *
* @param string $mobile 手机号
/** */
* 检测手机 public function check_mobile_exist()
* {
* @param string $mobile 手机号 $mobile = $this->request->request('mobile');
*/ $count = User::where('mobile', '=', $mobile)->count();
public function check_mobile_exist() if (!$count) {
{ $this->error(__('手机号不存在'));
$mobile = $this->request->request('mobile'); }
$count = User::where('mobile', '=', $mobile)->count(); $this->success();
if (!$count) }
{
$this->error(__('手机号不存在')); /**
} * 检测邮箱
$this->success(); *
} * @param string $mobile 邮箱
*/
/** public function check_email_exist()
* 检测邮箱 {
* $email = $this->request->request('email');
* @param string $mobile 邮箱 $count = User::where('email', '=', $email)->count();
*/ if (!$count) {
public function check_email_exist() $this->error(__('邮箱不存在'));
{ }
$email = $this->request->request('email'); $this->success();
$count = User::where('email', '=', $email)->count(); }
if (!$count)
{ /**
$this->error(__('邮箱不存在')); * 检测手机验证码
} *
$this->success(); * @param string $mobile 手机号
} * @param string $captcha 验证码
* @param string $event 事件
/** */
* 检测手机验证码 public function check_sms_correct()
* {
* @param string $mobile 手机号 $mobile = $this->request->request('mobile');
* @param string $captcha 验证码 $captcha = $this->request->request('captcha');
* @param string $event 事件 $event = $this->request->request('event');
*/ if (!\app\common\library\Sms::check($mobile, $captcha, $event)) {
public function check_sms_correct() $this->error(__('验证码不正确'));
{ }
$mobile = $this->request->request('mobile'); $this->success();
$captcha = $this->request->request('captcha'); }
$event = $this->request->request('event');
if (!\app\common\library\Sms::check($mobile, $captcha, $event)) /**
{ * 检测邮箱验证码
$this->error(__('验证码不正确')); *
} * @param string $email 邮箱
$this->success(); * @param string $captcha 验证码
} * @param string $event 事件
*/
/** public function check_ems_correct()
* 检测邮箱验证码 {
* $email = $this->request->request('email');
* @param string $email 邮箱 $captcha = $this->request->request('captcha');
* @param string $captcha 验证码 $event = $this->request->request('event');
* @param string $event 事件 if (!\app\common\library\Ems::check($email, $captcha, $event)) {
*/ $this->error(__('验证码不正确'));
public function check_ems_correct() }
{ $this->success();
$email = $this->request->request('email'); }
$captcha = $this->request->request('captcha'); }
$event = $this->request->request('event');
if (!\app\common\library\Ems::check($email, $captcha, $event))
{
$this->error(__('验证码不正确'));
}
$this->success();
}
}

View File

@ -2,16 +2,13 @@
return [ return [
'Keep login' => '保持会话', 'Keep login' => '保持会话',
'Sign in' => '登入',
'Username' => '用户名', 'Username' => '用户名',
'User id' => '会员ID', 'User id' => '会员ID',
'Username' => '用户名',
'Nickname' => '昵称', 'Nickname' => '昵称',
'Password' => '密码', 'Password' => '密码',
'Sign up' => '注 册', 'Sign up' => '注 册',
'Sign in' => '登 录', 'Sign in' => '登 录',
'Sign out' => '注 销', 'Sign out' => '注 销',
'Keep login' => '保持会话',
'Guest' => '游客', 'Guest' => '游客',
'Welcome' => '%s你好', 'Welcome' => '%s你好',
'Add' => '添加', 'Add' => '添加',
@ -56,13 +53,9 @@ return [
'Line' => '行号', 'Line' => '行号',
'File' => '文件', 'File' => '文件',
'Menu' => '菜单', 'Menu' => '菜单',
'Name' => '名称',
'Weigh' => '权重',
'Type' => '类型', 'Type' => '类型',
'Title' => '标题', 'Title' => '标题',
'Content' => '内容', 'Content' => '内容',
'Status' => '状态',
'Operate' => '操作',
'Append' => '追加', 'Append' => '追加',
'Memo' => '备注', 'Memo' => '备注',
'Parent' => '父级', 'Parent' => '父级',

View File

@ -9,7 +9,6 @@ return [
'Username must be 6 to 30 characters' => '用户名必须6-30个字符', 'Username must be 6 to 30 characters' => '用户名必须6-30个字符',
'Password can not be empty' => '密码不能为空', 'Password can not be empty' => '密码不能为空',
'Password must be 6 to 30 characters' => '密码必须6-30个字符', 'Password must be 6 to 30 characters' => '密码必须6-30个字符',
'Email is incorrect' => '邮箱格式不正确',
'Mobile is incorrect' => '手机格式不正确', 'Mobile is incorrect' => '手机格式不正确',
'Username already exist' => '用户名已经存在', 'Username already exist' => '用户名已经存在',
'Email already exist' => '邮箱已经存在', 'Email already exist' => '邮箱已经存在',
@ -27,9 +26,7 @@ return [
'Profile' => '个人资料', 'Profile' => '个人资料',
'Verify email' => '邮箱验证', 'Verify email' => '邮箱验证',
'Change password' => '修改密码', 'Change password' => '修改密码',
'Change password successful' => '修改密码成功',
'Captcha is incorrect' => '验证码不正确', 'Captcha is incorrect' => '验证码不正确',
'Sign up successful' => '注册成功',
'Logged in successful' => '登录成功', 'Logged in successful' => '登录成功',
'Logout successful' => '注销成功', 'Logout successful' => '注销成功',
'Operation failed' => '操作失败', 'Operation failed' => '操作失败',

View File

@ -14,20 +14,17 @@ class ExceptionHandle extends Handle
public function render(Exception $e) public function render(Exception $e)
{ {
// 在生产环境下返回code信息 // 在生产环境下返回code信息
if (!\think\Config::get('app_debug')) if (!\think\Config::get('app_debug')) {
{
$statuscode = $code = 500; $statuscode = $code = 500;
$msg = 'An error occurred'; $msg = 'An error occurred';
// 验证异常 // 验证异常
if ($e instanceof \think\exception\ValidateException) if ($e instanceof \think\exception\ValidateException) {
{
$code = 0; $code = 0;
$statuscode = 200; $statuscode = 200;
$msg = $e->getError(); $msg = $e->getError();
} }
// Http异常 // Http异常
if ($e instanceof \think\exception\HttpException) if ($e instanceof \think\exception\HttpException) {
{
$statuscode = $code = $e->getStatusCode(); $statuscode = $code = $e->getStatusCode();
} }
return json(['code' => $code, 'msg' => $msg, 'time' => time(), 'data' => null], $statuscode); return json(['code' => $code, 'msg' => $msg, 'time' => time(), 'data' => null], $statuscode);

View File

@ -8,7 +8,6 @@ use think\Loader;
class Common class Common
{ {
public function moduleInit(&$request) public function moduleInit(&$request)
{ {
// 设置mbstring字符编码 // 设置mbstring字符编码
@ -17,45 +16,37 @@ class Common
// 如果修改了index.php入口地址则需要手动修改cdnurl的值 // 如果修改了index.php入口地址则需要手动修改cdnurl的值
$url = preg_replace("/\/(\w+)\.php$/i", '', $request->root()); $url = preg_replace("/\/(\w+)\.php$/i", '', $request->root());
// 如果未设置__CDN__则自动匹配得出 // 如果未设置__CDN__则自动匹配得出
if (!Config::get('view_replace_str.__CDN__')) if (!Config::get('view_replace_str.__CDN__')) {
{
Config::set('view_replace_str.__CDN__', $url); Config::set('view_replace_str.__CDN__', $url);
} }
// 如果未设置__PUBLIC__则自动匹配得出 // 如果未设置__PUBLIC__则自动匹配得出
if (!Config::get('view_replace_str.__PUBLIC__')) if (!Config::get('view_replace_str.__PUBLIC__')) {
{
Config::set('view_replace_str.__PUBLIC__', $url . '/'); Config::set('view_replace_str.__PUBLIC__', $url . '/');
} }
// 如果未设置__ROOT__则自动匹配得出 // 如果未设置__ROOT__则自动匹配得出
if (!Config::get('view_replace_str.__ROOT__')) if (!Config::get('view_replace_str.__ROOT__')) {
{
Config::set('view_replace_str.__ROOT__', preg_replace("/\/public\/$/", '', $url . '/')); Config::set('view_replace_str.__ROOT__', preg_replace("/\/public\/$/", '', $url . '/'));
} }
// 如果未设置cdnurl则自动匹配得出 // 如果未设置cdnurl则自动匹配得出
if (!Config::get('site.cdnurl')) if (!Config::get('site.cdnurl')) {
{
Config::set('site.cdnurl', $url); Config::set('site.cdnurl', $url);
} }
// 如果未设置cdnurl则自动匹配得出 // 如果未设置cdnurl则自动匹配得出
if (!Config::get('upload.cdnurl')) if (!Config::get('upload.cdnurl')) {
{
Config::set('upload.cdnurl', $url); Config::set('upload.cdnurl', $url);
} }
if (Config::get('app_debug')) if (Config::get('app_debug')) {
{
// 如果是调试模式将version置为当前的时间戳可避免缓存 // 如果是调试模式将version置为当前的时间戳可避免缓存
Config::set('site.version', time()); Config::set('site.version', time());
// 如果是开发模式那么将异常模板修改成官方的 // 如果是开发模式那么将异常模板修改成官方的
Config::set('exception_tmpl', THINK_PATH . 'tpl' . DS . 'think_exception.tpl'); Config::set('exception_tmpl', THINK_PATH . 'tpl' . DS . 'think_exception.tpl');
} }
// 如果是trace模式且Ajax的情况下关闭trace // 如果是trace模式且Ajax的情况下关闭trace
if (Config::get('app_trace') && $request->isAjax()) if (Config::get('app_trace') && $request->isAjax()) {
{
Config::set('app_trace', false); Config::set('app_trace', false);
} }
// 切换多语言 // 切换多语言
if (Config::get('lang_switch_on') && $request->get('lang')) if (Config::get('lang_switch_on') && $request->get('lang')) {
{
\think\Cookie::set('think_var', $request->get('lang')); \think\Cookie::set('think_var', $request->get('lang'));
} }
// Form别名 // Form别名
@ -72,5 +63,4 @@ class Common
]); ]);
$this->moduleInit($request); $this->moduleInit($request);
} }
} }

View File

@ -52,13 +52,13 @@ class Api
/** /**
* 权限Auth * 权限Auth
* @var Auth * @var Auth
*/ */
protected $auth = null; protected $auth = null;
/** /**
* 默认响应输出类型,支持json/xml * 默认响应输出类型,支持json/xml
* @var string * @var string
*/ */
protected $responseType = 'json'; protected $responseType = 'json';
@ -75,13 +75,11 @@ class Api
$this->_initialize(); $this->_initialize();
// 前置操作方法 // 前置操作方法
if ($this->beforeActionList) if ($this->beforeActionList) {
{ foreach ($this->beforeActionList as $method => $options) {
foreach ($this->beforeActionList as $method => $options)
{
is_numeric($method) ? is_numeric($method) ?
$this->beforeAction($options) : $this->beforeAction($options) :
$this->beforeAction($method, $options); $this->beforeAction($method, $options);
} }
} }
} }
@ -108,30 +106,23 @@ class Api
// 设置当前请求的URI // 设置当前请求的URI
$this->auth->setRequestUri($path); $this->auth->setRequestUri($path);
// 检测是否需要验证登录 // 检测是否需要验证登录
if (!$this->auth->match($this->noNeedLogin)) if (!$this->auth->match($this->noNeedLogin)) {
{
//初始化 //初始化
$this->auth->init($token); $this->auth->init($token);
//检测是否登录 //检测是否登录
if (!$this->auth->isLogin()) if (!$this->auth->isLogin()) {
{
$this->error(__('Please login first'), null, 401); $this->error(__('Please login first'), null, 401);
} }
// 判断是否需要验证权限 // 判断是否需要验证权限
if (!$this->auth->match($this->noNeedRight)) if (!$this->auth->match($this->noNeedRight)) {
{
// 判断控制器和方法判断是否有对应权限 // 判断控制器和方法判断是否有对应权限
if (!$this->auth->check($path)) if (!$this->auth->check($path)) {
{
$this->error(__('You have no permission'), null, 403); $this->error(__('You have no permission'), null, 403);
} }
} }
} } else {
else
{
// 如果有传递token才验证是否登录状态 // 如果有传递token才验证是否登录状态
if ($token) if ($token) {
{
$this->auth->init($token); $this->auth->init($token);
} }
} }
@ -158,11 +149,11 @@ class Api
/** /**
* 操作成功返回的数据 * 操作成功返回的数据
* @param string $msg 提示信息 * @param string $msg 提示信息
* @param mixed $data 要返回的数据 * @param mixed $data 要返回的数据
* @param int $code 错误码默认为1 * @param int $code 错误码默认为1
* @param string $type 输出类型 * @param string $type 输出类型
* @param array $header 发送的 Header 信息 * @param array $header 发送的 Header 信息
*/ */
protected function success($msg = '', $data = null, $code = 1, $type = null, array $header = []) protected function success($msg = '', $data = null, $code = 1, $type = null, array $header = [])
{ {
@ -171,11 +162,11 @@ class Api
/** /**
* 操作失败返回的数据 * 操作失败返回的数据
* @param string $msg 提示信息 * @param string $msg 提示信息
* @param mixed $data 要返回的数据 * @param mixed $data 要返回的数据
* @param int $code 错误码默认为0 * @param int $code 错误码默认为0
* @param string $type 输出类型 * @param string $type 输出类型
* @param array $header 发送的 Header 信息 * @param array $header 发送的 Header 信息
*/ */
protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = []) protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = [])
{ {
@ -204,13 +195,10 @@ class Api
// 如果未设置类型则自动判断 // 如果未设置类型则自动判断
$type = $type ? $type : ($this->request->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType); $type = $type ? $type : ($this->request->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType);
if (isset($header['statuscode'])) if (isset($header['statuscode'])) {
{
$code = $header['statuscode']; $code = $header['statuscode'];
unset($header['statuscode']); unset($header['statuscode']);
} } else {
else
{
//未设置状态码,根据code值判断 //未设置状态码,根据code值判断
$code = $code >= 1000 || $code < 200 ? 200 : $code; $code = $code >= 1000 || $code < 200 ? 200 : $code;
} }
@ -227,27 +215,20 @@ class Api
*/ */
protected function beforeAction($method, $options = []) protected function beforeAction($method, $options = [])
{ {
if (isset($options['only'])) if (isset($options['only'])) {
{ if (is_string($options['only'])) {
if (is_string($options['only']))
{
$options['only'] = explode(',', $options['only']); $options['only'] = explode(',', $options['only']);
} }
if (!in_array($this->request->action(), $options['only'])) if (!in_array($this->request->action(), $options['only'])) {
{
return; return;
} }
} } elseif (isset($options['except'])) {
elseif (isset($options['except'])) if (is_string($options['except'])) {
{
if (is_string($options['except']))
{
$options['except'] = explode(',', $options['except']); $options['except'] = explode(',', $options['except']);
} }
if (in_array($this->request->action(), $options['except'])) if (in_array($this->request->action(), $options['except'])) {
{
return; return;
} }
} }
@ -281,16 +262,12 @@ class Api
*/ */
protected function validate($data, $validate, $message = [], $batch = false, $callback = null) protected function validate($data, $validate, $message = [], $batch = false, $callback = null)
{ {
if (is_array($validate)) if (is_array($validate)) {
{
$v = Loader::validate(); $v = Loader::validate();
$v->rule($validate); $v->rule($validate);
} } else {
else
{
// 支持场景 // 支持场景
if (strpos($validate, '.')) if (strpos($validate, '.')) {
{
list($validate, $scene) = explode('.', $validate); list($validate, $scene) = explode('.', $validate);
} }
@ -300,21 +277,20 @@ class Api
} }
// 批量验证 // 批量验证
if ($batch || $this->batchValidate) if ($batch || $this->batchValidate) {
$v->batch(true); $v->batch(true);
}
// 设置错误信息 // 设置错误信息
if (is_array($message)) if (is_array($message)) {
$v->message($message); $v->message($message);
}
// 使用回调验证 // 使用回调验证
if ($callback && is_callable($callback)) if ($callback && is_callable($callback)) {
{
call_user_func_array($callback, [$v, &$data]); call_user_func_array($callback, [$v, &$data]);
} }
if (!$v->check($data)) if (!$v->check($data)) {
{ if ($this->failException) {
if ($this->failException)
{
throw new ValidateException($v->getError()); throw new ValidateException($v->getError());
} }
@ -323,5 +299,4 @@ class Api
return true; return true;
} }
} }

View File

@ -121,10 +121,10 @@ class Backend extends Controller
$path = str_replace('.', '/', $controllername) . '/' . $actionname; $path = str_replace('.', '/', $controllername) . '/' . $actionname;
// 定义是否Addtabs请求 // 定义是否Addtabs请求
!defined('IS_ADDTABS') && define('IS_ADDTABS', input("addtabs") ? TRUE : FALSE); !defined('IS_ADDTABS') && define('IS_ADDTABS', input("addtabs") ? true : false);
// 定义是否Dialog请求 // 定义是否Dialog请求
!defined('IS_DIALOG') && define('IS_DIALOG', input("dialog") ? TRUE : FALSE); !defined('IS_DIALOG') && define('IS_DIALOG', input("dialog") ? true : false);
// 定义是否AJAX请求 // 定义是否AJAX请求
!defined('IS_AJAX') && define('IS_AJAX', $this->request->isAjax()); !defined('IS_AJAX') && define('IS_AJAX', $this->request->isAjax());
@ -233,7 +233,7 @@ class Backend extends Controller
/** /**
* 渲染配置信息 * 渲染配置信息
* @param mixed $name 键名或数组 * @param mixed $name 键名或数组
* @param mixed $value * @param mixed $value
*/ */
protected function assignconfig($name, $value = '') protected function assignconfig($name, $value = '')
@ -243,7 +243,7 @@ class Backend extends Controller
/** /**
* 生成查询所需要的条件,排序方式 * 生成查询所需要的条件,排序方式
* @param mixed $searchfields 快速查询的字段 * @param mixed $searchfields 快速查询的字段
* @param boolean $relationSearch 是否关联查询 * @param boolean $relationSearch 是否关联查询
* @return array * @return array
*/ */
@ -258,8 +258,8 @@ class Backend extends Controller
$order = $this->request->get("order", "DESC"); $order = $this->request->get("order", "DESC");
$offset = $this->request->get("offset", 0); $offset = $this->request->get("offset", 0);
$limit = $this->request->get("limit", 0); $limit = $this->request->get("limit", 0);
$filter = (array)json_decode($filter, TRUE); $filter = (array)json_decode($filter, true);
$op = (array)json_decode($op, TRUE); $op = (array)json_decode($op, true);
$filter = $filter ? $filter : []; $filter = $filter ? $filter : [];
$where = []; $where = [];
$tableName = ''; $tableName = '';
@ -325,13 +325,14 @@ class Backend extends Controller
case 'BETWEEN': case 'BETWEEN':
case 'NOT BETWEEN': case 'NOT BETWEEN':
$arr = array_slice(explode(',', $v), 0, 2); $arr = array_slice(explode(',', $v), 0, 2);
if (stripos($v, ',') === false || !array_filter($arr)) if (stripos($v, ',') === false || !array_filter($arr)) {
continue 2; continue 2;
}
//当出现一边为空时改变操作符 //当出现一边为空时改变操作符
if ($arr[0] === '') { if ($arr[0] === '') {
$sym = $sym == 'BETWEEN' ? '<=' : '>'; $sym = $sym == 'BETWEEN' ? '<=' : '>';
$arr = $arr[1]; $arr = $arr[1];
} else if ($arr[1] === '') { } elseif ($arr[1] === '') {
$sym = $sym == 'BETWEEN' ? '>=' : '<'; $sym = $sym == 'BETWEEN' ? '>=' : '<';
$arr = $arr[0]; $arr = $arr[0];
} }
@ -341,13 +342,14 @@ class Backend extends Controller
case 'NOT RANGE': case 'NOT RANGE':
$v = str_replace(' - ', ',', $v); $v = str_replace(' - ', ',', $v);
$arr = array_slice(explode(',', $v), 0, 2); $arr = array_slice(explode(',', $v), 0, 2);
if (stripos($v, ',') === false || !array_filter($arr)) if (stripos($v, ',') === false || !array_filter($arr)) {
continue 2; continue 2;
}
//当出现一边为空时改变操作符 //当出现一边为空时改变操作符
if ($arr[0] === '') { if ($arr[0] === '') {
$sym = $sym == 'RANGE' ? '<=' : '>'; $sym = $sym == 'RANGE' ? '<=' : '>';
$arr = $arr[1]; $arr = $arr[1];
} else if ($arr[1] === '') { } elseif ($arr[1] === '') {
$sym = $sym == 'RANGE' ? '>=' : '<'; $sym = $sym == 'RANGE' ? '>=' : '<';
$arr = $arr[0]; $arr = $arr[0];
} }
@ -488,11 +490,11 @@ class Backend extends Controller
'pid' => isset($item['pid']) ? $item['pid'] : 0 'pid' => isset($item['pid']) ? $item['pid'] : 0
]; ];
} }
if($istree) { if ($istree) {
$tree = Tree::instance(); $tree = Tree::instance();
$tree->init(collection($list)->toArray(), 'pid'); $tree->init(collection($list)->toArray(), 'pid');
$list = $tree->getTreeList($tree->getTreeArray(0), $field); $list = $tree->getTreeList($tree->getTreeArray(0), $field);
if(!$ishtml){ if (!$ishtml) {
foreach ($list as &$item) { foreach ($list as &$item) {
$item = str_replace('&nbsp;', ' ', $item); $item = str_replace('&nbsp;', ' ', $item);
} }
@ -503,5 +505,4 @@ class Backend extends Controller
//这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮 //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
return json(['list' => $list, 'total' => $total]); return json(['list' => $list, 'total' => $total]);
} }
} }

View File

@ -127,12 +127,11 @@ class Frontend extends Controller
/** /**
* 渲染配置信息 * 渲染配置信息
* @param mixed $name 键名或数组 * @param mixed $name 键名或数组
* @param mixed $value * @param mixed $value
*/ */
protected function assignconfig($name, $value = '') protected function assignconfig($name, $value = '')
{ {
$this->view->config = array_merge($this->view->config ? $this->view->config : [], is_array($name) ? $name : [$name => $value]); $this->view->config = array_merge($this->view->config ? $this->view->config : [], is_array($name) ? $name : [$name => $value]);
} }
} }

View File

@ -7,17 +7,17 @@ use app\common\model\UserRule;
use fast\Random; use fast\Random;
use think\Config; use think\Config;
use think\Db; use think\Db;
use think\Exception;
use think\Hook; use think\Hook;
use think\Request; use think\Request;
use think\Validate; use think\Validate;
class Auth class Auth
{ {
protected static $instance = null; protected static $instance = null;
protected $_error = ''; protected $_error = '';
protected $_logined = FALSE; protected $_logined = false;
protected $_user = NULL; protected $_user = null;
protected $_token = ''; protected $_token = '';
//Token默认有效时长 //Token默认有效时长
protected $keeptime = 2592000; protected $keeptime = 2592000;
@ -30,22 +30,20 @@ class Auth
public function __construct($options = []) public function __construct($options = [])
{ {
if ($config = Config::get('user')) if ($config = Config::get('user')) {
{
$this->config = array_merge($this->config, $config); $this->config = array_merge($this->config, $config);
} }
$this->options = array_merge($this->config, $options); $this->options = array_merge($this->config, $options);
} }
/** /**
* *
* @param array $options 参数 * @param array $options 参数
* @return Auth * @return Auth
*/ */
public static function instance($options = []) public static function instance($options = [])
{ {
if (is_null(self::$instance)) if (is_null(self::$instance)) {
{
self::$instance = new static($options); self::$instance = new static($options);
} }
@ -63,91 +61,82 @@ class Auth
/** /**
* 兼容调用user模型的属性 * 兼容调用user模型的属性
* *
* @param string $name * @param string $name
* @return mixed * @return mixed
*/ */
public function __get($name) public function __get($name)
{ {
return $this->_user ? $this->_user->$name : NULL; return $this->_user ? $this->_user->$name : null;
} }
/** /**
* 根据Token初始化 * 根据Token初始化
* *
* @param string $token Token * @param string $token Token
* @return boolean * @return boolean
*/ */
public function init($token) public function init($token)
{ {
if ($this->_logined) if ($this->_logined) {
{ return true;
return TRUE; }
if ($this->_error) {
return false;
} }
if ($this->_error)
return FALSE;
$data = Token::get($token); $data = Token::get($token);
if (!$data) if (!$data) {
{ return false;
return FALSE;
} }
$user_id = intval($data['user_id']); $user_id = intval($data['user_id']);
if ($user_id > 0) if ($user_id > 0) {
{
$user = User::get($user_id); $user = User::get($user_id);
if (!$user) if (!$user) {
{
$this->setError('Account not exist'); $this->setError('Account not exist');
return FALSE; return false;
} }
if ($user['status'] != 'normal') if ($user['status'] != 'normal') {
{
$this->setError('Account is locked'); $this->setError('Account is locked');
return FALSE; return false;
} }
$this->_user = $user; $this->_user = $user;
$this->_logined = TRUE; $this->_logined = true;
$this->_token = $token; $this->_token = $token;
//初始化成功的事件 //初始化成功的事件
Hook::listen("user_init_successed", $this->_user); Hook::listen("user_init_successed", $this->_user);
return TRUE; return true;
} } else {
else
{
$this->setError('You are not logged in'); $this->setError('You are not logged in');
return FALSE; return false;
} }
} }
/** /**
* 注册用户 * 注册用户
* *
* @param string $username 用户名 * @param string $username 用户名
* @param string $password 密码 * @param string $password 密码
* @param string $email 邮箱 * @param string $email 邮箱
* @param string $mobile 手机号 * @param string $mobile 手机号
* @param array $extend 扩展参数 * @param array $extend 扩展参数
* @return boolean * @return boolean
*/ */
public function register($username, $password, $email = '', $mobile = '', $extend = []) public function register($username, $password, $email = '', $mobile = '', $extend = [])
{ {
// 检测用户名或邮箱、手机号是否存在 // 检测用户名或邮箱、手机号是否存在
if (User::getByUsername($username)) if (User::getByUsername($username)) {
{
$this->setError('Username already exist'); $this->setError('Username already exist');
return FALSE; return false;
} }
if ($email && User::getByEmail($email)) if ($email && User::getByEmail($email)) {
{
$this->setError('Email already exist'); $this->setError('Email already exist');
return FALSE; return false;
} }
if ($mobile && User::getByMobile($mobile)) if ($mobile && User::getByMobile($mobile)) {
{
$this->setError('Mobile already exist'); $this->setError('Mobile already exist');
return FALSE; return false;
} }
$ip = request()->ip(); $ip = request()->ip();
@ -175,31 +164,11 @@ class Auth
$params['password'] = $this->getEncryptPassword($password, $params['salt']); $params['password'] = $this->getEncryptPassword($password, $params['salt']);
$params = array_merge($params, $extend); $params = array_merge($params, $extend);
////////////////同步到Ucenter////////////////
if (defined('UC_STATUS') && UC_STATUS)
{
$uc = new \addons\ucenter\library\client\Client();
$user_id = $uc->uc_user_register($username, $password, $email);
// 如果小于0则说明发生错误
if ($user_id <= 0)
{
$this->setError($user_id > -4 ? 'Username is incorrect' : 'Email is incorrect');
return FALSE;
}
else
{
$params['id'] = $user_id;
}
}
//账号注册时需要开启事务,避免出现垃圾数据 //账号注册时需要开启事务,避免出现垃圾数据
Db::startTrans(); Db::startTrans();
try try {
{ $user = User::create($params, true);
$user = User::create($params);
Db::commit();
// 此时的Model中只包含部分数据
$this->_user = User::get($user->id); $this->_user = User::get($user->id);
//设置Token //设置Token
@ -207,101 +176,99 @@ class Auth
Token::set($this->_token, $user->id, $this->keeptime); Token::set($this->_token, $user->id, $this->keeptime);
//注册成功的事件 //注册成功的事件
Hook::listen("user_register_successed", $this->_user); Hook::listen("user_register_successed", $this->_user, $data);
Db::commit();
return TRUE; } catch (Exception $e) {
}
catch (Exception $e)
{
$this->setError($e->getMessage()); $this->setError($e->getMessage());
Db::rollback(); Db::rollback();
return FALSE; return false;
} }
return true;
} }
/** /**
* 用户登录 * 用户登录
* *
* @param string $account 账号,用户名、邮箱、手机号 * @param string $account 账号,用户名、邮箱、手机号
* @param string $password 密码 * @param string $password 密码
* @return boolean * @return boolean
*/ */
public function login($account, $password) public function login($account, $password)
{ {
$field = Validate::is($account, 'email') ? 'email' : (Validate::regex($account, '/^1\d{10}$/') ? 'mobile' : 'username'); $field = Validate::is($account, 'email') ? 'email' : (Validate::regex($account, '/^1\d{10}$/') ? 'mobile' : 'username');
$user = User::get([$field => $account]); $user = User::get([$field => $account]);
if (!$user) if (!$user) {
{
$this->setError('Account is incorrect'); $this->setError('Account is incorrect');
return FALSE; return false;
} }
if ($user->status != 'normal') if ($user->status != 'normal') {
{
$this->setError('Account is locked'); $this->setError('Account is locked');
return FALSE; return false;
} }
if ($user->password != $this->getEncryptPassword($password, $user->salt)) if ($user->password != $this->getEncryptPassword($password, $user->salt)) {
{
$this->setError('Password is incorrect'); $this->setError('Password is incorrect');
return FALSE; return false;
} }
//直接登录会员 //直接登录会员
$this->direct($user->id); $this->direct($user->id);
return TRUE; return true;
} }
/** /**
* 注销 * 注销
* *
* @return boolean * @return boolean
*/ */
public function logout() public function logout()
{ {
if (!$this->_logined) if (!$this->_logined) {
{
$this->setError('You are not logged in'); $this->setError('You are not logged in');
return false; return false;
} }
//设置登录标识 //设置登录标识
$this->_logined = FALSE; $this->_logined = false;
//删除Token //删除Token
Token::delete($this->_token); Token::delete($this->_token);
//注销成功的事件 //注销成功的事件
Hook::listen("user_logout_successed", $this->_user); Hook::listen("user_logout_successed", $this->_user);
return TRUE; return true;
} }
/** /**
* 修改密码 * 修改密码
* @param string $newpassword 新密码 * @param string $newpassword 新密码
* @param string $oldpassword 旧密码 * @param string $oldpassword 旧密码
* @param bool $ignoreoldpassword 忽略旧密码 * @param bool $ignoreoldpassword 忽略旧密码
* @return boolean * @return boolean
*/ */
public function changepwd($newpassword, $oldpassword = '', $ignoreoldpassword = false) public function changepwd($newpassword, $oldpassword = '', $ignoreoldpassword = false)
{ {
if (!$this->_logined) if (!$this->_logined) {
{
$this->setError('You are not logged in'); $this->setError('You are not logged in');
return false; return false;
} }
//判断旧密码是否正确 //判断旧密码是否正确
if ($this->_user->password == $this->getEncryptPassword($oldpassword, $this->_user->salt) || $ignoreoldpassword) if ($this->_user->password == $this->getEncryptPassword($oldpassword, $this->_user->salt) || $ignoreoldpassword) {
{ Db::startTrans();
$salt = Random::alnum(); try {
$newpassword = $this->getEncryptPassword($newpassword, $salt); $salt = Random::alnum();
$this->_user->save(['password' => $newpassword, 'salt' => $salt]); $newpassword = $this->getEncryptPassword($newpassword, $salt);
$this->_user->save(['password' => $newpassword, 'salt' => $salt]);
Token::delete($this->_token); Token::delete($this->_token);
//修改密码成功的事件 //修改密码成功的事件
Hook::listen("user_changepwd_successed", $this->_user); Hook::listen("user_changepwd_successed", $this->_user);
Db::commit();
} catch (Exception $e) {
Db::rollback();
$this->setError($e->getMessage());
return false;
}
return true; return true;
} } else {
else
{
$this->setError('Password is incorrect'); $this->setError('Password is incorrect');
return false; return false;
} }
@ -315,75 +282,66 @@ class Auth
public function direct($user_id) public function direct($user_id)
{ {
$user = User::get($user_id); $user = User::get($user_id);
if ($user) if ($user) {
{ Db::startTrans();
////////////////同步到Ucenter//////////////// try {
if (defined('UC_STATUS') && UC_STATUS) $ip = request()->ip();
{ $time = time();
$uc = new \addons\ucenter\library\client\Client();
$re = $uc->uc_user_login($this->user->id, $this->user->password . '#split#' . $this->user->salt, 3); //判断连续登录和最大连续登录
// 如果小于0则说明发生错误 if ($user->logintime < \fast\Date::unixtime('day')) {
if ($re <= 0) $user->successions = $user->logintime < \fast\Date::unixtime('day', -1) ? 1 : $user->successions + 1;
{ $user->maxsuccessions = max($user->successions, $user->maxsuccessions);
$this->setError('Username or password is incorrect');
return FALSE;
} }
$user->prevtime = $user->logintime;
//记录本次登录的IP和时间
$user->loginip = $ip;
$user->logintime = $time;
$user->save();
$this->_user = $user;
$this->_token = Random::uuid();
Token::set($this->_token, $user->id, $this->keeptime);
$this->_logined = true;
//登录成功的事件
Hook::listen("user_login_successed", $this->_user);
Db::commit();
} catch (Exception $e) {
Db::rollback();
$this->setError($e->getMessage());
return false;
} }
return true;
$ip = request()->ip(); } else {
$time = time(); return false;
//判断连续登录和最大连续登录
if ($user->logintime < \fast\Date::unixtime('day'))
{
$user->successions = $user->logintime < \fast\Date::unixtime('day', -1) ? 1 : $user->successions + 1;
$user->maxsuccessions = max($user->successions, $user->maxsuccessions);
}
$user->prevtime = $user->logintime;
//记录本次登录的IP和时间
$user->loginip = $ip;
$user->logintime = $time;
$user->save();
$this->_user = $user;
$this->_token = Random::uuid();
Token::set($this->_token, $user->id, $this->keeptime);
$this->_logined = TRUE;
//登录成功的事件
Hook::listen("user_login_successed", $this->_user);
return TRUE;
}
else
{
return FALSE;
} }
} }
/** /**
* 检测是否是否有对应权限 * 检测是否是否有对应权限
* @param string $path 控制器/方法 * @param string $path 控制器/方法
* @param string $module 模块 默认为当前模块 * @param string $module 模块 默认为当前模块
* @return boolean * @return boolean
*/ */
public function check($path = NULL, $module = NULL) public function check($path = null, $module = null)
{ {
if (!$this->_logined) if (!$this->_logined) {
return false; return false;
}
$ruleList = $this->getRuleList(); $ruleList = $this->getRuleList();
$rules = []; $rules = [];
foreach ($ruleList as $k => $v) foreach ($ruleList as $k => $v) {
{
$rules[] = $v['name']; $rules[] = $v['name'];
} }
$url = ($module ? $module : request()->module()) . '/' . (is_null($path) ? $this->getRequestUri() : $path); $url = ($module ? $module : request()->module()) . '/' . (is_null($path) ? $this->getRequestUri() : $path);
$url = strtolower(str_replace('.', '/', $url)); $url = strtolower(str_replace('.', '/', $url));
return in_array($url, $rules) ? TRUE : FALSE; return in_array($url, $rules) ? true : false;
} }
/** /**
@ -392,8 +350,7 @@ class Auth
*/ */
public function isLogin() public function isLogin()
{ {
if ($this->_logined) if ($this->_logined) {
{
return true; return true;
} }
return false; return false;
@ -426,11 +383,11 @@ class Auth
*/ */
public function getRuleList() public function getRuleList()
{ {
if ($this->rules) if ($this->rules) {
return $this->rules; return $this->rules;
}
$group = $this->_user->group; $group = $this->_user->group;
if (!$group) if (!$group) {
{
return []; return [];
} }
$rules = explode(',', $group->rules); $rules = explode(',', $group->rules);
@ -482,43 +439,30 @@ class Auth
public function delete($user_id) public function delete($user_id)
{ {
$user = User::get($user_id); $user = User::get($user_id);
if (!$user) if (!$user) {
{ return false;
return FALSE;
} }
Db::startTrans();
try {
// 删除会员
User::destroy($user_id);
// 删除会员指定的所有Token
Token::clear($user_id);
////////////////同步到Ucenter////////////////
if (defined('UC_STATUS') && UC_STATUS)
{
$uc = new \addons\ucenter\library\client\Client();
$re = $uc->uc_user_delete($user['id']);
// 如果小于0则说明发生错误
if ($re <= 0)
{
$this->setError('Account is locked');
return FALSE;
}
}
// 调用事务删除账号
$result = Db::transaction(function($db) use($user_id) {
// 删除会员
User::destroy($user_id);
// 删除会员指定的所有Token
Token::clear($user_id);
return TRUE;
});
if ($result)
{
Hook::listen("user_delete_successed", $user); Hook::listen("user_delete_successed", $user);
Db::commit();
} catch (Exception $e) {
Db::rollback();
$this->setError($e->getMessage());
return false;
} }
return $result ? TRUE : FALSE; return true;
} }
/** /**
* 获取密码加密后的字符串 * 获取密码加密后的字符串
* @param string $password 密码 * @param string $password 密码
* @param string $salt 密码盐 * @param string $salt 密码盐
* @return string * @return string
*/ */
public function getEncryptPassword($password, $salt = '') public function getEncryptPassword($password, $salt = '')
@ -536,19 +480,17 @@ class Auth
{ {
$request = Request::instance(); $request = Request::instance();
$arr = is_array($arr) ? $arr : explode(',', $arr); $arr = is_array($arr) ? $arr : explode(',', $arr);
if (!$arr) if (!$arr) {
{ return false;
return FALSE;
} }
$arr = array_map('strtolower', $arr); $arr = array_map('strtolower', $arr);
// 是否存在 // 是否存在
if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) {
{ return true;
return TRUE;
} }
// 没找到匹配 // 没找到匹配
return FALSE; return false;
} }
/** /**
@ -562,39 +504,35 @@ class Auth
/** /**
* 渲染用户数据 * 渲染用户数据
* @param array $datalist 二维数组 * @param array $datalist 二维数组
* @param mixed $fields 加载的字段列表 * @param mixed $fields 加载的字段列表
* @param string $fieldkey 渲染的字段 * @param string $fieldkey 渲染的字段
* @param string $renderkey 结果字段 * @param string $renderkey 结果字段
* @return array * @return array
*/ */
public function render(&$datalist, $fields = [], $fieldkey = 'user_id', $renderkey = 'userinfo') public function render(&$datalist, $fields = [], $fieldkey = 'user_id', $renderkey = 'userinfo')
{ {
$fields = !$fields ? ['id', 'nickname', 'level', 'avatar'] : (is_array($fields) ? $fields : explode(',', $fields)); $fields = !$fields ? ['id', 'nickname', 'level', 'avatar'] : (is_array($fields) ? $fields : explode(',', $fields));
$ids = []; $ids = [];
foreach ($datalist as $k => $v) foreach ($datalist as $k => $v) {
{ if (!isset($v[$fieldkey])) {
if (!isset($v[$fieldkey]))
continue; continue;
}
$ids[] = $v[$fieldkey]; $ids[] = $v[$fieldkey];
} }
$list = []; $list = [];
if ($ids) if ($ids) {
{ if (!in_array('id', $fields)) {
if (!in_array('id', $fields))
{
$fields[] = 'id'; $fields[] = 'id';
} }
$ids = array_unique($ids); $ids = array_unique($ids);
$selectlist = User::where('id', 'in', $ids)->column($fields); $selectlist = User::where('id', 'in', $ids)->column($fields);
foreach ($selectlist as $k => $v) foreach ($selectlist as $k => $v) {
{
$list[$v['id']] = $v; $list[$v['id']] = $v;
} }
} }
foreach ($datalist as $k => &$v) foreach ($datalist as $k => &$v) {
{ $v[$renderkey] = isset($list[$v[$fieldkey]]) ? $list[$v[$fieldkey]] : null;
$v[$renderkey] = isset($list[$v[$fieldkey]]) ? $list[$v[$fieldkey]] : NULL;
} }
unset($v); unset($v);
return $datalist; return $datalist;
@ -620,5 +558,4 @@ class Auth
{ {
return $this->_error ? __($this->_error) : ''; return $this->_error ? __($this->_error) : '';
} }
} }

View File

@ -38,8 +38,7 @@ class Email
*/ */
public static function instance($options = []) public static function instance($options = [])
{ {
if (is_null(self::$instance)) if (is_null(self::$instance)) {
{
self::$instance = new static($options); self::$instance = new static($options);
} }
@ -52,8 +51,7 @@ class Email
*/ */
public function __construct($options = []) public function __construct($options = [])
{ {
if ($config = Config::get('site')) if ($config = Config::get('site')) {
{
$this->options = array_merge($this->options, $config); $this->options = array_merge($this->options, $config);
} }
$this->options = array_merge($this->options, $options); $this->options = array_merge($this->options, $options);
@ -114,7 +112,7 @@ class Email
/** /**
* 设置邮件正文 * 设置邮件正文
* @param string $body * @param string $body
* @param boolean $ishtml * @param boolean $ishtml
* @return $this * @return $this
*/ */
@ -150,27 +148,20 @@ class Email
public function send() public function send()
{ {
$result = false; $result = false;
switch ($this->options['mail_type']) switch ($this->options['mail_type']) {
{
case 1: case 1:
//使用phpmailer发送 //使用phpmailer发送
$this->mail->setFrom($this->options['from'], $this->options['from_name']); $this->mail->setFrom($this->options['from'], $this->options['from_name']);
$this->mail->addAddress($this->options['to'], $this->options['to_name']); $this->mail->addAddress($this->options['to'], $this->options['to_name']);
$this->mail->Subject = $this->options['subject']; $this->mail->Subject = $this->options['subject'];
if ($this->options['ishtml']) if ($this->options['ishtml']) {
{
$this->mail->msgHTML($this->options['body']); $this->mail->msgHTML($this->options['body']);
} } else {
else
{
$this->mail->Body = $this->options['body']; $this->mail->Body = $this->options['body'];
} }
try try {
{
$result = $this->mail->send(); $result = $this->mail->send();
} } catch (\phpmailerException $e) {
catch (\phpmailerException $e)
{
$this->setError($e->getMessage()); $this->setError($e->getMessage());
} }

View File

@ -1,144 +1,133 @@
<?php <?php
namespace app\common\library; namespace app\common\library;
use think\Hook; use think\Hook;
/** /**
* 邮箱验证码类 * 邮箱验证码类
*/ */
class Ems class Ems
{ {
/** /**
* 验证码有效时长 * 验证码有效时长
* @var int * @var int
*/ */
protected static $expire = 120; protected static $expire = 120;
/** /**
* 最大允许检测的次数 * 最大允许检测的次数
* @var int * @var int
*/ */
protected static $maxCheckNums = 10; protected static $maxCheckNums = 10;
/** /**
* 获取最后一次邮箱发送的数据 * 获取最后一次邮箱发送的数据
* *
* @param int $email 邮箱 * @param int $email 邮箱
* @param string $event 事件 * @param string $event 事件
* @return Ems * @return Ems
*/ */
public static function get($email, $event = 'default') public static function get($email, $event = 'default')
{ {
$ems = \app\common\model\Ems:: $ems = \app\common\model\Ems::
where(['email' => $email, 'event' => $event]) where(['email' => $email, 'event' => $event])
->order('id', 'DESC') ->order('id', 'DESC')
->find(); ->find();
Hook::listen('ems_get', $ems, null, true); Hook::listen('ems_get', $ems, null, true);
return $ems ? $ems : NULL; return $ems ? $ems : null;
} }
/** /**
* 发送验证码 * 发送验证码
* *
* @param int $email 邮箱 * @param int $email 邮箱
* @param int $code 验证码,为空时将自动生成4位数字 * @param int $code 验证码,为空时将自动生成4位数字
* @param string $event 事件 * @param string $event 事件
* @return boolean * @return boolean
*/ */
public static function send($email, $code = NULL, $event = 'default') public static function send($email, $code = null, $event = 'default')
{ {
$code = is_null($code) ? mt_rand(1000, 9999) : $code; $code = is_null($code) ? mt_rand(1000, 9999) : $code;
$time = time(); $time = time();
$ip = request()->ip(); $ip = request()->ip();
$ems = \app\common\model\Ems::create(['event' => $event, 'email' => $email, 'code' => $code, 'ip' => $ip, 'createtime' => $time]); $ems = \app\common\model\Ems::create(['event' => $event, 'email' => $email, 'code' => $code, 'ip' => $ip, 'createtime' => $time]);
$result = Hook::listen('ems_send', $ems, null, true); $result = Hook::listen('ems_send', $ems, null, true);
if (!$result) if (!$result) {
{ $ems->delete();
$ems->delete(); return false;
return FALSE; }
} return true;
return TRUE; }
}
/**
/** * 发送通知
* 发送通知 *
* * @param mixed $email 邮箱,多个以,分隔
* @param mixed $email 邮箱,多个以,分隔 * @param string $msg 消息内容
* @param string $msg 消息内容 * @param string $template 消息模板
* @param string $template 消息模板 * @return boolean
* @return boolean */
*/ public static function notice($email, $msg = '', $template = null)
public static function notice($email, $msg = '', $template = NULL) {
{ $params = [
$params = [ 'email' => $email,
'email' => $email, 'msg' => $msg,
'msg' => $msg, 'template' => $template
'template' => $template ];
]; $result = Hook::listen('ems_notice', $params, null, true);
$result = Hook::listen('ems_notice', $params, null, true); return $result ? true : false;
return $result ? TRUE : FALSE; }
}
/**
/** * 校验验证码
* 校验验证码 *
* * @param int $email 邮箱
* @param int $email 邮箱 * @param int $code 验证码
* @param int $code 验证码 * @param string $event 事件
* @param string $event 事件 * @return boolean
* @return boolean */
*/ public static function check($email, $code, $event = 'default')
public static function check($email, $code, $event = 'default') {
{ $time = time() - self::$expire;
$time = time() - self::$expire; $ems = \app\common\model\Ems::where(['email' => $email, 'event' => $event])
$ems = \app\common\model\Ems::where(['email' => $email, 'event' => $event]) ->order('id', 'DESC')
->order('id', 'DESC') ->find();
->find(); if ($ems) {
if ($ems) if ($ems['createtime'] > $time && $ems['times'] <= self::$maxCheckNums) {
{ $correct = $code == $ems['code'];
if ($ems['createtime'] > $time && $ems['times'] <= self::$maxCheckNums) if (!$correct) {
{ $ems->times = $ems->times + 1;
$correct = $code == $ems['code']; $ems->save();
if (!$correct) return false;
{ } else {
$ems->times = $ems->times + 1; $result = Hook::listen('ems_check', $ems, null, true);
$ems->save(); return true;
return FALSE; }
} } else {
else // 过期则清空该邮箱验证码
{ self::flush($email, $event);
$result = Hook::listen('ems_check', $ems, null, true); return false;
return TRUE; }
} } else {
} return false;
else }
{ }
// 过期则清空该邮箱验证码
self::flush($email, $event); /**
return FALSE; * 清空指定邮箱验证码
} *
} * @param int $email 邮箱
else * @param string $event 事件
{ * @return boolean
return FALSE; */
} public static function flush($email, $event = 'default')
} {
\app\common\model\Ems::
/** where(['email' => $email, 'event' => $event])
* 清空指定邮箱验证码 ->delete();
* Hook::listen('ems_flush');
* @param int $email 邮箱 return true;
* @param string $event 事件 }
* @return boolean }
*/
public static function flush($email, $event = 'default')
{
\app\common\model\Ems::
where(['email' => $email, 'event' => $event])
->delete();
Hook::listen('ems_flush');
return TRUE;
}
}

View File

@ -17,18 +17,14 @@ class Menu
*/ */
public static function create($menu, $parent = 0) public static function create($menu, $parent = 0)
{ {
if (!is_numeric($parent)) if (!is_numeric($parent)) {
{
$parentRule = AuthRule::getByName($parent); $parentRule = AuthRule::getByName($parent);
$pid = $parentRule ? $parentRule['id'] : 0; $pid = $parentRule ? $parentRule['id'] : 0;
} } else {
else
{
$pid = $parent; $pid = $parent;
} }
$allow = array_flip(['file', 'name', 'title', 'icon', 'condition', 'remark', 'ismenu']); $allow = array_flip(['file', 'name', 'title', 'icon', 'condition', 'remark', 'ismenu']);
foreach ($menu as $k => $v) foreach ($menu as $k => $v) {
{
$hasChild = isset($v['sublist']) && $v['sublist'] ? true : false; $hasChild = isset($v['sublist']) && $v['sublist'] ? true : false;
$data = array_intersect_key($v, $allow); $data = array_intersect_key($v, $allow);
@ -37,16 +33,12 @@ class Menu
$data['icon'] = isset($data['icon']) ? $data['icon'] : ($hasChild ? 'fa fa-list' : 'fa fa-circle-o'); $data['icon'] = isset($data['icon']) ? $data['icon'] : ($hasChild ? 'fa fa-list' : 'fa fa-circle-o');
$data['pid'] = $pid; $data['pid'] = $pid;
$data['status'] = 'normal'; $data['status'] = 'normal';
try try {
{
$menu = AuthRule::create($data); $menu = AuthRule::create($data);
if ($hasChild) if ($hasChild) {
{
self::create($v['sublist'], $menu->id); self::create($v['sublist'], $menu->id);
} }
} } catch (PDOException $e) {
catch (PDOException $e)
{
throw new Exception($e->getMessage()); throw new Exception($e->getMessage());
} }
} }
@ -54,14 +46,13 @@ class Menu
/** /**
* 删除菜单 * 删除菜单
* @param string $name 规则name * @param string $name 规则name
* @return boolean * @return boolean
*/ */
public static function delete($name) public static function delete($name)
{ {
$ids = self::getAuthRuleIdsByName($name); $ids = self::getAuthRuleIdsByName($name);
if (!$ids) if (!$ids) {
{
return false; return false;
} }
AuthRule::destroy($ids); AuthRule::destroy($ids);
@ -76,8 +67,7 @@ class Menu
public static function enable($name) public static function enable($name)
{ {
$ids = self::getAuthRuleIdsByName($name); $ids = self::getAuthRuleIdsByName($name);
if (!$ids) if (!$ids) {
{
return false; return false;
} }
AuthRule::where('id', 'in', $ids)->update(['status' => 'normal']); AuthRule::where('id', 'in', $ids)->update(['status' => 'normal']);
@ -92,8 +82,7 @@ class Menu
public static function disable($name) public static function disable($name)
{ {
$ids = self::getAuthRuleIdsByName($name); $ids = self::getAuthRuleIdsByName($name);
if (!$ids) if (!$ids) {
{
return false; return false;
} }
AuthRule::where('id', 'in', $ids)->update(['status' => 'hidden']); AuthRule::where('id', 'in', $ids)->update(['status' => 'hidden']);
@ -108,14 +97,12 @@ class Menu
public static function export($name) public static function export($name)
{ {
$ids = self::getAuthRuleIdsByName($name); $ids = self::getAuthRuleIdsByName($name);
if (!$ids) if (!$ids) {
{
return []; return [];
} }
$menuList = []; $menuList = [];
$menu = AuthRule::getByName($name); $menu = AuthRule::getByName($name);
if ($menu) if ($menu) {
{
$ruleList = collection(AuthRule::where('id', 'in', $ids)->select())->toArray(); $ruleList = collection(AuthRule::where('id', 'in', $ids)->select())->toArray();
$menuList = Tree::instance()->init($ruleList)->getTreeArray($menu['id']); $menuList = Tree::instance()->init($ruleList)->getTreeArray($menu['id']);
} }
@ -131,8 +118,7 @@ class Menu
{ {
$ids = []; $ids = [];
$menu = AuthRule::getByName($name); $menu = AuthRule::getByName($name);
if ($menu) if ($menu) {
{
// 必须将结果集转换为数组 // 必须将结果集转换为数组
$ruleList = collection(AuthRule::order('weigh', 'desc')->field('id,pid,name')->select())->toArray(); $ruleList = collection(AuthRule::order('weigh', 'desc')->field('id,pid,name')->select())->toArray();
// 构造菜单数据 // 构造菜单数据

View File

@ -1,144 +1,133 @@
<?php <?php
namespace app\common\library; namespace app\common\library;
use think\Hook; use think\Hook;
/** /**
* 短信验证码类 * 短信验证码类
*/ */
class Sms class Sms
{ {
/** /**
* 验证码有效时长 * 验证码有效时长
* @var int * @var int
*/ */
protected static $expire = 120; protected static $expire = 120;
/** /**
* 最大允许检测的次数 * 最大允许检测的次数
* @var int * @var int
*/ */
protected static $maxCheckNums = 10; protected static $maxCheckNums = 10;
/** /**
* 获取最后一次手机发送的数据 * 获取最后一次手机发送的数据
* *
* @param int $mobile 手机号 * @param int $mobile 手机号
* @param string $event 事件 * @param string $event 事件
* @return Sms * @return Sms
*/ */
public static function get($mobile, $event = 'default') public static function get($mobile, $event = 'default')
{ {
$sms = \app\common\model\Sms:: $sms = \app\common\model\Sms::
where(['mobile' => $mobile, 'event' => $event]) where(['mobile' => $mobile, 'event' => $event])
->order('id', 'DESC') ->order('id', 'DESC')
->find(); ->find();
Hook::listen('sms_get', $sms, null, true); Hook::listen('sms_get', $sms, null, true);
return $sms ? $sms : NULL; return $sms ? $sms : null;
} }
/** /**
* 发送验证码 * 发送验证码
* *
* @param int $mobile 手机号 * @param int $mobile 手机号
* @param int $code 验证码,为空时将自动生成4位数字 * @param int $code 验证码,为空时将自动生成4位数字
* @param string $event 事件 * @param string $event 事件
* @return boolean * @return boolean
*/ */
public static function send($mobile, $code = NULL, $event = 'default') public static function send($mobile, $code = null, $event = 'default')
{ {
$code = is_null($code) ? mt_rand(1000, 9999) : $code; $code = is_null($code) ? mt_rand(1000, 9999) : $code;
$time = time(); $time = time();
$ip = request()->ip(); $ip = request()->ip();
$sms = \app\common\model\Sms::create(['event' => $event, 'mobile' => $mobile, 'code' => $code, 'ip' => $ip, 'createtime' => $time]); $sms = \app\common\model\Sms::create(['event' => $event, 'mobile' => $mobile, 'code' => $code, 'ip' => $ip, 'createtime' => $time]);
$result = Hook::listen('sms_send', $sms, null, true); $result = Hook::listen('sms_send', $sms, null, true);
if (!$result) if (!$result) {
{ $sms->delete();
$sms->delete(); return false;
return FALSE; }
} return true;
return TRUE; }
}
/**
/** * 发送通知
* 发送通知 *
* * @param mixed $mobile 手机号,多个以,分隔
* @param mixed $mobile 手机号,多个以,分隔 * @param string $msg 消息内容
* @param string $msg 消息内容 * @param string $template 消息模板
* @param string $template 消息模板 * @return boolean
* @return boolean */
*/ public static function notice($mobile, $msg = '', $template = null)
public static function notice($mobile, $msg = '', $template = NULL) {
{ $params = [
$params = [ 'mobile' => $mobile,
'mobile' => $mobile, 'msg' => $msg,
'msg' => $msg, 'template' => $template
'template' => $template ];
]; $result = Hook::listen('sms_notice', $params, null, true);
$result = Hook::listen('sms_notice', $params, null, true); return $result ? true : false;
return $result ? TRUE : FALSE; }
}
/**
/** * 校验验证码
* 校验验证码 *
* * @param int $mobile 手机号
* @param int $mobile 手机号 * @param int $code 验证码
* @param int $code 验证码 * @param string $event 事件
* @param string $event 事件 * @return boolean
* @return boolean */
*/ public static function check($mobile, $code, $event = 'default')
public static function check($mobile, $code, $event = 'default') {
{ $time = time() - self::$expire;
$time = time() - self::$expire; $sms = \app\common\model\Sms::where(['mobile' => $mobile, 'event' => $event])
$sms = \app\common\model\Sms::where(['mobile' => $mobile, 'event' => $event]) ->order('id', 'DESC')
->order('id', 'DESC') ->find();
->find(); if ($sms) {
if ($sms) if ($sms['createtime'] > $time && $sms['times'] <= self::$maxCheckNums) {
{ $correct = $code == $sms['code'];
if ($sms['createtime'] > $time && $sms['times'] <= self::$maxCheckNums) if (!$correct) {
{ $sms->times = $sms->times + 1;
$correct = $code == $sms['code']; $sms->save();
if (!$correct) return false;
{ } else {
$sms->times = $sms->times + 1; $result = Hook::listen('sms_check', $sms, null, true);
$sms->save(); return $result;
return FALSE; }
} } else {
else // 过期则清空该手机验证码
{ self::flush($mobile, $event);
$result = Hook::listen('sms_check', $sms, null, true); return false;
return $result; }
} } else {
} return false;
else }
{ }
// 过期则清空该手机验证码
self::flush($mobile, $event); /**
return FALSE; * 清空指定手机号验证码
} *
} * @param int $mobile 手机号
else * @param string $event 事件
{ * @return boolean
return FALSE; */
} public static function flush($mobile, $event = 'default')
} {
\app\common\model\Sms::
/** where(['mobile' => $mobile, 'event' => $event])
* 清空指定手机号验证码 ->delete();
* Hook::listen('sms_flush');
* @param int $mobile 手机号 return true;
* @param string $event 事件 }
* @return boolean }
*/
public static function flush($mobile, $event = 'default')
{
\app\common\model\Sms::
where(['mobile' => $mobile, 'event' => $event])
->delete();
Hook::listen('sms_flush');
return TRUE;
}
}

View File

@ -25,8 +25,8 @@ class Token
/** /**
* 连接Token驱动 * 连接Token驱动
* @access public * @access public
* @param array $options 配置数组 * @param array $options 配置数组
* @param bool|string $name Token连接标识 true 强制重新连接 * @param bool|string $name Token连接标识 true 强制重新连接
* @return Driver * @return Driver
*/ */
public static function connect(array $options = [], $name = false) public static function connect(array $options = [], $name = false)
@ -102,8 +102,8 @@ class Token
/** /**
* 读取Token * 读取Token
* @access public * @access public
* @param string $token Token标识 * @param string $token Token标识
* @param mixed $default 默认值 * @param mixed $default 默认值
* @return mixed * @return mixed
*/ */
public static function get($token, $default = false) public static function get($token, $default = false)
@ -114,9 +114,9 @@ class Token
/** /**
* 写入Token * 写入Token
* @access public * @access public
* @param string $token Token标识 * @param string $token Token标识
* @param mixed $user_id 存储数据 * @param mixed $user_id 存储数据
* @param int|null $expire 有效时间 0为永久 * @param int|null $expire 有效时间 0为永久
* @return boolean * @return boolean
*/ */
public static function set($token, $user_id, $expire = null) public static function set($token, $user_id, $expire = null)

View File

@ -21,9 +21,9 @@ abstract class Driver
/** /**
* 存储Token * 存储Token
* @param string $token Token * @param string $token Token
* @param int $user_id 会员ID * @param int $user_id 会员ID
* @param int $expire 过期时长,0表示无限,单位秒 * @param int $expire 过期时长,0表示无限,单位秒
* @return bool * @return bool
*/ */
abstract function set($token, $user_id, $expire = 0); abstract function set($token, $user_id, $expire = 0);
@ -37,8 +37,8 @@ abstract class Driver
/** /**
* 判断Token是否可用 * 判断Token是否可用
* @param string $token Token * @param string $token Token
* @param int $user_id 会员ID * @param int $user_id 会员ID
* @return boolean * @return boolean
*/ */
abstract function check($token, $user_id); abstract function check($token, $user_id);

View File

@ -40,9 +40,9 @@ class Mysql extends Driver
/** /**
* 存储Token * 存储Token
* @param string $token Token * @param string $token Token
* @param int $user_id 会员ID * @param int $user_id 会员ID
* @param int $expire 过期时长,0表示无限,单位秒 * @param int $expire 过期时长,0表示无限,单位秒
* @return bool * @return bool
*/ */
public function set($token, $user_id, $expire = null) public function set($token, $user_id, $expire = null)
@ -77,8 +77,8 @@ class Mysql extends Driver
/** /**
* 判断Token是否可用 * 判断Token是否可用
* @param string $token Token * @param string $token Token
* @param int $user_id 会员ID * @param int $user_id 会员ID
* @return boolean * @return boolean
*/ */
public function check($token, $user_id) public function check($token, $user_id)

View File

@ -75,9 +75,9 @@ class Redis extends Driver
/** /**
* 存储Token * 存储Token
* @param string $token Token * @param string $token Token
* @param int $user_id 会员ID * @param int $user_id 会员ID
* @param int $expire 过期时长,0表示无限,单位秒 * @param int $expire 过期时长,0表示无限,单位秒
* @return bool * @return bool
*/ */
public function set($token, $user_id, $expire = 0) public function set($token, $user_id, $expire = 0)
@ -123,8 +123,8 @@ class Redis extends Driver
/** /**
* 判断Token是否可用 * 判断Token是否可用
* @param string $token Token * @param string $token Token
* @param int $user_id 会员ID * @param int $user_id 会员ID
* @return boolean * @return boolean
*/ */
public function check($token, $user_id) public function check($token, $user_id)

View File

@ -7,7 +7,7 @@ use think\Model;
/** /**
* 分类模型 * 分类模型
*/ */
class Category Extends Model class Category extends Model
{ {
// 开启自动写入时间戳字段 // 开启自动写入时间戳字段
@ -40,8 +40,7 @@ class Category Extends Model
public static function getTypeList() public static function getTypeList()
{ {
$typeList = config('site.categorytype'); $typeList = config('site.categorytype');
foreach ($typeList as $k => &$v) foreach ($typeList as $k => &$v) {
{
$v = __($v); $v = __($v);
} }
return $typeList; return $typeList;
@ -69,23 +68,20 @@ class Category Extends Model
/** /**
* 读取分类列表 * 读取分类列表
* @param string $type 指定类型 * @param string $type 指定类型
* @param string $status 指定状态 * @param string $status 指定状态
* @return array * @return array
*/ */
public static function getCategoryArray($type = NULL, $status = NULL) public static function getCategoryArray($type = null, $status = null)
{ {
$list = collection(self::where(function($query) use($type, $status) { $list = collection(self::where(function ($query) use ($type, $status) {
if (!is_null($type)) if (!is_null($type)) {
{ $query->where('type', '=', $type);
$query->where('type', '=', $type); }
} if (!is_null($status)) {
if (!is_null($status)) $query->where('status', '=', $status);
{ }
$query->where('status', '=', $status); })->order('weigh', 'desc')->select())->toArray();
}
})->order('weigh', 'desc')->select())->toArray();
return $list; return $list;
} }
} }

View File

@ -1,54 +1,50 @@
<?php <?php
namespace app\common\model; namespace app\common\model;
use think\Model; use think\Model;
class Version extends Model class Version extends Model
{ {
// 开启自动写入时间戳字段 // 开启自动写入时间戳字段
protected $autoWriteTimestamp = 'int'; protected $autoWriteTimestamp = 'int';
// 定义时间戳字段名 // 定义时间戳字段名
protected $createTime = 'createtime'; protected $createTime = 'createtime';
protected $updateTime = 'updatetime'; protected $updateTime = 'updatetime';
// 定义字段类型 // 定义字段类型
protected $type = [ protected $type = [
]; ];
/** /**
* 检测版本号 * 检测版本号
* *
* @param string $version 客户端版本号 * @param string $version 客户端版本号
* @return array * @return array
*/ */
public static function check($version) public static function check($version)
{ {
$versionlist = self::where('status', 'normal')->cache('__version__')->order('weigh desc,id desc')->select(); $versionlist = self::where('status', 'normal')->cache('__version__')->order('weigh desc,id desc')->select();
foreach ($versionlist as $k => $v) foreach ($versionlist as $k => $v) {
{ // 版本正常且新版本号不等于验证的版本号且找到匹配的旧版本
// 版本正常且新版本号不等于验证的版本号且找到匹配的旧版本 if ($v['status'] == 'normal' && $v['newversion'] !== $version && \fast\Version::check($version, $v['oldversion'])) {
if ($v['status'] == 'normal' && $v['newversion'] !== $version && \fast\Version::check($version, $v['oldversion'])) $updateversion = $v;
{ break;
$updateversion = $v; }
break; }
} if (isset($updateversion)) {
} $search = ['{version}', '{newversion}', '{downloadurl}', '{url}', '{packagesize}'];
if (isset($updateversion)) $replace = [$version, $updateversion['newversion'], $updateversion['downloadurl'], $updateversion['downloadurl'], $updateversion['packagesize']];
{ $upgradetext = str_replace($search, $replace, $updateversion['content']);
$search = ['{version}', '{newversion}', '{downloadurl}', '{url}', '{packagesize}']; return [
$replace = [$version, $updateversion['newversion'], $updateversion['downloadurl'], $updateversion['downloadurl'], $updateversion['packagesize']]; "enforce" => $updateversion['enforce'],
$upgradetext = str_replace($search, $replace, $updateversion['content']); "version" => $version,
return [ "newversion" => $updateversion['newversion'],
"enforce" => $updateversion['enforce'], "downloadurl" => $updateversion['downloadurl'],
"version" => $version, "packagesize" => $updateversion['packagesize'],
"newversion" => $updateversion['newversion'], "upgradetext" => $upgradetext
"downloadurl" => $updateversion['downloadurl'], ];
"packagesize" => $updateversion['packagesize'], }
"upgradetext" => $upgradetext return null;
]; }
} }
return NULL;
}
}

View File

@ -272,7 +272,7 @@ return [
//自动检测更新 //自动检测更新
'checkupdate' => false, 'checkupdate' => false,
//版本号 //版本号
'version' => '1.0.0.20190318_beta', 'version' => '1.0.0.20190407_beta',
//API接口地址 //API接口地址
'api_url' => 'https://api.fastadmin.net', 'api_url' => 'https://api.fastadmin.net',
], ],

View File

@ -12,11 +12,6 @@ class Index extends Frontend
protected $noNeedRight = '*'; protected $noNeedRight = '*';
protected $layout = ''; protected $layout = '';
public function _initialize()
{
parent::_initialize();
}
public function index() public function index()
{ {
return $this->view->fetch(); return $this->view->fetch();

View File

@ -61,7 +61,7 @@
<footer class="footer" style="clear:both"> <footer class="footer" style="clear:both">
<!-- FastAdmin是开源程序建议在您的网站底部保留一个FastAdmin的链接 --> <!-- FastAdmin是开源程序建议在您的网站底部保留一个FastAdmin的链接 -->
<p class="copyright">Copyright&nbsp;©&nbsp;2017-2018 Powered by <a href="https://www.fastadmin.net" target="_blank">FastAdmin</a> All Rights Reserved {$site.name} {:__('Copyrights')} <a href="http://www.miibeian.gov.cn" target="_blank">{$site.beian}</a></p> <p class="copyright">Copyright&nbsp;©&nbsp;2017-2019 Powered by <a href="https://www.fastadmin.net" target="_blank">FastAdmin</a> All Rights Reserved {$site.name} {:__('Copyrights')} <a href="http://www.miibeian.gov.cn" target="_blank">{$site.beian}</a></p>
</footer> </footer>
{include file="common/script" /} {include file="common/script" /}

View File

@ -36,7 +36,7 @@
<div class="form-body"> <div class="form-body">
<input type="hidden" name="action" value="resetpwd" /> <input type="hidden" name="action" value="resetpwd" />
<div class="form-group"> <div class="form-group">
<label for="" class="control-label col-xs-12 col-sm-3">{:__('Type')}:</label> <label class="control-label col-xs-12 col-sm-3">{:__('Type')}:</label>
<div class="col-xs-12 col-sm-8"> <div class="col-xs-12 col-sm-8">
<div class="radio"> <div class="radio">
<label for="type-email"><input id="type-email" checked="checked" name="type" data-send-url="{:url('api/ems/send')}" data-check-url="{:url('api/validate/check_ems_correct')}" type="radio" value="email"> {:__('Reset password by email')}</label> <label for="type-email"><input id="type-email" checked="checked" name="type" data-send-url="{:url('api/ems/send')}" data-check-url="{:url('api/validate/check_ems_correct')}" type="radio" value="email"> {:__('Reset password by email')}</label>

View File

@ -39,7 +39,7 @@
<h2 class="page-header">{:__('Profile')}</h2> <h2 class="page-header">{:__('Profile')}</h2>
<form id="profile-form" class="form-horizontal" role="form" data-toggle="validator" method="POST" action="{:url('api/user/profile')}"> <form id="profile-form" class="form-horizontal" role="form" data-toggle="validator" method="POST" action="{:url('api/user/profile')}">
{:token()} {:token()}
<input type="hidden" name="avatar" id="c-avatar" value="{$user.avatar}" /> <input type="hidden" name="avatar" id="c-avatar" value="{:$user->getData('avatar')}" />
<div class="form-group"> <div class="form-group">
<label class="control-label col-xs-12 col-sm-2"></label> <label class="control-label col-xs-12 col-sm-2"></label>
<div class="col-xs-12 col-sm-4"> <div class="col-xs-12 col-sm-4">

View File

@ -56,14 +56,9 @@ class Auth
'auth_user' => 'user', // 用户信息表 'auth_user' => 'user', // 用户信息表
]; ];
/**
* 类架构函数
* Auth constructor.
*/
public function __construct() public function __construct()
{ {
if ($auth = Config::get('auth')) if ($auth = Config::get('auth')) {
{
$this->config = array_merge($this->config, $auth); $this->config = array_merge($this->config, $auth);
} }
// 初始化request // 初始化request
@ -78,8 +73,7 @@ class Auth
*/ */
public static function instance($options = []) public static function instance($options = [])
{ {
if (is_null(self::$instance)) if (is_null(self::$instance)) {
{
self::$instance = new static($options); self::$instance = new static($options);
} }
@ -88,69 +82,56 @@ class Auth
/** /**
* 检查权限 * 检查权限
* @param $name string|array 需要验证的规则列表,支持逗号分隔的权限规则或索引数组 * @param string|array $name 需要验证的规则列表,支持逗号分隔的权限规则或索引数组
* @param $uid int 认证用户的id * @param int $uid 认证用户的id
* @param string $relation 如果为 'or' 表示满足任一条规则即通过验证;如果为 'and'则表示需满足所有规则才能通过验证 * @param string $relation 如果为 'or' 表示满足任一条规则即通过验证;如果为 'and'则表示需满足所有规则才能通过验证
* @param string $mode 执行验证的模式,可分为url,normal * @param string $mode 执行验证的模式,可分为url,normal
* @return bool 通过验证返回true;失败返回false * @return bool 通过验证返回true;失败返回false
*/ */
public function check($name, $uid, $relation = 'or', $mode = 'url') public function check($name, $uid, $relation = 'or', $mode = 'url')
{ {
if (!$this->config['auth_on']) if (!$this->config['auth_on']) {
{
return true; return true;
} }
// 获取用户需要验证的所有有效规则列表 // 获取用户需要验证的所有有效规则列表
$rulelist = $this->getRuleList($uid); $rulelist = $this->getRuleList($uid);
if (in_array('*', $rulelist)) if (in_array('*', $rulelist)) {
return true; return true;
}
if (is_string($name)) if (is_string($name)) {
{
$name = strtolower($name); $name = strtolower($name);
if (strpos($name, ',') !== false) if (strpos($name, ',') !== false) {
{
$name = explode(',', $name); $name = explode(',', $name);
} } else {
else
{
$name = [$name]; $name = [$name];
} }
} }
$list = []; //保存验证通过的规则名 $list = []; //保存验证通过的规则名
if ('url' == $mode) if ('url' == $mode) {
{
$REQUEST = unserialize(strtolower(serialize($this->request->param()))); $REQUEST = unserialize(strtolower(serialize($this->request->param())));
} }
foreach ($rulelist as $rule) foreach ($rulelist as $rule) {
{
$query = preg_replace('/^.+\?/U', '', $rule); $query = preg_replace('/^.+\?/U', '', $rule);
if ('url' == $mode && $query != $rule) if ('url' == $mode && $query != $rule) {
{
parse_str($query, $param); //解析规则中的param parse_str($query, $param); //解析规则中的param
$intersect = array_intersect_assoc($REQUEST, $param); $intersect = array_intersect_assoc($REQUEST, $param);
$rule = preg_replace('/\?.*$/U', '', $rule); $rule = preg_replace('/\?.*$/U', '', $rule);
if (in_array($rule, $name) && $intersect == $param) if (in_array($rule, $name) && $intersect == $param) {
{
//如果节点相符且url参数满足 //如果节点相符且url参数满足
$list[] = $rule; $list[] = $rule;
} }
} } else {
else if (in_array($rule, $name)) {
{
if (in_array($rule, $name))
{
$list[] = $rule; $list[] = $rule;
} }
} }
} }
if ('or' == $relation && !empty($list)) if ('or' == $relation && !empty($list)) {
{
return true; return true;
} }
$diff = array_diff($name, $list); $diff = array_diff($name, $list);
if ('and' == $relation && empty($diff)) if ('and' == $relation && empty($diff)) {
{
return true; return true;
} }
@ -159,51 +140,47 @@ class Auth
/** /**
* 根据用户id获取用户组,返回值为数组 * 根据用户id获取用户组,返回值为数组
* @param $uid int 用户id * @param int $uid 用户id
* @return array 用户所属的用户组 array( * @return array 用户所属的用户组 array(
* array('uid'=>'用户id','group_id'=>'用户组id','name'=>'用户组名称','rules'=>'用户组拥有的规则id,多个,号隔开'), * array('uid'=>'用户id','group_id'=>'用户组id','name'=>'用户组名称','rules'=>'用户组拥有的规则id,多个,号隔开'),
* ...) * ...)
*/ */
public function getGroups($uid) public function getGroups($uid)
{ {
static $groups = []; static $groups = [];
if (isset($groups[$uid])) if (isset($groups[$uid])) {
{
return $groups[$uid]; return $groups[$uid];
} }
// 执行查询 // 执行查询
$user_groups = Db::name($this->config['auth_group_access']) $user_groups = Db::name($this->config['auth_group_access'])
->alias('aga') ->alias('aga')
->join('__' . strtoupper($this->config['auth_group']) . '__ ag', 'aga.group_id = ag.id', 'LEFT') ->join('__' . strtoupper($this->config['auth_group']) . '__ ag', 'aga.group_id = ag.id', 'LEFT')
->field('aga.uid,aga.group_id,ag.id,ag.pid,ag.name,ag.rules') ->field('aga.uid,aga.group_id,ag.id,ag.pid,ag.name,ag.rules')
->where("aga.uid='{$uid}' and ag.status='normal'") ->where("aga.uid='{$uid}' and ag.status='normal'")
->select(); ->select();
$groups[$uid] = $user_groups ?: []; $groups[$uid] = $user_groups ?: [];
return $groups[$uid]; return $groups[$uid];
} }
/** /**
* 获得权限规则列表 * 获得权限规则列表
* @param integer $uid 用户id * @param int $uid 用户id
* @return array * @return array
*/ */
public function getRuleList($uid) public function getRuleList($uid)
{ {
static $_rulelist = []; //保存用户验证通过的权限列表 static $_rulelist = []; //保存用户验证通过的权限列表
if (isset($_rulelist[$uid])) if (isset($_rulelist[$uid])) {
{
return $_rulelist[$uid]; return $_rulelist[$uid];
} }
if (2 == $this->config['auth_type'] && Session::has('_rule_list_' . $uid)) if (2 == $this->config['auth_type'] && Session::has('_rule_list_' . $uid)) {
{
return Session::get('_rule_list_' . $uid); return Session::get('_rule_list_' . $uid);
} }
// 读取用户规则节点 // 读取用户规则节点
$ids = $this->getRuleIds($uid); $ids = $this->getRuleIds($uid);
if (empty($ids)) if (empty($ids)) {
{
$_rulelist[$uid] = []; $_rulelist[$uid] = [];
return []; return [];
} }
@ -212,8 +189,7 @@ class Auth
$where = [ $where = [
'status' => 'normal' 'status' => 'normal'
]; ];
if (!in_array('*', $ids)) if (!in_array('*', $ids)) {
{
$where['id'] = ['in', $ids]; $where['id'] = ['in', $ids];
} }
//读取用户组所有权限规则 //读取用户组所有权限规则
@ -221,34 +197,27 @@ class Auth
//循环规则,判断结果。 //循环规则,判断结果。
$rulelist = []; // $rulelist = []; //
if (in_array('*', $ids)) if (in_array('*', $ids)) {
{
$rulelist[] = "*"; $rulelist[] = "*";
} }
foreach ($this->rules as $rule) foreach ($this->rules as $rule) {
{
//超级管理员无需验证condition //超级管理员无需验证condition
if (!empty($rule['condition']) && !in_array('*', $ids)) if (!empty($rule['condition']) && !in_array('*', $ids)) {
{
//根据condition进行验证 //根据condition进行验证
$user = $this->getUserInfo($uid); //获取用户信息,一维数组 $user = $this->getUserInfo($uid); //获取用户信息,一维数组
$command = preg_replace('/\{(\w*?)\}/', '$user[\'\\1\']', $rule['condition']); $command = preg_replace('/\{(\w*?)\}/', '$user[\'\\1\']', $rule['condition']);
@(eval('$condition=(' . $command . ');')); @(eval('$condition=(' . $command . ');'));
if ($condition) if ($condition) {
{
$rulelist[$rule['id']] = strtolower($rule['name']); $rulelist[$rule['id']] = strtolower($rule['name']);
} }
} } else {
else
{
//只要存在就记录 //只要存在就记录
$rulelist[$rule['id']] = strtolower($rule['name']); $rulelist[$rule['id']] = strtolower($rule['name']);
} }
} }
$_rulelist[$uid] = $rulelist; $_rulelist[$uid] = $rulelist;
//登录验证则需要保存规则列表 //登录验证则需要保存规则列表
if (2 == $this->config['auth_type']) if (2 == $this->config['auth_type']) {
{
//规则列表结果保存到session //规则列表结果保存到session
Session::set('_rule_list_' . $uid, $rulelist); Session::set('_rule_list_' . $uid, $rulelist);
} }
@ -260,8 +229,7 @@ class Auth
//读取用户所属用户组 //读取用户所属用户组
$groups = $this->getGroups($uid); $groups = $this->getGroups($uid);
$ids = []; //保存用户所属用户组设置的所有权限规则id $ids = []; //保存用户所属用户组设置的所有权限规则id
foreach ($groups as $g) foreach ($groups as $g) {
{
$ids = array_merge($ids, explode(',', trim($g['rules'], ','))); $ids = array_merge($ids, explode(',', trim($g['rules'], ',')));
} }
$ids = array_unique($ids); $ids = array_unique($ids);
@ -270,7 +238,7 @@ class Auth
/** /**
* 获得用户资料 * 获得用户资料
* @param $uid * @param int $uid 用户id
* @return mixed * @return mixed
*/ */
protected function getUserInfo($uid) protected function getUserInfo($uid)
@ -280,12 +248,10 @@ class Auth
$user = Db::name($this->config['auth_user']); $user = Db::name($this->config['auth_user']);
// 获取用户表主键 // 获取用户表主键
$_pk = is_string($user->getPk()) ? $user->getPk() : 'uid'; $_pk = is_string($user->getPk()) ? $user->getPk() : 'uid';
if (!isset($user_info[$uid])) if (!isset($user_info[$uid])) {
{
$user_info[$uid] = $user->where($_pk, $uid)->find(); $user_info[$uid] = $user->where($_pk, $uid)->find();
} }
return $user_info[$uid]; return $user_info[$uid];
} }
}
}

View File

@ -7,7 +7,6 @@ namespace fast;
*/ */
class Date class Date
{ {
const YEAR = 31536000; const YEAR = 31536000;
const MONTH = 2592000; const MONTH = 2592000;
const WEEK = 604800; const WEEK = 604800;
@ -23,20 +22,18 @@ class Date
* [!!] A list of time zones that PHP supports can be found at * [!!] A list of time zones that PHP supports can be found at
* <http://php.net/timezones>. * <http://php.net/timezones>.
* *
* @param string $remote timezone that to find the offset of * @param string $remote timezone that to find the offset of
* @param string $local timezone used as the baseline * @param string $local timezone used as the baseline
* @param mixed $now UNIX timestamp or date string * @param mixed $now UNIX timestamp or date string
* @return integer * @return integer
*/ */
public static function offset($remote, $local = NULL, $now = NULL) public static function offset($remote, $local = null, $now = null)
{ {
if ($local === NULL) if ($local === null) {
{
// Use the default timezone // Use the default timezone
$local = date_default_timezone_get(); $local = date_default_timezone_get();
} }
if (is_int($now)) if (is_int($now)) {
{
// Convert the timestamp into a string // Convert the timestamp into a string
$now = date(DateTime::RFC2822, $now); $now = date(DateTime::RFC2822, $now);
} }
@ -57,21 +54,20 @@ class Date
* $span = self::span(60, 182, 'minutes,seconds'); // array('minutes' => 2, 'seconds' => 2) * $span = self::span(60, 182, 'minutes,seconds'); // array('minutes' => 2, 'seconds' => 2)
* $span = self::span(60, 182, 'minutes'); // 2 * $span = self::span(60, 182, 'minutes'); // 2
* *
* @param int $remote timestamp to find the span of * @param int $remote timestamp to find the span of
* @param int $local timestamp to use as the baseline * @param int $local timestamp to use as the baseline
* @param string $output formatting string * @param string $output formatting string
* @return string when only a single output is requested * @return string when only a single output is requested
* @return array associative list of all outputs requested * @return array associative list of all outputs requested
* @from https://github.com/kohana/ohanzee-helpers/blob/master/src/Date.php * @from https://github.com/kohana/ohanzee-helpers/blob/master/src/Date.php
*/ */
public static function span($remote, $local = NULL, $output = 'years,months,weeks,days,hours,minutes,seconds') public static function span($remote, $local = null, $output = 'years,months,weeks,days,hours,minutes,seconds')
{ {
// Normalize output // Normalize output
$output = trim(strtolower((string) $output)); $output = trim(strtolower((string)$output));
if (!$output) if (!$output) {
{
// Invalid output // Invalid output
return FALSE; return false;
} }
// Array with the output formats // Array with the output formats
$output = preg_split('/[^a-z]+/', $output); $output = preg_split('/[^a-z]+/', $output);
@ -79,44 +75,35 @@ class Date
$output = array_combine($output, array_fill(0, count($output), 0)); $output = array_combine($output, array_fill(0, count($output), 0));
// Make the output values into keys // Make the output values into keys
extract(array_flip($output), EXTR_SKIP); extract(array_flip($output), EXTR_SKIP);
if ($local === NULL) if ($local === null) {
{
// Calculate the span from the current time // Calculate the span from the current time
$local = time(); $local = time();
} }
// Calculate timespan (seconds) // Calculate timespan (seconds)
$timespan = abs($remote - $local); $timespan = abs($remote - $local);
if (isset($output['years'])) if (isset($output['years'])) {
{ $timespan -= self::YEAR * ($output['years'] = (int)floor($timespan / self::YEAR));
$timespan -= self::YEAR * ($output['years'] = (int) floor($timespan / self::YEAR));
} }
if (isset($output['months'])) if (isset($output['months'])) {
{ $timespan -= self::MONTH * ($output['months'] = (int)floor($timespan / self::MONTH));
$timespan -= self::MONTH * ($output['months'] = (int) floor($timespan / self::MONTH));
} }
if (isset($output['weeks'])) if (isset($output['weeks'])) {
{ $timespan -= self::WEEK * ($output['weeks'] = (int)floor($timespan / self::WEEK));
$timespan -= self::WEEK * ($output['weeks'] = (int) floor($timespan / self::WEEK));
} }
if (isset($output['days'])) if (isset($output['days'])) {
{ $timespan -= self::DAY * ($output['days'] = (int)floor($timespan / self::DAY));
$timespan -= self::DAY * ($output['days'] = (int) floor($timespan / self::DAY));
} }
if (isset($output['hours'])) if (isset($output['hours'])) {
{ $timespan -= self::HOUR * ($output['hours'] = (int)floor($timespan / self::HOUR));
$timespan -= self::HOUR * ($output['hours'] = (int) floor($timespan / self::HOUR));
} }
if (isset($output['minutes'])) if (isset($output['minutes'])) {
{ $timespan -= self::MINUTE * ($output['minutes'] = (int)floor($timespan / self::MINUTE));
$timespan -= self::MINUTE * ($output['minutes'] = (int) floor($timespan / self::MINUTE));
} }
// Seconds ago, 1 // Seconds ago, 1
if (isset($output['seconds'])) if (isset($output['seconds'])) {
{
$output['seconds'] = $timespan; $output['seconds'] = $timespan;
} }
if (count($output) === 1) if (count($output) === 1) {
{
// Only a single output was requested, return it // Only a single output was requested, return it
return array_pop($output); return array_pop($output);
} }
@ -127,10 +114,10 @@ class Date
/** /**
* 格式化 UNIX 时间戳为人易读的字符串 * 格式化 UNIX 时间戳为人易读的字符串
* *
* @param int Unix 时间戳 * @param int Unix 时间戳
* @param mixed $local 本地时间 * @param mixed $local 本地时间
* *
* @return string 格式化的日期字符串 * @return string 格式化的日期字符串
*/ */
public static function human($remote, $local = null) public static function human($remote, $local = null)
{ {
@ -145,12 +132,10 @@ class Date
array(1, 'second') array(1, 'second')
); );
for ($i = 0, $j = count($chunks); $i < $j; $i++) for ($i = 0, $j = count($chunks); $i < $j; $i++) {
{
$seconds = $chunks[$i][0]; $seconds = $chunks[$i][0];
$name = $chunks[$i][1]; $name = $chunks[$i][1];
if (($count = floor($timediff / $seconds)) != 0) if (($count = floor($timediff / $seconds)) != 0) {
{
break; break;
} }
} }
@ -160,14 +145,14 @@ class Date
/** /**
* 获取一个基于时间偏移的Unix时间戳 * 获取一个基于时间偏移的Unix时间戳
* *
* @param string $type 时间类型默认为day可选minute,hour,day,week,month,quarter,year * @param string $type 时间类型默认为day可选minute,hour,day,week,month,quarter,year
* @param int $offset 时间偏移量 默认为0正数表示当前type之后负数表示当前type之前 * @param int $offset 时间偏移量 默认为0正数表示当前type之后负数表示当前type之前
* @param string $position 时间的开始或结束默认为begin可选前(begin,start,first,front)end * @param string $position 时间的开始或结束默认为begin可选前(begin,start,first,front)end
* @param int $year 基准年默认为null即以当前年为基准 * @param int $year 基准年默认为null即以当前年为基准
* @param int $month 基准月默认为null即以当前月为基准 * @param int $month 基准月默认为null即以当前月为基准
* @param int $day 基准天默认为null即以当前天为基准 * @param int $day 基准天默认为null即以当前天为基准
* @param int $hour 基准小时默认为null即以当前年小时基准 * @param int $hour 基准小时默认为null即以当前年小时基准
* @param int $minute 基准分钟默认为null即以当前分钟为基准 * @param int $minute 基准分钟默认为null即以当前分钟为基准
* @return int 处理后的Unix时间戳 * @return int 处理后的Unix时间戳
*/ */
public static function unixtime($type = 'day', $offset = 0, $position = 'begin', $year = null, $month = null, $day = null, $hour = null, $minute = null) public static function unixtime($type = 'day', $offset = 0, $position = 'begin', $year = null, $month = null, $day = null, $hour = null, $minute = null)
@ -179,8 +164,7 @@ class Date
$minute = is_null($minute) ? date('i') : $minute; $minute = is_null($minute) ? date('i') : $minute;
$position = in_array($position, array('begin', 'start', 'first', 'front')); $position = in_array($position, array('begin', 'start', 'first', 'front'));
switch ($type) switch ($type) {
{
case 'minute': case 'minute':
$time = $position ? mktime($hour, $minute + $offset, 0, $month, $day, $year) : mktime($hour, $minute + $offset, 59, $month, $day, $year); $time = $position ? mktime($hour, $minute + $offset, 0, $month, $day, $year) : mktime($hour, $minute + $offset, 59, $month, $day, $year);
break; break;
@ -192,16 +176,16 @@ class Date
break; break;
case 'week': case 'week':
$time = $position ? $time = $position ?
mktime(0, 0, 0, $month, $day - date("w", mktime(0, 0, 0, $month, $day, $year)) + 1 - 7 * (-$offset), $year) : mktime(0, 0, 0, $month, $day - date("w", mktime(0, 0, 0, $month, $day, $year)) + 1 - 7 * (-$offset), $year) :
mktime(23, 59, 59, $month, $day - date("w", mktime(0, 0, 0, $month, $day, $year)) + 7 - 7 * (-$offset), $year); mktime(23, 59, 59, $month, $day - date("w", mktime(0, 0, 0, $month, $day, $year)) + 7 - 7 * (-$offset), $year);
break; break;
case 'month': case 'month':
$time = $position ? mktime(0, 0, 0, $month + $offset, 1, $year) : mktime(23, 59, 59, $month + $offset, cal_days_in_month(CAL_GREGORIAN, $month + $offset, $year), $year); $time = $position ? mktime(0, 0, 0, $month + $offset, 1, $year) : mktime(23, 59, 59, $month + $offset, cal_days_in_month(CAL_GREGORIAN, $month + $offset, $year), $year);
break; break;
case 'quarter': case 'quarter':
$time = $position ? $time = $position ?
mktime(0, 0, 0, 1 + ((ceil(date('n', mktime(0, 0, 0, $month, $day, $year)) / 3) + $offset) - 1) * 3, 1, $year) : mktime(0, 0, 0, 1 + ((ceil(date('n', mktime(0, 0, 0, $month, $day, $year)) / 3) + $offset) - 1) * 3, 1, $year) :
mktime(23, 59, 59, (ceil(date('n', mktime(0, 0, 0, $month, $day, $year)) / 3) + $offset) * 3, cal_days_in_month(CAL_GREGORIAN, (ceil(date('n', mktime(0, 0, 0, $month, $day, $year)) / 3) + $offset) * 3, $year), $year); mktime(23, 59, 59, (ceil(date('n', mktime(0, 0, 0, $month, $day, $year)) / 3) + $offset) * 3, cal_days_in_month(CAL_GREGORIAN, (ceil(date('n', mktime(0, 0, 0, $month, $day, $year)) / 3) + $offset) * 3, $year), $year);
break; break;
case 'year': case 'year':
$time = $position ? mktime(0, 0, 0, 1, 1, $year + $offset) : mktime(23, 59, 59, 12, 31, $year + $offset); $time = $position ? mktime(0, 0, 0, 1, 1, $year + $offset) : mktime(23, 59, 59, 12, 31, $year + $offset);
@ -212,5 +196,4 @@ class Date
} }
return $time; return $time;
} }
} }

View File

@ -6,7 +6,7 @@ use ArrayAccess;
/** /**
* 表单元素生成 * 表单元素生成
* @class Form * @class Form
* @package fast * @package fast
* @method string token() static 生成Token * @method string token() static 生成Token
* @method string label(string $name, string $value = null, array $options = []) static label标签 * @method string label(string $name, string $value = null, array $options = []) static label标签
@ -51,11 +51,6 @@ use ArrayAccess;
class Form class Form
{ {
public function __construct()
{
}
/** /**
* @param $name * @param $name
* @param $arguments * @param $arguments
@ -65,7 +60,6 @@ class Form
{ {
return call_user_func_array([FormBuilder::instance(), $name], $arguments); return call_user_func_array([FormBuilder::instance(), $name], $arguments);
} }
} }
/** /**
@ -105,11 +99,6 @@ class FormBuilder
protected $escapeHtml = true; protected $escapeHtml = true;
protected static $instance; protected static $instance;
public function __construct()
{
}
/** /**
* 获取单例 * 获取单例
* @param array $options * @param array $options
@ -170,7 +159,7 @@ class FormBuilder
* *
* @param string $name * @param string $name
* @param string $value * @param string $value
* @param array $options * @param array $options
* @return string * @return string
*/ */
public function label($name, $value = null, $options = []) public function label($name, $value = null, $options = [])
@ -186,7 +175,7 @@ class FormBuilder
/** /**
* Format the label value. * Format the label value.
* *
* @param string $name * @param string $name
* @param string|null $value * @param string|null $value
* @return string * @return string
*/ */
@ -201,13 +190,14 @@ class FormBuilder
* @param string $type * @param string $type
* @param string $name * @param string $name
* @param string $value * @param string $value
* @param array $options * @param array $options
* @return string * @return string
*/ */
public function input($type, $name, $value = null, $options = []) public function input($type, $name, $value = null, $options = [])
{ {
if (!isset($options['name'])) if (!isset($options['name'])) {
$options['name'] = $name; $options['name'] = $name;
}
$id = $this->getIdAttribute($name, $options); $id = $this->getIdAttribute($name, $options);
@ -227,7 +217,7 @@ class FormBuilder
* *
* @param string $name * @param string $name
* @param string $value * @param string $value
* @param array $options * @param array $options
* @return string * @return string
*/ */
public function text($name, $value = null, $options = []) public function text($name, $value = null, $options = [])
@ -239,7 +229,7 @@ class FormBuilder
* 生成密码文本框 * 生成密码文本框
* *
* @param string $name * @param string $name
* @param array $options * @param array $options
* @return string * @return string
*/ */
public function password($name, $options = []) public function password($name, $options = [])
@ -252,7 +242,7 @@ class FormBuilder
* *
* @param string $name * @param string $name
* @param string $value * @param string $value
* @param array $options * @param array $options
* @return string * @return string
*/ */
public function hidden($name, $value = null, $options = []) public function hidden($name, $value = null, $options = [])
@ -265,7 +255,7 @@ class FormBuilder
* *
* @param string $name * @param string $name
* @param string $value * @param string $value
* @param array $options * @param array $options
* @return string * @return string
*/ */
public function email($name, $value = null, $options = []) public function email($name, $value = null, $options = [])
@ -278,7 +268,7 @@ class FormBuilder
* *
* @param string $name * @param string $name
* @param string $value * @param string $value
* @param array $options * @param array $options
* @return string * @return string
*/ */
public function url($name, $value = null, $options = []) public function url($name, $value = null, $options = [])
@ -290,7 +280,7 @@ class FormBuilder
* 生成上传文件组件 * 生成上传文件组件
* *
* @param string $name * @param string $name
* @param array $options * @param array $options
* @return string * @return string
*/ */
public function file($name, $options = []) public function file($name, $options = [])
@ -303,13 +293,14 @@ class FormBuilder
* *
* @param string $name * @param string $name
* @param string $value * @param string $value
* @param array $options * @param array $options
* @return string * @return string
*/ */
public function textarea($name, $value = null, $options = []) public function textarea($name, $value = null, $options = [])
{ {
if (!isset($options['name'])) if (!isset($options['name'])) {
$options['name'] = $name; $options['name'] = $name;
}
$options = $this->setTextAreaSize($options); $options = $this->setTextAreaSize($options);
$options['id'] = $this->getIdAttribute($name, $options); $options['id'] = $this->getIdAttribute($name, $options);
@ -328,7 +319,7 @@ class FormBuilder
* *
* @param string $name * @param string $name
* @param string $value * @param string $value
* @param array $options * @param array $options
* @return string * @return string
*/ */
public function editor($name, $value = null, $options = []) public function editor($name, $value = null, $options = [])
@ -369,28 +360,29 @@ class FormBuilder
/** /**
* 生成滑块 * 生成滑块
* *
* @param string $name * @param string $name
* @param string $min * @param string $min
* @param string $max * @param string $max
* @param string $step * @param string $step
* @param string $value * @param string $value
* @param array $options * @param array $options
* @return string * @return string
*/ */
public function slider($name, $min, $max, $step, $value = null, $options = []) public function slider($name, $min, $max, $step, $value = null, $options = [])
{ {
$options = array_merge($options, ['data-slider-min' => $min, 'data-slider-max' => $max, 'data-slider-step' => $step,'data-slider-value' => $value ? $value : '']); $options = array_merge($options, ['data-slider-min' => $min, 'data-slider-max' => $max, 'data-slider-step' => $step, 'data-slider-value' => $value ? $value : '']);
$options['class'] = isset($options['class']) ? $options['class'] . (stripos($options['class'], 'form-control') !== false ? '' : ' slider form-control') : 'slider form-control'; $options['class'] = isset($options['class']) ? $options['class'] . (stripos($options['class'], 'form-control') !== false ? '' : ' slider form-control') : 'slider form-control';
return $this->input('text', $name, $value, $options); return $this->input('text', $name, $value, $options);
} }
/** /**
* 生成下拉列表框 * 生成下拉列表框
* *
* @param string $name * @param string $name
* @param array $list * @param array $list
* @param mixed $selected * @param mixed $selected
* @param array $options * @param array $options
* @return string * @return string
*/ */
public function select($name, $list = [], $selected = null, $options = []) public function select($name, $list = [], $selected = null, $options = [])
@ -399,8 +391,9 @@ class FormBuilder
$options['id'] = $this->getIdAttribute($name, $options); $options['id'] = $this->getIdAttribute($name, $options);
if (!isset($options['name'])) if (!isset($options['name'])) {
$options['name'] = $name; $options['name'] = $name;
}
$html = []; $html = [];
foreach ($list as $value => $display) { foreach ($list as $value => $display) {
@ -418,9 +411,9 @@ class FormBuilder
* 下拉列表(多选) * 下拉列表(多选)
* *
* @param string $name * @param string $name
* @param array $list * @param array $list
* @param mixed $selected * @param mixed $selected
* @param array $options * @param array $options
* @return string * @return string
*/ */
public function selects($name, $list = [], $selected = null, $options = []) public function selects($name, $list = [], $selected = null, $options = [])
@ -433,9 +426,9 @@ class FormBuilder
* 下拉列表(友好) * 下拉列表(友好)
* *
* @param string $name * @param string $name
* @param array $list * @param array $list
* @param mixed $selected * @param mixed $selected
* @param array $options * @param array $options
* @return string * @return string
*/ */
public function selectpicker($name, $list = [], $selected = null, $options = []) public function selectpicker($name, $list = [], $selected = null, $options = [])
@ -448,9 +441,9 @@ class FormBuilder
* 下拉列表(友好)(多选) * 下拉列表(友好)(多选)
* *
* @param string $name * @param string $name
* @param array $list * @param array $list
* @param mixed $selected * @param mixed $selected
* @param array $options * @param array $options
* @return string * @return string
*/ */
public function selectpickers($name, $list = [], $selected = null, $options = []) public function selectpickers($name, $list = [], $selected = null, $options = [])
@ -462,12 +455,12 @@ class FormBuilder
/** /**
* 生成动态下拉列表 * 生成动态下拉列表
* *
* @param string $name 名称 * @param string $name 名称
* @param mixed $value * @param mixed $value
* @param string $url 数据源地址 * @param string $url 数据源地址
* @param string $field 显示的字段名称,默认为name * @param string $field 显示的字段名称,默认为name
* @param string $primaryKey 主键,数据库中保存的值,默认为id * @param string $primaryKey 主键,数据库中保存的值,默认为id
* @param array $options * @param array $options
* @return string * @return string
*/ */
public function selectpage($name, $value, $url, $field = null, $primaryKey = null, $options = []) public function selectpage($name, $value, $url, $field = null, $primaryKey = null, $options = [])
@ -481,12 +474,12 @@ class FormBuilder
/** /**
* 生成动态下拉列表(复选) * 生成动态下拉列表(复选)
* *
* @param string $name 名称 * @param string $name 名称
* @param mixed $value * @param mixed $value
* @param string $url 数据源地址 * @param string $url 数据源地址
* @param string $field 显示的字段名称,默认为name * @param string $field 显示的字段名称,默认为name
* @param string $primaryKey 主键,数据库中保存的值,默认为id * @param string $primaryKey 主键,数据库中保存的值,默认为id
* @param array $options * @param array $options
* @return string * @return string
*/ */
public function selectpages($name, $value, $url, $field = null, $primaryKey = null, $options = []) public function selectpages($name, $value, $url, $field = null, $primaryKey = null, $options = [])
@ -499,8 +492,8 @@ class FormBuilder
* 生成城市选择框 * 生成城市选择框
* *
* @param string $name * @param string $name
* @param mixed $value * @param mixed $value
* @param array $options * @param array $options
* @return string * @return string
*/ */
public function citypicker($name, $value, $options = []) public function citypicker($name, $value, $options = [])
@ -513,8 +506,8 @@ class FormBuilder
* 生成switch组件 * 生成switch组件
* *
* @param string $name * @param string $name
* @param mixed $value * @param mixed $value
* @param array $options * @param array $options
* @return string * @return string
*/ */
public function switcher($name, $value, $options = []) public function switcher($name, $value, $options = [])
@ -542,8 +535,8 @@ EOD;
/** /**
* 日期选择器 * 日期选择器
* @param string $name * @param string $name
* @param mixed $value * @param mixed $value
* @param array $options * @param array $options
* @return string * @return string
*/ */
public function datepicker($name, $value, $options = []) public function datepicker($name, $value, $options = [])
@ -560,8 +553,8 @@ EOD;
* 时间选择器 * 时间选择器
* *
* @param string $name * @param string $name
* @param mixed $value * @param mixed $value
* @param array $options * @param array $options
* @return string * @return string
*/ */
public function timepicker($name, $value, $options = []) public function timepicker($name, $value, $options = [])
@ -578,8 +571,8 @@ EOD;
* 日期时间选择器 * 日期时间选择器
* *
* @param string $name * @param string $name
* @param mixed $value * @param mixed $value
* @param array $options * @param array $options
* @return string * @return string
*/ */
public function datetimepicker($name, $value, $options = []) public function datetimepicker($name, $value, $options = [])
@ -599,7 +592,7 @@ EOD;
* *
* @param string $name * @param string $name
* @param string $value * @param string $value
* @param array $options * @param array $options
* @return string * @return string
*/ */
public function daterange($name, $value, $options = []) public function daterange($name, $value, $options = [])
@ -618,7 +611,7 @@ EOD;
* *
* @param string $name * @param string $name
* @param string $value * @param string $value
* @param array $options * @param array $options
* @return string * @return string
*/ */
public function timerange($name, $value, $options = []) public function timerange($name, $value, $options = [])
@ -640,7 +633,7 @@ EOD;
* *
* @param string $name * @param string $name
* @param string $value * @param string $value
* @param array $options * @param array $options
* @return string * @return string
*/ */
public function datetimerange($name, $value, $options = []) public function datetimerange($name, $value, $options = [])
@ -659,10 +652,10 @@ EOD;
* 生成字段列表组件 * 生成字段列表组件
* *
* @param string $name * @param string $name
* @param mixed $value * @param mixed $value
* @param array $title * @param array $title
* @param string $template * @param string $template
* @param array $options * @param array $options
* @return string * @return string
*/ */
public function fieldlist($name, $value, $title = null, $template = null, $options = []) public function fieldlist($name, $value, $title = null, $template = null, $options = [])
@ -692,10 +685,10 @@ EOD;
/** /**
* 生成联动下拉列表 * 生成联动下拉列表
* *
* @param string $url 联动获取数据源的URL地址 * @param string $url 联动获取数据源的URL地址
* @param array $names 联动字段名称 * @param array $names 联动字段名称
* @param array $values 联动字段默认选中的值 * @param array $values 联动字段默认选中的值
* @param array $options 扩展属性 * @param array $options 扩展属性
* @return string * @return string
*/ */
public function cxselect($url, $names = [], $values = [], $options = []) public function cxselect($url, $names = [], $values = [], $options = [])
@ -730,7 +723,7 @@ EOD;
* @param string $begin * @param string $begin
* @param string $end * @param string $end
* @param string $selected * @param string $selected
* @param array $options * @param array $options
* @return string * @return string
*/ */
public function selectRange($name, $begin, $end, $selected = null, $options = []) public function selectRange($name, $begin, $end, $selected = null, $options = [])
@ -746,7 +739,7 @@ EOD;
* @param string $begin * @param string $begin
* @param string $end * @param string $end
* @param string $selected * @param string $selected
* @param array $options * @param array $options
* @return string * @return string
*/ */
public function selectYear($name, $begin, $end, $selected, $options) public function selectYear($name, $begin, $end, $selected, $options)
@ -759,7 +752,7 @@ EOD;
* *
* @param string $name * @param string $name
* @param string $selected * @param string $selected
* @param array $options * @param array $options
* @param string $format * @param string $format
* @return string * @return string
*/ */
@ -794,7 +787,7 @@ EOD;
/** /**
* 生成optionGroup * 生成optionGroup
* *
* @param array $list * @param array $list
* @param string $label * @param string $label
* @param string $selected * @param string $selected
* @return string * @return string
@ -847,15 +840,16 @@ EOD;
* 生成复选按钮 * 生成复选按钮
* *
* @param string $name * @param string $name
* @param mixed $value * @param mixed $value
* @param bool $checked * @param bool $checked
* @param array $options * @param array $options
* @return string * @return string
*/ */
public function checkbox($name, $value = 1, $checked = null, $options = []) public function checkbox($name, $value = 1, $checked = null, $options = [])
{ {
if ($checked) if ($checked) {
$options['checked'] = 'checked'; $options['checked'] = 'checked';
}
return $this->input('checkbox', $name, $value, $options); return $this->input('checkbox', $name, $value, $options);
} }
@ -864,9 +858,9 @@ EOD;
* 生成一组筛选框 * 生成一组筛选框
* *
* @param string $name * @param string $name
* @param array $list * @param array $list
* @param mixed $checked * @param mixed $checked
* @param array $options * @param array $options
* @return string * @return string
*/ */
public function checkboxs($name, $list, $checked, $options = []) public function checkboxs($name, $list, $checked, $options = [])
@ -885,18 +879,20 @@ EOD;
* 生成单选按钮 * 生成单选按钮
* *
* @param string $name * @param string $name
* @param mixed $value * @param mixed $value
* @param bool $checked * @param bool $checked
* @param array $options * @param array $options
* @return string * @return string
*/ */
public function radio($name, $value = null, $checked = null, $options = []) public function radio($name, $value = null, $checked = null, $options = [])
{ {
if (is_null($value)) if (is_null($value)) {
$value = $name; $value = $name;
}
if ($checked) if ($checked) {
$options['checked'] = 'checked'; $options['checked'] = 'checked';
}
return $this->input('radio', $name, $value, $options); return $this->input('radio', $name, $value, $options);
} }
@ -905,9 +901,9 @@ EOD;
* 生成一组单选框 * 生成一组单选框
* *
* @param string $name * @param string $name
* @param array $list * @param array $list
* @param mixed $checked * @param mixed $checked
* @param array $options * @param array $options
* @return string * @return string
*/ */
public function radios($name, $list, $checked = null, $options = []) public function radios($name, $list, $checked = null, $options = [])
@ -927,15 +923,14 @@ EOD;
* *
* @param string $name * @param string $name
* @param string $value * @param string $value
* @param array $inputAttr * @param array $inputAttr
* @param array $uploadAttr * @param array $uploadAttr
* @param array $chooseAttr * @param array $chooseAttr
* @param array $previewAttr * @param array $previewAttr
* @return string * @return string
*/ */
public function image($name = null, $value, $inputAttr = [], $uploadAttr = [], $chooseAttr = [], $previewAttr = []) public function image($name = null, $value, $inputAttr = [], $uploadAttr = [], $chooseAttr = [], $previewAttr = [])
{ {
$default = [ $default = [
'data-mimetype' => 'image/gif,image/jpeg,image/png,image/jpg,image/bmp' 'data-mimetype' => 'image/gif,image/jpeg,image/png,image/jpg,image/bmp'
]; ];
@ -949,10 +944,10 @@ EOD;
* *
* @param string $name * @param string $name
* @param string $value * @param string $value
* @param array $inputAttr * @param array $inputAttr
* @param array $uploadAttr * @param array $uploadAttr
* @param array $chooseAttr * @param array $chooseAttr
* @param array $previewAttr * @param array $previewAttr
* @return string * @return string
*/ */
public function images($name = null, $value, $inputAttr = [], $uploadAttr = [], $chooseAttr = [], $previewAttr = []) public function images($name = null, $value, $inputAttr = [], $uploadAttr = [], $chooseAttr = [], $previewAttr = [])
@ -971,10 +966,10 @@ EOD;
* *
* @param string $name * @param string $name
* @param string $value * @param string $value
* @param array $inputAttr * @param array $inputAttr
* @param array $uploadAttr * @param array $uploadAttr
* @param array $chooseAttr * @param array $chooseAttr
* @param array $previewAttr * @param array $previewAttr
* @return string * @return string
*/ */
public function upload($name = null, $value, $inputAttr = [], $uploadAttr = [], $chooseAttr = [], $previewAttr = []) public function upload($name = null, $value, $inputAttr = [], $uploadAttr = [], $chooseAttr = [], $previewAttr = [])
@ -987,10 +982,10 @@ EOD;
* *
* @param string $name * @param string $name
* @param string $value * @param string $value
* @param array $inputAttr * @param array $inputAttr
* @param array $uploadAttr * @param array $uploadAttr
* @param array $chooseAttr * @param array $chooseAttr
* @param array $previewAttr * @param array $previewAttr
* @return string * @return string
*/ */
public function uploads($name = null, $value, $inputAttr = [], $uploadAttr = [], $chooseAttr = [], $previewAttr = []) public function uploads($name = null, $value, $inputAttr = [], $uploadAttr = [], $chooseAttr = [], $previewAttr = [])
@ -1048,7 +1043,7 @@ EOD;
* 生成一个按钮 * 生成一个按钮
* *
* @param string $value * @param string $value
* @param array $options * @param array $options
* @return string * @return string
*/ */
public function button($value = null, $options = []) public function button($value = null, $options = [])
@ -1064,12 +1059,11 @@ EOD;
* 获取ID属性值 * 获取ID属性值
* *
* @param string $name * @param string $name
* @param array $attributes * @param array $attributes
* @return string * @return string
*/ */
public function getIdAttribute($name, $attributes) public function getIdAttribute($name, $attributes)
{ {
if (array_key_exists('id', $attributes)) { if (array_key_exists('id', $attributes)) {
return $attributes['id']; return $attributes['id'];
} }
@ -1088,12 +1082,13 @@ EOD;
*/ */
public function getValueAttribute($name, $value = null) public function getValueAttribute($name, $value = null)
{ {
if (is_null($name)) if (is_null($name)) {
return $value; return $value;
}
if (!is_null($value)) if (!is_null($value)) {
return $value; return $value;
}
} }
/** /**
@ -1110,8 +1105,9 @@ EOD;
// 会已 required="required" 拼接起来,而不是用数字keys去拼接 // 会已 required="required" 拼接起来,而不是用数字keys去拼接
foreach ((array)$attributes as $key => $value) { foreach ((array)$attributes as $key => $value) {
$element = $this->attributeElement($key, $value); $element = $this->attributeElement($key, $value);
if (!is_null($element)) if (!is_null($element)) {
$html[] = $element; $html[] = $element;
}
} }
return count($html) > 0 ? ' ' . implode(' ', $html) : ''; return count($html) > 0 ? ' ' . implode(' ', $html) : '';
} }
@ -1125,8 +1121,9 @@ EOD;
*/ */
protected function attributeElement($key, $value) protected function attributeElement($key, $value)
{ {
if (is_numeric($key)) if (is_numeric($key)) {
$key = $value; $key = $value;
}
if (!is_null($value)) { if (!is_null($value)) {
if (is_array($value) || stripos($value, '"') !== false) { if (is_array($value) || stripos($value, '"') !== false) {
$value = is_array($value) ? json_encode($value, JSON_UNESCAPED_UNICODE) : $value; $value = is_array($value) ? json_encode($value, JSON_UNESCAPED_UNICODE) : $value;
@ -1136,7 +1133,6 @@ EOD;
} }
} }
} }
} }
class Arr class Arr
@ -1157,7 +1153,7 @@ class Arr
* Determine if the given key exists in the provided array. * Determine if the given key exists in the provided array.
* *
* @param \ArrayAccess|array $array * @param \ArrayAccess|array $array
* @param string|int $key * @param string|int $key
* @return bool * @return bool
*/ */
public static function exists($array, $key) public static function exists($array, $key)
@ -1172,8 +1168,8 @@ class Arr
* Get an item from an array using "dot" notation. * Get an item from an array using "dot" notation.
* *
* @param \ArrayAccess|array $array * @param \ArrayAccess|array $array
* @param string $key * @param string $key
* @param mixed $default * @param mixed $default
* @return mixed * @return mixed
*/ */
public static function get($array, $key, $default = null) public static function get($array, $key, $default = null)
@ -1200,7 +1196,7 @@ class Arr
/** /**
* Get all of the given array except for a specified array of items. * Get all of the given array except for a specified array of items.
* *
* @param array $array * @param array $array
* @param array|string $keys * @param array|string $keys
* @return array * @return array
*/ */
@ -1213,7 +1209,7 @@ class Arr
/** /**
* Remove one or many array items from a given array using "dot" notation. * Remove one or many array items from a given array using "dot" notation.
* *
* @param array $array * @param array $array
* @param array|string $keys * @param array|string $keys
* @return void * @return void
*/ */
@ -1244,7 +1240,6 @@ class Arr
unset($array[array_shift($parts)]); unset($array[array_shift($parts)]);
} }
} }
} }
if (!function_exists('array_get')) { if (!function_exists('array_get')) {
@ -1253,15 +1248,14 @@ if (!function_exists('array_get')) {
* Get an item from an array using "dot" notation. * Get an item from an array using "dot" notation.
* *
* @param \ArrayAccess|array $array * @param \ArrayAccess|array $array
* @param string $key * @param string $key
* @param mixed $default * @param mixed $default
* @return mixed * @return mixed
*/ */
function array_get($array, $key, $default = null) function array_get($array, $key, $default = null)
{ {
return Arr::get($array, $key, $default); return Arr::get($array, $key, $default);
} }
} }
if (!function_exists('e')) { if (!function_exists('e')) {
@ -1278,14 +1272,13 @@ if (!function_exists('e')) {
} }
return htmlspecialchars($value, ENT_QUOTES, 'UTF-8', false); return htmlspecialchars($value, ENT_QUOTES, 'UTF-8', false);
} }
} }
if (!function_exists('array_except')) { if (!function_exists('array_except')) {
/** /**
* Get all of the given array except for a specified array of items. * Get all of the given array except for a specified array of items.
* *
* @param array $array * @param array $array
* @param array|string $keys * @param array|string $keys
* @return array * @return array
*/ */
@ -1293,5 +1286,4 @@ if (!function_exists('array_except')) {
{ {
return Arr::except($array, $keys); return Arr::except($array, $keys);
} }
}
}

View File

@ -10,6 +10,10 @@ class Http
/** /**
* 发送一个POST请求 * 发送一个POST请求
* @param string $url 请求URL
* @param array $params 请求参数
* @param array $options 扩展参数
* @return mixed|string
*/ */
public static function post($url, $params = [], $options = []) public static function post($url, $params = [], $options = [])
{ {
@ -19,6 +23,10 @@ class Http
/** /**
* 发送一个GET请求 * 发送一个GET请求
* @param string $url 请求URL
* @param array $params 请求参数
* @param array $options 扩展参数
* @return mixed|string
*/ */
public static function get($url, $params = [], $options = []) public static function get($url, $params = [], $options = [])
{ {
@ -28,10 +36,10 @@ class Http
/** /**
* CURL发送Request请求,含POST和REQUEST * CURL发送Request请求,含POST和REQUEST
* @param string $url 请求的链接 * @param string $url 请求的链接
* @param mixed $params 传递的参数 * @param mixed $params 传递的参数
* @param string $method 请求的方法 * @param string $method 请求的方法
* @param mixed $options CURL的参数 * @param mixed $options CURL的参数
* @return array * @return array
*/ */
public static function sendRequest($url, $params = [], $method = 'POST', $options = []) public static function sendRequest($url, $params = [], $method = 'POST', $options = [])
@ -42,53 +50,45 @@ class Http
$ch = curl_init(); $ch = curl_init();
$defaults = []; $defaults = [];
if ('GET' == $method) if ('GET' == $method) {
{ $geturl = $query_string ? $url . (stripos($url, "?") !== false ? "&" : "?") . $query_string : $url;
$geturl = $query_string ? $url . (stripos($url, "?") !== FALSE ? "&" : "?") . $query_string : $url;
$defaults[CURLOPT_URL] = $geturl; $defaults[CURLOPT_URL] = $geturl;
} } else {
else
{
$defaults[CURLOPT_URL] = $url; $defaults[CURLOPT_URL] = $url;
if ($method == 'POST') if ($method == 'POST') {
{
$defaults[CURLOPT_POST] = 1; $defaults[CURLOPT_POST] = 1;
} } else {
else
{
$defaults[CURLOPT_CUSTOMREQUEST] = $method; $defaults[CURLOPT_CUSTOMREQUEST] = $method;
} }
$defaults[CURLOPT_POSTFIELDS] = $query_string; $defaults[CURLOPT_POSTFIELDS] = $query_string;
} }
$defaults[CURLOPT_HEADER] = FALSE; $defaults[CURLOPT_HEADER] = false;
$defaults[CURLOPT_USERAGENT] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.98 Safari/537.36"; $defaults[CURLOPT_USERAGENT] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.98 Safari/537.36";
$defaults[CURLOPT_FOLLOWLOCATION] = TRUE; $defaults[CURLOPT_FOLLOWLOCATION] = true;
$defaults[CURLOPT_RETURNTRANSFER] = TRUE; $defaults[CURLOPT_RETURNTRANSFER] = true;
$defaults[CURLOPT_CONNECTTIMEOUT] = 3; $defaults[CURLOPT_CONNECTTIMEOUT] = 3;
$defaults[CURLOPT_TIMEOUT] = 3; $defaults[CURLOPT_TIMEOUT] = 3;
// disable 100-continue // disable 100-continue
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:')); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
if ('https' == $protocol) if ('https' == $protocol) {
{ $defaults[CURLOPT_SSL_VERIFYPEER] = false;
$defaults[CURLOPT_SSL_VERIFYPEER] = FALSE; $defaults[CURLOPT_SSL_VERIFYHOST] = false;
$defaults[CURLOPT_SSL_VERIFYHOST] = FALSE;
} }
curl_setopt_array($ch, (array) $options + $defaults); curl_setopt_array($ch, (array)$options + $defaults);
$ret = curl_exec($ch); $ret = curl_exec($ch);
$err = curl_error($ch); $err = curl_error($ch);
if (FALSE === $ret || !empty($err)) if (false === $ret || !empty($err)) {
{
$errno = curl_errno($ch); $errno = curl_errno($ch);
$info = curl_getinfo($ch); $info = curl_getinfo($ch);
curl_close($ch); curl_close($ch);
return [ return [
'ret' => FALSE, 'ret' => false,
'errno' => $errno, 'errno' => $errno,
'msg' => $err, 'msg' => $err,
'info' => $info, 'info' => $info,
@ -96,15 +96,15 @@ class Http
} }
curl_close($ch); curl_close($ch);
return [ return [
'ret' => TRUE, 'ret' => true,
'msg' => $ret, 'msg' => $ret,
]; ];
} }
/** /**
* 异步发送一个请求 * 异步发送一个请求
* @param string $url 请求的链接 * @param string $url 请求的链接
* @param mixed $params 请求的参数 * @param mixed $params 请求的参数
* @param string $method 请求的方法 * @param string $method 请求的方法
* @return boolean TRUE * @return boolean TRUE
*/ */
@ -113,58 +113,56 @@ class Http
$method = strtoupper($method); $method = strtoupper($method);
$method = $method == 'POST' ? 'POST' : 'GET'; $method = $method == 'POST' ? 'POST' : 'GET';
//构造传递的参数 //构造传递的参数
if (is_array($params)) if (is_array($params)) {
{
$post_params = []; $post_params = [];
foreach ($params as $k => &$v) foreach ($params as $k => &$v) {
{ if (is_array($v)) {
if (is_array($v))
$v = implode(',', $v); $v = implode(',', $v);
}
$post_params[] = $k . '=' . urlencode($v); $post_params[] = $k . '=' . urlencode($v);
} }
$post_string = implode('&', $post_params); $post_string = implode('&', $post_params);
}else } else {
{
$post_string = $params; $post_string = $params;
} }
$parts = parse_url($url); $parts = parse_url($url);
//构造查询的参数 //构造查询的参数
if ($method == 'GET' && $post_string) if ($method == 'GET' && $post_string) {
{
$parts['query'] = isset($parts['query']) ? $parts['query'] . '&' . $post_string : $post_string; $parts['query'] = isset($parts['query']) ? $parts['query'] . '&' . $post_string : $post_string;
$post_string = ''; $post_string = '';
} }
$parts['query'] = isset($parts['query']) && $parts['query'] ? '?' . $parts['query'] : ''; $parts['query'] = isset($parts['query']) && $parts['query'] ? '?' . $parts['query'] : '';
//发送socket请求,获得连接句柄 //发送socket请求,获得连接句柄
$fp = fsockopen($parts['host'], isset($parts['port']) ? $parts['port'] : 80, $errno, $errstr, 3); $fp = fsockopen($parts['host'], isset($parts['port']) ? $parts['port'] : 80, $errno, $errstr, 3);
if (!$fp) if (!$fp) {
return FALSE; return false;
}
//设置超时时间 //设置超时时间
stream_set_timeout($fp, 3); stream_set_timeout($fp, 3);
$out = "{$method} {$parts['path']}{$parts['query']} HTTP/1.1\r\n"; $out = "{$method} {$parts['path']}{$parts['query']} HTTP/1.1\r\n";
$out.= "Host: {$parts['host']}\r\n"; $out .= "Host: {$parts['host']}\r\n";
$out.= "Content-Type: application/x-www-form-urlencoded\r\n"; $out .= "Content-Type: application/x-www-form-urlencoded\r\n";
$out.= "Content-Length: " . strlen($post_string) . "\r\n"; $out .= "Content-Length: " . strlen($post_string) . "\r\n";
$out.= "Connection: Close\r\n\r\n"; $out .= "Connection: Close\r\n\r\n";
if ($post_string !== '') if ($post_string !== '') {
$out .= $post_string; $out .= $post_string;
}
fwrite($fp, $out); fwrite($fp, $out);
//不用关心服务器返回结果 //不用关心服务器返回结果
//echo fread($fp, 1024); //echo fread($fp, 1024);
fclose($fp); fclose($fp);
return TRUE; return true;
} }
/** /**
* 发送文件到客户端 * 发送文件到客户端
* @param string $file * @param string $file
* @param bool $delaftersend * @param bool $delaftersend
* @param bool $exitaftersend * @param bool $exitaftersend
*/ */
public static function sendToBrowser($file, $delaftersend = true, $exitaftersend = true) public static function sendToBrowser($file, $delaftersend = true, $exitaftersend = true)
{ {
if (file_exists($file) && is_readable($file)) if (file_exists($file) && is_readable($file)) {
{
header('Content-Description: File Transfer'); header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream'); header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment;filename = ' . basename($file)); header('Content-Disposition: attachment;filename = ' . basename($file));
@ -176,15 +174,12 @@ class Http
ob_clean(); ob_clean();
flush(); flush();
readfile($file); readfile($file);
if ($delaftersend) if ($delaftersend) {
{
unlink($file); unlink($file);
} }
if ($exitaftersend) if ($exitaftersend) {
{
exit; exit;
} }
} }
} }
} }

View File

@ -7,16 +7,15 @@ namespace fast;
*/ */
class Pinyin class Pinyin
{ {
protected static $keys = "a|ai|an|ang|ao|ba|bai|ban|bang|bao|bei|ben|beng|bi|bian|biao|bie|bin|bing|bo|bu|ca|cai|can|cang|cao|ce|ceng|cha|chai|chan|chang|chao|che|chen|cheng|chi|chong|chou|chu|chuai|chuan|chuang|chui|chun|chuo|ci|cong|cou|cu|cuan|cui|cun|cuo|da|dai|dan|dang|dao|de|deng|di|dian|diao|die|ding|diu|dong|dou|du|duan|dui|dun|duo|e|en|er|fa|fan|fang|fei|fen|feng|fo|fou|fu|ga|gai|gan|gang|gao|ge|gei|gen|geng|gong|gou|gu|gua|guai|guan|guang|gui|gun|guo|ha|hai|han|hang|hao|he|hei|hen|heng|hong|hou|hu|hua|huai|huan|huang|hui|hun|huo|ji|jia|jian|jiang|jiao|jie|jin|jing|jiong|jiu|ju|juan|jue|jun|ka|kai|kan|kang|kao|ke|ken|keng|kong|kou|ku|kua|kuai|kuan|kuang|kui|kun|kuo|la|lai|lan|lang|lao|le|lei|leng|li|lia|lian|liang|liao|lie|lin|ling|liu|long|lou|lu|lv|luan|lue|lun|luo|ma|mai|man|mang|mao|me|mei|men|meng|mi|mian|miao|mie|min|ming|miu|mo|mou|mu|na|nai|nan|nang|nao|ne|nei|nen|neng|ni|nian|niang|niao|nie|nin|ning|niu|nong|nu|nv|nuan|nue|nuo|o|ou|pa|pai|pan|pang|pao|pei|pen|peng|pi|pian|piao|pie|pin|ping|po|pu|qi|qia|qian|qiang|qiao|qie|qin|qing|qiong|qiu|qu|quan|que|qun|ran|rang|rao|re|ren|reng|ri|rong|rou|ru|ruan|rui|run|ruo|sa|sai|san|sang|sao|se|sen|seng|sha|shai|shan|shang|shao|she|shen|sheng|shi|shou|shu|shua|shuai|shuan|shuang|shui|shun|shuo|si|song|sou|su|suan|sui|sun|suo|ta|tai|tan|tang|tao|te|teng|ti|tian|tiao|tie|ting|tong|tou|tu|tuan|tui|tun|tuo|wa|wai|wan|wang|wei|wen|weng|wo|wu|xi|xia|xian|xiang|xiao|xie|xin|xing|xiong|xiu|xu|xuan|xue|xun|ya|yan|yang|yao|ye|yi|yin|ying|yo|yong|you|yu|yuan|yue|yun|za|zai|zan|zang|zao|ze|zei|zen|zeng|zha|zhai|zhan|zhang|zhao|zhe|zhen|zheng|zhi|zhong|zhou|zhu|zhua|zhuai|zhuan|zhuang|zhui|zhun|zhuo|zi|zong|zou|zu|zuan|zui|zun|zuo"; protected static $keys = "a|ai|an|ang|ao|ba|bai|ban|bang|bao|bei|ben|beng|bi|bian|biao|bie|bin|bing|bo|bu|ca|cai|can|cang|cao|ce|ceng|cha|chai|chan|chang|chao|che|chen|cheng|chi|chong|chou|chu|chuai|chuan|chuang|chui|chun|chuo|ci|cong|cou|cu|cuan|cui|cun|cuo|da|dai|dan|dang|dao|de|deng|di|dian|diao|die|ding|diu|dong|dou|du|duan|dui|dun|duo|e|en|er|fa|fan|fang|fei|fen|feng|fo|fou|fu|ga|gai|gan|gang|gao|ge|gei|gen|geng|gong|gou|gu|gua|guai|guan|guang|gui|gun|guo|ha|hai|han|hang|hao|he|hei|hen|heng|hong|hou|hu|hua|huai|huan|huang|hui|hun|huo|ji|jia|jian|jiang|jiao|jie|jin|jing|jiong|jiu|ju|juan|jue|jun|ka|kai|kan|kang|kao|ke|ken|keng|kong|kou|ku|kua|kuai|kuan|kuang|kui|kun|kuo|la|lai|lan|lang|lao|le|lei|leng|li|lia|lian|liang|liao|lie|lin|ling|liu|long|lou|lu|lv|luan|lue|lun|luo|ma|mai|man|mang|mao|me|mei|men|meng|mi|mian|miao|mie|min|ming|miu|mo|mou|mu|na|nai|nan|nang|nao|ne|nei|nen|neng|ni|nian|niang|niao|nie|nin|ning|niu|nong|nu|nv|nuan|nue|nuo|o|ou|pa|pai|pan|pang|pao|pei|pen|peng|pi|pian|piao|pie|pin|ping|po|pu|qi|qia|qian|qiang|qiao|qie|qin|qing|qiong|qiu|qu|quan|que|qun|ran|rang|rao|re|ren|reng|ri|rong|rou|ru|ruan|rui|run|ruo|sa|sai|san|sang|sao|se|sen|seng|sha|shai|shan|shang|shao|she|shen|sheng|shi|shou|shu|shua|shuai|shuan|shuang|shui|shun|shuo|si|song|sou|su|suan|sui|sun|suo|ta|tai|tan|tang|tao|te|teng|ti|tian|tiao|tie|ting|tong|tou|tu|tuan|tui|tun|tuo|wa|wai|wan|wang|wei|wen|weng|wo|wu|xi|xia|xian|xiang|xiao|xie|xin|xing|xiong|xiu|xu|xuan|xue|xun|ya|yan|yang|yao|ye|yi|yin|ying|yo|yong|you|yu|yuan|yue|yun|za|zai|zan|zang|zao|ze|zei|zen|zeng|zha|zhai|zhan|zhang|zhao|zhe|zhen|zheng|zhi|zhong|zhou|zhu|zhua|zhuai|zhuan|zhuang|zhui|zhun|zhuo|zi|zong|zou|zu|zuan|zui|zun|zuo";
protected static $values = "-20319|-20317|-20304|-20295|-20292|-20283|-20265|-20257|-20242|-20230|-20051|-20036|-20032|-20026|-20002|-19990|-19986|-19982|-19976|-19805|-19784|-19775|-19774|-19763|-19756|-19751|-19746|-19741|-19739|-19728|-19725|-19715|-19540|-19531|-19525|-19515|-19500|-19484|-19479|-19467|-19289|-19288|-19281|-19275|-19270|-19263|-19261|-19249|-19243|-19242|-19238|-19235|-19227|-19224|-19218|-19212|-19038|-19023|-19018|-19006|-19003|-18996|-18977|-18961|-18952|-18783|-18774|-18773|-18763|-18756|-18741|-18735|-18731|-18722|-18710|-18697|-18696|-18526|-18518|-18501|-18490|-18478|-18463|-18448|-18447|-18446|-18239|-18237|-18231|-18220|-18211|-18201|-18184|-18183|-18181|-18012|-17997|-17988|-17970|-17964|-17961|-17950|-17947|-17931|-17928|-17922|-17759|-17752|-17733|-17730|-17721|-17703|-17701|-17697|-17692|-17683|-17676|-17496|-17487|-17482|-17468|-17454|-17433|-17427|-17417|-17202|-17185|-16983|-16970|-16942|-16915|-16733|-16708|-16706|-16689|-16664|-16657|-16647|-16474|-16470|-16465|-16459|-16452|-16448|-16433|-16429|-16427|-16423|-16419|-16412|-16407|-16403|-16401|-16393|-16220|-16216|-16212|-16205|-16202|-16187|-16180|-16171|-16169|-16158|-16155|-15959|-15958|-15944|-15933|-15920|-15915|-15903|-15889|-15878|-15707|-15701|-15681|-15667|-15661|-15659|-15652|-15640|-15631|-15625|-15454|-15448|-15436|-15435|-15419|-15416|-15408|-15394|-15385|-15377|-15375|-15369|-15363|-15362|-15183|-15180|-15165|-15158|-15153|-15150|-15149|-15144|-15143|-15141|-15140|-15139|-15128|-15121|-15119|-15117|-15110|-15109|-14941|-14937|-14933|-14930|-14929|-14928|-14926|-14922|-14921|-14914|-14908|-14902|-14894|-14889|-14882|-14873|-14871|-14857|-14678|-14674|-14670|-14668|-14663|-14654|-14645|-14630|-14594|-14429|-14407|-14399|-14384|-14379|-14368|-14355|-14353|-14345|-14170|-14159|-14151|-14149|-14145|-14140|-14137|-14135|-14125|-14123|-14122|-14112|-14109|-14099|-14097|-14094|-14092|-14090|-14087|-14083|-13917|-13914|-13910|-13907|-13906|-13905|-13896|-13894|-13878|-13870|-13859|-13847|-13831|-13658|-13611|-13601|-13406|-13404|-13400|-13398|-13395|-13391|-13387|-13383|-13367|-13359|-13356|-13343|-13340|-13329|-13326|-13318|-13147|-13138|-13120|-13107|-13096|-13095|-13091|-13076|-13068|-13063|-13060|-12888|-12875|-12871|-12860|-12858|-12852|-12849|-12838|-12831|-12829|-12812|-12802|-12607|-12597|-12594|-12585|-12556|-12359|-12346|-12320|-12300|-12120|-12099|-12089|-12074|-12067|-12058|-12039|-11867|-11861|-11847|-11831|-11798|-11781|-11604|-11589|-11536|-11358|-11340|-11339|-11324|-11303|-11097|-11077|-11067|-11055|-11052|-11045|-11041|-11038|-11024|-11020|-11019|-11018|-11014|-10838|-10832|-10815|-10800|-10790|-10780|-10764|-10587|-10544|-10533|-10519|-10331|-10329|-10328|-10322|-10315|-10309|-10307|-10296|-10281|-10274|-10270|-10262|-10260|-10256|-10254"; protected static $values = "-20319|-20317|-20304|-20295|-20292|-20283|-20265|-20257|-20242|-20230|-20051|-20036|-20032|-20026|-20002|-19990|-19986|-19982|-19976|-19805|-19784|-19775|-19774|-19763|-19756|-19751|-19746|-19741|-19739|-19728|-19725|-19715|-19540|-19531|-19525|-19515|-19500|-19484|-19479|-19467|-19289|-19288|-19281|-19275|-19270|-19263|-19261|-19249|-19243|-19242|-19238|-19235|-19227|-19224|-19218|-19212|-19038|-19023|-19018|-19006|-19003|-18996|-18977|-18961|-18952|-18783|-18774|-18773|-18763|-18756|-18741|-18735|-18731|-18722|-18710|-18697|-18696|-18526|-18518|-18501|-18490|-18478|-18463|-18448|-18447|-18446|-18239|-18237|-18231|-18220|-18211|-18201|-18184|-18183|-18181|-18012|-17997|-17988|-17970|-17964|-17961|-17950|-17947|-17931|-17928|-17922|-17759|-17752|-17733|-17730|-17721|-17703|-17701|-17697|-17692|-17683|-17676|-17496|-17487|-17482|-17468|-17454|-17433|-17427|-17417|-17202|-17185|-16983|-16970|-16942|-16915|-16733|-16708|-16706|-16689|-16664|-16657|-16647|-16474|-16470|-16465|-16459|-16452|-16448|-16433|-16429|-16427|-16423|-16419|-16412|-16407|-16403|-16401|-16393|-16220|-16216|-16212|-16205|-16202|-16187|-16180|-16171|-16169|-16158|-16155|-15959|-15958|-15944|-15933|-15920|-15915|-15903|-15889|-15878|-15707|-15701|-15681|-15667|-15661|-15659|-15652|-15640|-15631|-15625|-15454|-15448|-15436|-15435|-15419|-15416|-15408|-15394|-15385|-15377|-15375|-15369|-15363|-15362|-15183|-15180|-15165|-15158|-15153|-15150|-15149|-15144|-15143|-15141|-15140|-15139|-15128|-15121|-15119|-15117|-15110|-15109|-14941|-14937|-14933|-14930|-14929|-14928|-14926|-14922|-14921|-14914|-14908|-14902|-14894|-14889|-14882|-14873|-14871|-14857|-14678|-14674|-14670|-14668|-14663|-14654|-14645|-14630|-14594|-14429|-14407|-14399|-14384|-14379|-14368|-14355|-14353|-14345|-14170|-14159|-14151|-14149|-14145|-14140|-14137|-14135|-14125|-14123|-14122|-14112|-14109|-14099|-14097|-14094|-14092|-14090|-14087|-14083|-13917|-13914|-13910|-13907|-13906|-13905|-13896|-13894|-13878|-13870|-13859|-13847|-13831|-13658|-13611|-13601|-13406|-13404|-13400|-13398|-13395|-13391|-13387|-13383|-13367|-13359|-13356|-13343|-13340|-13329|-13326|-13318|-13147|-13138|-13120|-13107|-13096|-13095|-13091|-13076|-13068|-13063|-13060|-12888|-12875|-12871|-12860|-12858|-12852|-12849|-12838|-12831|-12829|-12812|-12802|-12607|-12597|-12594|-12585|-12556|-12359|-12346|-12320|-12300|-12120|-12099|-12089|-12074|-12067|-12058|-12039|-11867|-11861|-11847|-11831|-11798|-11781|-11604|-11589|-11536|-11358|-11340|-11339|-11324|-11303|-11097|-11077|-11067|-11055|-11052|-11045|-11041|-11038|-11024|-11020|-11019|-11018|-11014|-10838|-10832|-10815|-10800|-10790|-10780|-10764|-10587|-10544|-10533|-10519|-10331|-10329|-10328|-10322|-10315|-10309|-10307|-10296|-10281|-10274|-10270|-10262|-10260|-10256|-10254";
/** /**
* 获取文字的拼音 * 获取文字的拼音
* @param string $chinese 中文汉字 * @param string $chinese 中文汉字
* @param boolean $onlyfirst 是否只返回拼音首字母 * @param boolean $onlyfirst 是否只返回拼音首字母
* @param string $delimiter 分隔符 * @param string $delimiter 分隔符
* @param string $charset 文字编码 * @param string $charset 文字编码
* @return string * @return string
*/ */
public static function get($chinese, $onlyfirst = false, $delimiter = '', $ucfirst = false, $charset = 'utf-8') public static function get($chinese, $onlyfirst = false, $delimiter = '', $ucfirst = false, $charset = 'utf-8')
@ -26,22 +25,20 @@ class Pinyin
$data = array_combine($keys_a, $values_a); $data = array_combine($keys_a, $values_a);
arsort($data); arsort($data);
reset($data); reset($data);
if ($charset != 'gb2312') if ($charset != 'gb2312') {
$chinese = self::_u2_utf8_gb($chinese); $chinese = self::_u2_utf8_gb($chinese);
}
$result = ''; $result = '';
for ($i = 0; $i < strlen($chinese); $i++) for ($i = 0; $i < strlen($chinese); $i++) {
{
$_P = ord(substr($chinese, $i, 1)); $_P = ord(substr($chinese, $i, 1));
if ($_P > 160) if ($_P > 160) {
{
$_Q = ord(substr($chinese, ++$i, 1)); $_Q = ord(substr($chinese, ++$i, 1));
$_P = $_P * 256 + $_Q - 65536; $_P = $_P * 256 + $_Q - 65536;
} }
$result .= ($onlyfirst ? substr(self::_pinyin($_P, $data), 0, 1) : self::_pinyin($_P, $data)); $result .= ($onlyfirst ? substr(self::_pinyin($_P, $data), 0, 1) : self::_pinyin($_P, $data));
$result .= $delimiter; $result .= $delimiter;
} }
if ($delimiter) if ($delimiter) {
{
$result = rtrim($result, $delimiter); $result = rtrim($result, $delimiter);
} }
@ -50,16 +47,15 @@ class Pinyin
private static function _pinyin($num, $data) private static function _pinyin($num, $data)
{ {
if ($num > 0 && $num < 160) if ($num > 0 && $num < 160) {
return chr($num); return chr($num);
elseif ($num < -20319 || $num > -10247) } elseif ($num < -20319 || $num > -10247) {
return ''; return '';
else } else {
{ foreach ($data as $k => $v) {
foreach ($data as $k => $v) if ($v <= $num) {
{
if ($v <= $num)
break; break;
}
} }
return $k; return $k;
@ -69,21 +65,16 @@ class Pinyin
private static function _u2_utf8_gb($c) private static function _u2_utf8_gb($c)
{ {
$string = ''; $string = '';
if ($c < 0x80) if ($c < 0x80) {
$string .= $c; $string .= $c;
elseif ($c < 0x800) } elseif ($c < 0x800) {
{
$string .= chr(0xC0 | $c >> 6); $string .= chr(0xC0 | $c >> 6);
$string .= chr(0x80 | $c & 0x3F); $string .= chr(0x80 | $c & 0x3F);
} } elseif ($c < 0x10000) {
elseif ($c < 0x10000)
{
$string .= chr(0xE0 | $c >> 12); $string .= chr(0xE0 | $c >> 12);
$string .= chr(0x80 | $c >> 6 & 0x3F); $string .= chr(0x80 | $c >> 6 & 0x3F);
$string .= chr(0x80 | $c & 0x3F); $string .= chr(0x80 | $c & 0x3F);
} } elseif ($c < 0x200000) {
elseif ($c < 0x200000)
{
$string .= chr(0xF0 | $c >> 18); $string .= chr(0xF0 | $c >> 18);
$string .= chr(0x80 | $c >> 12 & 0x3F); $string .= chr(0x80 | $c >> 12 & 0x3F);
$string .= chr(0x80 | $c >> 6 & 0x3F); $string .= chr(0x80 | $c >> 6 & 0x3F);
@ -91,5 +82,4 @@ class Pinyin
} }
return iconv('UTF-8', 'GB2312//IGNORE', $string); return iconv('UTF-8', 'GB2312//IGNORE', $string);
} }
} }

View File

@ -55,19 +55,17 @@ class Random
/** /**
* 能用的随机数生成 * 能用的随机数生成
* @param string $type 类型 alpha/alnum/numeric/nozero/unique/md5/encrypt/sha1 * @param string $type 类型 alpha/alnum/numeric/nozero/unique/md5/encrypt/sha1
* @param int $len 长度 * @param int $len 长度
* @return string * @return string
*/ */
public static function build($type = 'alnum', $len = 8) public static function build($type = 'alnum', $len = 8)
{ {
switch ($type) switch ($type) {
{
case 'alpha': case 'alpha':
case 'alnum': case 'alnum':
case 'numeric': case 'numeric':
case 'nozero': case 'nozero':
switch ($type) switch ($type) {
{
case 'alpha': case 'alpha':
$pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
break; break;
@ -87,80 +85,64 @@ class Random
return md5(uniqid(mt_rand())); return md5(uniqid(mt_rand()));
case 'encrypt': case 'encrypt':
case 'sha1': case 'sha1':
return sha1(uniqid(mt_rand(), TRUE)); return sha1(uniqid(mt_rand(), true));
} }
} }
/** /**
* 根据数组元素的概率获得键名 * 根据数组元素的概率获得键名
* *
* @param array $ps array('p1'=>20, 'p2'=>30, 'p3'=>50); * @param array $ps array('p1'=>20, 'p2'=>30, 'p3'=>50);
* @param array $num 默认为1,即随机出来的数量 * @param int $num 默认为1,即随机出来的数量
* @param array $unique 默认为true,即当num>1,随机出的数量是否唯一 * @param bool $unique 默认为true,即当num>1,随机出的数量是否唯一
* @return mixed 当num为1时返回键名,反之返回一维数组 * @return mixed 当num为1时返回键名,反之返回一维数组
*/ */
public static function lottery($ps, $num = 1, $unique = true) public static function lottery($ps, $num = 1, $unique = true)
{ {
if (!$ps) if (!$ps) {
{
return $num == 1 ? '' : []; return $num == 1 ? '' : [];
} }
if ($num >= count($ps) && $unique) if ($num >= count($ps) && $unique) {
{
$res = array_keys($ps); $res = array_keys($ps);
return $num == 1 ? $res[0] : $res; return $num == 1 ? $res[0] : $res;
} }
$max_exp = 0; $max_exp = 0;
$res = []; $res = [];
foreach ($ps as $key => $value) foreach ($ps as $key => $value) {
{
$value = substr($value, 0, stripos($value, ".") + 6); $value = substr($value, 0, stripos($value, ".") + 6);
$exp = strlen(strchr($value, '.')) - 1; $exp = strlen(strchr($value, '.')) - 1;
if ($exp > $max_exp) if ($exp > $max_exp) {
{
$max_exp = $exp; $max_exp = $exp;
} }
} }
$pow_exp = pow(10, $max_exp); $pow_exp = pow(10, $max_exp);
if ($pow_exp > 1) if ($pow_exp > 1) {
{
reset($ps); reset($ps);
foreach ($ps as $key => $value) foreach ($ps as $key => $value) {
{
$ps[$key] = $value * $pow_exp; $ps[$key] = $value * $pow_exp;
} }
} }
$pro_sum = array_sum($ps); $pro_sum = array_sum($ps);
if ($pro_sum < 1) if ($pro_sum < 1) {
{
return $num == 1 ? '' : []; return $num == 1 ? '' : [];
} }
for ($i = 0; $i < $num; $i++) for ($i = 0; $i < $num; $i++) {
{
$rand_num = mt_rand(1, $pro_sum); $rand_num = mt_rand(1, $pro_sum);
reset($ps); reset($ps);
foreach ($ps as $key => $value) foreach ($ps as $key => $value) {
{ if ($rand_num <= $value) {
if ($rand_num <= $value)
{
break; break;
} } else {
else
{
$rand_num -= $value; $rand_num -= $value;
} }
} }
if ($num == 1) if ($num == 1) {
{
$res = $key; $res = $key;
break; break;
} } else {
else
{
$res[$i] = $key; $res[$i] = $key;
} }
if ($unique) if ($unique) {
{
$pro_sum -= $value; $pro_sum -= $value;
unset($ps[$key]); unset($ps[$key]);
} }
@ -175,8 +157,15 @@ class Random
public static function uuid() public static function uuid()
{ {
return sprintf( return sprintf(
'%04x%04x-%04x-%04x-%04x-%04x%04x%04x', mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0x0fff) | 0x4000, mt_rand(0, 0x3fff) | 0x8000, mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff) '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000,
mt_rand(0, 0x3fff) | 0x8000,
mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0xffff)
); );
} }
} }

View File

@ -7,7 +7,6 @@ namespace fast;
*/ */
class Rsa class Rsa
{ {
public $publicKey = ''; public $publicKey = '';
public $privateKey = ''; public $privateKey = '';
private $_privKey; private $_privKey;
@ -28,23 +27,27 @@ class Rsa
/** /**
* * the construtor,the param $path is the keys saving path * * the construtor,the param $path is the keys saving path
* @param string $publicKey 公钥
* @param string $privateKey 私钥
*/ */
function __construct($publicKey = null, $privateKey = null) public function __construct($publicKey = null, $privateKey = null)
{ {
$this->setKey($publicKey, $privateKey); $this->setKey($publicKey, $privateKey);
} }
/** /**
* 设置公钥和私钥 * 设置公钥和私钥
* @param string $publicKey 公钥 * @param string $publicKey 公钥
* @param string $privateKey 私钥 * @param string $privateKey 私钥
*/ */
public function setKey($publicKey = null, $privateKey = null) public function setKey($publicKey = null, $privateKey = null)
{ {
if (!is_null($publicKey)) if (!is_null($publicKey)) {
$this->publicKey = $publicKey; $this->publicKey = $publicKey;
if (!is_null($privateKey)) }
if (!is_null($privateKey)) {
$this->privateKey = $privateKey; $this->privateKey = $privateKey;
}
} }
/** /**
@ -52,8 +55,7 @@ class Rsa
*/ */
private function setupPrivKey() private function setupPrivKey()
{ {
if (is_resource($this->_privKey)) if (is_resource($this->_privKey)) {
{
return true; return true;
} }
$pem = chunk_split($this->privateKey, 64, "\n"); $pem = chunk_split($this->privateKey, 64, "\n");
@ -67,8 +69,7 @@ class Rsa
*/ */
private function setupPubKey() private function setupPubKey()
{ {
if (is_resource($this->_pubKey)) if (is_resource($this->_pubKey)) {
{
return true; return true;
} }
$pem = chunk_split($this->publicKey, 64, "\n"); $pem = chunk_split($this->publicKey, 64, "\n");
@ -82,14 +83,12 @@ class Rsa
*/ */
public function privEncrypt($data) public function privEncrypt($data)
{ {
if (!is_string($data)) if (!is_string($data)) {
{
return null; return null;
} }
$this->setupPrivKey(); $this->setupPrivKey();
$r = openssl_private_encrypt($data, $encrypted, $this->_privKey); $r = openssl_private_encrypt($data, $encrypted, $this->_privKey);
if ($r) if ($r) {
{
return base64_encode($encrypted); return base64_encode($encrypted);
} }
return null; return null;
@ -100,15 +99,13 @@ class Rsa
*/ */
public function privDecrypt($encrypted) public function privDecrypt($encrypted)
{ {
if (!is_string($encrypted)) if (!is_string($encrypted)) {
{
return null; return null;
} }
$this->setupPrivKey(); $this->setupPrivKey();
$encrypted = base64_decode($encrypted); $encrypted = base64_decode($encrypted);
$r = openssl_private_decrypt($encrypted, $decrypted, $this->_privKey); $r = openssl_private_decrypt($encrypted, $decrypted, $this->_privKey);
if ($r) if ($r) {
{
return $decrypted; return $decrypted;
} }
return null; return null;
@ -119,14 +116,12 @@ class Rsa
*/ */
public function pubEncrypt($data) public function pubEncrypt($data)
{ {
if (!is_string($data)) if (!is_string($data)) {
{
return null; return null;
} }
$this->setupPubKey(); $this->setupPubKey();
$r = openssl_public_encrypt($data, $encrypted, $this->_pubKey); $r = openssl_public_encrypt($data, $encrypted, $this->_pubKey);
if ($r) if ($r) {
{
return base64_encode($encrypted); return base64_encode($encrypted);
} }
return null; return null;
@ -137,15 +132,13 @@ class Rsa
*/ */
public function pubDecrypt($crypted) public function pubDecrypt($crypted)
{ {
if (!is_string($crypted)) if (!is_string($crypted)) {
{
return null; return null;
} }
$this->setupPubKey(); $this->setupPubKey();
$crypted = base64_decode($crypted); $crypted = base64_decode($crypted);
$r = openssl_public_decrypt($crypted, $decrypted, $this->_pubKey); $r = openssl_public_decrypt($crypted, $decrypted, $this->_pubKey);
if ($r) if ($r) {
{
return $decrypted; return $decrypted;
} }
return null; return null;
@ -183,5 +176,4 @@ class Rsa
is_resource($this->_privKey) && @openssl_free_key($this->_privKey); is_resource($this->_privKey) && @openssl_free_key($this->_privKey);
is_resource($this->_pubKey) && @openssl_free_key($this->_pubKey); is_resource($this->_pubKey) && @openssl_free_key($this->_pubKey);
} }
} }

View File

@ -10,7 +10,6 @@ use think\Config;
*/ */
class Tree class Tree
{ {
protected static $instance; protected static $instance;
//默认配置 //默认配置
protected $config = []; protected $config = [];
@ -32,8 +31,7 @@ class Tree
public function __construct($options = []) public function __construct($options = [])
{ {
if ($config = Config::get('tree')) if ($config = Config::get('tree')) {
{
$this->options = array_merge($this->config, $config); $this->options = array_merge($this->config, $config);
} }
$this->options = array_merge($this->config, $options); $this->options = array_merge($this->config, $options);
@ -47,8 +45,7 @@ class Tree
*/ */
public static function instance($options = []) public static function instance($options = [])
{ {
if (is_null(self::$instance)) if (is_null(self::$instance)) {
{
self::$instance = new static($options); self::$instance = new static($options);
} }
@ -56,11 +53,9 @@ class Tree
} }
/** /**
* 初始化方法 * 初始化方法
* @param array $arr 2维数组,例如:
* @param array 2维数组,例如: * array(
* array(
* 1 => array('id'=>'1','pid'=>0,'name'=>'一级栏目一'), * 1 => array('id'=>'1','pid'=>0,'name'=>'一级栏目一'),
* 2 => array('id'=>'2','pid'=>0,'name'=>'一级栏目二'), * 2 => array('id'=>'2','pid'=>0,'name'=>'一级栏目二'),
* 3 => array('id'=>'3','pid'=>1,'name'=>'二级栏目一'), * 3 => array('id'=>'3','pid'=>1,'name'=>'二级栏目一'),
@ -69,14 +64,19 @@ class Tree
* 6 => array('id'=>'6','pid'=>3,'name'=>'三级栏目一'), * 6 => array('id'=>'6','pid'=>3,'name'=>'三级栏目一'),
* 7 => array('id'=>'7','pid'=>3,'name'=>'三级栏目二') * 7 => array('id'=>'7','pid'=>3,'name'=>'三级栏目二')
* ) * )
* @param string $pidname 父字段名称
* @param string $nbsp 空格占位符
* @return Tree
*/ */
public function init($arr = [], $pidname = NULL, $nbsp = NULL) public function init($arr = [], $pidname = null, $nbsp = null)
{ {
$this->arr = $arr; $this->arr = $arr;
if (!is_null($pidname)) if (!is_null($pidname)) {
$this->pidname = $pidname; $this->pidname = $pidname;
if (!is_null($nbsp)) }
if (!is_null($nbsp)) {
$this->nbsp = $nbsp; $this->nbsp = $nbsp;
}
return $this; return $this;
} }
@ -88,37 +88,34 @@ class Tree
public function getChild($myid) public function getChild($myid)
{ {
$newarr = []; $newarr = [];
foreach ($this->arr as $value) foreach ($this->arr as $value) {
{ if (!isset($value['id'])) {
if (!isset($value['id']))
continue; continue;
if ($value[$this->pidname] == $myid) }
if ($value[$this->pidname] == $myid) {
$newarr[$value['id']] = $value; $newarr[$value['id']] = $value;
}
} }
return $newarr; return $newarr;
} }
/** /**
* 读取指定节点的所有孩子节点 * 读取指定节点的所有孩子节点
* @param int $myid 节点ID * @param int $myid 节点ID
* @param boolean $withself 是否包含自身 * @param boolean $withself 是否包含自身
* @return array * @return array
*/ */
public function getChildren($myid, $withself = FALSE) public function getChildren($myid, $withself = false)
{ {
$newarr = []; $newarr = [];
foreach ($this->arr as $value) foreach ($this->arr as $value) {
{ if (!isset($value['id'])) {
if (!isset($value['id']))
continue; continue;
if ($value[$this->pidname] == $myid) }
{ if ($value[$this->pidname] == $myid) {
$newarr[] = $value; $newarr[] = $value;
$newarr = array_merge($newarr, $this->getChildren($value['id'])); $newarr = array_merge($newarr, $this->getChildren($value['id']));
} } elseif ($withself && $value['id'] == $myid) {
else if ($withself && $value['id'] == $myid)
{
$newarr[] = $value; $newarr[] = $value;
} }
} }
@ -126,50 +123,42 @@ class Tree
} }
/** /**
* 读取指定节点的所有孩子节点ID * 读取指定节点的所有孩子节点ID
* @param int $myid 节点ID * @param int $myid 节点ID
* @param boolean $withself 是否包含自身 * @param boolean $withself 是否包含自身
* @return array * @return array
*/ */
public function getChildrenIds($myid, $withself = FALSE) public function getChildrenIds($myid, $withself = false)
{ {
$childrenlist = $this->getChildren($myid, $withself); $childrenlist = $this->getChildren($myid, $withself);
$childrenids = []; $childrenids = [];
foreach ($childrenlist as $k => $v) foreach ($childrenlist as $k => $v) {
{
$childrenids[] = $v['id']; $childrenids[] = $v['id'];
} }
return $childrenids; return $childrenids;
} }
/** /**
* 得到当前位置父辈数组 * 得到当前位置父辈数组
* @param int * @param int
* @return array * @return array
*/ */
public function getParent($myid) public function getParent($myid)
{ {
$pid = 0; $pid = 0;
$newarr = []; $newarr = [];
foreach ($this->arr as $value) foreach ($this->arr as $value) {
{ if (!isset($value['id'])) {
if (!isset($value['id']))
continue; continue;
if ($value['id'] == $myid) }
{ if ($value['id'] == $myid) {
$pid = $value[$this->pidname]; $pid = $value[$this->pidname];
break; break;
} }
} }
if ($pid) if ($pid) {
{ foreach ($this->arr as $value) {
foreach ($this->arr as $value) if ($value['id'] == $pid) {
{
if ($value['id'] == $pid)
{
$newarr[] = $value; $newarr[] = $value;
break; break;
} }
@ -179,33 +168,29 @@ class Tree
} }
/** /**
* 得到当前位置所有父辈数组 * 得到当前位置所有父辈数组
* @param int * @param int
* @param bool $withself 是否包含自己
* @return array * @return array
*/ */
public function getParents($myid, $withself = FALSE) public function getParents($myid, $withself = false)
{ {
$pid = 0; $pid = 0;
$newarr = []; $newarr = [];
foreach ($this->arr as $value) foreach ($this->arr as $value) {
{ if (!isset($value['id'])) {
if (!isset($value['id']))
continue; continue;
if ($value['id'] == $myid) }
{ if ($value['id'] == $myid) {
if ($withself) if ($withself) {
{
$newarr[] = $value; $newarr[] = $value;
} }
$pid = $value[$this->pidname]; $pid = $value[$this->pidname];
break; break;
} }
} }
if ($pid) if ($pid) {
{ $arr = $this->getParents($pid, true);
$arr = $this->getParents($pid, TRUE);
$newarr = array_merge($arr, $newarr); $newarr = array_merge($arr, $newarr);
} }
return $newarr; return $newarr;
@ -213,52 +198,44 @@ class Tree
/** /**
* 读取指定节点所有父类节点ID * 读取指定节点所有父类节点ID
* @param int $myid * @param int $myid
* @param boolean $withself * @param boolean $withself
* @return array * @return array
*/ */
public function getParentsIds($myid, $withself = FALSE) public function getParentsIds($myid, $withself = false)
{ {
$parentlist = $this->getParents($myid, $withself); $parentlist = $this->getParents($myid, $withself);
$parentsids = []; $parentsids = [];
foreach ($parentlist as $k => $v) foreach ($parentlist as $k => $v) {
{
$parentsids[] = $v['id']; $parentsids[] = $v['id'];
} }
return $parentsids; return $parentsids;
} }
/** /**
* 树型结构Option * 树型结构Option
* @param int $myid 表示获得这个ID下的所有子级 * @param int $myid 表示获得这个ID下的所有子级
* @param string $itemtpl 条目模板 如:"<option value=@id @selected @disabled>@spacer@name</option>" * @param string $itemtpl 条目模板 如:"<option value=@id @selected @disabled>@spacer@name</option>"
* @param mixed $selectedids 被选中的ID比如在做树型下拉框的时候需要用到 * @param mixed $selectedids 被选中的ID比如在做树型下拉框的时候需要用到
* @param mixed $disabledids 被禁用的ID比如在做树型下拉框的时候需要用到 * @param mixed $disabledids 被禁用的ID比如在做树型下拉框的时候需要用到
* @param string $itemprefix 每一项前缀 * @param string $itemprefix 每一项前缀
* @param string $toptpl 顶级栏目的模板 * @param string $toptpl 顶级栏目的模板
* @return string * @return string
*/ */
public function getTree($myid, $itemtpl = "<option value=@id @selected @disabled>@spacer@name</option>", $selectedids = '', $disabledids = '', $itemprefix = '', $toptpl = '') public function getTree($myid, $itemtpl = "<option value=@id @selected @disabled>@spacer@name</option>", $selectedids = '', $disabledids = '', $itemprefix = '', $toptpl = '')
{ {
$ret = ''; $ret = '';
$number = 1; $number = 1;
$childs = $this->getChild($myid); $childs = $this->getChild($myid);
if ($childs) if ($childs) {
{
$total = count($childs); $total = count($childs);
foreach ($childs as $value) foreach ($childs as $value) {
{
$id = $value['id']; $id = $value['id'];
$j = $k = ''; $j = $k = '';
if ($number == $total) if ($number == $total) {
{
$j .= $this->icon[2]; $j .= $this->icon[2];
$k = $itemprefix ? $this->nbsp : ''; $k = $itemprefix ? $this->nbsp : '';
} } else {
else
{
$j .= $this->icon[1]; $j .= $this->icon[1];
$k = $itemprefix ? $this->icon[0] : ''; $k = $itemprefix ? $this->icon[0] : '';
} }
@ -266,10 +243,10 @@ class Tree
$selected = $selectedids && in_array($id, (is_array($selectedids) ? $selectedids : explode(',', $selectedids))) ? 'selected' : ''; $selected = $selectedids && in_array($id, (is_array($selectedids) ? $selectedids : explode(',', $selectedids))) ? 'selected' : '';
$disabled = $disabledids && in_array($id, (is_array($disabledids) ? $disabledids : explode(',', $disabledids))) ? 'disabled' : ''; $disabled = $disabledids && in_array($id, (is_array($disabledids) ? $disabledids : explode(',', $disabledids))) ? 'disabled' : '';
$value = array_merge($value, array('selected' => $selected, 'disabled' => $disabled, 'spacer' => $spacer)); $value = array_merge($value, array('selected' => $selected, 'disabled' => $disabled, 'spacer' => $spacer));
$value = array_combine(array_map(function($k) { $value = array_combine(array_map(function ($k) {
return '@' . $k; return '@' . $k;
}, array_keys($value)), $value); }, array_keys($value)), $value);
$nstr = strtr((($value["@{$this->pidname}"] == 0 || $this->getChild($id) ) && $toptpl ? $toptpl : $itemtpl), $value); $nstr = strtr((($value["@{$this->pidname}"] == 0 || $this->getChild($id)) && $toptpl ? $toptpl : $itemtpl), $value);
$ret .= $nstr; $ret .= $nstr;
$ret .= $this->getTree($id, $itemtpl, $selectedids, $disabledids, $itemprefix . $k . $this->nbsp, $toptpl); $ret .= $this->getTree($id, $itemtpl, $selectedids, $disabledids, $itemprefix . $k . $this->nbsp, $toptpl);
$number++; $number++;
@ -279,32 +256,29 @@ class Tree
} }
/** /**
* 树型结构UL * 树型结构UL
* @param int $myid 表示获得这个ID下的所有子级 * @param int $myid 表示获得这个ID下的所有子级
* @param string $itemtpl 条目模板 如:"<li value=@id @selected @disabled>@name @childlist</li>" * @param string $itemtpl 条目模板 如:"<li value=@id @selected @disabled>@name @childlist</li>"
* @param string $selectedids 选中的ID * @param string $selectedids 选中的ID
* @param string $disabledids 禁用的ID * @param string $disabledids 禁用的ID
* @param string $wraptag 子列表包裹标签 * @param string $wraptag 子列表包裹标签
* @param string $wrapattr 子列表包裹属性
* @return string * @return string
*/ */
public function getTreeUl($myid, $itemtpl, $selectedids = '', $disabledids = '', $wraptag = 'ul', $wrapattr = '') public function getTreeUl($myid, $itemtpl, $selectedids = '', $disabledids = '', $wraptag = 'ul', $wrapattr = '')
{ {
$str = ''; $str = '';
$childs = $this->getChild($myid); $childs = $this->getChild($myid);
if ($childs) if ($childs) {
{ foreach ($childs as $value) {
foreach ($childs as $value)
{
$id = $value['id']; $id = $value['id'];
unset($value['child']); unset($value['child']);
$selected = $selectedids && in_array($id, (is_array($selectedids) ? $selectedids : explode(',', $selectedids))) ? 'selected' : ''; $selected = $selectedids && in_array($id, (is_array($selectedids) ? $selectedids : explode(',', $selectedids))) ? 'selected' : '';
$disabled = $disabledids && in_array($id, (is_array($disabledids) ? $disabledids : explode(',', $disabledids))) ? 'disabled' : ''; $disabled = $disabledids && in_array($id, (is_array($disabledids) ? $disabledids : explode(',', $disabledids))) ? 'disabled' : '';
$value = array_merge($value, array('selected' => $selected, 'disabled' => $disabled)); $value = array_merge($value, array('selected' => $selected, 'disabled' => $disabled));
$value = array_combine(array_map(function($k) { $value = array_combine(array_map(function ($k) {
return '@' . $k; return '@' . $k;
}, array_keys($value)), $value); }, array_keys($value)), $value);
$nstr = strtr($itemtpl, $value); $nstr = strtr($itemtpl, $value);
$childdata = $this->getTreeUl($id, $itemtpl, $selectedids, $disabledids, $wraptag, $wrapattr); $childdata = $this->getTreeUl($id, $itemtpl, $selectedids, $disabledids, $wraptag, $wrapattr);
$childlist = $childdata ? "<{$wraptag} {$wrapattr}>" . $childdata . "</{$wraptag}>" : ""; $childlist = $childdata ? "<{$wraptag} {$wrapattr}>" . $childdata . "</{$wraptag}>" : "";
@ -316,31 +290,29 @@ class Tree
/** /**
* 菜单数据 * 菜单数据
* @param int $myid * @param int $myid
* @param string $itemtpl * @param string $itemtpl
* @param mixed $selectedids * @param mixed $selectedids
* @param mixed $disabledids * @param mixed $disabledids
* @param string $wraptag * @param string $wraptag
* @param string $wrapattr * @param string $wrapattr
* @param int $deeplevel * @param int $deeplevel
* @return string * @return string
*/ */
public function getTreeMenu($myid, $itemtpl, $selectedids = '', $disabledids = '', $wraptag = 'ul', $wrapattr = '', $deeplevel = 0) public function getTreeMenu($myid, $itemtpl, $selectedids = '', $disabledids = '', $wraptag = 'ul', $wrapattr = '', $deeplevel = 0)
{ {
$str = ''; $str = '';
$childs = $this->getChild($myid); $childs = $this->getChild($myid);
if ($childs) if ($childs) {
{ foreach ($childs as $value) {
foreach ($childs as $value)
{
$id = $value['id']; $id = $value['id'];
unset($value['child']); unset($value['child']);
$selected = in_array($id, (is_array($selectedids) ? $selectedids : explode(',', $selectedids))) ? 'selected' : ''; $selected = in_array($id, (is_array($selectedids) ? $selectedids : explode(',', $selectedids))) ? 'selected' : '';
$disabled = in_array($id, (is_array($disabledids) ? $disabledids : explode(',', $disabledids))) ? 'disabled' : ''; $disabled = in_array($id, (is_array($disabledids) ? $disabledids : explode(',', $disabledids))) ? 'disabled' : '';
$value = array_merge($value, array('selected' => $selected, 'disabled' => $disabled)); $value = array_merge($value, array('selected' => $selected, 'disabled' => $disabled));
$value = array_combine(array_map(function($k) { $value = array_combine(array_map(function ($k) {
return '@' . $k; return '@' . $k;
}, array_keys($value)), $value); }, array_keys($value)), $value);
$bakvalue = array_intersect_key($value, array_flip(['@url', '@caret', '@class'])); $bakvalue = array_intersect_key($value, array_flip(['@url', '@caret', '@class']));
$value = array_diff_key($value, $bakvalue); $value = array_diff_key($value, $bakvalue);
$nstr = strtr($itemtpl, $value); $nstr = strtr($itemtpl, $value);
@ -364,12 +336,12 @@ class Tree
/** /**
* 特殊 * 特殊
* @param integer $myid 要查询的ID * @param integer $myid 要查询的ID
* @param string $itemtpl1 第一种HTML代码方式 * @param string $itemtpl1 第一种HTML代码方式
* @param string $itemtpl2 第二种HTML代码方式 * @param string $itemtpl2 第二种HTML代码方式
* @param mixed $selectedids 默认选中 * @param mixed $selectedids 默认选中
* @param mixed $disabledids 禁用 * @param mixed $disabledids 禁用
* @param string $itemprefix 前缀 * @param string $itemprefix 前缀
* @return string * @return string
*/ */
public function getTreeSpecial($myid, $itemtpl1, $itemtpl2, $selectedids = 0, $disabledids = 0, $itemprefix = '') public function getTreeSpecial($myid, $itemtpl1, $itemtpl2, $selectedids = 0, $disabledids = 0, $itemprefix = '')
@ -377,19 +349,14 @@ class Tree
$ret = ''; $ret = '';
$number = 1; $number = 1;
$childs = $this->getChild($myid); $childs = $this->getChild($myid);
if ($childs) if ($childs) {
{
$total = count($childs); $total = count($childs);
foreach ($childs as $id => $value) foreach ($childs as $id => $value) {
{
$j = $k = ''; $j = $k = '';
if ($number == $total) if ($number == $total) {
{
$j .= $this->icon[2]; $j .= $this->icon[2];
$k = $itemprefix ? $this->nbsp : ''; $k = $itemprefix ? $this->nbsp : '';
} } else {
else
{
$j .= $this->icon[1]; $j .= $this->icon[1];
$k = $itemprefix ? $this->icon[0] : ''; $k = $itemprefix ? $this->icon[0] : '';
} }
@ -397,9 +364,9 @@ class Tree
$selected = $selectedids && in_array($id, (is_array($selectedids) ? $selectedids : explode(',', $selectedids))) ? 'selected' : ''; $selected = $selectedids && in_array($id, (is_array($selectedids) ? $selectedids : explode(',', $selectedids))) ? 'selected' : '';
$disabled = $disabledids && in_array($id, (is_array($disabledids) ? $disabledids : explode(',', $disabledids))) ? 'disabled' : ''; $disabled = $disabledids && in_array($id, (is_array($disabledids) ? $disabledids : explode(',', $disabledids))) ? 'disabled' : '';
$value = array_merge($value, array('selected' => $selected, 'disabled' => $disabled, 'spacer' => $spacer)); $value = array_merge($value, array('selected' => $selected, 'disabled' => $disabled, 'spacer' => $spacer));
$value = array_combine(array_map(function($k) { $value = array_combine(array_map(function ($k) {
return '@' . $k; return '@' . $k;
}, array_keys($value)), $value); }, array_keys($value)), $value);
$nstr = strtr(!isset($value['@disabled']) || !$value['@disabled'] ? $itemtpl1 : $itemtpl2, $value); $nstr = strtr(!isset($value['@disabled']) || !$value['@disabled'] ? $itemtpl1 : $itemtpl2, $value);
$ret .= $nstr; $ret .= $nstr;
@ -413,7 +380,7 @@ class Tree
/** /**
* *
* 获取树状数组 * 获取树状数组
* @param string $myid 要查询的ID * @param string $myid 要查询的ID
* @param string $itemprefix 前缀 * @param string $itemprefix 前缀
* @return array * @return array
*/ */
@ -423,19 +390,14 @@ class Tree
$n = 0; $n = 0;
$data = []; $data = [];
$number = 1; $number = 1;
if ($childs) if ($childs) {
{
$total = count($childs); $total = count($childs);
foreach ($childs as $id => $value) foreach ($childs as $id => $value) {
{
$j = $k = ''; $j = $k = '';
if ($number == $total) if ($number == $total) {
{
$j .= $this->icon[2]; $j .= $this->icon[2];
$k = $itemprefix ? $this->nbsp : ''; $k = $itemprefix ? $this->nbsp : '';
} } else {
else
{
$j .= $this->icon[1]; $j .= $this->icon[1];
$k = $itemprefix ? $this->icon[0] : ''; $k = $itemprefix ? $this->icon[0] : '';
} }
@ -452,26 +414,25 @@ class Tree
/** /**
* 将getTreeArray的结果返回为二维数组 * 将getTreeArray的结果返回为二维数组
* @param array $data * @param array $data
* @param string $field
* @return array * @return array
*/ */
public function getTreeList($data = [], $field = 'name') public function getTreeList($data = [], $field = 'name')
{ {
$arr = []; $arr = [];
foreach ($data as $k => $v) foreach ($data as $k => $v) {
{
$childlist = isset($v['childlist']) ? $v['childlist'] : []; $childlist = isset($v['childlist']) ? $v['childlist'] : [];
unset($v['childlist']); unset($v['childlist']);
$v[$field] = $v['spacer'] . ' ' . $v[$field]; $v[$field] = $v['spacer'] . ' ' . $v[$field];
$v['haschild'] = $childlist ? 1 : 0; $v['haschild'] = $childlist ? 1 : 0;
if ($v['id']) if ($v['id']) {
$arr[] = $v; $arr[] = $v;
if ($childlist) }
{ if ($childlist) {
$arr = array_merge($arr, $this->getTreeList($childlist, $field)); $arr = array_merge($arr, $this->getTreeList($childlist, $field));
} }
} }
return $arr; return $arr;
} }
} }

View File

@ -11,47 +11,42 @@ class Version
/** /**
* 检测版本是否的版本要求的数据中 * 检测版本是否的版本要求的数据中
* *
* @param string $version * @param string $version
* @param array $data * @param array $data
* @return bool
*/ */
public static function check($version, $data = []) public static function check($version, $data = [])
{ {
//版本号以.分隔 //版本号以.分隔
$data = is_array($data) ? $data : [$data]; $data = is_array($data) ? $data : [$data];
if ($data) if ($data) {
{ if (in_array("*", $data) || in_array($version, $data)) {
if (in_array("*", $data) || in_array($version, $data)) return true;
{
return TRUE;
} }
$ver = explode('.', $version); $ver = explode('.', $version);
if ($ver) if ($ver) {
{
$versize = count($ver); $versize = count($ver);
//验证允许的版本 //验证允许的版本
foreach ($data as $m) foreach ($data as $m) {
{
$c = explode('.', $m); $c = explode('.', $m);
if (!$c || $versize != count($c)) if (!$c || $versize != count($c)) {
continue; continue;
}
$i = 0; $i = 0;
foreach ($c as $a => $k) foreach ($c as $a => $k) {
{ if (!self::compare($ver[$a], $k)) {
if (!self::compare($ver[$a], $k))
{
continue 2; continue 2;
} } else {
else
{
$i++; $i++;
} }
} }
if ($i == $versize) if ($i == $versize) {
return TRUE; return true;
}
} }
} }
} }
return FALSE; return false;
} }
/** /**
@ -63,31 +58,22 @@ class Version
*/ */
public static function compare($v1, $v2) public static function compare($v1, $v2)
{ {
if ($v2 == "*" || $v1 == $v2) if ($v2 == "*" || $v1 == $v2) {
{ return true;
return TRUE; } else {
}
else
{
$values = []; $values = [];
$k = explode(',', $v2); $k = explode(',', $v2);
foreach ($k as $v) foreach ($k as $v) {
{ if (strpos($v, '-') !== false) {
if (strpos($v, '-') !== FALSE)
{
list($start, $stop) = explode('-', $v); list($start, $stop) = explode('-', $v);
for ($i = $start; $i <= $stop; $i++) for ($i = $start; $i <= $stop; $i++) {
{
$values[] = $i; $values[] = $i;
} }
} } else {
else
{
$values[] = $v; $values[] = $v;
} }
} }
return in_array($v1, $values) ? TRUE : FALSE; return in_array($v1, $values) ? true : false;
} }
} }
} }

View File

@ -73,6 +73,9 @@ body {
#header-navbar li.dropdown ul.dropdown-menu { #header-navbar li.dropdown ul.dropdown-menu {
min-width: 94px; min-width: 94px;
} }
form.form-horizontal .control-label {
font-weight: normal;
}
.panel-default { .panel-default {
padding: 0 15px; padding: 0 15px;
border-color: #e4ecf3; border-color: #e4ecf3;

File diff suppressed because one or more lines are too long

View File

@ -21,6 +21,21 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'template'], function
}); });
} }
}); });
table.on('load-error.bs.table', function (e, status, res) {
if (status == 404 && $(".btn-switch.active").data("type") != "local") {
Layer.confirm(__('Store now available tips'), {
title: __('Warmtips'),
btn: [__('Switch to the local'), __('Try to reload')]
}, function (index) {
layer.close(index);
$(".btn-switch[data-type='local']").trigger("click");
}, function (index) {
layer.close(index);
table.bootstrapTable('refresh');
});
return false;
}
});
table.on('post-body.bs.table', function (e, settings, json, xhr) { table.on('post-body.bs.table', function (e, settings, json, xhr) {
var parenttable = table.closest('.bootstrap-table'); var parenttable = table.closest('.bootstrap-table');
var d = $(".fixed-table-toolbar", parenttable).find(".search input"); var d = $(".fixed-table-toolbar", parenttable).find(".search input");

File diff suppressed because one or more lines are too long

View File

@ -748,8 +748,14 @@ define('fast',['jquery', 'bootstrap', 'toastr', 'layer', 'lang'], function ($, u
return url; return url;
}, },
//获取修复后可访问的cdn链接 //获取修复后可访问的cdn链接
cdnurl: function (url) { cdnurl: function (url, domain) {
return /^(?:[a-z]+:)?\/\//i.test(url) ? url : Config.upload.cdnurl + url; var rule = new RegExp("^((?:[a-z]+:)?\\/\\/|data:image\\/)", "i");
var url = rule.test(url) ? url : Config.upload.cdnurl + url;
if (domain && !rule.test(url)) {
domain = typeof domain === 'string' ? domain : location.origin;
url = domain + url;
}
return url;
}, },
//查询Url参数 //查询Url参数
query: function (name, url) { query: function (name, url) {
@ -770,7 +776,7 @@ define('fast',['jquery', 'bootstrap', 'toastr', 'layer', 'lang'], function ($, u
title = options && options.title ? options.title : (title ? title : ""); title = options && options.title ? options.title : (title ? title : "");
url = Fast.api.fixurl(url); url = Fast.api.fixurl(url);
url = url + (url.indexOf("?") > -1 ? "&" : "?") + "dialog=1"; url = url + (url.indexOf("?") > -1 ? "&" : "?") + "dialog=1";
var area = [$(window).width() > 800 ? '800px' : '95%', $(window).height() > 600 ? '600px' : '95%']; var area = Fast.config.openArea != undefined ? Fast.config.openArea : [$(window).width() > 800 ? '800px' : '95%', $(window).height() > 600 ? '600px' : '95%'];
options = $.extend({ options = $.extend({
type: 2, type: 2,
title: title, title: title,

View File

@ -96,6 +96,10 @@ body {
min-width:94px; min-width:94px;
} }
form.form-horizontal .control-label {
font-weight: normal;
}
.panel-default { .panel-default {
padding: 0 15px; padding: 0 15px;
border-color: #e4ecf3; border-color: #e4ecf3;