diff --git a/niucloud/addon/hello_world/admin/src/layout/hellow/index.vue b/niucloud/addon/hello_world/admin/src/layout/hellow/index.vue new file mode 100644 index 000000000..d738f66b7 --- /dev/null +++ b/niucloud/addon/hello_world/admin/src/layout/hellow/index.vue @@ -0,0 +1,21 @@ + + + + + diff --git a/niucloud/addon/hello_world/app/event.php b/niucloud/addon/hello_world/app/event.php index ae85b7ce3..a8e996c2c 100644 --- a/niucloud/addon/hello_world/app/event.php +++ b/niucloud/addon/hello_world/app/event.php @@ -9,6 +9,7 @@ return [ //应用管理 'AppManage' => ['addon\hello_world\app\listener\AppManageListener'], + 'SiteLayout' => ['addon\hello_world\app\listener\SiteLayout'] ], 'subscribe' => [ diff --git a/niucloud/addon/hello_world/app/lang/zh-cn/dict.php b/niucloud/addon/hello_world/app/lang/zh-cn/dict.php index b05f981a5..c6599356f 100644 --- a/niucloud/addon/hello_world/app/lang/zh-cn/dict.php +++ b/niucloud/addon/hello_world/app/lang/zh-cn/dict.php @@ -19,5 +19,8 @@ return [ 'hello_world_link' => 'hello world链接', 'hello_world_index' => 'hello world index 插件', 'hello_world_info' => 'hello world info 插件' + ], + 'dict_site_layout' => [ + 'hellow_world' => '你好' ] ]; diff --git a/niucloud/addon/hello_world/app/listener/AppManageListener.php b/niucloud/addon/hello_world/app/listener/AppManageListener.php index 15a75a85d..c1ce86352 100644 --- a/niucloud/addon/hello_world/app/listener/AppManageListener.php +++ b/niucloud/addon/hello_world/app/listener/AppManageListener.php @@ -21,7 +21,7 @@ class AppManageListener { /** * 应用管理 - * @param $data + * @return array */ public function handle() { diff --git a/niucloud/addon/hello_world/app/listener/SiteLayout.php b/niucloud/addon/hello_world/app/listener/SiteLayout.php new file mode 100644 index 000000000..dea2eb6bb --- /dev/null +++ b/niucloud/addon/hello_world/app/listener/SiteLayout.php @@ -0,0 +1,29 @@ + get_lang("dict_site_layout.hellow_world"), + "key" => "hellow", + "image" => "static/resource/images/system/layout-hellow.jpg", + "sort" => 1 + ]; + } +} \ No newline at end of file diff --git a/niucloud/addon/hello_world/info.json b/niucloud/addon/hello_world/info.json index f2d50b5d7..666ef504e 100644 --- a/niucloud/addon/hello_world/info.json +++ b/niucloud/addon/hello_world/info.json @@ -4,7 +4,6 @@ "key": "hello_world", "version": "1.0.1", "author": "niucloud", - "url": "https://www.niucloud.com", "type": "addon", "support_app": "niucloud" } \ No newline at end of file diff --git a/niucloud/addon/hello_world/resource/images/system/layout-hellow.jpg b/niucloud/addon/hello_world/resource/images/system/layout-hellow.jpg new file mode 100644 index 000000000..9e4831eee Binary files /dev/null and b/niucloud/addon/hello_world/resource/images/system/layout-hellow.jpg differ diff --git a/niucloud/app/ExceptionHandle.php b/niucloud/app/ExceptionHandle.php index f89092007..16e1848d8 100644 --- a/niucloud/app/ExceptionHandle.php +++ b/niucloud/app/ExceptionHandle.php @@ -99,13 +99,13 @@ class ExceptionHandle extends Handle 'previous' => $e->getPrevious(), ]); } elseif ($e instanceof ValidateException) { - return fail($e->getMessage(), []); + return fail($e->getMessage()); } else if($e instanceof UnexpectedValueException){ return fail($e->getMessage(), [], 401); }else if($e instanceof AuthException || $e instanceof AdminException){ return fail($e->getMessage(), [], $e->getCode() ?: 400); }else if($e instanceof ServerException){ - return fail($e->getMessage(), [], http_code:$e->getCode()); + return fail($e->getMessage(), http_code:$e->getCode()); }else { return fail($e->getMessage(), $massageData); } diff --git a/niucloud/app/Request.php b/niucloud/app/Request.php index c8e8751ac..2477c9de7 100644 --- a/niucloud/app/Request.php +++ b/niucloud/app/Request.php @@ -28,13 +28,19 @@ class Request extends \think\Request $filter_rule = ''; foreach ($params as $param) { $key = $param[0]; + // 解析name + if (strpos($key, '/')) { + [$name, $type] = explode('/', $key); + }else{ + $name = $key; + } $default = $param[1]; $item_filter = $param[2] ?? $filter; $input[$key] = $this->paramFilter($this->param($key, $default, $filter_rule ?? ''), $item_filter); //过滤后产生空字符串,按照默认值 - if($input[$key] === '') + if($input[$name] === '') { - $input[$key] = $default; + $input[$name] = $default; } } return $input; @@ -55,13 +61,13 @@ class Request extends \think\Request "/(<[^>]*)on[a-zA-Z]+\s*=([^>]*>)/isU", "/select|join|where|drop|like|modify|rename|insert|update|table|database|alter|truncate|\'|\/\*|\.\.\/|\.\/|union|into|load_file|outfile/is" ]; - $param = preg_replace($filter_rule, '', $param); - return $param; + return preg_replace($filter_rule, '', $param); } /** * 获取登录用户的uid - * @param $params + * @param int $uid + * @return int|mixed|void */ public function uid(int $uid = 0) { @@ -87,7 +93,7 @@ class Request extends \think\Request /** * 站点id - * @param int $site_id + * @param int|string|null $site_id * @return int */ public function siteId(int|string|null $site_id = 0) @@ -116,7 +122,7 @@ class Request extends \think\Request /** * 定义站点类型 - * @param string $site_type + * @param string $app_type * @return mixed|string */ public function appType(string $app_type = ''){ @@ -129,7 +135,7 @@ class Request extends \think\Request /** * 获取管理端token - * @return void + * @return array|string|null */ public function adminToken(){ return $this->header(system_name('admin_token_name')); @@ -195,4 +201,18 @@ class Request extends \think\Request $param = $this->header(); $this->withHeader(array_merge($param, $data)); } + + /** + * 授权信息 + * @param $key + * @param $value + * @return mixed|string|void + */ + public function auth($key, $value = ''){ + if (!empty($value)) { + static::$auth_info[$key] = $value; + } else { + return static::$auth_info[$key] ?? ''; + } + } } diff --git a/niucloud/app/adminapi/config/config.php b/niucloud/app/adminapi/config/config.php index 9e9d39970..9c7de888a 100644 --- a/niucloud/app/adminapi/config/config.php +++ b/niucloud/app/adminapi/config/config.php @@ -11,5 +11,5 @@ return [ // 默认输出类型 - 'default_return_type' => 'json', + 'default_return_type' => 'json', ]; \ No newline at end of file diff --git a/niucloud/app/adminapi/config/route.php b/niucloud/app/adminapi/config/route.php index 030366974..28a8a0ff1 100644 --- a/niucloud/app/adminapi/config/route.php +++ b/niucloud/app/adminapi/config/route.php @@ -11,11 +11,11 @@ return [ // 是否强制使用路由 - 'url_route_must' => true, + 'url_route_must' => true, // 合并路由规则 - 'route_rule_merge' => true, + 'route_rule_merge' => true, // 路由是否完全匹配 - 'route_complete_match' => true, + 'route_complete_match' => true, // 是否自动转换URL中的控制器和操作名 - 'url_convert' => false, + 'url_convert' => false, ]; diff --git a/niucloud/app/adminapi/controller/addon/Addon.php b/niucloud/app/adminapi/controller/addon/Addon.php index a28600638..926824cf9 100644 --- a/niucloud/app/adminapi/controller/addon/Addon.php +++ b/niucloud/app/adminapi/controller/addon/Addon.php @@ -24,7 +24,7 @@ class Addon extends BaseAdminController */ public function getLocalAddonList() { - return success(( new CoreAddonService() )->getLocalAddonList()); + return success((new CoreAddonService())->getLocalAddonList()); } /** @@ -33,36 +33,38 @@ class Addon extends BaseAdminController */ public function install($addon) { - return ( new AddonService() )->install($addon); + return (new AddonService())->install($addon); } /** * 执行安装 * @param $addon - * @return void + * @return Response */ public function execute($addon) { - return ( new AddonService() )->executeInstall($addon); + return (new AddonService())->executeInstall($addon); } /** * 插件安装环境检测 * @param $addon - * @return mixed + * @return Response */ public function installCheck($addon) { - return ( new AddonService() )->installCheck($addon); + return (new AddonService())->installCheck($addon); } /** * 查询插件安装状态 * @param $addon + * @param $key + * @return Response */ public function getInstallState($addon, $key) { - return success(( new AddonService() )->getInstallState($addon, $key)); + return success((new AddonService())->getInstallState($addon, $key)); } /** @@ -71,7 +73,7 @@ class Addon extends BaseAdminController */ public function uninstall($addon) { - ( new AddonService() )->uninstall($addon); + (new AddonService())->uninstall($addon); return success('ADDON_UNINSTALL_SUCCESS'); } @@ -82,18 +84,19 @@ class Addon extends BaseAdminController public function lists() { $data = $this->request->params([ - [ 'title', '' ], + ['title', ''], ]); - return success(( new AddonService() )->getPage($data)); + return success((new AddonService())->getPage($data)); } /** * 插件详情 * @param int $id + * @return Response */ public function info(int $id) { - return success(( new AddonService() )->getInfo($id)); + return success((new AddonService())->getInfo($id)); } /** @@ -104,9 +107,28 @@ class Addon extends BaseAdminController */ public function setStatus(int $id, int $status) { - ( new AddonService() )->setStatus($id, $status); + (new AddonService())->setStatus($id, $status); return success('SET_SUCCESS'); } + /** + * 下载插件 + * @param $app_key + * @return Response + */ + public function download($addon){ + (new AddonService())->download($addon); + return success('DOWNLOAD_SUCCESS'); + } + + /** + * 更新插件 + * @param $app_key + * @return Response + */ + public function update($addon){ + (new AddonService())->update($addon); + return success('DOWNLOAD_SUCCESS'); + } } diff --git a/niucloud/app/adminapi/controller/addon/App.php b/niucloud/app/adminapi/controller/addon/App.php index 12912d58e..f8e42c914 100644 --- a/niucloud/app/adminapi/controller/addon/App.php +++ b/niucloud/app/adminapi/controller/addon/App.php @@ -22,7 +22,7 @@ class App extends BaseAdminController */ public function getAppList() { - return success(( new CoreAddonService() )->getAppList()); + return success((new CoreAddonService())->getAppList()); } } diff --git a/niucloud/app/adminapi/controller/aliapp/Config.php b/niucloud/app/adminapi/controller/aliapp/Config.php index 3f6c051a9..561b38632 100644 --- a/niucloud/app/adminapi/controller/aliapp/Config.php +++ b/niucloud/app/adminapi/controller/aliapp/Config.php @@ -21,7 +21,8 @@ class Config extends BaseAdminController * 获取支付宝配置信息 * @return Response */ - public function get(){ + public function get() + { return success((new AliappConfigService())->getAliappConfig()); } @@ -29,7 +30,8 @@ class Config extends BaseAdminController * 设置支付宝配置信息 * @return Response */ - public function set(){ + public function set() + { $data = $this->request->params([ ['name', ''], ['app_id', ''], @@ -49,7 +51,8 @@ class Config extends BaseAdminController * 静态资源 * @return Response */ - public function static(){ + public function static() + { return success((new AliappConfigService())->static()); } } diff --git a/niucloud/app/adminapi/controller/applet/SiteVersion.php b/niucloud/app/adminapi/controller/applet/SiteVersion.php index 93a5e85ae..01488e9d0 100644 --- a/niucloud/app/adminapi/controller/applet/SiteVersion.php +++ b/niucloud/app/adminapi/controller/applet/SiteVersion.php @@ -11,8 +11,6 @@ namespace app\adminapi\controller\applet; -use app\model\applet\AppletSiteVersion; -use app\service\admin\applet\AppletVersionService; use app\service\admin\applet\AppletVersionSiteService; use core\base\BaseAdminController; use think\Response; @@ -31,16 +29,17 @@ class SiteVersion extends BaseAdminController $data = $this->request->params([ ]); - return success(( new AppletVersionSiteService())->getPage($data)); + return success((new AppletVersionSiteService())->getPage($data)); } /** * 详情 * @param int $id + * @return Response */ public function info(int $id) { - return success(( new AppletVersionSiteService() )->getInfo($id)); + return success((new AppletVersionSiteService())->getInfo($id)); } /** @@ -48,9 +47,19 @@ class SiteVersion extends BaseAdminController * @param string $type * @return Response */ - public function getLastVersion(string $type){ - return success(( new AppletVersionSiteService() )->getLastVersion($type)); + public function getLastVersion(string $type) + { + return success((new AppletVersionSiteService())->getLastVersion($type)); } + /** + * 查看可升级的最高版本 + * @param string $type + * @return Response + */ + public function getUpgradeVersion(string $type) + { + return success((new AppletVersionSiteService())->getUpgradeVersion($type)); + } } diff --git a/niucloud/app/adminapi/controller/applet/Version.php b/niucloud/app/adminapi/controller/applet/Version.php index 2f1948333..5fd69e473 100644 --- a/niucloud/app/adminapi/controller/applet/Version.php +++ b/niucloud/app/adminapi/controller/applet/Version.php @@ -13,6 +13,7 @@ namespace app\adminapi\controller\applet; use app\service\admin\applet\AppletVersionService; use core\base\BaseAdminController; +use Exception; use think\Response; /** @@ -29,16 +30,17 @@ class Version extends BaseAdminController $data = $this->request->params([ ]); - return success(( new AppletVersionService() )->getPage($data)); + return success((new AppletVersionService())->getPage($data)); } /** * 详情 * @param int $id + * @return Response */ public function info(int $id) { - return success(( new AppletVersionService() )->getInfo($id)); + return success((new AppletVersionService())->getInfo($id)); } /** @@ -48,13 +50,13 @@ class Version extends BaseAdminController public function add() { $data = $this->request->params([ - [ 'type', '' ], - [ 'desc', '' ], - [ 'status', '' ], - [ 'path', '' ], - [ 'version', '' ], + ['type', ''], + ['desc', ''], + ['status', ''], + ['path', ''], + ['version', ''], ]); - $id = ( new AppletVersionService() )->add($data); + $id = (new AppletVersionService())->add($data); return success('ADD_SUCCESS'); } @@ -66,45 +68,49 @@ class Version extends BaseAdminController public function edit(int $id) { $data = $this->request->params([ - [ 'desc', '' ], - [ 'status', '' ], - [ 'path', '' ], - [ 'version', '' ], + ['desc', ''], + ['status', ''], + ['path', ''], + ['version', ''], ]); - ( new AppletVersionService() )->edit($id, $data); + (new AppletVersionService())->edit($id, $data); return success('EDIT_SUCCESS'); } /** * 删除 * @param int $id + * @return Response */ public function del(int $id) { - ( new AppletVersionService() )->del($id); + (new AppletVersionService())->del($id); return success('DELETE_SUCCESS'); } /** * 设置状态 * @param int $id - * @param $type + * @param $status * @return Response */ - public function setStatus(int $id, $status){ - ( new AppletVersionService() )->setStatus($id, $status); + public function setStatus(int $id, $status) + { + (new AppletVersionService())->setStatus($id, $status); return success('EDIT_SUCCESS'); } + /** * 小程序包上传 * @return Response - * @throws \Exception + * @throws Exception */ - public function upload(){ + public function upload() + { $data = $this->request->params([ ['file', 'file'], - ], true); - return success(data:( new AppletVersionService() )->upload($data['file'])); + ]); + return success(data: (new AppletVersionService())->upload($data['file'])); } } diff --git a/niucloud/app/adminapi/controller/applet/VersionDownload.php b/niucloud/app/adminapi/controller/applet/VersionDownload.php index fe34d72df..ee1a5226f 100644 --- a/niucloud/app/adminapi/controller/applet/VersionDownload.php +++ b/niucloud/app/adminapi/controller/applet/VersionDownload.php @@ -13,6 +13,7 @@ namespace app\adminapi\controller\applet; use app\service\admin\applet\AppletDownloadService; use core\base\BaseAdminController; +use think\response\File; /** * 小程序版本下载控制器 @@ -23,9 +24,10 @@ class VersionDownload extends BaseAdminController /** * 下载 * @param $id - * @return mixed + * @return File */ - public function download($id){ + public function download($id) + { return (new AppletDownloadService())->download($id); } diff --git a/niucloud/app/adminapi/controller/article/Article.php b/niucloud/app/adminapi/controller/article/Article.php index b0b532a43..8c599b74d 100644 --- a/niucloud/app/adminapi/controller/article/Article.php +++ b/niucloud/app/adminapi/controller/article/Article.php @@ -29,21 +29,22 @@ class Article extends BaseAdminController public function lists() { $data = $this->request->params([ - [ 'title', '' ], - [ 'category_id', '' ], - [ 'sort', '' ], - [ 'is_show', '' ], + ['title', ''], + ['category_id', ''], + ['sort', ''], + ['is_show', ''], ]); - return success(( new ArticleService() )->getPage($data)); + return success((new ArticleService())->getPage($data)); } /** * 文章详情 * @param int $id + * @return Response */ public function info(int $id) { - return success(( new ArticleService() )->getInfo($id)); + return success((new ArticleService())->getInfo($id)); } /** @@ -53,20 +54,20 @@ class Article extends BaseAdminController public function add() { $data = $this->request->params([ - [ 'title', '' ], - [ 'category_id', '' ], - [ 'intro', '' ], - [ 'summary', '' ], - [ 'image', '' ], - [ 'author', '' ], - [ 'content', '' , false], - [ 'visit_virtual', 0 ], - [ 'is_show', 1 ], - [ 'sort', 0 ], + ['title', ''], + ['category_id', ''], + ['intro', ''], + ['summary', ''], + ['image', ''], + ['author', ''], + ['content', '', false], + ['visit_virtual', 0], + ['is_show', 1], + ['sort', 0], ]); $this->validate($data, 'app\validate\article\Article.add'); - $id = ( new ArticleService() )->add($data); - return success('ADD_SUCCESS', [ 'id' => $id ]); + $id = (new ArticleService())->add($data); + return success('ADD_SUCCESS', ['id' => $id]); } /** @@ -77,30 +78,31 @@ class Article extends BaseAdminController public function edit(int $id) { $data = $this->request->params([ - [ 'title', '' ], - [ 'category_id', '' ], - [ 'intro', '' ], - [ 'summary', '' ], - [ 'image', '' ], - [ 'author', '' ], - [ 'content', '' , false], - [ 'visit_virtual', 0 ], - [ 'is_show', 1 ], - [ 'sort', 0 ], + ['title', ''], + ['category_id', ''], + ['intro', ''], + ['summary', ''], + ['image', ''], + ['author', ''], + ['content', '', false], + ['visit_virtual', 0], + ['is_show', 1], + ['sort', 0], ]); $this->validate($data, 'app\validate\article\Article.edit'); - ( new ArticleService() )->edit($id, $data); + (new ArticleService())->edit($id, $data); return success('EDIT_SUCCESS'); } /** * 文章删除 * @param int $id + * @return Response */ public function del(int $id) { - ( new ArticleService() )->del($id); + (new ArticleService())->del($id); return success('DELETE_SUCCESS'); } diff --git a/niucloud/app/adminapi/controller/article/ArticleCategory.php b/niucloud/app/adminapi/controller/article/ArticleCategory.php index ac5c16519..3324441fd 100644 --- a/niucloud/app/adminapi/controller/article/ArticleCategory.php +++ b/niucloud/app/adminapi/controller/article/ArticleCategory.php @@ -21,7 +21,8 @@ class ArticleCategory extends BaseAdminController * 文章分类列表 * @return Response */ - public function lists(){ + public function lists() + { $data = $this->request->params([ ['name', ''], ]); @@ -32,15 +33,18 @@ class ArticleCategory extends BaseAdminController * 查询所有分类(文章添加,编辑,索引) * @return Response */ - public function all(){ + public function all() + { return success((new ArticleCategoryService())->getAll()); } /** * 文章分类详情 * @param int $id + * @return Response */ - public function info(int $id){ + public function info(int $id) + { return success((new ArticleCategoryService())->getInfo($id)); } @@ -48,7 +52,8 @@ class ArticleCategory extends BaseAdminController * 添加文章分类 * @return Response */ - public function add(){ + public function add() + { $data = $this->request->params([ ['name', ''], ['is_show', 1], @@ -61,10 +66,11 @@ class ArticleCategory extends BaseAdminController /** * 文章分类编辑 - * @param int $category_id //分类id + * @param int $category_id //分类id * @return Response */ - public function edit(int $category_id){ + public function edit(int $category_id) + { $data = $this->request->params([ ['name', ''], ['is_show', 1], @@ -78,8 +84,10 @@ class ArticleCategory extends BaseAdminController /** * 文章分类删除 * @param int $category_id + * @return Response */ - public function del(int $category_id){ + public function del(int $category_id) + { (new ArticleCategoryService())->del($category_id); return success('DELETE_SUCCESS'); } diff --git a/niucloud/app/adminapi/controller/auth/Auth.php b/niucloud/app/adminapi/controller/auth/Auth.php index 22b9509d9..60bd51776 100644 --- a/niucloud/app/adminapi/controller/auth/Auth.php +++ b/niucloud/app/adminapi/controller/auth/Auth.php @@ -14,6 +14,10 @@ namespace app\adminapi\controller\auth; use app\service\admin\auth\AuthService; use app\service\admin\auth\AuthSiteService; use core\base\BaseAdminController; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; +use think\Response; class Auth extends BaseAdminController @@ -22,15 +26,17 @@ class Auth extends BaseAdminController /** * 登录用户菜单列表的接口 */ - public function authMenuList(){ + public function authMenuList() + { return success((new AuthService())->getAuthMenuList(1)); } /** * 获取登录用户信息 - * @return \think\Response + * @return Response */ - public function get(){ + public function get() + { return success((new AuthService())->getAuthInfo()); } @@ -38,9 +44,10 @@ class Auth extends BaseAdminController /** * 修改登录用户信息 * @param $field - * @return \think\Response + * @return Response */ - public function modify($field){ + public function modify($field) + { $data = $this->request->params([ ['value', ''], ['field', $field] @@ -54,7 +61,8 @@ class Auth extends BaseAdminController /** * 更新用户 */ - public function edit(){ + public function edit() + { $data = $this->request->params([ ['real_name', ''], ['head_img', ''], @@ -67,20 +75,22 @@ class Auth extends BaseAdminController /** * 获取当前登录站点信息 - * @return \think\Response + * @return Response */ - public function site(){ + public function site() + { return success((new AuthSiteService())->getSiteInfo()); } /** * 选择可以选择的页面 - * @return \think\Response - * @throws \think\db\exception\DataNotFoundException - * @throws \think\db\exception\DbException - * @throws \think\db\exception\ModelNotFoundException + * @return Response + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ - public function getShowMenuList(){ + public function getShowMenuList() + { return success((new AuthSiteService())->getShowMenuList()); } } diff --git a/niucloud/app/adminapi/controller/channel/H5.php b/niucloud/app/adminapi/controller/channel/H5.php index a51394654..95b84347b 100644 --- a/niucloud/app/adminapi/controller/channel/H5.php +++ b/niucloud/app/adminapi/controller/channel/H5.php @@ -21,7 +21,8 @@ class H5 extends BaseAdminController * 获取H5配置信息 * @return Response */ - public function get(){ + public function get() + { return success((new H5Service())->getH5()); } @@ -29,7 +30,8 @@ class H5 extends BaseAdminController * 设置H5配置信息 * @return Response */ - public function set(){ + public function set() + { $data = $this->request->params([ ['is_open', 0], ]); diff --git a/niucloud/app/adminapi/controller/diy/Config.php b/niucloud/app/adminapi/controller/diy/Config.php index 7f568e7a4..9e8c64ad9 100644 --- a/niucloud/app/adminapi/controller/diy/Config.php +++ b/niucloud/app/adminapi/controller/diy/Config.php @@ -13,6 +13,7 @@ namespace app\adminapi\controller\diy; use app\service\admin\diy\DiyConfigService; use core\base\BaseAdminController; +use think\Response; /** @@ -24,24 +25,24 @@ class Config extends BaseAdminController { /** * 获取底部导航 - * @return \think\Response + * @return Response */ public function getBottom() { - return success(( new DiyConfigService() )->getBottomConfig()); + return success((new DiyConfigService())->getBottomConfig()); } /** * 设置底部导航 - * @return \think\Response + * @return Response */ public function setBottom() { $data = $this->request->params([ - [ 'menu', [] ] + ['menu', []] ]); - ( new DiyConfigService() )->setBottomConfig($data[ 'menu' ]); - return success('SUCCESS'); + (new DiyConfigService())->setBottomConfig($data['menu']); + return success(); } } diff --git a/niucloud/app/adminapi/controller/diy/Diy.php b/niucloud/app/adminapi/controller/diy/Diy.php index 4cc147cc8..1fa519366 100644 --- a/niucloud/app/adminapi/controller/diy/Diy.php +++ b/niucloud/app/adminapi/controller/diy/Diy.php @@ -13,6 +13,11 @@ namespace app\adminapi\controller\diy; use app\service\admin\diy\DiyService; use core\base\BaseAdminController; +use Exception; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; +use think\Response; /** @@ -24,117 +29,120 @@ class Diy extends BaseAdminController { /** * @notes 获取自定义页面分页列表 - * @return \think\Response + * @return Response */ public function lists() { $data = $this->request->params([ - [ "title", "" ], - [ "type", "" ], - [ 'mode', '' ] + ["title", ""], + ["type", ""], + ['mode', ''] ]); - return success(( new DiyService() )->getPage($data)); + return success((new DiyService())->getPage($data)); } /** * @notes 获取自定义页面列表 - * @return \think\Response + * @return Response + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function getList() { $data = $this->request->params([ - [ "title", "" ], - [ "type", "" ], - [ 'mode', '' ] + ["title", ""], + ["type", ""], + ['mode', ''] ]); - return success(( new DiyService() )->getList($data)); + return success((new DiyService())->getList($data)); } /** * 自定义页面详情 * @param int $id - * @return \think\Response + * @return Response */ public function info(int $id) { - return success(( new DiyService() )->getInfo($id)); + return success((new DiyService())->getInfo($id)); } /** * 添加自定义页面 - * @return \think\Response + * @return Response */ public function add() { $data = $this->request->params([ - [ "title", "" ], - [ "name", "" ], - [ "type", "" ], - [ 'template', '' ], - [ 'mode', 'diy' ], // 页面展示模式,diy:自定义,fixed:固定 - [ "value", "" ], - [ 'is_default', 0 ], - [ 'is_change', '' ] + ["title", ""], + ["name", ""], + ["type", ""], + ['template', ''], + ['mode', 'diy'], // 页面展示模式,diy:自定义,fixed:固定 + ["value", ""], + ['is_default', 0], + ['is_change', ''] ]); $this->validate($data, 'app\validate\diy\Diy.add'); - $id = ( new DiyService() )->add($data); - return success('ADD_SUCCESS', [ 'id' => $id ]); + $id = (new DiyService())->add($data); + return success('ADD_SUCCESS', ['id' => $id]); } /** * 自定义页面编辑 * @param $id - * @return \think\Response + * @return Response */ public function edit($id) { $data = $this->request->params([ - [ "title", "" ], - [ "name", "" ], - [ "value", "" ], - [ 'is_change', '' ] + ["title", ""], + ["name", ""], + ["value", ""], + ['is_change', ''] ]); $this->validate($data, 'app\validate\diy\Diy.edit'); - ( new DiyService() )->edit($id, $data); + (new DiyService())->edit($id, $data); return success('MODIFY_SUCCESS'); } /** * 自定义页面删除 - * @param $id - * @return \think\Response + * @param int $id + * @return Response */ public function del(int $id) { - ( new DiyService() )->del($id); + (new DiyService())->del($id); return success('DELETE_SUCCESS'); } /** * 设为使用 * @param $id - * @return \think\Response - * @throws \Exception + * @return Response + * @throws Exception */ public function setUse($id) { - ( new DiyService() )->setUse($id); + (new DiyService())->setUse($id); return success('MODIFY_SUCCESS'); } /** * 获取页面初始化数据 - * @return \think\Response + * @return Response */ public function getPageInit() { $params = $this->request->params([ - [ 'id', "" ], - [ "name", "" ], - [ "type", "" ], - [ 'template', '' ], - [ "title", "" ], + ['id', ""], + ["name", ""], + ["type", ""], + ['template', ''], + ["title", ""], ]); $diy_service = new DiyService(); @@ -152,14 +160,14 @@ class Diy extends BaseAdminController /** * 获取页面模板 - * @return \think\Response + * @return Response */ public function getTemplate() { $params = $this->request->params([ - [ 'type', "" ], // 页面类型模板 - [ 'action', '' ], // 页面是否装修标识,为空标识不装修,decorate:装修 - [ 'mode', '' ] // 页面展示模式,diy:自定义,fixed:固定 + ['type', ""], // 页面类型模板 + ['action', ''], // 页面是否装修标识,为空标识不装修,decorate:装修 + ['mode', ''] // 页面展示模式,diy:自定义,fixed:固定 ]); $diy_service = new DiyService(); return success($diy_service->getTemplate($params)); @@ -168,13 +176,14 @@ class Diy extends BaseAdminController /** * 修改页面分享内容 * @param int $id + * @return Response */ public function modifyShare(int $id) { $data = $this->request->params([ - [ "share", "" ], + ["share", ""], ]); - ( new DiyService() )->modifyShare($id, $data); + (new DiyService())->modifyShare($id, $data); return success('MODIFY_SUCCESS'); } @@ -183,7 +192,7 @@ class Diy extends BaseAdminController */ public function getDecoratePage() { - return success(( new DiyService() )->getDecoratePage()); + return success((new DiyService())->getDecoratePage()); } /** @@ -192,12 +201,12 @@ class Diy extends BaseAdminController public function changeTemplate() { $data = $this->request->params([ - [ "id", "" ], - [ 'type', '' ], // 页面类型 - [ 'mode', '' ], // 页面展示模式,diy:自定义,fixed:固定 - [ 'template', '' ] // 模板名称 + ["id", ""], + ['type', ''], // 页面类型 + ['mode', ''], // 页面展示模式,diy:自定义,fixed:固定 + ['template', ''] // 模板名称 ]); - return success(( new DiyService() )->changeTemplate($data)); + return success((new DiyService())->changeTemplate($data)); } /** @@ -206,10 +215,10 @@ class Diy extends BaseAdminController public function getPreviewData() { $data = $this->request->params([ - [ "id", "" ], - [ 'name', '' ] + ["id", ""], + ['name', ''] ]); - $res = ( new DiyService() )->getPreviewData($data); + $res = (new DiyService())->getPreviewData($data); return success($res); } diff --git a/niucloud/app/adminapi/controller/diy/DiyRoute.php b/niucloud/app/adminapi/controller/diy/DiyRoute.php index f3cd0cb4e..5fb37c645 100644 --- a/niucloud/app/adminapi/controller/diy/DiyRoute.php +++ b/niucloud/app/adminapi/controller/diy/DiyRoute.php @@ -13,6 +13,7 @@ namespace app\adminapi\controller\diy; use app\service\admin\diy\DiyRouteService; use core\base\BaseAdminController; +use think\Response; /** @@ -24,80 +25,81 @@ class DiyRoute extends BaseAdminController { /** * @notes 获取自定义路由表列表 - * @return \think\Response + * @return Response */ public function lists() { $data = $this->request->params([ - [ "title", "" ], + ["title", ""], ]); - return success(( new DiyRouteService() )->getList($data)); + return success((new DiyRouteService())->getList($data)); } /** * 自定义路由表详情 * @param int $id - * @return \think\Response + * @return Response */ public function info(int $id) { - return success(( new DiyRouteService() )->getInfo($id)); + return success((new DiyRouteService())->getInfo($id)); } /** * 自定义路由表详情 * @param string $name + * @return Response */ public function getInfoByName(string $name) { - return success(( new DiyRouteService() )->getInfoByName($name)); + return success((new DiyRouteService())->getInfoByName($name)); } /** * 添加自定义路由表 - * @return \think\Response + * @return Response */ public function add() { $data = $this->request->params([ - [ "title", "" ], - [ "name", "" ], - [ "page", "" ], - [ "share", "" ], - [ "is_share", "" ] + ["title", ""], + ["name", ""], + ["page", ""], + ["share", ""], + ["is_share", ""] ]); $this->validate($data, 'app\validate\diy\DiyRoute.add'); - $id = ( new DiyRouteService() )->add($data); - return success('ADD_SUCCESS', [ 'id' => $id ]); + $id = (new DiyRouteService())->add($data); + return success('ADD_SUCCESS', ['id' => $id]); } /** * 自定义路由表编辑 * @param $id - * @return \think\Response + * @return Response */ public function edit($id) { $data = $this->request->params([ - [ "title", "" ], - [ "name", "" ], - [ "page", "" ], - [ "share", "" ], - [ "is_share", "" ] + ["title", ""], + ["name", ""], + ["page", ""], + ["share", ""], + ["is_share", ""] ]); $this->validate($data, 'app\validate\diy\DiyRoute.edit'); - ( new DiyRouteService() )->edit($id, $data); + (new DiyRouteService())->edit($id, $data); return success('MODIFY_SUCCESS'); } /** * 自定义路由表删除 - * @param $id - * @return \think\Response + * @param int $id + * @return Response */ public function del(int $id) { - ( new DiyRouteService() )->del($id); + (new DiyRouteService())->del($id); return success('DELETE_SUCCESS'); } @@ -107,14 +109,14 @@ class DiyRoute extends BaseAdminController public function modifyShare() { $data = $this->request->params([ - [ 'share', '' ], - [ 'title', '' ], - [ 'name', '' ], - [ 'page', '' ], - [ 'is_share', 0 ], - [ 'sort', 0 ] + ['share', ''], + ['title', ''], + ['name', ''], + ['page', ''], + ['is_share', 0], + ['sort', 0] ]); - ( new DiyRouteService() )->modifyShare($data); + (new DiyRouteService())->modifyShare($data); return success('MODIFY_SUCCESS'); } diff --git a/niucloud/app/adminapi/controller/generator/Generator.php b/niucloud/app/adminapi/controller/generator/Generator.php index b378720ac..0e085b70d 100644 --- a/niucloud/app/adminapi/controller/generator/Generator.php +++ b/niucloud/app/adminapi/controller/generator/Generator.php @@ -13,6 +13,10 @@ namespace app\adminapi\controller\generator; use app\service\admin\generator\GenerateService; use core\base\BaseController; +use Exception; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; use think\Response; /** @@ -30,34 +34,38 @@ class Generator extends BaseController { $data = $this->request->params([ - [ 'table_name', '' ], - [ 'table_content', '' ], + ['table_name', ''], + ['table_content', ''], ]); - return success(( new GenerateService() )->getPage($data)); + return success((new GenerateService())->getPage($data)); } /** * 代码生成详情 * @param int $id * @return Response + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function info(int $id) { - return success(( new GenerateService() )->getInfo($id)); + return success((new GenerateService())->getInfo($id)); } /** * 添加代码生成 * @return Response + * @throws Exception */ public function add() { $data = $this->request->params([ - [ "table_name", "" ], + ["table_name", ""], ], false); $this->validate($data, 'app\validate\generator\Generator.add'); - $id = ( new GenerateService() )->add($data); - return success('ADD_SUCCESS', [ 'id' => $id ]); + $id = (new GenerateService())->add($data); + return success('ADD_SUCCESS', ['id' => $id]); } /** @@ -68,15 +76,15 @@ class Generator extends BaseController public function edit($id) { $data = $this->request->params([ - [ "table_name", "" ], - [ "table_content", "" ], - [ "class_name", "" ], - [ "module_name", "" ], - [ "edit_type", "1" ], - [ "table_column", "" ], + ["table_name", ""], + ["table_content", ""], + ["class_name", ""], + ["module_name", ""], + ["edit_type", "1"], + ["table_column", ""], ], false); $this->validate($data, 'app\validate\generator\Generator.edit'); - ( new GenerateService() )->edit($id, $data); + (new GenerateService())->edit($id, $data); return success('MODIFY_SUCCESS'); } @@ -87,7 +95,7 @@ class Generator extends BaseController */ public function del(int $id) { - ( new GenerateService() )->del($id); + (new GenerateService())->del($id); return success('DELETE_SUCCESS'); } @@ -98,10 +106,10 @@ class Generator extends BaseController public function create() { $data = $this->request->params([ - [ 'id', '' ], + ['id', ''], ]); - $data = ( new GenerateService() )->generate($data); + $data = (new GenerateService())->generate($data); return success('ADD_SUCCESS', $data); } @@ -112,10 +120,10 @@ class Generator extends BaseController public function tableList() { $data = $this->request->params([ - [ "name", "" ], - [ "comment", "" ], + ["name", ""], + ["comment", ""], ]); - $list = ( new GenerateService() )->tableList($data); + $list = (new GenerateService())->tableList($data); return success('ADD_SUCCESS', $list); } diff --git a/niucloud/app/adminapi/controller/login/Captcha.php b/niucloud/app/adminapi/controller/login/Captcha.php index bffc104da..5deb56d18 100644 --- a/niucloud/app/adminapi/controller/login/Captcha.php +++ b/niucloud/app/adminapi/controller/login/Captcha.php @@ -23,7 +23,8 @@ class Captcha extends BaseAdminController * 创建验证码 * @return Response */ - public function create(){ + public function create() + { return success((new CaptchaService())->create()); } @@ -31,7 +32,8 @@ class Captcha extends BaseAdminController * 一次校验验证码 * @return Response */ - public function check(){ + public function check() + { return success((new CaptchaService())->check()); } @@ -39,7 +41,8 @@ class Captcha extends BaseAdminController * 二次校验验证码 * @return Response */ - public function verification(){ + public function verification() + { return success((new CaptchaService())->verification()); } diff --git a/niucloud/app/adminapi/controller/login/Config.php b/niucloud/app/adminapi/controller/login/Config.php index 45a4522d0..308f0a6ab 100644 --- a/niucloud/app/adminapi/controller/login/Config.php +++ b/niucloud/app/adminapi/controller/login/Config.php @@ -12,7 +12,6 @@ namespace app\adminapi\controller\login; use app\service\admin\auth\ConfigService; -use app\service\core\upload\CoreImageService; use core\base\BaseAdminController; use think\Response; @@ -27,7 +26,7 @@ class Config extends BaseAdminController */ public function getConfig() { - return success(( new ConfigService() )->getConfig()); + return success((new ConfigService())->getConfig()); } /** @@ -37,12 +36,12 @@ class Config extends BaseAdminController public function setConfig() { $data = $this->request->params([ - [ 'is_captcha', 0 ], - [ 'is_site_captcha', 0 ], - [ 'bg', '' ], - [ 'site_bg', '' ], + ['is_captcha', 0], + ['is_site_captcha', 0], + ['bg', ''], + ['site_bg', ''], ]); - ( new ConfigService() )->setConfig($data); + (new ConfigService())->setConfig($data); return success('MODIFY_SUCCESS'); } } diff --git a/niucloud/app/adminapi/controller/login/Login.php b/niucloud/app/adminapi/controller/login/Login.php index 1aa47a756..4dd9ef8a0 100644 --- a/niucloud/app/adminapi/controller/login/Login.php +++ b/niucloud/app/adminapi/controller/login/Login.php @@ -26,12 +26,12 @@ class Login extends BaseAdminController { $data = $this->request->params([ - [ 'username', '' ], - [ 'password', '' ], + ['username', ''], + ['password', ''], ]); //参数验证 //验证码验证 - $result = ( new LoginService() )->login($data[ 'username' ], $data[ 'password' ], $app_type); + $result = (new LoginService())->login($data['username'], $data['password'], $app_type); if (!$result) { //账号密码错误...., 重置验证码 return fail('USER_ERROR'); @@ -46,18 +46,17 @@ class Login extends BaseAdminController */ public function logout() { - ( new LoginService )->logout(); + (new LoginService)->logout(); return success('LOGOUT'); } - /** * 获取登录设置 * @return Response */ public function getConfig() { - return success(( new ConfigService() )->getConfig()); + return success((new ConfigService())->getConfig()); } } diff --git a/niucloud/app/adminapi/controller/member/Account.php b/niucloud/app/adminapi/controller/member/Account.php index c0977a5ff..4d63fd64e 100644 --- a/niucloud/app/adminapi/controller/member/Account.php +++ b/niucloud/app/adminapi/controller/member/Account.php @@ -26,13 +26,13 @@ class Account extends BaseAdminController public function point() { $data = $this->request->params([ - [ 'member_id', '' ], - [ 'from_type', '' ], - [ 'create_time', [] ], - [ 'keywords', '' ], + ['member_id', ''], + ['from_type', ''], + ['create_time', []], + ['keywords', ''], ]); - $data[ 'account_type' ] = 'point'; - return success(( new MemberAccountService() )->getPage($data)); + $data['account_type'] = 'point'; + return success((new MemberAccountService())->getPage($data)); } /** @@ -41,23 +41,22 @@ class Account extends BaseAdminController public function sumPoint() { $data = $this->request->params([ - [ 'member_id', '' ], + ['member_id', ''], ]); $member_account_service = new MemberAccountService(); $member_service = new MemberService(); - if(empty($data['member_id'])) - { + if (empty($data['member_id'])) { $commission_data = [ 'point_get' => $member_service->getSum('point_get'),//累计 'point_use' => abs($member_account_service->getExpensesSumAccount(MemberAccountTypeDict::POINT)), ]; return success($commission_data); - }else{ + } else { $info = $member_account_service->getMemberAccountInfo($data['member_id']); $commission_data = [ 'point_get' => $info['point_get'], - 'point_use' => abs($member_account_service->getExpensesSumAccount(MemberAccountTypeDict::POINT,$data['member_id'])), + 'point_use' => abs($member_account_service->getExpensesSumAccount(MemberAccountTypeDict::POINT, $data['member_id'])), ]; return success($commission_data); } @@ -70,13 +69,13 @@ class Account extends BaseAdminController public function balance() { $data = $this->request->params([ - [ 'member_id', '' ], - [ 'from_type', '' ], - [ 'create_time', [] ], - [ 'keywords', '' ], + ['member_id', ''], + ['from_type', ''], + ['create_time', []], + ['keywords', ''], ]); - $data[ 'account_type' ] = 'balance'; - return success(( new MemberAccountService() )->getPage($data)); + $data['account_type'] = 'balance'; + return success((new MemberAccountService())->getPage($data)); } /** @@ -86,13 +85,13 @@ class Account extends BaseAdminController public function money() { $data = $this->request->params([ - [ 'member_id', '' ], - [ 'from_type', '' ], - [ 'create_time', [] ], - [ 'keywords', '' ], + ['member_id', ''], + ['from_type', ''], + ['create_time', []], + ['keywords', ''], ]); - $data[ 'account_type' ] = 'money'; - return success(( new MemberAccountService() )->getPage($data)); + $data['account_type'] = 'money'; + return success((new MemberAccountService())->getPage($data)); } /** @@ -101,12 +100,12 @@ class Account extends BaseAdminController public function adjustPoint() { $data = $this->request->params([ - [ 'member_id', '' ], - [ 'account_data', 0 ], - [ 'memo', '' ], + ['member_id', ''], + ['account_data', 0], + ['memo', ''], ]); - $res = ( new MemberAccountService() )->adjustPoint($data); - return success('SUCCESS', [ 'id' => $res ]); + $res = (new MemberAccountService())->adjustPoint($data); + return success('SUCCESS', ['id' => $res]); } /** @@ -115,12 +114,12 @@ class Account extends BaseAdminController public function adjustBalance() { $data = $this->request->params([ - [ 'member_id', '' ], - [ 'account_data', 0 ], - [ 'memo', '' ], + ['member_id', ''], + ['account_data', 0], + ['memo', ''], ]); - $res = ( new MemberAccountService() )->adjustBalance($data); - return success('SUCCESS', [ 'id' => $res ]); + $res = (new MemberAccountService())->adjustBalance($data); + return success('SUCCESS', ['id' => $res]); } /** @@ -130,12 +129,12 @@ class Account extends BaseAdminController public function adjustMoney() { $data = $this->request->params([ - [ 'member_id', '' ], - [ 'account_data', 0 ], - [ 'memo', '' ], + ['member_id', ''], + ['account_data', 0], + ['memo', ''], ]); - $res = ( new MemberAccountService() )->adjustMoney($data); - return success('SUCCESS', [ 'id' => $res ]); + $res = (new MemberAccountService())->adjustMoney($data); + return success('SUCCESS', ['id' => $res]); } /** @@ -145,13 +144,13 @@ class Account extends BaseAdminController public function commission() { $data = $this->request->params([ - [ 'member_id', '' ], - [ 'from_type', '' ], - [ 'create_time', [] ], - [ 'keywords', '' ], + ['member_id', ''], + ['from_type', ''], + ['create_time', []], + ['keywords', ''], ]); - $data[ 'account_type' ] = 'commission'; - return success(( new MemberAccountService() )->getPage($data)); + $data['account_type'] = 'commission'; + return success((new MemberAccountService())->getPage($data)); } /** @@ -160,13 +159,12 @@ class Account extends BaseAdminController public function sumCommission() { $data = $this->request->params([ - [ 'member_id', '' ], + ['member_id', ''], ]); $member_account_service = new MemberAccountService(); $member_service = new MemberService(); - if(empty($data['member_id'])) - { + if (empty($data['member_id'])) { $commission_data = [ 'total_commission' => $member_service->getSum('commission_get'),//累计 'commission' => $member_service->getSum('commission'),//未提现 @@ -174,7 +172,7 @@ class Account extends BaseAdminController 'commission_cash_outing' => $member_service->getSum('commission_cash_outing'),//提现中 ]; return success($commission_data); - }else{ + } else { $info = $member_account_service->getMemberAccountInfo($data['member_id']); $commission_data = [ 'commission' => $info['commission'], @@ -192,29 +190,29 @@ class Account extends BaseAdminController public function sumBalance() { $data = $this->request->params([ - [ 'member_id', '' ], + ['member_id', ''], ]); $member_account_service = new MemberAccountService(); - if(empty($data['member_id'])) - { + if (empty($data['member_id'])) { $balance_data = [ MemberAccountTypeDict::BALANCE => number_format($member_account_service->getSumAccount(MemberAccountTypeDict::BALANCE), 2), MemberAccountTypeDict::MONEY => number_format($member_account_service->getSumAccount(MemberAccountTypeDict::MONEY), 2), ]; return success($balance_data); - }else{ + } else { return success($member_account_service->getMemberAccountInfo($data['member_id'])); } } /** * 账户变化类型 - * @param $account_type + * @param string $account_type + * @return Response */ public function changeType(string $account_type) { - $res = ( new MemberAccountService() )->getFromType($account_type); + $res = (new MemberAccountService())->getFromType($account_type); return success($res); } diff --git a/niucloud/app/adminapi/controller/member/CashOut.php b/niucloud/app/adminapi/controller/member/CashOut.php index f7b0ccd96..bc9f3cb1d 100644 --- a/niucloud/app/adminapi/controller/member/CashOut.php +++ b/niucloud/app/adminapi/controller/member/CashOut.php @@ -54,7 +54,7 @@ class CashOut extends BaseAdminController ['refuse_reason', ''], ]); (new MemberCashOutService())->audit($id, $action, $data); - return success('SUCCESS'); + return success(); } /** @@ -79,14 +79,15 @@ class CashOut extends BaseAdminController ['transfer_type', ''] ]); (new MemberCashOutService())->transfer($id, $data); - return success('SUCCESS'); + return success(); } /** * 状态 * @return Response */ - public function getStatusList(){ + public function getStatusList() + { return success(MemberCashOutDict::getStatus()); } diff --git a/niucloud/app/adminapi/controller/member/Config.php b/niucloud/app/adminapi/controller/member/Config.php index 50f8cfa18..648f27bb3 100644 --- a/niucloud/app/adminapi/controller/member/Config.php +++ b/niucloud/app/adminapi/controller/member/Config.php @@ -23,7 +23,7 @@ class Config extends BaseAdminController */ public function getLoginConfig() { - return success(( new MemberConfigService() )->getLoginConfig()); + return success((new MemberConfigService())->getLoginConfig()); } /** @@ -33,14 +33,14 @@ class Config extends BaseAdminController public function setLoginConfig() { $data = $this->request->params([ - [ 'is_username', 1 ], - [ 'is_mobile', 0 ], - [ 'is_auth_register', 1 ], - [ 'is_bind_mobile', 0 ], - [ 'agreement_show', 0 ] + ['is_username', 1], + ['is_mobile', 0], + ['is_auth_register', 1], + ['is_bind_mobile', 0], + ['agreement_show', 0] ]); $this->validate($data, 'app\validate\member\LoginConfig.set'); - ( new MemberConfigService() )->setLoginConfig($data); + (new MemberConfigService())->setLoginConfig($data); return success('MODIFY_SUCCESS'); } @@ -50,7 +50,7 @@ class Config extends BaseAdminController */ public function getCashOutConfig() { - return success(( new MemberConfigService() )->getCashOutConfig()); + return success((new MemberConfigService())->getCashOutConfig()); } /** @@ -60,15 +60,15 @@ class Config extends BaseAdminController public function setCashOutConfig() { $data = $this->request->params([ - [ 'is_open', 0 ], //是否开启 - [ 'min', 0.01 ], //最低提现金额 - [ 'rate', 0 ], //提现手续费比率 - [ 'is_auto_verify', 0 ], //是否自动审核 - [ 'is_auto_transfer', 0 ], //是否自动转账 - [ 'transfer_type', [] ] //转账方式 + ['is_open', 0], //是否开启 + ['min', 0.01], //最低提现金额 + ['rate', 0], //提现手续费比率 + ['is_auto_verify', 0], //是否自动审核 + ['is_auto_transfer', 0], //是否自动转账 + ['transfer_type', []] //转账方式 ]); $this->validate($data, 'app\validate\member\CashOutConfig.set'); - ( new MemberConfigService() )->setCashOutConfig($data); + (new MemberConfigService())->setCashOutConfig($data); return success('SET_SUCCESS'); } @@ -76,21 +76,23 @@ class Config extends BaseAdminController * 获取会员配置 * @return Response */ - public function getMemberConfig(){ - return success(( new MemberConfigService() )->getMemberConfig()); + public function getMemberConfig() + { + return success((new MemberConfigService())->getMemberConfig()); } /** * 设置会员配置 * @return Response */ - public function setMemberConfig(){ + public function setMemberConfig() + { $data = $this->request->params([ - [ 'prefix', '' ], - [ 'length', 10 ] + ['prefix', ''], + ['length', 10] ]); $this->validate($data, 'app\validate\member\MemberConfig.set'); - ( new MemberConfigService() )->setMemberConfig($data); + (new MemberConfigService())->setMemberConfig($data); return success('MODIFY_SUCCESS'); } } diff --git a/niucloud/app/adminapi/controller/member/Member.php b/niucloud/app/adminapi/controller/member/Member.php index 7a6ce885f..45d50c420 100644 --- a/niucloud/app/adminapi/controller/member/Member.php +++ b/niucloud/app/adminapi/controller/member/Member.php @@ -16,6 +16,9 @@ use app\dict\member\MemberRegisterChannelDict; use app\dict\member\MemberRegisterTypeDict; use app\service\admin\member\MemberService; use core\base\BaseAdminController; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; use think\Response; class Member extends BaseAdminController @@ -38,7 +41,7 @@ class Member extends BaseAdminController /** * 会员详情 - * @param int $member_id + * @param int $id * @return Response */ public function info(int $id) @@ -113,7 +116,7 @@ class Member extends BaseAdminController /** * 会员使用场景 - * @return array|mixed|string + * @return Response */ public function getMemberRegisterType() { @@ -123,6 +126,9 @@ class Member extends BaseAdminController /** * 会员列表 * @return Response + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function getMemberList() { @@ -144,9 +150,10 @@ class Member extends BaseAdminController /** * 设置会员的状态 * @param $status - * @return void + * @return Response */ - public function setStatus($status){ + public function setStatus($status) + { $data = $this->request->params([ ['member_ids', []], @@ -160,7 +167,8 @@ class Member extends BaseAdminController * 获取状态枚举 * @return Response */ - public function getStatusList(){ + public function getStatusList() + { return success(MemberDict::getStatus()); } @@ -168,7 +176,8 @@ class Member extends BaseAdminController * 获取会员编码 * @return Response */ - public function getMemberNo(){ + public function getMemberNo() + { $member_no = (new MemberService())->getMemberNo(); return success('SUCCESS', $member_no); } diff --git a/niucloud/app/adminapi/controller/member/MemberLabel.php b/niucloud/app/adminapi/controller/member/MemberLabel.php index f04370074..55e24cb74 100644 --- a/niucloud/app/adminapi/controller/member/MemberLabel.php +++ b/niucloud/app/adminapi/controller/member/MemberLabel.php @@ -13,6 +13,9 @@ namespace app\adminapi\controller\member; use app\service\admin\member\MemberLabelService; use core\base\BaseAdminController; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; use think\Response; class MemberLabel extends BaseAdminController @@ -21,7 +24,8 @@ class MemberLabel extends BaseAdminController * 会员标签列表 * @return Response */ - public function lists(){ + public function lists() + { $data = $this->request->params([ ['label_name', ''], @@ -32,8 +36,10 @@ class MemberLabel extends BaseAdminController /** * 会员标签详情 * @param int $id + * @return Response */ - public function info(int $id){ + public function info(int $id) + { return success((new MemberLabelService())->getInfo($id)); } @@ -41,7 +47,8 @@ class MemberLabel extends BaseAdminController * 添加会员标签 * @return Response */ - public function add(){ + public function add() + { $data = $this->request->params([ ['label_name', ''], @@ -56,7 +63,8 @@ class MemberLabel extends BaseAdminController /** * 菜单或接口更新 */ - public function edit($id){ + public function edit($id) + { $data = $this->request->params([ ['label_name', ''], ['memo', ''], @@ -70,8 +78,10 @@ class MemberLabel extends BaseAdminController /** * 会员标签删除 * @param int $id + * @return Response */ - public function del(int $id){ + public function del(int $id) + { (new MemberLabelService())->del($id); return success('DELETE_SUCCESS'); @@ -79,9 +89,13 @@ class MemberLabel extends BaseAdminController /** * 获取标签 - * @return void + * @return Response + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ - public function getAll(){ + public function getAll() + { return success((new MemberLabelService())->getAll()); } diff --git a/niucloud/app/adminapi/controller/niucloud/Module.php b/niucloud/app/adminapi/controller/niucloud/Module.php new file mode 100644 index 000000000..d48e98042 --- /dev/null +++ b/niucloud/app/adminapi/controller/niucloud/Module.php @@ -0,0 +1,46 @@ +getAuthInfo()); + } + + /** + * 设置 授权信息 + */ + public function setAuthorize() + { + $data = $this->request->params([ + ['auth_code', ''], + ['auth_secret', ''] + ]); + + return success("SUCCESS", (new NiucloudService())->setAuthorize($data)); + } + + /** + * 获取 授权信息 + */ + public function getAuthorize() + { + return success((new NiucloudService())->getAuthorize()); + } +} diff --git a/niucloud/app/adminapi/controller/notice/Notice.php b/niucloud/app/adminapi/controller/notice/Notice.php index d3d5dae3e..fc72e269b 100644 --- a/niucloud/app/adminapi/controller/notice/Notice.php +++ b/niucloud/app/adminapi/controller/notice/Notice.php @@ -36,6 +36,7 @@ class Notice extends BaseAdminController $res = (new NoticeService())->getInfo($key); return success($res); } + /** * 消息启动与关闭 * @return Response @@ -79,13 +80,12 @@ class Notice extends BaseAdminController { //参数获取 $sms_type_list = SmsDict::getType(); - if(!array_key_exists($sms_type, $sms_type_list)) throw new AdminException('SMS_TYPE_NOT_EXIST'); + if (!array_key_exists($sms_type, $sms_type_list)) throw new AdminException('SMS_TYPE_NOT_EXIST'); //数据验证 $data = [ ['is_use', 0] ]; - foreach ($sms_type_list[$sms_type]['params'] as $k_param => $v_param) - { + foreach ($sms_type_list[$sms_type]['params'] as $k_param => $v_param) { $data[] = [$k_param, '']; } diff --git a/niucloud/app/adminapi/controller/notice/NoticeLog.php b/niucloud/app/adminapi/controller/notice/NoticeLog.php index 138c3d4b4..49d834ca4 100644 --- a/niucloud/app/adminapi/controller/notice/NoticeLog.php +++ b/niucloud/app/adminapi/controller/notice/NoticeLog.php @@ -25,18 +25,18 @@ class NoticeLog extends BaseAdminController public function lists() { $data = $this->request->params([ - [ 'key', '' ], - [ 'receiver', '' ], - [ 'create_time', [] ] + ['key', ''], + ['receiver', ''], + ['create_time', []] ]); - $res = ( new NoticeLogService() )->getPage($data); + $res = (new NoticeLogService())->getPage($data); return success($res); } public function info($id) { - $res = ( new NoticeLogService() )->getInfo($id); + $res = (new NoticeLogService())->getInfo($id); return success($res); } diff --git a/niucloud/app/adminapi/controller/notice/SmsLog.php b/niucloud/app/adminapi/controller/notice/SmsLog.php index 60303af6d..33531e07b 100644 --- a/niucloud/app/adminapi/controller/notice/SmsLog.php +++ b/niucloud/app/adminapi/controller/notice/SmsLog.php @@ -11,7 +11,6 @@ namespace app\adminapi\controller\notice; -use app\service\admin\notice\NoticeLogService; use app\service\admin\notice\NoticeSmsLogService; use core\base\BaseAdminController; use think\Response; @@ -26,18 +25,18 @@ class SmsLog extends BaseAdminController public function lists() { $data = $this->request->params([ - [ 'mobile', '' ], - [ 'sms_type', '' ], - [ 'key', '' ], + ['mobile', ''], + ['sms_type', ''], + ['key', ''], ]); - $res = ( new NoticeSmsLogService() )->getPage($data); + $res = (new NoticeSmsLogService())->getPage($data); return success($res); } public function info($id) { - $res = ( new NoticeSmsLogService() )->getInfo($id); + $res = (new NoticeSmsLogService())->getInfo($id); return success($res); } diff --git a/niucloud/app/adminapi/controller/order/Recharge.php b/niucloud/app/adminapi/controller/order/Recharge.php index 83c3d04b6..5e768c1e2 100644 --- a/niucloud/app/adminapi/controller/order/Recharge.php +++ b/niucloud/app/adminapi/controller/order/Recharge.php @@ -59,19 +59,6 @@ class Recharge extends BaseAdminController return fail($res); } - - /** - * 充值统计 - */ - public function stat() - { - $data = $this->request->params([ - [ 'member_id', '' ], - ]); - $res = (new RechargeOrderService())->stat($data); - return success($res); - } - /** * 退款列表 * @return Response @@ -91,7 +78,7 @@ class Recharge extends BaseAdminController /** * 退款详情 - * @param int $order_id + * @param int $refund_id * @return Response */ public function refundDetail(int $refund_id) @@ -101,7 +88,6 @@ class Recharge extends BaseAdminController /** * 查询退款状态 - * @param $type * @return Response */ public function refundStatus() @@ -117,5 +103,17 @@ class Recharge extends BaseAdminController return success((new RechargeOrderRefundService())->stat()); } + /** + * 充值统计 + */ + public function stat() + { + $data = $this->request->params([ + ['member_id', ''], + ]); + $res = (new RechargeOrderService())->stat($data); + return success($res); + } + } diff --git a/niucloud/app/adminapi/controller/pay/Pay.php b/niucloud/app/adminapi/controller/pay/Pay.php new file mode 100644 index 000000000..a4466cf01 --- /dev/null +++ b/niucloud/app/adminapi/controller/pay/Pay.php @@ -0,0 +1,61 @@ +request->params([ + ['create_time', []], + ['out_trade_no', ''], + ['status', ''] + ]); + return success(data: (new PayService())->getAuditPage($data)); + } + + /** + * 查询详情 + * @param string $out_trade_no + * @return \think\Response + */ + public function detail(int $id){ + return success(data: (new PayService())->getDetail($id)); + } + + /** + * 支付审核通过 + * @param string $out_trade_no + * @return \think\Response + */ + public function pass(string $out_trade_no){ + return success(data: (new PayService())->pass($out_trade_no)); + } + + /** + * 审核拒绝 + * @param string $out_trade_no + * @return void + */ + public function refuse(string $out_trade_no){ + $reason = input('reason', ''); + return success(data: (new PayService())->refuse($out_trade_no, $reason)); + } +} \ No newline at end of file diff --git a/niucloud/app/adminapi/controller/pay/PayChannel.php b/niucloud/app/adminapi/controller/pay/PayChannel.php index 972ad4792..d9e32084b 100644 --- a/niucloud/app/adminapi/controller/pay/PayChannel.php +++ b/niucloud/app/adminapi/controller/pay/PayChannel.php @@ -14,6 +14,9 @@ namespace app\adminapi\controller\pay; use app\dict\pay\PayDict; use app\service\admin\pay\PayChannelService; use core\base\BaseAdminController; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; use think\Response; class PayChannel extends BaseAdminController @@ -23,7 +26,8 @@ class PayChannel extends BaseAdminController * 支付渠道设置 * @return Response */ - public function set($channel, $type){ + public function set($channel, $type) + { $data = $this->request->params([ ['is_default', 0], ['config', []], @@ -40,19 +44,21 @@ class PayChannel extends BaseAdminController * 支付渠道列表 * @return Response */ - public function lists(){ - return success((new PayChannelService())->getChannelList()); + public function lists() + { + return success((new PayChannelService())->getChannelList()); } /** * 通过渠道获取支付配置 * @param $channel * @return Response - * @throws \think\db\exception\DataNotFoundException - * @throws \think\db\exception\DbException - * @throws \think\db\exception\ModelNotFoundException + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ - public function getListByChannel($channel){ + public function getListByChannel($channel) + { return success((new PayChannelService())->getListByChannel($channel)); } @@ -61,7 +67,8 @@ class PayChannel extends BaseAdminController * 支付设置 * @return Response */ - public function setTransfer(){ + public function setTransfer() + { $data = $this->request->params([ ['wechatpay_config', []], ['alipay_config', []], @@ -76,7 +83,8 @@ class PayChannel extends BaseAdminController * 多渠道支付设置 * @return Response */ - public function setAll(){ + public function setAll() + { $data = $this->request->params([ ['config', []], ]); diff --git a/niucloud/app/adminapi/controller/site/Site.php b/niucloud/app/adminapi/controller/site/Site.php index c2af25072..fd3fb98d1 100644 --- a/niucloud/app/adminapi/controller/site/Site.php +++ b/niucloud/app/adminapi/controller/site/Site.php @@ -38,6 +38,7 @@ class Site extends BaseAdminController /** * 站点详情 * @param int $id + * @return Response */ public function info(int $id) { @@ -65,21 +66,6 @@ class Site extends BaseAdminController return success('ADD_SUCCESS', ['site_id' => $site_id]); } - /** - * 菜单或接口更新 - */ - public function edit($id) - { - $data = $this->request->params([ - ['site_name', ''], - ['group_id', 0], - ['expire_time', 0] - ]); - $this->validate($data, 'app\validate\site\Site.edit'); - (new SiteService())->edit($id, $data); - return success('MODIFY_SUCCESS'); - } - /** * 站点状态 * @return Response @@ -93,7 +79,8 @@ class Site extends BaseAdminController * 站点菜单 * @return Response */ - public function menu(){ + public function menu() + { return success((new AuthSiteService())->getMenuList(1, 'all')); } @@ -106,7 +93,22 @@ class Site extends BaseAdminController ['status', SiteDict::CLOSE], ]); (new SiteService())->edit($id, $data); - return success('SUCCESS'); + return success(); + } + + /** + * 菜单或接口更新 + */ + public function edit($id) + { + $data = $this->request->params([ + ['site_name', ''], + ['group_id', 0], + ['expire_time', 0] + ]); + $this->validate($data, 'app\validate\site\Site.edit'); + (new SiteService())->edit($id, $data); + return success('MODIFY_SUCCESS'); } /** @@ -118,8 +120,9 @@ class Site extends BaseAdminController ['status', SiteDict::ON], ]); (new SiteService())->edit($id, $data); - return success('SUCCESS'); + return success(); } + public function indexConfig() { diff --git a/niucloud/app/adminapi/controller/site/SiteAccount.php b/niucloud/app/adminapi/controller/site/SiteAccount.php index 66f965c2f..2daa9e707 100644 --- a/niucloud/app/adminapi/controller/site/SiteAccount.php +++ b/niucloud/app/adminapi/controller/site/SiteAccount.php @@ -12,10 +12,7 @@ namespace app\adminapi\controller\site; use app\dict\site\SiteAccountLogDict; -use app\dict\site\SiteDict; -use app\service\admin\auth\AuthSiteService; use app\service\admin\site\SiteAccountLogService; -use app\service\admin\site\SiteService; use core\base\BaseAdminController; use think\Response; @@ -37,11 +34,13 @@ class SiteAccount extends BaseAdminController /** * 账单详情 * @param int $id + * @return Response */ public function info(int $id) { return success((new SiteAccountLogService())->getInfo($id)); } + /** * 累计账单 */ diff --git a/niucloud/app/adminapi/controller/site/SiteGroup.php b/niucloud/app/adminapi/controller/site/SiteGroup.php index 1a8a90a97..9bd62ff54 100644 --- a/niucloud/app/adminapi/controller/site/SiteGroup.php +++ b/niucloud/app/adminapi/controller/site/SiteGroup.php @@ -13,6 +13,7 @@ namespace app\adminapi\controller\site; use app\service\admin\site\SiteGroupService; use core\base\BaseAdminController; +use Exception; use think\Response; /** @@ -26,7 +27,8 @@ class SiteGroup extends BaseAdminController * 站点列表 * @return Response */ - public function lists(){ + public function lists() + { $data = $this->request->params([ ['keywords', ''], ]); @@ -38,16 +40,18 @@ class SiteGroup extends BaseAdminController * @param int $group_id * @return Response */ - public function info(int $group_id){ + public function info(int $group_id) + { return success((new SiteGroupService())->getInfo($group_id)); } /** * 添加分组 * @return Response - * @throws \Exception + * @throws Exception */ - public function add(){ + public function add() + { $data = $this->request->params([ ['group_name', ''], ['group_desc', ''], @@ -63,7 +67,8 @@ class SiteGroup extends BaseAdminController * @param $group_id * @return Response */ - public function edit($group_id){ + public function edit($group_id) + { $data = $this->request->params([ ['group_name', ''], ['group_desc', ''], @@ -79,7 +84,8 @@ class SiteGroup extends BaseAdminController * @param $group_id * @return Response */ - public function del($group_id){ + public function del($group_id) + { (new SiteGroupService())->del($group_id); return success('DELETE_SUCCESS'); @@ -89,8 +95,9 @@ class SiteGroup extends BaseAdminController * 所有分组 * @return Response */ - public function all(){ - return success( (new SiteGroupService())->getAll()); + public function all() + { + return success((new SiteGroupService())->getAll()); } } diff --git a/niucloud/app/adminapi/controller/site/User.php b/niucloud/app/adminapi/controller/site/User.php index d01e3c812..6e4a8eb22 100644 --- a/niucloud/app/adminapi/controller/site/User.php +++ b/niucloud/app/adminapi/controller/site/User.php @@ -15,6 +15,7 @@ use app\dict\sys\UserDict; use app\service\admin\site\SiteUserService; use app\service\admin\user\UserService; use core\base\BaseAdminController; +use Exception; use think\Response; /** @@ -24,7 +25,8 @@ use think\Response; */ class User extends BaseAdminController { - public function lists(){ + public function lists() + { $data = $this->request->params([ ['username', ''], ['realname', ''], @@ -41,15 +43,18 @@ class User extends BaseAdminController * @param $uid * @return Response */ - public function info($uid){ + public function info($uid) + { return success((new SiteUserService())->getInfo($uid)); } /** * 新增用户 * @return Response + * @throws Exception */ - public function add(){ + public function add() + { $data = $this->request->params([ ['username', ''], ['password', ''], @@ -67,7 +72,8 @@ class User extends BaseAdminController /** * 更新用户 */ - public function edit($uid){ + public function edit($uid) + { $data = $this->request->params([ ['real_name', ''], ['head_img', ''], @@ -85,7 +91,8 @@ class User extends BaseAdminController * @param $field * @return Response */ - public function modify($uid, $field){ + public function modify($uid, $field) + { $data = $this->request->params([ ['value', ''], ['field', $field] @@ -99,8 +106,10 @@ class User extends BaseAdminController /** * 删除单个用户 * @param $uid + * @return Response */ - public function del($uid){ + public function del($uid) + { (new UserService())->del($uid); return success('DELETE_SUCCESS'); } @@ -108,7 +117,8 @@ class User extends BaseAdminController /** * 锁定用户 */ - public function lock($uid){ + public function lock($uid) + { (new SiteUserService())->lock($uid); return success('MODIFY_SUCCESS'); @@ -117,7 +127,8 @@ class User extends BaseAdminController /** * 解锁用户 */ - public function unlock($uid){ + public function unlock($uid) + { (new SiteUserService())->unlock($uid); return success('MODIFY_SUCCESS'); diff --git a/niucloud/app/adminapi/controller/site/UserLog.php b/niucloud/app/adminapi/controller/site/UserLog.php index c66931b08..5031844ae 100644 --- a/niucloud/app/adminapi/controller/site/UserLog.php +++ b/niucloud/app/adminapi/controller/site/UserLog.php @@ -21,7 +21,8 @@ class UserLog extends BaseAdminController * 操作日志列表 * @return Response */ - public function lists(){ + public function lists() + { $data = $this->request->params([ ['uid', 0], ['create_time', []], @@ -41,7 +42,8 @@ class UserLog extends BaseAdminController * @param $id * @return Response */ - public function info($id){ + public function info($id) + { return success((new UserLogService())->getInfo($id)); } diff --git a/niucloud/app/adminapi/controller/stat/SiteStat.php b/niucloud/app/adminapi/controller/stat/SiteStat.php index 04957ede1..e4d6f098d 100644 --- a/niucloud/app/adminapi/controller/stat/SiteStat.php +++ b/niucloud/app/adminapi/controller/stat/SiteStat.php @@ -13,6 +13,7 @@ namespace app\adminapi\controller\stat; use app\service\admin\stat\SiteStatService; use core\base\BaseAdminController; +use think\Response; /** * 统计数据 @@ -23,7 +24,7 @@ class SiteStat extends BaseAdminController { /** * 首页数据 - * @return \think\Response + * @return Response */ public function index() { diff --git a/niucloud/app/adminapi/controller/stat/Stat.php b/niucloud/app/adminapi/controller/stat/Stat.php index 064c185f1..381b616b8 100644 --- a/niucloud/app/adminapi/controller/stat/Stat.php +++ b/niucloud/app/adminapi/controller/stat/Stat.php @@ -13,6 +13,7 @@ namespace app\adminapi\controller\stat; use app\service\admin\stat\StatService; use core\base\BaseAdminController; +use think\Response; /** * 统计数据 @@ -23,7 +24,7 @@ class Stat extends BaseAdminController { /** * 首页数据 - * @return \think\Response + * @return Response */ public function index() { diff --git a/niucloud/app/adminapi/controller/sys/Agreement.php b/niucloud/app/adminapi/controller/sys/Agreement.php index 8d2f738e5..43d7d64c6 100644 --- a/niucloud/app/adminapi/controller/sys/Agreement.php +++ b/niucloud/app/adminapi/controller/sys/Agreement.php @@ -48,7 +48,8 @@ class Agreement extends BaseAdminController * @param string $key * @return Response */ - public function edit(string $key){ + public function edit(string $key) + { $data = $this->request->params([ ['title', ''], ['content', ''], diff --git a/niucloud/app/adminapi/controller/sys/App.php b/niucloud/app/adminapi/controller/sys/App.php index d1b5c8005..12018ca55 100644 --- a/niucloud/app/adminapi/controller/sys/App.php +++ b/niucloud/app/adminapi/controller/sys/App.php @@ -13,6 +13,7 @@ namespace app\adminapi\controller\sys; use app\service\admin\sys\AppService; use core\base\BaseAdminController; +use think\Response; /** * 应用管理 @@ -21,9 +22,10 @@ class App extends BaseAdminController { /** * 获取应用链接列表 - * @return \think\Response + * @return Response */ - public function getAppList(){ + public function getAppList() + { return success((new AppService())->getAppList()); } diff --git a/niucloud/app/adminapi/controller/sys/Area.php b/niucloud/app/adminapi/controller/sys/Area.php index d5c520544..691a64bdb 100644 --- a/niucloud/app/adminapi/controller/sys/Area.php +++ b/niucloud/app/adminapi/controller/sys/Area.php @@ -13,22 +13,24 @@ namespace app\adminapi\controller\sys; use app\service\admin\sys\AreaService; use core\base\BaseAdminController; +use think\Response; class Area extends BaseAdminController { /** * 拖过pid获取子项列表 * @param int $pid - * @return mixed + * @return Response */ - public function listByPid(int $pid){ + public function listByPid(int $pid) + { return success((new AreaService())->getListByPid($pid)); } /** * 获取层级列表 * @param int $level - * @return mixed + * @return Response */ public function tree(int $level) { @@ -36,10 +38,10 @@ class Area extends BaseAdminController } /** - * @param string $address - * 地址解析 + * @return Response */ - public function addressInfo(){ + public function addressInfo() + { $data = $this->request->params([ ['address', ''], ]); @@ -47,10 +49,10 @@ class Area extends BaseAdminController } /** - * @param string $location - * 逆地址解析 + * @return Response */ - public function contraryAddress(){ + public function contraryAddress() + { $data = $this->request->params([ ['location', ''], ]); diff --git a/niucloud/app/adminapi/controller/sys/Attachment.php b/niucloud/app/adminapi/controller/sys/Attachment.php index 50dd47012..12c8bd4c9 100644 --- a/niucloud/app/adminapi/controller/sys/Attachment.php +++ b/niucloud/app/adminapi/controller/sys/Attachment.php @@ -25,13 +25,13 @@ class Attachment extends BaseAdminController public function lists() { $data = $this->request->params([ - [ 'att_type', '' ], - [ 'cate_id', 0 ], - [ 'real_name', '' ], - [ 'page', 0 ], - [ 'limit', 0 ], + ['att_type', ''], + ['cate_id', 0], + ['real_name', ''], + ['page', 0], + ['limit', 0], ]); - return success(( new AttachmentService() )->getPage($data)); + return success((new AttachmentService())->getPage($data)); } /** @@ -51,9 +51,9 @@ class Attachment extends BaseAdminController public function batchDel() { $data = $this->request->params([ - [ 'att_ids', [] ], + ['att_ids', []], ]); - ( new AttachmentService() )->delAll($data[ 'att_ids' ]); + (new AttachmentService())->delAll($data['att_ids']); return success('DELETE_SUCCESS'); } @@ -64,11 +64,11 @@ class Attachment extends BaseAdminController public function addCategory() { $data = $this->request->params([ - [ 'type', FileDict::IMAGE ], - [ 'name', '' ] + ['type', FileDict::IMAGE], + ['name', ''] ]); $this->validate($data, 'app\validate\sys\AttachmentCategory.add'); - ( new AttachmentService() )->addCategory($data); + (new AttachmentService())->addCategory($data); return success('ADD_SUCCESS'); } @@ -78,10 +78,10 @@ class Attachment extends BaseAdminController public function categoryLists() { $data = $this->request->params([ - [ 'type', '' ], - [ 'name', '' ], + ['type', ''], + ['name', ''], ]); - return success(( new AttachmentService() )->getCategoryList($data)); + return success((new AttachmentService())->getCategoryList($data)); } /** @@ -91,10 +91,10 @@ class Attachment extends BaseAdminController public function editCategory($id) { $data = $this->request->params([ - [ 'name', '' ] + ['name', ''] ]); $this->validate($data, 'app\validate\sys\AttachmentCategory.edit'); - ( new AttachmentService() )->editCategory($id, $data); + (new AttachmentService())->editCategory($id, $data); return success('EDIT_SUCCESS'); } @@ -105,36 +105,35 @@ class Attachment extends BaseAdminController */ public function deleteCategory($id) { - ( new AttachmentService() )->delCategory($id); + (new AttachmentService())->delCategory($id); return success('DELETE_SUCCESS'); } /** * 移动图片分组 - * @return void + * @return Response */ public function moveCategory($att_id) { $data = $this->request->params([ - [ 'cate_id', '' ] + ['cate_id', ''] ]); - ( new AttachmentService() )->modifyCategory($att_id, $data[ 'cate_id' ]); - return success('SUCCESS'); + (new AttachmentService())->modifyCategory($att_id, $data['cate_id']); + return success(); } /** * 批量移动图片分组 - * @param $att_ids * @return Response */ public function batchMoveCategory() { $data = $this->request->params([ - [ 'cate_id', '' ], - [ 'att_ids', [] ] + ['cate_id', ''], + ['att_ids', []] ]); - ( new AttachmentService() )->batchModifyCategory($data[ 'att_ids' ], $data[ 'cate_id' ]); - return success('SUCCESS'); + (new AttachmentService())->batchModifyCategory($data['att_ids'], $data['cate_id']); + return success(); } /** @@ -143,9 +142,9 @@ class Attachment extends BaseAdminController public function getIconCategoryList() { $data = $this->request->params([ - [ 'name', '' ], + ['name', ''], ]); - return success(( new AttachmentService() )->getIconCategoryList($data)); + return success((new AttachmentService())->getIconCategoryList($data)); } /** @@ -154,12 +153,12 @@ class Attachment extends BaseAdminController public function getIconList() { $data = $this->request->params([ - [ 'page', 0 ], - [ 'limit', 0 ], - [ 'cate_id', 0 ], - [ 'real_name', '' ], + ['page', 0], + ['limit', 0], + ['cate_id', 0], + ['real_name', ''], ]); - return success(( new AttachmentService() )->getIconList($data)); + return success((new AttachmentService())->getIconList($data)); } } diff --git a/niucloud/app/adminapi/controller/sys/Channel.php b/niucloud/app/adminapi/controller/sys/Channel.php index f1479e124..a532b95fe 100644 --- a/niucloud/app/adminapi/controller/sys/Channel.php +++ b/niucloud/app/adminapi/controller/sys/Channel.php @@ -13,14 +13,14 @@ namespace app\adminapi\controller\sys; use app\dict\common\ChannelDict; use core\base\BaseAdminController; +use think\Response; class Channel extends BaseAdminController { /** * 获取渠道列表 - * @param int $level - * @return mixed + * @return Response */ public function getChannelType() { diff --git a/niucloud/app/adminapi/controller/sys/Common.php b/niucloud/app/adminapi/controller/sys/Common.php index 9916cce90..fe2c5173d 100644 --- a/niucloud/app/adminapi/controller/sys/Common.php +++ b/niucloud/app/adminapi/controller/sys/Common.php @@ -13,6 +13,7 @@ namespace app\adminapi\controller\sys; use app\dict\sys\DateDict; use core\base\BaseAdminController; +use think\Response; /** * 公共数据字典 @@ -21,17 +22,19 @@ class Common extends BaseAdminController { /** * 月份 - * @return \think\Response + * @return Response */ - public function getMonth(){ + public function getMonth() + { return success((new DateDict())->getMonth()); } /** * 星期 - * @return \think\Response + * @return Response */ - public function getWeek(){ + public function getWeek() + { return success((new DateDict())->getWeek()); } diff --git a/niucloud/app/adminapi/controller/sys/Config.php b/niucloud/app/adminapi/controller/sys/Config.php index 2eaf22d2f..720cebc06 100644 --- a/niucloud/app/adminapi/controller/sys/Config.php +++ b/niucloud/app/adminapi/controller/sys/Config.php @@ -21,7 +21,8 @@ class Config extends BaseAdminController * 获取网站设置 * @return Response */ - public function getWebsite(){ + public function getWebsite() + { return success((new ConfigService())->getWebSite()); } @@ -29,23 +30,24 @@ class Config extends BaseAdminController * 网站设置 * @return Response */ - public function setWebsite(){ + public function setWebsite() + { $data = $this->request->params([ - ["site_name",""], - ["logo",""], - ["keywords",""], - ["desc",""], - ["latitude",""], - ["longitude",""], - ["province_id",0], - ["city_id",0], - ["district_id",0], - ["address",""], - ["full_address",""], - ["phone",""], - ["business_hours",""], - ["site_name",""], - ["logo",""], + ["site_name", ""], + ["logo", ""], + ["keywords", ""], + ["desc", ""], + ["latitude", ""], + ["longitude", ""], + ["province_id", 0], + ["city_id", 0], + ["district_id", 0], + ["address", ""], + ["full_address", ""], + ["phone", ""], + ["business_hours", ""], + ["site_name", ""], + ["logo", ""], ["front_end_name", ""], ["front_end_logo", ""], ["icon", ""] @@ -54,9 +56,9 @@ class Config extends BaseAdminController (new ConfigService())->setWebSite($data); $service_data = $this->request->params([ - ["wechat_code",""], - ["enterprise_wechat",""], - ["tel",""], + ["wechat_code", ""], + ["enterprise_wechat", ""], + ["tel", ""], ]); (new ConfigService())->setService($service_data); @@ -67,14 +69,16 @@ class Config extends BaseAdminController * 获取版权信息 * @return Response */ - public function getCopyright(){ + public function getCopyright() + { return success((new ConfigService())->getCopyright()); } /**设置版权信息 * @return Response */ - public function setCopyright(){ + public function setCopyright() + { $data = $this->request->params([ ['icp', ''], ['gov_record', ''], @@ -93,7 +97,8 @@ class Config extends BaseAdminController * 场景域名 * @return Response */ - public function getSceneDomain(){ + public function getSceneDomain() + { return success((new ConfigService())->getSceneDomain()); } @@ -101,14 +106,16 @@ class Config extends BaseAdminController * 获取服务信息 * @return Response */ - public function getServiceInfo(){ + public function getServiceInfo() + { return success((new ConfigService())->getService()); } /**设置版权信息 * @return Response */ - public function setMap(){ + public function setMap() + { $data = $this->request->params([ ['key', ''], ]); @@ -120,7 +127,8 @@ class Config extends BaseAdminController * 获取地图设置 * @return Response */ - public function getMap(){ + public function getMap() + { return success((new ConfigService())->getMap()); } @@ -144,6 +152,26 @@ class Config extends BaseAdminController return success(); } + /** + * 获取站点首页列表(如果正在使用is_use = 1) + */ + public function getAdminIndexList() + { + return success((new ConfigService())->getAdminIndexList()); + } + + /** + * 首页配置 + */ + public function setAdminIndex() + { + $data = $this->request->params([ + ['view_path', ''], + ]); + (new ConfigService())->setAdminIndexConfig($data); + return success(); + } + /** * 设置快捷菜单 */ @@ -161,6 +189,6 @@ class Config extends BaseAdminController */ public function getShortcutMenu() { - return success(data:(new ConfigService())->getShortcutMenu()); + return success(data: (new ConfigService())->getShortcutMenu()); } } diff --git a/niucloud/app/adminapi/controller/sys/Menu.php b/niucloud/app/adminapi/controller/sys/Menu.php index 5f3b668e2..20ee45626 100644 --- a/niucloud/app/adminapi/controller/sys/Menu.php +++ b/niucloud/app/adminapi/controller/sys/Menu.php @@ -17,7 +17,6 @@ use app\dict\sys\MethodDict; use app\service\admin\install\InstallSystemService; use app\service\admin\sys\MenuService; use core\base\BaseAdminController; -use think\Exception; use think\Response; class Menu extends BaseAdminController @@ -27,17 +26,19 @@ class Menu extends BaseAdminController * 菜单列表(todo 限制只有平台端可以访问) * @return Response */ - public function lists($app_type){ + public function lists($app_type) + { return success((new MenuService())->getAllMenuList($app_type, 'all', 1)); } /** * 菜单信息 - * @param $id + * @param $menu_key * @return Response */ - public function info($menu_key){ + public function info($menu_key) + { return success((new MenuService())->get($menu_key)); } @@ -45,7 +46,8 @@ class Menu extends BaseAdminController * 新增菜单接口 * @return Response */ - public function add(){ + public function add() + { $data = $this->request->params([ ['menu_name', ''], ['menu_type', 0], @@ -71,7 +73,8 @@ class Menu extends BaseAdminController /** * 菜单或接口更新 */ - public function edit($menu_key){ + public function edit($menu_key) + { $data = $this->request->params([ ['menu_name', ''], ['parent_key', ''], @@ -98,7 +101,8 @@ class Menu extends BaseAdminController * 获取菜单类型静态资源 * @return Response */ - public function getMenuType(){ + public function getMenuType() + { return success(MenuTypeDict::getMenuType()); } @@ -106,7 +110,8 @@ class Menu extends BaseAdminController * 获取请求方式 * @return Response */ - public function getMethodType(){ + public function getMethodType() + { return success(MethodDict::getMethodType()); } @@ -114,14 +119,15 @@ class Menu extends BaseAdminController * 删除菜单 * @param $menu_key * @return Response - * @throws Exception */ - public function del($menu_key){ + public function del($menu_key) + { (new MenuService())->del($menu_key); return success('DELETE_SUCCESS'); } - public function refreshMenu(){ + public function refreshMenu() + { (new InstallSystemService())->install(); return success('REFRESH_SUCCESS'); } diff --git a/niucloud/app/adminapi/controller/sys/Role.php b/niucloud/app/adminapi/controller/sys/Role.php index ca925d440..9c1d2edb5 100644 --- a/niucloud/app/adminapi/controller/sys/Role.php +++ b/niucloud/app/adminapi/controller/sys/Role.php @@ -14,11 +14,13 @@ namespace app\adminapi\controller\sys; use app\dict\sys\RoleStatusDict; use app\service\admin\sys\RoleService; use core\base\BaseAdminController; +use think\db\exception\DbException; use think\Response; class Role extends BaseAdminController { - public function lists(){ + public function lists() + { $data = $this->request->params([ ['role_name', ''], ]); @@ -29,10 +31,11 @@ class Role extends BaseAdminController /** * 用户组详情 - * @param $uid + * @param $role_id * @return Response */ - public function info($role_id){ + public function info($role_id) + { return success((new RoleService())->getInfo($role_id)); } @@ -40,14 +43,17 @@ class Role extends BaseAdminController * 获取全部权限 * @return Response */ - public function all(){ + public function all() + { return success((new RoleService())->getAll()); } + /** * 新增用户组 * @return Response */ - public function add(){ + public function add() + { $data = $this->request->params([ ['role_name', ''], ['rules', []], @@ -62,7 +68,8 @@ class Role extends BaseAdminController /** * 更新用户组 */ - public function edit($role_id){ + public function edit($role_id) + { $data = $this->request->params([ ['role_name', ''], ['rules', []], @@ -76,9 +83,12 @@ class Role extends BaseAdminController /** * 删除单个用户组 - * @param $uid + * @param $role_id + * @return Response + * @throws DbException */ - public function del($role_id){ + public function del($role_id) + { (new RoleService())->del($role_id); return success('DELETE_SUCCESS'); } diff --git a/niucloud/app/adminapi/controller/sys/Schedule.php b/niucloud/app/adminapi/controller/sys/Schedule.php index dcf516c66..f185a93f6 100644 --- a/niucloud/app/adminapi/controller/sys/Schedule.php +++ b/niucloud/app/adminapi/controller/sys/Schedule.php @@ -14,6 +14,7 @@ namespace app\adminapi\controller\sys; use app\dict\schedule\ScheduleDict; use app\service\admin\schedule\ScheduleService; use core\base\BaseAdminController; +use think\Response; /** * 自动任务 @@ -22,40 +23,44 @@ class Schedule extends BaseAdminController { /** * 任务列表 - * @return \think\Response + * @return Response */ - public function lists(){ + public function lists() + { $data = $this->request->params([ ['key', ''], ['status', ''], ]); - return success(data:(new ScheduleService())->getPage($data)); + return success(data: (new ScheduleService())->getPage($data)); } /** * 计划任务模板 - * @return \think\Response + * @return Response */ - public function template(){ - return success(data:(new ScheduleService())->getTemplateList()); + public function template() + { + return success(data: (new ScheduleService())->getTemplateList()); } /** * 获取任务模式 - * @return \think\Response + * @return Response */ - public function getType(){ - return success(data:ScheduleDict::getType()); + public function getType() + { + return success(data: ScheduleDict::getType()); } /** * 详情 * @param int $id + * @return Response */ public function info(int $id) { - return success(( new ScheduleService() )->getInfo($id)); + return success((new ScheduleService())->getInfo($id)); } /** @@ -65,12 +70,12 @@ class Schedule extends BaseAdminController public function add() { $data = $this->request->params([ - [ 'key', '' ], - [ 'time', [] ], - [ 'status', ScheduleDict::OFF ], + ['key', ''], + ['time', []], + ['status', ScheduleDict::OFF], ]); $this->validate($data, 'app\validate\sys\Schedule.add'); - ( new ScheduleService() )->add($data); + (new ScheduleService())->add($data); return success('ADD_SUCCESS'); } @@ -83,40 +88,44 @@ class Schedule extends BaseAdminController { $data = $this->request->params([ // [ 'key', '' ], - [ 'time', [] ], - [ 'status', ScheduleDict::OFF ], + ['time', []], + ['status', ScheduleDict::OFF], ]); - ( new ScheduleService() )->edit($id, $data); + (new ScheduleService())->edit($id, $data); return success('EDIT_SUCCESS'); } /** * 启用或关闭 * @param int $id - * @return \think\Response + * @return Response */ - public function modifyStatus(int $id){ + public function modifyStatus(int $id) + { $data = $this->request->params([ - [ 'status', ScheduleDict::OFF ], + ['status', ScheduleDict::OFF], ]); - ( new ScheduleService() )->modifyStatus($id, $data['status']); + (new ScheduleService())->modifyStatus($id, $data['status']); return success('EDIT_SUCCESS'); } + /** * 删除 * @param int $id + * @return Response */ public function del(int $id) { - ( new ScheduleService() )->del($id); + (new ScheduleService())->del($id); return success('DELETE_SUCCESS'); } /** * 时间间隔类型 - * @return \think\Response + * @return Response */ - public function getDateType(){ - return success(data:ScheduleDict::getDateType()); + public function getDateType() + { + return success(data: ScheduleDict::getDateType()); } } diff --git a/niucloud/app/adminapi/controller/sys/System.php b/niucloud/app/adminapi/controller/sys/System.php index 46fd3c567..4527bd21b 100644 --- a/niucloud/app/adminapi/controller/sys/System.php +++ b/niucloud/app/adminapi/controller/sys/System.php @@ -11,9 +11,9 @@ namespace app\adminapi\controller\sys; -use app\service\admin\schedule\ScheduleService; use app\service\admin\sys\SystemService; use core\base\BaseAdminController; +use think\Response; /** * 系统信息查询 @@ -24,7 +24,7 @@ class System extends BaseAdminController { /** * 获取当前系统信息 - * @return array|mixed + * @return Response */ public function info() { @@ -33,7 +33,7 @@ class System extends BaseAdminController /** * 获取当前url配置 - * @return array|mixed + * @return Response */ public function url() { @@ -42,35 +42,59 @@ class System extends BaseAdminController /** * 获取系统环境配置 - * @return \think\Response + * @return Response */ - public function getSystemInfo(){ + public function getSystemInfo() + { return success((new SystemService())->getSystemInfo()); } /** * 清理缓存,更新菜单 */ - public function schemaCache(){ + public function schemaCache() + { return success((new SystemService())->schemaCache()); } /** * 校验消息队列是否正常运行 - * @return \think\Response + * @return Response */ - public function checkJob(){ - return success(data:(new SystemService())->checkJob()); + public function checkJob() + { + return success(data: (new SystemService())->checkJob()); } /** * 校验计划任务是否正常运行 - * @return \think\Response + * @return Response */ - public function checkSchedule(){ - return success(data:(new SystemService())->checkSchedule()); + public function checkSchedule() + { + return success(data: (new SystemService())->checkSchedule()); } + /** + * 获取布局 + * @return Response + */ + public function layout() { + $layouts = event('SiteLayout'); + if (count($layouts) > 1) { + array_multisort(array_column($layouts, 'sort'), SORT_ASC, $layouts); + } + return success($layouts); + } + /** + * + * 设置布局 + * @return Response + */ + public function setLayout(){ + $key = input('key', ''); + return success(data: (new SystemService())->setLayout($key)); + } } diff --git a/niucloud/app/adminapi/controller/upload/Upload.php b/niucloud/app/adminapi/controller/upload/Upload.php index dd4f1a913..79efca276 100644 --- a/niucloud/app/adminapi/controller/upload/Upload.php +++ b/niucloud/app/adminapi/controller/upload/Upload.php @@ -27,10 +27,11 @@ class Upload extends BaseAdminController $data = $this->request->params([ ['file', 'file'], - ['cate_id', '=', 0] - ], true); + ['cate_id', 0], + ['is_attachment', 1] + ]); $upload_service = new UploadService(); - return success($upload_service->image($data['file'], $data['cate_id'])); + return success($upload_service->image($data['file'], $data['cate_id'], boolval($data['is_attachment']))); } /** @@ -41,8 +42,8 @@ class Upload extends BaseAdminController { $data = $this->request->params([ ['file', 'file'], - ['cate_id', '=', 0] - ], true); + ['cate_id', 0] + ]); $upload_service = new UploadService(); return success($upload_service->video($data['file'], $data['cate_id'])); } @@ -51,17 +52,18 @@ class Upload extends BaseAdminController * 文件上传(默认不上云) * @return Response */ - public function document($type){ + public function document($type) + { $data = $this->request->params([ ['file', 'file'], - ], true); + ]); $upload_service = new UploadService(); return success($upload_service->document($data['file'], $type)); } /** * 上传配置 - * @return void + * @return Response */ public function setUploadConfig() { diff --git a/niucloud/app/adminapi/controller/user/User.php b/niucloud/app/adminapi/controller/user/User.php index 2cb42fb04..76fe1cbfe 100644 --- a/niucloud/app/adminapi/controller/user/User.php +++ b/niucloud/app/adminapi/controller/user/User.php @@ -17,7 +17,8 @@ use think\Response; class User extends BaseAdminController { - public function lists(){ + public function lists() + { $data = $this->request->params([ ['username', ''], ['real_name', ''] @@ -33,7 +34,8 @@ class User extends BaseAdminController * @param $uid * @return Response */ - public function info($uid){ + public function info($uid) + { return success((new UserService())->getUserAdminInfo($uid)); } diff --git a/niucloud/app/adminapi/controller/weapp/Config.php b/niucloud/app/adminapi/controller/weapp/Config.php index aef4327c7..6e4a0f5d4 100644 --- a/niucloud/app/adminapi/controller/weapp/Config.php +++ b/niucloud/app/adminapi/controller/weapp/Config.php @@ -21,7 +21,8 @@ class Config extends BaseAdminController * 获取微信小程序配置信息 * @return Response */ - public function get(){ + public function get() + { return success((new WeappConfigService())->getWeappConfig()); } @@ -29,7 +30,8 @@ class Config extends BaseAdminController * 设置微信小程序配置信息 * @return Response */ - public function set(){ + public function set() + { $data = $this->request->params([ ['weapp_name', ''], ['weapp_original', ''], diff --git a/niucloud/app/adminapi/controller/weapp/Package.php b/niucloud/app/adminapi/controller/weapp/Package.php index 098579f41..c9a0831b4 100644 --- a/niucloud/app/adminapi/controller/weapp/Package.php +++ b/niucloud/app/adminapi/controller/weapp/Package.php @@ -11,18 +11,18 @@ namespace app\adminapi\controller\weapp; -use app\service\admin\weapp\WeappConfigService; use core\base\BaseAdminController; -use think\Response; class Package extends BaseAdminController { - public function lists(){ + public function lists() + { return success(); } - public function add(){ + public function add() + { $data = $this->request->params([ ['version', ''], ['path', ''], diff --git a/niucloud/app/adminapi/controller/weapp/Template.php b/niucloud/app/adminapi/controller/weapp/Template.php index 332d73794..954b1c312 100644 --- a/niucloud/app/adminapi/controller/weapp/Template.php +++ b/niucloud/app/adminapi/controller/weapp/Template.php @@ -13,6 +13,7 @@ namespace app\adminapi\controller\weapp; use app\service\admin\weapp\WeappTemplateService; use core\base\BaseAdminController; +use think\Response; /** * 微信小程序订阅消息 @@ -22,9 +23,10 @@ class Template extends BaseAdminController /** * 订阅消息 - * @return \think\Response + * @return Response */ - public function lists(){ + public function lists() + { $wechat_template_service = new WeappTemplateService(); return success($wechat_template_service->getList()); } @@ -32,9 +34,10 @@ class Template extends BaseAdminController /** * 菜单信息 - * @return \think\Response + * @return Response */ - public function sync(){ + public function sync() + { $data = $this->request->params([ ['keys', []] ]); diff --git a/niucloud/app/adminapi/controller/wechat/Config.php b/niucloud/app/adminapi/controller/wechat/Config.php index 9c95b7c7c..4b98a5633 100644 --- a/niucloud/app/adminapi/controller/wechat/Config.php +++ b/niucloud/app/adminapi/controller/wechat/Config.php @@ -21,7 +21,8 @@ class Config extends BaseAdminController * 获取微信配置信息 * @return Response */ - public function get(){ + public function get() + { return success((new WechatConfigService())->getWechatConfig()); } @@ -29,7 +30,8 @@ class Config extends BaseAdminController * 设置微信配置信息 * @return Response */ - public function set(){ + public function set() + { $data = $this->request->params([ ['wechat_name', ''], ['wechat_original', ''], @@ -49,7 +51,8 @@ class Config extends BaseAdminController * 获取微信静态资源 * @return Response */ - public function static(){ + public function static() + { return success((new WechatConfigService())->getWechatStaticInfo()); } diff --git a/niucloud/app/adminapi/controller/wechat/Menu.php b/niucloud/app/adminapi/controller/wechat/Menu.php index e79bb6795..881ce5f06 100644 --- a/niucloud/app/adminapi/controller/wechat/Menu.php +++ b/niucloud/app/adminapi/controller/wechat/Menu.php @@ -13,6 +13,9 @@ namespace app\adminapi\controller\wechat; use app\service\admin\wechat\WechatMenuService; use core\base\BaseAdminController; +use EasyWeChat\Kernel\Exceptions\InvalidConfigException; +use GuzzleHttp\Exception\GuzzleException; +use think\Response; /** * 微信公众号管理菜单 @@ -22,18 +25,22 @@ class Menu extends BaseAdminController /** * 菜单信息 - * @return void + * @return Response */ - public function info(){ + public function info() + { $wechat_menu_service = new WechatMenuService(); return success($wechat_menu_service->getInfo()); } /** * 设置菜单 - * @return void + * @return Response + * @throws InvalidConfigException + * @throws GuzzleException */ - public function edit(){ + public function edit() + { $wechat_menu_service = new WechatMenuService(); $data = $this->request->params([ ['button', []] diff --git a/niucloud/app/adminapi/controller/wechat/Reply.php b/niucloud/app/adminapi/controller/wechat/Reply.php index 9dc92ab98..3c14b23ef 100644 --- a/niucloud/app/adminapi/controller/wechat/Reply.php +++ b/niucloud/app/adminapi/controller/wechat/Reply.php @@ -23,14 +23,16 @@ class Reply extends BaseAdminController /** * 关键词回复 - * @return void + * @return Response */ - public function keyword($id){ + public function keyword($id) + { $wechat_reply_service = new WechatReplyService(); return success($wechat_reply_service->getKeywordInfo($id)); } - public function getKeywordLists(){ + public function getKeywordLists() + { $data = $this->request->params([ ['keyword', ''], ['name', ''] @@ -38,11 +40,13 @@ class Reply extends BaseAdminController $wechat_reply_service = new WechatReplyService(); return success($wechat_reply_service->getKeywordPage($data)); } + /** * 新增关键词回复 - * @return void + * @return Response */ - public function addKeyword(){ + public function addKeyword() + { $wechat_reply_service = new WechatReplyService(); $data = $this->request->params([ ['name', ''], @@ -58,9 +62,10 @@ class Reply extends BaseAdminController /** * 更新关键词回复 - * @return void + * @return Response */ - public function editKeyword($id){ + public function editKeyword($id) + { $wechat_reply_service = new WechatReplyService(); $data = $this->request->params([ ['name', ''], @@ -76,9 +81,10 @@ class Reply extends BaseAdminController /** * 删除关键字回复 - * @return void + * @return Response */ - public function delKeyword($id){ + public function delKeyword($id) + { $wechat_reply_service = new WechatReplyService(); return success($wechat_reply_service->delKeyword($id)); } @@ -87,7 +93,8 @@ class Reply extends BaseAdminController * 获取默认回复 * @return Response */ - public function default(){ + public function default() + { $wechat_reply_service = new WechatReplyService(); return success($wechat_reply_service->getDefault()); } @@ -96,7 +103,8 @@ class Reply extends BaseAdminController * 更新默认回复 * @return Response */ - public function editDefault(){ + public function editDefault() + { $data = $this->request->params([ ['content_type', ''], ['content', ''], @@ -110,7 +118,8 @@ class Reply extends BaseAdminController * 获取关注回复 * @return Response */ - public function subscribe(){ + public function subscribe() + { $wechat_reply_service = new WechatReplyService(); return success($wechat_reply_service->getSubscribe()); } @@ -119,7 +128,8 @@ class Reply extends BaseAdminController * 更新关注回复 * @return Response */ - public function editSubscribe(){ + public function editSubscribe() + { $data = $this->request->params([ ['content_type', ''], ['content', ''], @@ -130,5 +140,4 @@ class Reply extends BaseAdminController } - } diff --git a/niucloud/app/adminapi/controller/wechat/Template.php b/niucloud/app/adminapi/controller/wechat/Template.php index bf51b8af5..838887a1a 100644 --- a/niucloud/app/adminapi/controller/wechat/Template.php +++ b/niucloud/app/adminapi/controller/wechat/Template.php @@ -13,6 +13,7 @@ namespace app\adminapi\controller\wechat; use app\service\admin\wechat\WechatTemplateService; use core\base\BaseAdminController; +use think\Response; /** * 微信公众号管理菜单 @@ -22,9 +23,10 @@ class Template extends BaseAdminController /** * 菜单信息 - * @return void + * @return Response */ - public function sync(){ + public function sync() + { $data = $this->request->params([ ['keys', []] ]); @@ -34,9 +36,10 @@ class Template extends BaseAdminController /** * 模板消息 - * @return \think\Response + * @return Response */ - public function lists(){ + public function lists() + { $wechat_template_service = new WechatTemplateService(); return success($wechat_template_service->getList()); } diff --git a/niucloud/app/adminapi/middleware.php b/niucloud/app/adminapi/middleware.php index 8a4400dd5..f1ed80e58 100644 --- a/niucloud/app/adminapi/middleware.php +++ b/niucloud/app/adminapi/middleware.php @@ -2,6 +2,7 @@ // 全局中间件定义文件 use app\adminapi\middleware\AllowCrossDomain; use think\middleware\LoadLangPack; + return [ //跨域请求中间件 AllowCrossDomain::class, diff --git a/niucloud/app/adminapi/middleware/AdminCheckRole.php b/niucloud/app/adminapi/middleware/AdminCheckRole.php index fea99421a..ae3c57d6b 100644 --- a/niucloud/app/adminapi/middleware/AdminCheckRole.php +++ b/niucloud/app/adminapi/middleware/AdminCheckRole.php @@ -13,7 +13,6 @@ namespace app\adminapi\middleware; use app\Request; - use app\service\admin\auth\AuthService; use Closure; diff --git a/niucloud/app/adminapi/middleware/AdminLog.php b/niucloud/app/adminapi/middleware/AdminLog.php index e8fe709de..46ce90c21 100644 --- a/niucloud/app/adminapi/middleware/AdminLog.php +++ b/niucloud/app/adminapi/middleware/AdminLog.php @@ -26,8 +26,7 @@ class AdminLog public function handle(Request $request, Closure $next) { //写入日志 - if($request->method() != 'GET') - { + if ($request->method() != 'GET') { $data = [ 'uid' => $request->uid(), 'username' => $request->username(), diff --git a/niucloud/app/adminapi/middleware/AllowCrossDomain.php b/niucloud/app/adminapi/middleware/AllowCrossDomain.php index 8965ecd7e..d6baf409e 100644 --- a/niucloud/app/adminapi/middleware/AllowCrossDomain.php +++ b/niucloud/app/adminapi/middleware/AllowCrossDomain.php @@ -13,7 +13,6 @@ namespace app\adminapi\middleware; use app\Request; use Closure; -use core\exception\ServerException; /** * http跨域请求中间件 @@ -30,7 +29,7 @@ class AllowCrossDomain system_name('channel_name'), 'lang' ]; - header("Access-Control-Allow-Headers: Authorization, Sec-Fetch-Mode, DNT, X-Mx-ReqToken, Keep-Alive, User-Agent, If-Match, If-None-Match, If-Unmodified-Since, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Accept-Language, Origin, Accept-Encoding,Access-Token,version,".implode(',', $allow_header)); + header("Access-Control-Allow-Headers: Authorization, Sec-Fetch-Mode, DNT, X-Mx-ReqToken, Keep-Alive, User-Agent, If-Match, If-None-Match, If-Unmodified-Since, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Accept-Language, Origin, Accept-Encoding,Access-Token,version," . implode(',', $allow_header)); header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, post'); header('Access-Control-Max-Age: 1728000'); header('Access-Control-Allow-Credentials:true'); diff --git a/niucloud/app/adminapi/route/addon.php b/niucloud/app/adminapi/route/addon.php index 74f64b886..557d335ac 100644 --- a/niucloud/app/adminapi/route/addon.php +++ b/niucloud/app/adminapi/route/addon.php @@ -34,6 +34,8 @@ Route::group(function () { Route::post('addon/install/execute/:addon', 'addon.Addon/execute'); //插件安装状态 Route::get('addon/install/:addon/status/:key', 'addon.Addon/getInstallState'); + //下载插件 + Route::post('addon/download/:addon', 'addon.Addon/download'); //卸载插件 Route::post('addon/uninstall/:addon', 'addon.Addon/uninstall'); @@ -41,6 +43,8 @@ Route::group(function () { Route::post('addon/edit/:addon', 'addon.Addon/edit'); //应用列表(...) Route::get('app/list', 'addon.App/getAppList'); + + })->middleware([ AdminCheckToken::class, AdminCheckRole::class, diff --git a/niucloud/app/adminapi/route/app.php b/niucloud/app/adminapi/route/app.php index e632604ea..4aa83b79e 100644 --- a/niucloud/app/adminapi/route/app.php +++ b/niucloud/app/adminapi/route/app.php @@ -9,10 +9,11 @@ // | Author: Niucloud Team // +---------------------------------------------------------------------- -use think\facade\Route; +use core\exception\CommonException; +use think\facade\Request; $is_demo = env('system.is_demo', 0); -if ($is_demo && !\think\facade\Request::isGet()) { +if ($is_demo && !Request::isGet()) { //加载插件路由 - throw new \core\exception\CommonException("演示数据不能进行修改"); + throw new CommonException("演示数据不能进行修改"); } \ No newline at end of file diff --git a/niucloud/app/adminapi/route/applet.php b/niucloud/app/adminapi/route/applet.php index e3e33785e..b07c14a9a 100644 --- a/niucloud/app/adminapi/route/applet.php +++ b/niucloud/app/adminapi/route/applet.php @@ -42,11 +42,12 @@ Route::group('applet', function () { //详情 Route::get('site/version/:id', 'applet.SiteVersion/info'); //最后一个升级的版本 - Route::post('site/version/last', 'applet.SiteVersion/getLastVersion'); - + Route::get('site/version/last', 'applet.SiteVersion/getLastVersion'); + //查看最新的版本 + Route::get('site/version/upgrade', 'applet.SiteVersion/getUpgradeVersion'); //下载 - Route::post('version/download/:id', 'applet.VersionDownload/download'); + Route::get('version/download/:id', 'applet.VersionDownload/download'); })->middleware([ AdminCheckToken::class, AdminCheckRole::class, diff --git a/niucloud/app/adminapi/route/diy.php b/niucloud/app/adminapi/route/diy.php index 94945a497..dc4b7fb7c 100644 --- a/niucloud/app/adminapi/route/diy.php +++ b/niucloud/app/adminapi/route/diy.php @@ -18,7 +18,7 @@ use think\facade\Route; /** * 自定义页面控制器 */ -Route::group('diy', function() { +Route::group('diy', function () { /***************************************************** 自定义页面管理 ****************************************************/ //自定义页面分页列表 diff --git a/niucloud/app/adminapi/route/niucloud.php b/niucloud/app/adminapi/route/niucloud.php new file mode 100644 index 000000000..a69c8bcfd --- /dev/null +++ b/niucloud/app/adminapi/route/niucloud.php @@ -0,0 +1,46 @@ +middleware([ + AdminCheckToken::class, + AdminCheckRole::class, + AdminLog::class +]); diff --git a/niucloud/app/adminapi/route/pay.php b/niucloud/app/adminapi/route/pay.php index 519b9d932..cd7526ca2 100644 --- a/niucloud/app/adminapi/route/pay.php +++ b/niucloud/app/adminapi/route/pay.php @@ -31,6 +31,14 @@ Route::group('pay', function () { Route::post('channel/set/transfer', 'pay.PayChannel/setTransfer'); //多渠道设置 Route::post('channel/set/all', 'pay.PayChannel/setAll'); + // 支付审核 + Route::get('audit', 'pay.Pay/audit'); + // 审核通过 + Route::put('pass/:out_trade_no', 'pay.Pay/pass'); + // 审核拒绝 + Route::put('refuse/:out_trade_no', 'pay.Pay/refuse'); + // 支付单据详情 + Route::get('detail/:id', 'pay.Pay/detail'); })->middleware([ AdminCheckToken::class, AdminCheckRole::class, diff --git a/niucloud/app/adminapi/route/route.php b/niucloud/app/adminapi/route/route.php index db625b3a5..46f2e0aab 100644 --- a/niucloud/app/adminapi/route/route.php +++ b/niucloud/app/adminapi/route/route.php @@ -9,6 +9,7 @@ // | Author: Niucloud Team // +---------------------------------------------------------------------- +use core\dict\DictLoader; use think\facade\Route; /** @@ -30,4 +31,4 @@ Route::group(function () { }); //加载插件路由 -(new \core\dict\DictLoader("Route"))->load(['app_type' => 'adminapi']); \ No newline at end of file +(new DictLoader("Route"))->load(['app_type' => 'adminapi']); \ No newline at end of file diff --git a/niucloud/app/adminapi/route/sys.php b/niucloud/app/adminapi/route/sys.php index 263c9c553..3876a54a8 100644 --- a/niucloud/app/adminapi/route/sys.php +++ b/niucloud/app/adminapi/route/sys.php @@ -77,6 +77,11 @@ Route::group('sys', function () { //获取首页加载 Route::get('config/site_index', 'sys.Config/getSiteIndexList'); + //平台首页加载设置 + Route::put('config/admin_index', 'sys.Config/setAdminIndex'); + //获取平台首页加载 + Route::get('config/admin_index', 'sys.Config/getAdminIndexList'); + //快捷菜单设置 Route::put('config/shortcut_menu', 'sys.Config/setShortcutMenu'); //获取快捷菜单 @@ -185,6 +190,9 @@ Route::group('sys', function () { Route::get('date/month', 'sys.Common/getMonth'); Route::get('date/week', 'sys.Common/getWeek'); + /***************************************************** 获取布局 ****************************************************/ + Route::get('layout', 'sys.System/layout'); + Route::put('layout', 'sys.System/setLayout'); })->middleware([ AdminCheckToken::class, AdminCheckRole::class, diff --git a/niucloud/app/adminapi/route/upload.php b/niucloud/app/adminapi/route/upload.php index 3b0c234af..030f6eab9 100644 --- a/niucloud/app/adminapi/route/upload.php +++ b/niucloud/app/adminapi/route/upload.php @@ -9,8 +9,3 @@ // | Author: Niucloud Team // +---------------------------------------------------------------------- -use app\adminapi\middleware\AdminCheckRole; -use app\adminapi\middleware\AdminCheckToken; -use app\adminapi\middleware\AdminLog; -use think\facade\Route; - diff --git a/niucloud/app/api/controller/article/Article.php b/niucloud/app/api/controller/article/Article.php index 27bbaada4..0744b6dd4 100644 --- a/niucloud/app/api/controller/article/Article.php +++ b/niucloud/app/api/controller/article/Article.php @@ -47,6 +47,7 @@ class Article extends BaseApiController /** * 文章详情 * @param int $id + * @return Response */ public function info(int $id){ return success((new ArticleService())->getInfo($id)); diff --git a/niucloud/app/api/controller/article/ArticleCategory.php b/niucloud/app/api/controller/article/ArticleCategory.php index 45177a853..bef562201 100644 --- a/niucloud/app/api/controller/article/ArticleCategory.php +++ b/niucloud/app/api/controller/article/ArticleCategory.php @@ -36,6 +36,7 @@ class ArticleCategory extends BaseApiController /** * 文章分类详情 * @param int $id + * @return Response */ public function info(int $id){ return success((new ArticleCategoryService())->getInfo($id)); diff --git a/niucloud/app/api/controller/diy/Diy.php b/niucloud/app/api/controller/diy/Diy.php index 6313a2f47..fed9c6756 100644 --- a/niucloud/app/api/controller/diy/Diy.php +++ b/niucloud/app/api/controller/diy/Diy.php @@ -44,7 +44,7 @@ class Diy extends BaseApiController /** * 分享内容 - * @return Response|void + * @return Response */ public function share() { diff --git a/niucloud/app/api/controller/login/Config.php b/niucloud/app/api/controller/login/Config.php index 414aa1c55..f917652fa 100644 --- a/niucloud/app/api/controller/login/Config.php +++ b/niucloud/app/api/controller/login/Config.php @@ -21,7 +21,8 @@ class Config extends BaseController * 获取登录注册设置 * @return Response */ - public function getLoginConfig(){ + public function getLoginConfig() + { return success((new MemberConfigService())->getLoginConfig()); } diff --git a/niucloud/app/api/controller/login/Login.php b/niucloud/app/api/controller/login/Login.php index 40f953b56..11d97d7f8 100644 --- a/niucloud/app/api/controller/login/Login.php +++ b/niucloud/app/api/controller/login/Login.php @@ -14,6 +14,7 @@ namespace app\api\controller\login; use app\service\api\captcha\CaptchaService; use app\service\api\login\LoginService; use core\base\BaseController; +use Exception; use think\Response; class Login extends BaseController @@ -22,7 +23,8 @@ class Login extends BaseController * 登录 * @return Response */ - public function login(){ + public function login() + { $data = $this->request->params([ ['username', ''], @@ -31,7 +33,7 @@ class Login extends BaseController //参数验证 //验证码验证 $result = (new LoginService())->account($data['username'], $data['password']); - if(!$result){ + if (!$result) { //账号密码错误, 重置验证码 return fail('ACCOUNT_OR_PASSWORD_ERROR'); } @@ -43,7 +45,8 @@ class Login extends BaseController * 登出 * @return Response */ - public function logout(){ + public function logout() + { (new LoginService)->logout(); return success('MEMBER_LOGOUT'); } @@ -52,28 +55,33 @@ class Login extends BaseController * 创建验证码 * @return Response */ - public function captcha(){ + public function captcha() + { return success((new CaptchaService())->create()); } /** * 发送手机验证码 - * @return void + * @param $type + * @return Response + * @throws Exception */ - public function sendMobileCode($type){ + public function sendMobileCode($type) + { $data = $this->request->params([ - ['mobile', ''], + ['mobile', ''], ]); return success((new LoginService())->sendMobileCode($data['mobile'], $type)); } /** * 手机号登录 - * @return void + * @return Response */ - public function mobile(){ + public function mobile() + { $data = $this->request->params([ - ['mobile', ''], + ['mobile', ''], ]); return success((new LoginService())->mobile($data['mobile'])); } @@ -82,9 +90,10 @@ class Login extends BaseController * 重置密码 * @return Response */ - public function resetPassword(){ + public function resetPassword() + { $data = $this->request->params([ - ['mobile', ''], + ['mobile', ''], ['password', ''] ]); //参数验证 diff --git a/niucloud/app/api/controller/login/Register.php b/niucloud/app/api/controller/login/Register.php index 5ba403e2b..d56fb8fbf 100644 --- a/niucloud/app/api/controller/login/Register.php +++ b/niucloud/app/api/controller/login/Register.php @@ -22,12 +22,13 @@ class Register extends BaseController * 账号密码注册 * @return Response */ - public function account(){ + public function account() + { $data = $this->request->params([ ['username', ''], ['password', ''], - ['mobile', ''], + ['mobile', ''], ]); //参数验证 $this->validate($data, 'app\validate\member\Member.account_register'); @@ -40,9 +41,10 @@ class Register extends BaseController * 手机号注册 * @return Response */ - public function mobile(){ + public function mobile() + { $data = $this->request->params([ - ['mobile', ''], + ['mobile', ''], ]); //参数验证 $this->validate($data, [ @@ -54,9 +56,4 @@ class Register extends BaseController } - - - - - } diff --git a/niucloud/app/api/controller/member/Account.php b/niucloud/app/api/controller/member/Account.php index 8c7034f63..db65679bb 100644 --- a/niucloud/app/api/controller/member/Account.php +++ b/niucloud/app/api/controller/member/Account.php @@ -15,6 +15,7 @@ use app\dict\member\MemberAccountChangeTypeDict; use app\dict\member\MemberAccountTypeDict; use app\service\api\member\MemberAccountService; use core\base\BaseApiController; +use think\db\exception\DbException; use think\Response; /** @@ -28,7 +29,8 @@ class Account extends BaseApiController * 积分流水 * @return Response */ - public function point(){ + public function point(): Response + { $data = $this->request->params([ ['from_type', ''] ]); @@ -40,7 +42,8 @@ class Account extends BaseApiController * 余额流水 * @return Response */ - public function balance(){ + public function balance(): Response + { $data = $this->request->params([ ['from_type', ''] ]); @@ -52,7 +55,8 @@ class Account extends BaseApiController * 零钱流水 * @return Response */ - public function money(){ + public function money(): Response + { $data = $this->request->params([ ['from_type', ''] ]); @@ -63,8 +67,10 @@ class Account extends BaseApiController /** * 账户记录数量 * @return Response + * @throws DbException */ - public function count(){ + public function count(): Response + { $data = $this->request->params([ ['from_type', ''], ['account_type', ''] @@ -76,7 +82,8 @@ class Account extends BaseApiController * 佣金流水 * @return Response */ - public function commission(){ + public function commission(): Response + { $data = $this->request->params([ ['from_type', ''] ]); @@ -89,7 +96,8 @@ class Account extends BaseApiController * @param $account_type * @return Response */ - public function getFromType($account_type){ + public function getFromType($account_type): Response + { return success(MemberAccountChangeTypeDict::getType($account_type)); } diff --git a/niucloud/app/api/controller/member/CashOutAccount.php b/niucloud/app/api/controller/member/CashOutAccount.php index 9a32248fd..f65b291b1 100644 --- a/niucloud/app/api/controller/member/CashOutAccount.php +++ b/niucloud/app/api/controller/member/CashOutAccount.php @@ -13,6 +13,7 @@ namespace app\api\controller\member; use app\service\api\member\MemberCashOutAccountService; use core\base\BaseApiController; +use think\Response; class CashOutAccount extends BaseApiController { @@ -30,7 +31,7 @@ class CashOutAccount extends BaseApiController /** * 提现账户信息 * @param int $account_id - * @return \think\Response + * @return Response */ public function info(int $account_id){ return success((new MemberCashOutAccountService())->getInfo($account_id)); @@ -38,7 +39,7 @@ class CashOutAccount extends BaseApiController /** * 查询首条提现账户按账户类型 - * @return void + * @return Response */ public function firstInfo(){ $data = $this->request->params([ @@ -49,7 +50,7 @@ class CashOutAccount extends BaseApiController /** * 添加提现账号 - * @return void + * @return Response */ public function add(){ $data = $this->request->params([ @@ -66,7 +67,7 @@ class CashOutAccount extends BaseApiController /** * 编辑提现账号 * @param int $account_id - * @return void + * @return Response */ public function edit(int $account_id){ $data = $this->request->params([ @@ -83,7 +84,7 @@ class CashOutAccount extends BaseApiController /** * 删除提现账号 * @param int $account_id - * @return \think\Response + * @return Response */ public function del(int $account_id){ (new MemberCashOutAccountService())->del($account_id); diff --git a/niucloud/app/api/controller/member/Member.php b/niucloud/app/api/controller/member/Member.php index dd2eea787..00ae9a3f0 100644 --- a/niucloud/app/api/controller/member/Member.php +++ b/niucloud/app/api/controller/member/Member.php @@ -15,6 +15,9 @@ use app\service\api\login\AuthService; use app\service\api\member\MemberLogService; use app\service\api\member\MemberService; use core\base\BaseApiController; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; use think\Response; class Member extends BaseApiController @@ -38,7 +41,6 @@ class Member extends BaseApiController /** * 修改会员 - * @param $member_id * @param $field * @return Response */ @@ -67,7 +69,7 @@ class Member extends BaseApiController /** * 绑定手机号 - * @return void + * @return Response */ public function mobile(){ $data = $this->request->params([ @@ -88,6 +90,13 @@ class Member extends BaseApiController ['pre_route', ''] ]); (new MemberLogService())->log($data); - return success('SUCCESS'); + return success(); + } + + /** + * 获取会员码 + */ + public function qrcode(){ + return success((new MemberService())->getQrcode()); } } diff --git a/niucloud/app/api/controller/member/MemberCashOut.php b/niucloud/app/api/controller/member/MemberCashOut.php index 805f05281..545fdfb56 100644 --- a/niucloud/app/api/controller/member/MemberCashOut.php +++ b/niucloud/app/api/controller/member/MemberCashOut.php @@ -64,7 +64,7 @@ class MemberCashOut extends BaseApiController /** * 申请提现 - * @return void + * @return Response */ public function apply() { diff --git a/niucloud/app/api/controller/pay/Pay.php b/niucloud/app/api/controller/pay/Pay.php index e041225cc..a991136c7 100644 --- a/niucloud/app/api/controller/pay/Pay.php +++ b/niucloud/app/api/controller/pay/Pay.php @@ -13,6 +13,10 @@ namespace app\api\controller\pay; use app\service\api\pay\PayService; use core\base\BaseApiController; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; +use think\Response; /** * 微信服务端通信以及网页授权 @@ -22,7 +26,7 @@ class Pay extends BaseApiController /** * 接收消息并推送 - * @return void + * @return void|null */ public function notify($site_id, $channel, $type, $action) { @@ -31,26 +35,39 @@ class Pay extends BaseApiController /** * 去支付 - * @return \think\Response + * @return Response */ public function pay() { $data = $this->request->params([ ['type', ''], - ['out_trade_no', ''], +// ['out_trade_no', ''], + ['trade_type', ''],//业务类型 + ['trade_id', ''],//业务id ['quit_url', ''], ['buyer_id', ''], - ['return_url', ''] + ['return_url', ''], + ['voucher', ''] ]); - return success('SUCCESS',(new PayService())->pay($data['type'], $data['out_trade_no'], $data['return_url'], $data['quit_url'], $data['buyer_id'])); + return success('SUCCESS',(new PayService())->pay($data['type'], $data['trade_type'], $data['trade_id'], $data['return_url'], $data['quit_url'], $data['buyer_id'], $data['voucher'])); } - public function info($out_trade_no) + public function info($trade_type, $trade_id) { + return success((new PayService())->getInfoByTrade($trade_type, $trade_id)); + } - return success((new PayService())->getInfoByOutTradeNo($out_trade_no)); - + /** + * 获取可用的支付方法 + * @param $trade_type + * @return Response + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException + */ + public function getPayType($trade_type){ + return success((new PayService())->getPayTypeByTrade($trade_type)); } } diff --git a/niucloud/app/api/controller/upload/Upload.php b/niucloud/app/api/controller/upload/Upload.php index 83e6187c6..9a3b331e5 100644 --- a/niucloud/app/api/controller/upload/Upload.php +++ b/niucloud/app/api/controller/upload/Upload.php @@ -15,13 +15,14 @@ use app\service\api\upload\Base64Service; use app\service\api\upload\FetchService; use app\service\api\upload\UploadService; use core\base\BaseApiController; +use think\Response; class Upload extends BaseApiController { /** * 图片上传 - * @return \think\Response + * @return Response */ public function image(){ $data = $this->request->params([ @@ -33,7 +34,7 @@ class Upload extends BaseApiController /** * 远程图片拉取 - * @return \think\Response + * @return Response */ public function imageFetch(){ $data = $this->request->params([ @@ -46,7 +47,7 @@ class Upload extends BaseApiController /** * base64图片上传 - * @return \think\Response + * @return Response */ public function imageBase64(){ $data = $this->request->params([ diff --git a/niucloud/app/api/controller/weapp/Weapp.php b/niucloud/app/api/controller/weapp/Weapp.php index b5e564a51..3ec070ea5 100644 --- a/niucloud/app/api/controller/weapp/Weapp.php +++ b/niucloud/app/api/controller/weapp/Weapp.php @@ -22,7 +22,7 @@ class Weapp extends BaseApiController /** * 授权登录 - * @return void + * @return Response */ public function login(){ $data = $this->request->params([['code', '']]); @@ -33,7 +33,6 @@ class Weapp extends BaseApiController /** * 注册 * @return Response - * @throws InvalidArgumentException */ public function register(){ $data = $this->request->params([ diff --git a/niucloud/app/api/controller/wechat/Serve.php b/niucloud/app/api/controller/wechat/Serve.php index 52bf156e4..525f9d2b0 100644 --- a/niucloud/app/api/controller/wechat/Serve.php +++ b/niucloud/app/api/controller/wechat/Serve.php @@ -13,6 +13,12 @@ namespace app\api\controller\wechat; use app\service\api\wechat\WechatServeService; use core\base\BaseController; +use EasyWeChat\Kernel\Exceptions\BadRequestException; +use EasyWeChat\Kernel\Exceptions\InvalidArgumentException; +use EasyWeChat\Kernel\Exceptions\RuntimeException; +use ReflectionException; +use Symfony\Component\HttpFoundation\Response; +use Throwable; /** * 微信服务端通信以及网页授权 @@ -22,7 +28,13 @@ class Serve extends BaseController /** * 接收消息并推送 - * @return void + * @param $site_id + * @return Response + * @throws BadRequestException + * @throws InvalidArgumentException + * @throws RuntimeException + * @throws ReflectionException + * @throws Throwable */ public function serve($site_id){ diff --git a/niucloud/app/api/controller/wechat/Wechat.php b/niucloud/app/api/controller/wechat/Wechat.php index ab9e3536b..914bcbfa2 100644 --- a/niucloud/app/api/controller/wechat/Wechat.php +++ b/niucloud/app/api/controller/wechat/Wechat.php @@ -14,6 +14,9 @@ namespace app\api\controller\wechat; use app\service\api\wechat\WechatAuthService; use core\base\BaseController; use EasyWeChat\Kernel\Exceptions\InvalidArgumentException; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; use think\Response; class Wechat extends BaseController @@ -23,7 +26,6 @@ class Wechat extends BaseController /** * 获取跳转获取code * @return Response - * @throws InvalidArgumentException */ public function getCodeUrl(){ $data = $this->request->params([ @@ -36,7 +38,10 @@ class Wechat extends BaseController /** * 授权登录 - * @return void + * @return Response + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function login(){ $data = $this->request->params([ @@ -49,7 +54,6 @@ class Wechat extends BaseController /** * 注册 * @return Response - * @throws InvalidArgumentException */ public function register(){ $data = $this->request->params([ @@ -67,7 +71,6 @@ class Wechat extends BaseController /** * 同步 * @return Response - * @throws InvalidArgumentException */ public function sync(){ $data = $this->request->params([ @@ -91,7 +94,7 @@ class Wechat extends BaseController /** * 扫码登录 - * @return void + * @return Response */ public function scanLogin(){ $wechat_auth_service = new WechatAuthService(); diff --git a/niucloud/app/api/middleware/AllowCrossDomain.php b/niucloud/app/api/middleware/AllowCrossDomain.php index f1dd83dbb..75014fe8f 100644 --- a/niucloud/app/api/middleware/AllowCrossDomain.php +++ b/niucloud/app/api/middleware/AllowCrossDomain.php @@ -13,7 +13,6 @@ namespace app\api\middleware; use app\Request; use Closure; -use core\exception\ServerException; /** * http跨域请求中间件 diff --git a/niucloud/app/api/middleware/ApiChannel.php b/niucloud/app/api/middleware/ApiChannel.php index c3850ed31..ccbaba79a 100644 --- a/niucloud/app/api/middleware/ApiChannel.php +++ b/niucloud/app/api/middleware/ApiChannel.php @@ -12,11 +12,8 @@ namespace app\api\middleware; use app\Request; -use app\service\core\site\CoreSiteService; use Closure; -use core\exception\AuthException; use Exception; -use think\facade\Log; /** @@ -40,7 +37,7 @@ class ApiChannel if (in_array($request->rule()->getRule(), $channel_rules)) { $site_id = $request->param('site_id', -1); if ($site_id != -1) { - $request->pushHeader([ system_name('api_site_id_name') => $site_id ]); + $request->pushHeader([system_name('api_site_id_name') => $site_id]); } } return $next($request); diff --git a/niucloud/app/api/route/auth.php b/niucloud/app/api/route/auth.php index fbb101359..e52151c2f 100644 --- a/niucloud/app/api/route/auth.php +++ b/niucloud/app/api/route/auth.php @@ -18,7 +18,7 @@ use think\facade\Route; /** * 路由 */ -Route::group('auth',function () { +Route::group('auth', function () { Route::put('logout', 'login.Login/logout'); diff --git a/niucloud/app/api/route/member.php b/niucloud/app/api/route/member.php index 209c550d4..092b26c1c 100644 --- a/niucloud/app/api/route/member.php +++ b/niucloud/app/api/route/member.php @@ -18,7 +18,7 @@ use think\facade\Route; /** * 会员个人信息管理 */ -Route::group('member', function() { +Route::group('member', function () { /***************************************************** 会员管理 ****************************************************/ //会员个人详情 @@ -31,6 +31,8 @@ Route::group('member', function() { Route::put('edit', 'member.Member/edit'); //绑定手机号 Route::put('mobile', 'member.Member/mobile'); + //获取会员码 + Route::get('qrcode', 'member.Member/qrcode'); /***************************************************** 会员账户 ****************************************************/ //会员积分流水 @@ -76,7 +78,7 @@ Route::group('member', function() { ->middleware(ApiLog::class); -Route::group('member', function() { +Route::group('member', function () { /***************************************************** 会员管理 ****************************************************/ //会员日志 diff --git a/niucloud/app/api/route/pay.php b/niucloud/app/api/route/pay.php index 65b555be3..ccc6c5512 100644 --- a/niucloud/app/api/route/pay.php +++ b/niucloud/app/api/route/pay.php @@ -26,7 +26,9 @@ Route::group('pay',function () { //去支付 Route::post('', 'pay.Pay/pay'); //支付信息 - Route::get('info/:out_trade_no', 'pay.Pay/info'); + Route::get('info/:trade_type/:trade_id', 'pay.Pay/info'); + // + Route::get('type/:trade_type', 'pay.Pay/getPayType'); })->middleware(ApiChannel::class) ->middleware(ApiCheckToken::class) diff --git a/niucloud/app/api/route/route.php b/niucloud/app/api/route/route.php index 7f263c747..7b38ab207 100644 --- a/niucloud/app/api/route/route.php +++ b/niucloud/app/api/route/route.php @@ -12,7 +12,10 @@ use app\api\middleware\ApiChannel; use app\api\middleware\ApiCheckToken; use app\api\middleware\ApiLog; +use app\api\route\dispatch\BindDispatch; +use core\dict\DictLoader; use think\facade\Route; +use app\service\core\niucloud\CoreNotifyService; //公众号消息推送 Route::any('wechat/serve/:site_id', 'wechat.Serve/serve') @@ -20,6 +23,12 @@ Route::any('wechat/serve/:site_id', 'wechat.Serve/serve') ->middleware(ApiCheckToken::class) ->middleware(ApiLog::class); +Route::group(function() { + Route::post('niucloud/notify', function(){ + return (new CoreNotifyService())->notify(); + }); + +}); /** * 路由 @@ -45,7 +54,7 @@ Route::group(function() { //登录 Route::get('login', 'login.Login/login'); //第三方绑定 - Route::post('bind', \app\api\route\dispatch\BindDispatch::class); + Route::post('bind', BindDispatch::class); //密码重置 Route::post('password/reset', 'login.Login/resetPassword'); //账号密码注册 @@ -78,4 +87,4 @@ Route::group(function() { ->middleware(ApiCheckToken::class) ->middleware(ApiLog::class); //加载插件路由 -( new \core\dict\DictLoader("Route") )->load([ 'app_type' => 'api' ]); \ No newline at end of file +( new DictLoader("Route") )->load([ 'app_type' => 'api' ]); \ No newline at end of file diff --git a/niucloud/app/command/Addon/Install.php b/niucloud/app/command/Addon/Install.php index 73767d2cc..675735b67 100644 --- a/niucloud/app/command/Addon/Install.php +++ b/niucloud/app/command/Addon/Install.php @@ -1,13 +1,14 @@ $step(); $output->writeln("Command executed successfully"); - } catch (\Exception $e) { + } catch ( Exception $e ) { $output->writeln("Command failed " . $e->getMessage()); } } diff --git a/niucloud/app/command/Addon/Uninstall.php b/niucloud/app/command/Addon/Uninstall.php index b8b8a053c..756e4064d 100644 --- a/niucloud/app/command/Addon/Uninstall.php +++ b/niucloud/app/command/Addon/Uninstall.php @@ -1,5 +1,5 @@ expression($this->getCrontab($this->vars['time'])); } - /** - * 执行任务 - * @return mixed - */ - protected function execute() - { - //...具体的任务执行 - (new CoreScheduleService())->execute($this->vars); - } - protected function getCrontab($data): string { - $crontab = ''; $min = $data['min'] ?? '*'; $hour = $data['hour'] ?? '*'; $day = $data['day'] ?? '*'; $week = $data['week'] ?? '*'; - switch ($data['type']) { + $type = $data['type'] ?? ''; + switch ($type) { case 'min':// 每隔几分 - $crontab = '*/' . $min . ' * * * *'; + $crontab = '*/' . $min . ' * * * *'; break; case 'hour':// 每隔几时第几分钟执行 $crontab = $min . ' */' . $hour . ' * * *'; break; case 'day':// 每隔几日几时几分几秒执行 - $crontab = $min . ' ' . $hour . ' */' . $day . ' * *'; + $crontab = $min . ' ' . $hour . ' */' . $day . ' * *'; break; case 'week':// 每周一次,周几具体时间执行 $crontab = $min . ' ' . $hour . ' * * ' . $week; @@ -49,6 +37,16 @@ class Schedule extends Task $crontab = $min . ' ' . $hour . ' ' . $day . ' * *'; break; } - return $crontab; + return $crontab ?? '* * * * *'; + } + + /** + * 执行任务 + * @return void + */ + protected function execute() + { + //...具体的任务执行 + (new CoreScheduleService())->execute($this->vars); } } diff --git a/niucloud/app/common.php b/niucloud/app/common.php index 5d29a4734..179736214 100644 --- a/niucloud/app/common.php +++ b/niucloud/app/common.php @@ -11,8 +11,11 @@ use app\service\core\upload\CoreImageService; /** * 接口操作成功,返回信息 - * @param int $msg - * @param array $ + * @param string $msg + * @param array|string|bool|null $data + * @param int $code + * @param int $http_code + * @return Response */ function success($msg = 'SUCCESS', array|string|bool|null $data = [], int $code = 1, int $http_code = 200): Response { @@ -26,6 +29,11 @@ function success($msg = 'SUCCESS', array|string|bool|null $data = [], int $code /** * 接口操作失败,返回信息 + * @param $msg + * @param array|null $data + * @param int $code + * @param int $http_code + * @return Response */ function fail($msg = 'FAIL', ?array $data = [], int $code = 0, int $http_code = 200): Response { @@ -38,7 +46,7 @@ function fail($msg = 'FAIL', ?array $data = [], int $code = 0, int $http_code = /** * 自动侦测语言并转化 - * @param string + * @param string $str * @return lang() */ function get_lang($str) @@ -87,7 +95,7 @@ function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = 'child', $root = * 生成加密密码 * @param $password * @param $salt 手动提供散列密码的盐值(salt)。这将避免自动生成盐值(salt)。,默认不填写将自动生成 - * @return bool|string + * @return string */ function create_password($password, $salt = '') { @@ -98,6 +106,7 @@ function create_password($password, $salt = '') * 校验比对密码和加密密码是否一致 * @param $password * @param $hash + * @return bool */ function check_password($password, $hash) { @@ -174,38 +183,6 @@ function del_target_dir($path, $delDir) } } - -/** - * @notes 下载文件 - * @param $url - * @param $saveDir - * @param $fileName - * @return string - */ -function download_file($url, $saveDir, $fileName) -{ - if (!file_exists($saveDir)) { - mkdir($saveDir, 0775, true); - } - $fileSrc = $saveDir . $fileName; - file_exists($fileSrc) && unlink($fileSrc); - $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, $url); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); - $file = curl_exec($ch); - curl_close($ch); - $resource = fopen($fileSrc, 'a'); - fwrite($resource, $file); - fclose($resource); - if (filesize($fileSrc) == 0) { - unlink($fileSrc); - return ''; - } - return $fileSrc; -} - - /** * 获取一些公共的系统参数 * @param string|null $key @@ -235,12 +212,12 @@ function system_name(?string $key = '') */ function get_date_by_time(?int $time = null) { - return date('Y-m-d h:i:s', time()); + return date('Y-m-d h:i:s', $time); } function get_start_and_end_time_by_day($day = '') { - $date = $day ?: date('Y-m-d', time()); + $date = $day ?: date('Y-m-d'); $day_start_time = strtotime($date); //当天结束之间 $day_end_time = $day_start_time + 86400; @@ -268,13 +245,27 @@ function url_to_path($url) return public_path() . trim(str_replace('/', DIRECTORY_SEPARATOR, $url)); } +/** + * 获取本地文件的对外网络路径 + * @param string $path + * @return string + */ +function get_file_url(string $path) +{ + if (!$path) return ''; + if (!str_contains($path, 'http://') && !str_contains($path, 'https://')) { + return request()->domain() .'/'. path_to_url($path); + } else { + return path_to_url($path); + } +} /** * 新增队列工作 * @param $job * @param $data * @param $delay * @param $queue - * @return void + * @return bool */ function create_job($job, $data = '', $delay = 0, $queue = null) { @@ -309,7 +300,7 @@ function is_write($file) { if (is_dir($file)) { $dir = $file; - if ($fp = @fopen("$dir/test.txt", 'w')) { + if ($fp = @fopen("$dir/test.txt", 'wb')) { @fclose($fp); @unlink("$dir/test.txt"); $writeable = true; @@ -317,7 +308,7 @@ function is_write($file) $writeable = false; } } else { - if ($fp = @fopen($file, 'a+')) { + if ($fp = @fopen($file, 'ab+')) { @fclose($fp); $writeable = true; } else { @@ -364,9 +355,10 @@ function filter($string) /** * 生成编号 - * @param string $type + * @param string $prefix * @param string $tag 业务标识 例如member_id ... - * @return void + * @return string + * @throws Exception */ function create_no(string $prefix = '', string $tag = '') { @@ -374,7 +366,7 @@ function create_no(string $prefix = '', string $tag = '') $machine_id = 2; $snowflake = new Snowflake($data_center_id, $machine_id); $id = $snowflake->generateId(); - return $prefix.date('Ymd').$tag.(string)$id; + return $prefix.date('Ymd').$tag.$id; } /** @@ -391,6 +383,19 @@ function mkdirs($dir, $mode = 0777) return @mkdir($dir, $mode); } +/** + * 创建文件夹 + * @param $dir + * @param $mode + * @return true + */ +function mkdirs_or_notexist($dir, $mode = 0777) +{ + if (! is_dir($dir) && ! mkdir($dir, $mode, true) && ! is_dir($dir)) { + throw new \RuntimeException(sprintf('Directory "%s" was not created', $dir)); + } + return true; +} /** * 删除缓存文件使用 * @param $dir @@ -426,7 +431,7 @@ function unique_random($len = 10) /** * 校验事件结果 * @param $result - * @return void + * @return bool */ function check_event_result($result) { @@ -441,8 +446,9 @@ function check_event_result($result) /** * 二维数组合并 - * @param $array1 - * @param $array2 + * @param array $array1 + * @param array $array2 + * @return array */ function array_merge2(array $array1, array $array2) { @@ -450,7 +456,7 @@ function array_merge2(array $array1, array $array2) if (array_key_exists($array2_k, $array1)) { foreach ($array2_v as $array2_kk => $array2_vv) { if (array_key_exists($array2_kk, $array1[$array2_k])) { - if (gettype($array2_vv) == 'array') { + if (is_array($array2_vv)) { $array1[$array2_k][$array2_kk] = array_merge($array1[$array2_k][$array2_kk], $array2_vv); } } else { @@ -577,7 +583,7 @@ function parse_sql($content = '', $string = false, $replace = []) $content = str_replace(["\r\n", "\r"], "\n", $content); $content = explode("\n", trim($content)); // 循环处理每一行 - foreach ($content as $key => $line) { + foreach ($content as $line) { // 跳过空行 if ($line == '') { continue; @@ -591,12 +597,12 @@ function parse_sql($content = '', $string = false, $replace = []) continue; } // 多行注释开始 - if (substr($line, 0, 2) == '/*') { + if (str_starts_with($line, '/*')) { $comment = true; continue; } // 多行注释结束 - if (substr($line, -2) == '*/') { + if (str_ends_with($line, '*/')) { $comment = false; continue; } @@ -703,7 +709,7 @@ function cache_remember(string $name = null, $value = '', $tag = null, $options /** * 项目目录 - * @return void + * @return string */ function project_path() { return dirname(root_path()) . DIRECTORY_SEPARATOR; @@ -713,7 +719,7 @@ function project_path() { * 图片转base64 * @param string $path * @param $is_delete 转换后是否删除原图 - * @return void + * @return string */ function image_to_base64(string $path, $is_delete = false) { if (!file_exists($path)) return 'image not exist'; @@ -725,13 +731,15 @@ function image_to_base64(string $path, $is_delete = false) { if ($is_delete) @unlink($path); - return "data:{$mime};base64,{$base64_data}"; + return "data:$mime;base64,$base64_data"; } + /** * 获取缩略图 * @param $site_id * @param $image - * @param $thumb_type + * @param string $thumb_type + * @param bool $is_throw_exception * @return mixed * @throws Exception */ @@ -739,9 +747,10 @@ function get_thumb_images($site_id, $image, $thumb_type = 'all', bool $is_throw_ return (new CoreImageService())->thumb($site_id, $image, $thumb_type, $is_throw_exception); } + /** * 版本号转整数 例如1.0.0=001.000.000=001000000=1000000 - * @param string $ver + * @param $version * @return int */ function version_to_int($version) { @@ -761,14 +770,14 @@ function version_to_int($version) { function version_to_string($ver) { if($ver > 999) { if($ver > 999999) { - $ver = $ver . ""; + $ver .= ""; $v3 = (int) substr($ver, -3); $v2 = (int) substr($ver, -6, 3); - $v1 = (int) substr($ver, 0, strlen($ver) - 6); + $v1 = (int) substr($ver, 0, -6); } else { - $ver = $ver . ""; + $ver .= ""; $v3 = (int) substr($ver, -3); - $v2 = (int) substr($ver, 0, strlen($ver) - 3); + $v2 = (int) substr($ver, 0, -3); $v1 = 0; } } else { @@ -778,3 +787,12 @@ function version_to_string($ver) { } return "{$v1}.{$v2}.{$v3}"; } + +/** + * 检测文件是否是本地图片 + * @param string $file_path + * @return void + */ +function check_file_is_remote(string $file_path){ + return str_contains($file_path, 'https://') || str_contains($file_path, 'http://') || str_contains($file_path, '.com'); +} \ No newline at end of file diff --git a/niucloud/app/dict/addon/AddonDict.php b/niucloud/app/dict/addon/AddonDict.php index cfed0d706..36c705bb1 100644 --- a/niucloud/app/dict/addon/AddonDict.php +++ b/niucloud/app/dict/addon/AddonDict.php @@ -32,13 +32,14 @@ class AddonDict // 执行成功 const INSTALL_SUCCESS = 'success'; // 执行失败 - CONST INSTALL_FAIL = 'fail'; + const INSTALL_FAIL = 'fail'; /** * 插件操作方式 * @return array */ - public static function getActionType(){ + public static function getActionType() + { return [ self::INSTALL => get_lang('dict_addon.install'), self::UNINSTALL => get_lang('dict_addon.uninstall'), @@ -50,10 +51,11 @@ class AddonDict * 状态 * @return array */ - public static function getStatus(){ + public static function getStatus() + { return [ self::ON => get_lang('dict_addon.status_on'),//展示 - self::OFF => get_lang('dict_addon.status_off'),//隐藏 + self::OFF => get_lang('dict_addon.status_off'),//隐藏 ]; } } \ No newline at end of file diff --git a/niucloud/app/dict/applet/AppletlDict.php b/niucloud/app/dict/applet/AppletlDict.php index e782a258b..bd00235bd 100644 --- a/niucloud/app/dict/applet/AppletlDict.php +++ b/niucloud/app/dict/applet/AppletlDict.php @@ -20,24 +20,23 @@ namespace app\dict\applet; class AppletlDict { - const ON = '1';//草稿 - //微信公众号 - const OFF = '2'; + public const ON = '1'; - const PUBLISHED = '3'; + public const OFF = '2'; - const DOWNLOAD = 'download';//下载 - const UPGRADE = 'upgrade';//升级 + public const DOWNLOAD = 'download';//下载 + public const UPGRADE = 'upgrade';//升级 + /** * 小程序版本状态 * @return array */ - public static function getStatus(){ - $data = [ - self::ON => get_lang('dict_applet.channel_weapp'),//启用 - self::OFF => get_lang('dict_applet.channel_wechat'),//下架 + public static function getStatus() + { + return [ + self::ON => get_lang('dict_applet.channel_weapp'),//启用 + self::OFF => get_lang('dict_applet.channel_wechat'),//下架 ]; - return $data; } } \ No newline at end of file diff --git a/niucloud/app/dict/cash_out/CashOutTypeDict.php b/niucloud/app/dict/cash_out/CashOutTypeDict.php index 8ed6275a4..fb0ff8b26 100644 --- a/niucloud/app/dict/cash_out/CashOutTypeDict.php +++ b/niucloud/app/dict/cash_out/CashOutTypeDict.php @@ -18,8 +18,7 @@ namespace app\dict\cash_out; class CashOutTypeDict { //会员零钱提现 - const MEMBER_CASH_OUT = 'member_cash_out'; - + public const MEMBER_CASH_OUT = 'member_cash_out'; } \ No newline at end of file diff --git a/niucloud/app/dict/channel/CertDict.php b/niucloud/app/dict/channel/CertDict.php index bca7a6553..d959aaccc 100644 --- a/niucloud/app/dict/channel/CertDict.php +++ b/niucloud/app/dict/channel/CertDict.php @@ -16,21 +16,22 @@ class CertDict /************************************************* 证书 *****************************************/ - const WECHATPAY = 'wechatpay'; + public const WECHATPAY = 'wechatpay'; - const WECHAT = 'wechat'; + public const WECHAT = 'wechat'; - const ALIYUN = 'aliyun'; + public const ALIYUN = 'aliyun'; - const WEAPP = 'weapp'; + public const WEAPP = 'weapp'; - const ALIAPP = 'aliapp'; + public const ALIAPP = 'aliapp'; /** * 加解密方式 * @return array */ - public static function getCertType(){ + public static function getCertType() + { return [ self::WECHATPAY, self::WECHAT, diff --git a/niucloud/app/dict/channel/ReplyDict.php b/niucloud/app/dict/channel/ReplyDict.php index 8defb9dd8..02157d42d 100644 --- a/niucloud/app/dict/channel/ReplyDict.php +++ b/niucloud/app/dict/channel/ReplyDict.php @@ -33,10 +33,11 @@ class ReplyDict const MATCHING_TYPE_FULL = 'full';//全匹配 const MATCHING_TYPE_LIKE = 'like';//模糊匹配 - public static function getStatus(){ + public static function getStatus() + { return [ self::STATUS_ON => get_lang('dict_wechat_reply.status_on'),//启用 - self::STATUS_OFF => get_lang('dict_wechat_reply.status_off'),//关闭 + self::STATUS_OFF => get_lang('dict_wechat_reply.status_off'),//关闭 ]; } } \ No newline at end of file diff --git a/niucloud/app/dict/channel/WechatDict.php b/niucloud/app/dict/channel/WechatDict.php index 4a04c4f98..994532f01 100644 --- a/niucloud/app/dict/channel/WechatDict.php +++ b/niucloud/app/dict/channel/WechatDict.php @@ -34,7 +34,7 @@ class WechatDict /************************************************* 请求事件的类型 *****************************************/ - //事件类型 - 关注 + //事件类型 - 关注 const EVENT_SUBSCRIBE = 'subscribe'; const EVENT_SCAN = 'SCAN'; @@ -52,11 +52,12 @@ class WechatDict * 加解密方式 * @return array */ - public static function getEncryptionType(){ + public static function getEncryptionType() + { return [ self::NOT_ENCRYPT => get_lang('dict_wechat_config.not_encrypt'),//明文 - self::COMPATIBLE => get_lang('dict_wechat_config.compatible'),//兼容 - self::SAFE => get_lang('dict_wechat_config.safe'),//安全 + self::COMPATIBLE => get_lang('dict_wechat_config.compatible'),//兼容 + self::SAFE => get_lang('dict_wechat_config.safe'),//安全 ]; } diff --git a/niucloud/app/dict/common/ChannelDict.php b/niucloud/app/dict/common/ChannelDict.php index 2e75e9f81..b96ffcbe0 100644 --- a/niucloud/app/dict/common/ChannelDict.php +++ b/niucloud/app/dict/common/ChannelDict.php @@ -20,26 +20,27 @@ namespace app\dict\common; class ChannelDict { //微信小程序 - const WEAPP = 'weapp'; + public const WEAPP = 'weapp'; //微信公众号 - const WECHAT = 'wechat'; + public const WECHAT = 'wechat'; //手机端H5 - const H5 = 'h5'; + public const H5 = 'h5'; //电脑端PC - const PC = 'pc'; + public const PC = 'pc'; //app端 - const APP = 'app'; + public const APP = 'app'; - public static function getType($type = ''){ + public static function getType($type = '') + { $data = [ - self::WEAPP => get_lang('dict_channel.channel_weapp'),//微信小程序 - self::WECHAT => get_lang('dict_channel.channel_wechat'),//'微信公众号', - self::H5 => get_lang('dict_channel.channel_h5'),//'手机H5', - self::PC => get_lang('dict_channel.channel_pc'),//'电脑PC', - self::APP => get_lang('dict_channel.channel_app'),//'手机app', + self::WEAPP => get_lang('dict_channel.channel_weapp'),//微信小程序 + self::WECHAT => get_lang('dict_channel.channel_wechat'),//'微信公众号', + self::H5 => get_lang('dict_channel.channel_h5'),//'手机H5', + self::PC => get_lang('dict_channel.channel_pc'),//'电脑PC', + self::APP => get_lang('dict_channel.channel_app'),//'手机app', ]; - if(empty($type)){ + if (empty($type)) { return $data; } return $data[$type] ?? ''; diff --git a/niucloud/app/dict/common/CommonDict.php b/niucloud/app/dict/common/CommonDict.php index eda77f614..6e7fe8d0e 100644 --- a/niucloud/app/dict/common/CommonDict.php +++ b/niucloud/app/dict/common/CommonDict.php @@ -9,20 +9,21 @@ namespace app\dict\common; */ class CommonDict { - const UNKNOWN = 0; - const MAN = 1; - const WOMAN = 2; + public const UNKNOWN = 0; + public const MAN = 1; + public const WOMAN = 2; /** * 性别 * @return array */ - public static function getSexType(){ + public static function getSexType() + { return [ self::UNKNOWN => get_lang('dict_sex.unknown'),//未知 - self::MAN => get_lang('dict_sex.man'),//男 - self::WOMAN => get_lang('dict_sex.woman'),//女 + self::MAN => get_lang('dict_sex.man'),//男 + self::WOMAN => get_lang('dict_sex.woman'),//女 ]; } } \ No newline at end of file diff --git a/niucloud/app/dict/diy/ComponentDict.php b/niucloud/app/dict/diy/ComponentDict.php index 2955b02f4..c2f41f1b8 100644 --- a/niucloud/app/dict/diy/ComponentDict.php +++ b/niucloud/app/dict/diy/ComponentDict.php @@ -170,17 +170,34 @@ class ComponentDict ], ] ], - 'Article' => [ - 'title' => '文章', - 'icon' => 'iconfont-iconwenzhang', - 'path' => 'edit-article', + 'RubikCube' => [ + 'title' => '魔方', + 'icon' => 'iconfont-iconmofang1', + 'path' => 'edit-rubik-cube', 'support_page' => [], 'uses' => 0, 'sort' => 10004, 'value' => [ - 'sources' => 'initial', - 'count' => 8, - 'articleIds' => [] + "mode" => "row1-of2", + "imageGap" => 0, + "list" => [ + [ + "imageUrl" => "", + "imgWidth" => 0, + "imgHeight" => 0, + "link" => [ + "name" => "" + ] + ], + [ + "imageUrl" => "", + "imgWidth" => 0, + "imgHeight" => 0, + "link" => [ + "name" => "" + ] + ] + ] ], ], 'HorzBlank' => [ @@ -194,13 +211,40 @@ class ComponentDict 'height' => 20 ], ], + 'HotArea' => [ + 'title' => '热区', + 'icon' => 'iconfont-iconrequ', + 'path' => 'edit-hot-area', + 'support_page' => [], + 'uses' => 0, + 'sort' => 10006, + 'value' => [ + "imageUrl" => "", + "imgWidth" => 0, + "imgHeight" => 0, + "heatMapData" => [] + ], + ], + 'Article' => [ + 'title' => '文章', + 'icon' => 'iconfont-iconwenzhang', + 'path' => 'edit-article', + 'support_page' => [], + 'uses' => 0, + 'sort' => 10007, + 'value' => [ + 'sources' => 'initial', + 'count' => 8, + 'articleIds' => [] + ], + ], 'MemberInfo' => [ 'title' => '会员信息', 'icon' => 'iconfont-iconhuiyuanzhongxin', 'path' => 'edit-member-info', 'support_page' => [ 'DIY_MEMBER_INDEX' ], 'uses' => 1, - 'sort' => 10006, + 'sort' => 10008, 'value' => [ "style" => "style-1", "styleName" => "风格1", diff --git a/niucloud/app/dict/diy/LinkDict.php b/niucloud/app/dict/diy/LinkDict.php index 404529a89..2f8f5afae 100644 --- a/niucloud/app/dict/diy/LinkDict.php +++ b/niucloud/app/dict/diy/LinkDict.php @@ -84,7 +84,7 @@ class LinkDict 'child_list' => [] ] ]; - return ( new DictLoader("UniappLink") )->load($system_links); + return (new DictLoader("UniappLink"))->load($system_links); } } \ No newline at end of file diff --git a/niucloud/app/dict/diy/PagesDict.php b/niucloud/app/dict/diy/PagesDict.php index ee55ffbe6..19fe14739 100644 --- a/niucloud/app/dict/diy/PagesDict.php +++ b/niucloud/app/dict/diy/PagesDict.php @@ -260,6 +260,7 @@ class PagesDict // 'mode' => 'fixed', // 页面模式:diy:自定义,fixed:固定 // 'data' => [ // "global" => [ +// 'component' => 'demo-index', // 模板组件名称 DemoIndex // "title" => "固定模板示例", // "pageBgColor" => "#F8F8F8", // 'bgUrl' => '', @@ -300,27 +301,7 @@ class PagesDict // ], // ] // ], -// "value" => [ -// [ -// "id" => "524jcssmp8c0", -// "componentName" => "DemoIndex", -// "componentTitle" => "固定模板示例", -// "uses" => 0, -// "ignore" => [], -// "pageBgColor" => "", -// "componentBgColor" => "rgba(255, 255, 255, 1)", -// "topRounded" => 0, -// "bottomRounded" => 0, -// "elementBgColor" => "", -// "topElementRounded" => 0, -// "bottomElementRounded" => 0, -// "margin" => [ -// "top" => 0, -// "bottom" => 0, -// "both" => 0 -// ] -// ] -// ] +// "value" => [] // ] // ] ], @@ -988,14 +969,14 @@ class PagesDict ] ]; - $pages = ( new DictLoader("UniappPages") )->load($system_pages); - if (!empty($params[ 'type' ])) { - if (!empty($pages[ $params[ 'type' ] ])) { - $temp = $pages[ $params[ 'type' ] ]; - if (isset($params[ 'mode' ]) && !empty($params[ 'mode' ])) { + $pages = (new DictLoader("UniappPages"))->load($system_pages); + if (!empty($params['type'])) { + if (!empty($pages[$params['type']])) { + $temp = $pages[$params['type']]; + if (isset($params['mode']) && !empty($params['mode'])) { foreach ($temp as $k => $v) { - if ($params[ 'mode' ] != $v[ 'mode' ]) { - unset($temp[ $k ]); + if ($params['mode'] != $v['mode']) { + unset($temp[$k]); } } } diff --git a/niucloud/app/dict/diy/TemplateDict.php b/niucloud/app/dict/diy/TemplateDict.php index 78be3dd33..ca33c5464 100644 --- a/niucloud/app/dict/diy/TemplateDict.php +++ b/niucloud/app/dict/diy/TemplateDict.php @@ -41,17 +41,17 @@ class TemplateDict ] ]; - $pages = ( new DictLoader("UniappTemplate") )->load($system_pages); + $pages = (new DictLoader("UniappTemplate"))->load($system_pages); - if (!empty($params[ 'type' ]) && !empty($pages[ $params[ 'type' ] ])) { - return [ $params[ 'type' ] => $pages[ $params[ 'type' ] ] ]; + if (!empty($params['type']) && !empty($pages[$params['type']])) { + return [$params['type'] => $pages[$params['type']]]; } - if (!empty($params[ 'action' ])) { + if (!empty($params['action'])) { $temp = []; foreach ($pages as $k => $v) { - if (isset($v[ 'action' ]) && $params[ 'action' ] == $v[ 'action' ]) { - $temp[ $k ] = $v; + if (isset($v['action']) && $params['action'] == $v['action']) { + $temp[$k] = $v; } } diff --git a/niucloud/app/dict/member/MemberAccountChangeTypeDict.php b/niucloud/app/dict/member/MemberAccountChangeTypeDict.php index f0a56c609..439ecc430 100644 --- a/niucloud/app/dict/member/MemberAccountChangeTypeDict.php +++ b/niucloud/app/dict/member/MemberAccountChangeTypeDict.php @@ -32,7 +32,7 @@ class MemberAccountChangeTypeDict if (empty($type)) { return $account_change_type; } - return $account_change_type[ $type ] ?? ''; + return $account_change_type[$type] ?? ''; } } \ No newline at end of file diff --git a/niucloud/app/dict/member/MemberAccountTypeDict.php b/niucloud/app/dict/member/MemberAccountTypeDict.php index b0c32c2e3..1f59a6673 100644 --- a/niucloud/app/dict/member/MemberAccountTypeDict.php +++ b/niucloud/app/dict/member/MemberAccountTypeDict.php @@ -20,15 +20,15 @@ namespace app\dict\member; class MemberAccountTypeDict { //会员积分 - const POINT = 'point'; + public const POINT = 'point'; //会员余额 - const BALANCE = 'balance'; + public const BALANCE = 'balance'; //会员可提现余额 - const MONEY = 'money'; + public const MONEY = 'money'; //会员佣金 - const COMMISSION = 'commission'; + public const COMMISSION = 'commission'; public static function getType($type = '') @@ -42,7 +42,7 @@ class MemberAccountTypeDict if (empty($type)) { return $data; } - return $data[ $type ] ?? ''; + return $data[$type] ?? ''; } } \ No newline at end of file diff --git a/niucloud/app/dict/member/MemberCashOutDict.php b/niucloud/app/dict/member/MemberCashOutDict.php index 857b0f361..570ae454f 100644 --- a/niucloud/app/dict/member/MemberCashOutDict.php +++ b/niucloud/app/dict/member/MemberCashOutDict.php @@ -18,23 +18,24 @@ namespace app\dict\member; */ class MemberCashOutDict { - const WAIT_AUDIT = 1;//待审核 - const WAIT_TRANSFER = 2;//待转账 - const TRANSFERED = 3;//已转账 - const REFUSE = -1;//已拒绝 - const CANCEL = -2;//已取消 + public const WAIT_AUDIT = 1;//待审核 + public const WAIT_TRANSFER = 2;//待转账 + public const TRANSFERED = 3;//已转账 + public const REFUSE = -1;//已拒绝 + public const CANCEL = -2;//已取消 /** * 提现状态 * @return array */ - public static function getStatus(){ + public static function getStatus() + { return [ self::WAIT_AUDIT => get_lang('dict_member_cash_out.status_wait_audit'),//待审核 - self::WAIT_TRANSFER => get_lang('dict_member_cash_out.status_wait_transfer'),//待转账 + self::WAIT_TRANSFER => get_lang('dict_member_cash_out.status_wait_transfer'),//待转账 self::TRANSFERED => get_lang('dict_member_cash_out.status_transfered'),//已转账 - self::REFUSE => get_lang('dict_member_cash_out.status_refuse'),//已拒绝 - self::CANCEL => get_lang('dict_member_cash_out.status_cancel'),//已取消 + self::REFUSE => get_lang('dict_member_cash_out.status_refuse'),//已拒绝 + self::CANCEL => get_lang('dict_member_cash_out.status_cancel'),//已取消 ]; } diff --git a/niucloud/app/dict/member/MemberDict.php b/niucloud/app/dict/member/MemberDict.php index 45d9a5372..bcca0a508 100644 --- a/niucloud/app/dict/member/MemberDict.php +++ b/niucloud/app/dict/member/MemberDict.php @@ -27,10 +27,11 @@ class MemberDict extends ChannelDict * 会员状态 * @return array */ - public static function getStatus(){ + public static function getStatus() + { return [ self::ON => get_lang('dict_member.status_on'),//正常 - self::OFF => get_lang('dict_member.status_off'),//无效 + self::OFF => get_lang('dict_member.status_off'),//无效 ]; } } \ No newline at end of file diff --git a/niucloud/app/dict/member/MemberLoginTypeDict.php b/niucloud/app/dict/member/MemberLoginTypeDict.php index 934255a01..251b8c44a 100644 --- a/niucloud/app/dict/member/MemberLoginTypeDict.php +++ b/niucloud/app/dict/member/MemberLoginTypeDict.php @@ -19,22 +19,23 @@ namespace app\dict\member; class MemberLoginTypeDict { //用户名密码注册登录 - const USERNAME = 'username'; + public const USERNAME = 'username'; //手机验证码登录 - const MOBILE = 'mobile'; + public const MOBILE = 'mobile'; //微信公众号授权登录 - const WECHAT = 'wechat'; + public const WECHAT = 'wechat'; //微信小程序授权登录 - const WEAPP = 'weapp'; + public const WEAPP = 'weapp'; - public static function getType($type = ''){ + public static function getType($type = '') + { $data = [ - self::USERNAME => get_lang('dict_member.login_username'),//用户名密码登录 - self::MOBILE => get_lang('dict_member.login_mobile'),//手机号验证码登录, - self::WECHAT => get_lang('dict_member.login_wechat'),//'微信公众号授权登录', - self::WEAPP => get_lang('dict_member.login_weapp'),//'微信小程序授权登录', + self::USERNAME => get_lang('dict_member.login_username'),//用户名密码登录 + self::MOBILE => get_lang('dict_member.login_mobile'),//手机号验证码登录, + self::WECHAT => get_lang('dict_member.login_wechat'),//'微信公众号授权登录', + self::WEAPP => get_lang('dict_member.login_weapp'),//'微信小程序授权登录', ]; - if(empty($type)){ + if (empty($type)) { return $data; } return $data[$type] ?? ''; diff --git a/niucloud/app/dict/member/MemberRegisterChannelDict.php b/niucloud/app/dict/member/MemberRegisterChannelDict.php index d95491e29..734ba6c26 100644 --- a/niucloud/app/dict/member/MemberRegisterChannelDict.php +++ b/niucloud/app/dict/member/MemberRegisterChannelDict.php @@ -20,13 +20,14 @@ use app\dict\common\ChannelDict; class MemberRegisterChannelDict extends ChannelDict { //手动添加 - const MANUAL = 'manual'; + const MANUAL = 'manual'; - public static function getType($type = ''){ + public static function getType($type = '') + { $data = ChannelDict::getType($type); $data[self::MANUAL] = get_lang('dict_member.register_manual');//手动添加 - if(empty($type)){ + if (empty($type)) { return $data; } return $data[$type] ?? ''; diff --git a/niucloud/app/dict/member/MemberRegisterTypeDict.php b/niucloud/app/dict/member/MemberRegisterTypeDict.php index 0a5439225..bc1139245 100644 --- a/niucloud/app/dict/member/MemberRegisterTypeDict.php +++ b/niucloud/app/dict/member/MemberRegisterTypeDict.php @@ -19,26 +19,27 @@ namespace app\dict\member; class MemberRegisterTypeDict { //微信小程序 - const WEAPP = 'weapp'; + const WEAPP = 'weapp'; //微信公众号 - const WECHAT = 'wechat'; + const WECHAT = 'wechat'; //用户名密码注册登录 - const USERNAME = 'username'; + const USERNAME = 'username'; //手机验证码登录 - const MOBILE = 'mobile'; + const MOBILE = 'mobile'; //手动添加 - const MANUAL = 'manual'; + const MANUAL = 'manual'; - public static function getType($type = ''){ + public static function getType($type = '') + { $data = [ - self::WEAPP => get_lang('dict_member.register_weapp'),//微信小程序 - self::WECHAT => get_lang('dict_member.register_wechat'),//'微信公众号', - self::MANUAL => get_lang('dict_member.register_manual'),//'手动添加', - self::USERNAME => get_lang('dict_member.register_username'),//用户名密码登录 - self::MOBILE => get_lang('dict_member.register_mobile'),//手机号验证码登录, + self::WEAPP => get_lang('dict_member.register_weapp'),//微信小程序 + self::WECHAT => get_lang('dict_member.register_wechat'),//'微信公众号', + self::MANUAL => get_lang('dict_member.register_manual'),//'手动添加', + self::USERNAME => get_lang('dict_member.register_username'),//用户名密码登录 + self::MOBILE => get_lang('dict_member.register_mobile'),//手机号验证码登录, ]; - if(empty($type)){ + if (empty($type)) { return $data; } return $data[$type] ?? ''; diff --git a/niucloud/app/dict/menu/admin.php b/niucloud/app/dict/menu/admin.php index 8949f9642..918479557 100644 --- a/niucloud/app/dict/menu/admin.php +++ b/niucloud/app/dict/menu/admin.php @@ -1,557 +1,637 @@ '控制台', - 'menu_key' => 'overview', - 'menu_type' => 1, - 'icon' => 'element-Monitor', - 'api_url' => '', - 'router_path' => 'index', - 'view_path' => 'index/index', - 'methods' => '', - 'sort' => 100, - 'status' => 1, - 'is_show' => 1, - ], - [ - 'menu_name' => '站点管理', - 'menu_key' => 'site', - 'menu_type' => 0, - 'icon' => 'element-Memo', - 'api_url' => '', - 'router_path' => 'site', - 'view_path' => '', - 'methods' => '', - 'sort' => 50, - 'status' => 1, - 'is_show' => 1, - 'children' => [ - [ - 'menu_name' => '站点列表', - 'menu_key' => 'site_list', - 'menu_type' => 1, - 'icon' => 'element-OfficeBuilding', - 'api_url' => 'site/site', - 'router_path' => 'list', - 'view_path' => 'site/list', - 'methods' => 'get', - 'sort' => 100, - 'status' => 1, - 'is_show' => 1, - ], - [ - 'menu_name' => '站点详情', - 'menu_key' => 'site_info', - 'menu_type' => 1, - 'icon' => '', - 'api_url' => 'site/site/', - 'router_path' => 'info', - 'view_path' => 'site/info', - 'methods' => 'get', - 'sort' => 90, - 'status' => 1, - 'is_show' => 0, - ], - [ - 'menu_name' => '站点套餐', - 'menu_key' => 'site_group', - 'menu_type' => 1, - 'icon' => 'element-PriceTag', - 'api_url' => 'site/group', - 'router_path' => 'group', - 'view_path' => 'site/group', - 'methods' => 'get', - 'sort' => 80, - 'status' => 1, - 'is_show' => 1, - ], - [ - 'menu_name' => '站点管理员', - 'menu_key' => 'site_user', - 'menu_type' => 1, - 'icon' => 'element-User', - 'api_url' => 'user/user', - 'router_path' => 'user', - 'view_path' => 'site/user', - 'methods' => 'get', - 'sort' => 70, - 'status' => 1, - 'is_show' => 1, - ] + 'menu_name' => '控制台', + 'menu_key' => 'overview', + 'menu_type' => 1, + 'icon' => 'element-Monitor', + 'api_url' => '', + 'router_path' => 'index', + 'view_path' => 'index/index', + 'methods' => '', + 'sort' => 100, + 'status' => 1, + 'is_show' => 1, + ], + [ + 'menu_name' => '站点管理', + 'menu_key' => 'site', + 'menu_type' => 0, + 'icon' => 'element-Memo', + 'api_url' => '', + 'router_path' => 'site', + 'view_path' => '', + 'methods' => '', + 'sort' => 50, + 'status' => 1, + 'is_show' => 1, + 'children' => [ + [ + 'menu_name' => '站点列表', + 'menu_key' => 'site_list', + 'menu_type' => 1, + 'icon' => 'element-OfficeBuilding', + 'api_url' => 'site/site', + 'router_path' => 'list', + 'view_path' => 'site/list', + 'methods' => 'get', + 'sort' => 100, + 'status' => 1, + 'is_show' => 1, + ], + [ + 'menu_name' => '站点详情', + 'menu_key' => 'site_info', + 'menu_type' => 1, + 'icon' => '', + 'api_url' => 'site/site/', + 'router_path' => 'info', + 'view_path' => 'site/info', + 'methods' => 'get', + 'sort' => 90, + 'status' => 1, + 'is_show' => 0, + ], + [ + 'menu_name' => '站点套餐', + 'menu_key' => 'site_group', + 'menu_type' => 1, + 'icon' => 'element-PriceTag', + 'api_url' => 'site/group', + 'router_path' => 'group', + 'view_path' => 'site/group', + 'methods' => 'get', + 'sort' => 80, + 'status' => 1, + 'is_show' => 1, + ], + [ + 'menu_name' => '站点管理员', + 'menu_key' => 'site_user', + 'menu_type' => 1, + 'icon' => 'element-User', + 'api_url' => 'user/user', + 'router_path' => 'user', + 'view_path' => 'site/user', + 'methods' => 'get', + 'sort' => 70, + 'status' => 1, + 'is_show' => 1, ] - ], - [ - 'menu_name' => '权限管理', - 'menu_key' => 'auth', - 'menu_type' => 0, - 'icon' => 'element-Lock', - 'api_url' => '', - 'router_path' => 'auth', - 'view_path' => '', - 'methods' => '', - 'sort' => 40, - 'status' => 1, - 'is_show' => 1, - 'children' => [ - [ - 'menu_name' => '菜单管理', - 'menu_key' => 'menu_list', - 'menu_type' => 1, - 'icon' => 'element-Operation', - 'api_url' => '', - 'router_path' => 'menu', - 'view_path' => '', - 'methods' => '', - 'sort' => 100, - 'status' => 1, - 'is_show' => 1, - 'children' => [ - [ - 'menu_name' => '平台菜单', - 'menu_key' => 'auth_menu', - 'menu_type' => 1, - 'icon' => '', - 'api_url' => 'sys/menu', - 'router_path' => 'admin', - 'view_path' => 'auth/menu', - 'methods' => 'get', - 'sort' => 100, - 'status' => 1, - 'is_show' => 1, - 'children' => [ - [ - 'menu_name' => '新增', - 'menu_key' => 'auth_menu_add', - 'menu_type' => 2, - 'icon' => '', - 'api_url' => 'sys/menu', - 'router_path' => '', - 'view_path' => '', - 'methods' => 'post', - 'sort' => 1, - 'status' => 1, - 'is_show' => 1, - ], - [ - 'menu_name' => '编辑', - 'menu_key' => 'auth_menu_update', - 'menu_type' => 2, - 'icon' => '', - 'api_url' => 'sys/menu/', - 'router_path' => '', - 'view_path' => '', - 'methods' => 'put', - 'sort' => 1, - 'status' => 1, - 'is_show' => 1, - ], - [ - 'menu_name' => '删除', - 'menu_key' => 'auth_menu_del', - 'menu_type' => 2, - 'icon' => '', - 'api_url' => 'sys/menu', - 'router_path' => '', - 'view_path' => '', - 'methods' => 'delete', - 'sort' => 1, - 'status' => 1, - 'is_show' => 1, - ], - [ - 'menu_name' => '详情', - 'menu_key' => 'auth_menu_info', - 'menu_type' => 2, - 'icon' => '', - 'api_url' => 'sys/menu/', - 'router_path' => '', - 'view_path' => '', - 'methods' => 'get', - 'sort' => 0, - 'status' => 1, - 'is_show' => 1, - ], + ] + ], + [ + 'menu_name' => '权限管理', + 'menu_key' => 'auth', + 'menu_type' => 0, + 'icon' => 'element-Lock', + 'api_url' => '', + 'router_path' => 'auth', + 'view_path' => '', + 'methods' => '', + 'sort' => 40, + 'status' => 1, + 'is_show' => 1, + 'children' => [ + [ + 'menu_name' => '菜单管理', + 'menu_key' => 'menu_list', + 'menu_type' => 1, + 'icon' => 'element-Operation', + 'api_url' => '', + 'router_path' => 'menu', + 'view_path' => '', + 'methods' => '', + 'sort' => 100, + 'status' => 1, + 'is_show' => 1, + 'children' => [ + [ + 'menu_name' => '平台菜单', + 'menu_key' => 'auth_menu', + 'menu_type' => 1, + 'icon' => '', + 'api_url' => 'sys/menu', + 'router_path' => 'admin', + 'view_path' => 'auth/menu', + 'methods' => 'get', + 'sort' => 100, + 'status' => 1, + 'is_show' => 1, + 'children' => [ + [ + 'menu_name' => '新增', + 'menu_key' => 'auth_menu_add', + 'menu_type' => 2, + 'icon' => '', + 'api_url' => 'sys/menu', + 'router_path' => '', + 'view_path' => '', + 'methods' => 'post', + 'sort' => 1, + 'status' => 1, + 'is_show' => 1, ], - ], - [ - 'menu_name' => '站点菜单', - 'menu_key' => 'auth_site_menu', - 'menu_type' => 1, - 'icon' => '', - 'api_url' => 'sys/menu', - 'router_path' => 'site', - 'view_path' => 'auth/site_menu', - 'methods' => 'get', - 'sort' => 90, - 'status' => 1, - 'is_show' => 1, - 'children' => [ - [ - 'menu_name' => '新增', - 'menu_key' => 'auth_site_menu_add', - 'menu_type' => 2, - 'icon' => '', - 'api_url' => 'sys/menu', - 'router_path' => '', - 'view_path' => '', - 'methods' => 'post', - 'sort' => 1, - 'status' => 1, - 'is_show' => 1, - ], - [ - 'menu_name' => '编辑', - 'menu_key' => 'auth_site_menu_update', - 'menu_type' => 2, - 'icon' => '', - 'api_url' => 'sys/menu/', - 'router_path' => '', - 'view_path' => '', - 'methods' => 'put', - 'sort' => 1, - 'status' => 1, - 'is_show' => 1, - ], - [ - 'menu_name' => '删除', - 'menu_key' => 'auth_site_menu_del', - 'menu_type' => 2, - 'icon' => '', - 'api_url' => 'sys/menu', - 'router_path' => '', - 'view_path' => '', - 'methods' => 'delete', - 'sort' => 1, - 'status' => 1, - 'is_show' => 1, - ], - [ - 'menu_name' => '详情', - 'menu_key' => 'auth_site_menu_info', - 'menu_type' => 2, - 'icon' => '', - 'api_url' => 'sys/menu/', - 'router_path' => '', - 'view_path' => '', - 'methods' => 'get', - 'sort' => 0, - 'status' => 1, - 'is_show' => 1, - ], + [ + 'menu_name' => '编辑', + 'menu_key' => 'auth_menu_update', + 'menu_type' => 2, + 'icon' => '', + 'api_url' => 'sys/menu/', + 'router_path' => '', + 'view_path' => '', + 'methods' => 'put', + 'sort' => 1, + 'status' => 1, + 'is_show' => 1, + ], + [ + 'menu_name' => '删除', + 'menu_key' => 'auth_menu_del', + 'menu_type' => 2, + 'icon' => '', + 'api_url' => 'sys/menu', + 'router_path' => '', + 'view_path' => '', + 'methods' => 'delete', + 'sort' => 1, + 'status' => 1, + 'is_show' => 1, + ], + [ + 'menu_name' => '详情', + 'menu_key' => 'auth_menu_info', + 'menu_type' => 2, + 'icon' => '', + 'api_url' => 'sys/menu/', + 'router_path' => '', + 'view_path' => '', + 'methods' => 'get', + 'sort' => 0, + 'status' => 1, + 'is_show' => 1, ], - ] - ] - ], - [ - - 'menu_name' => '平台管理员', - 'menu_key' => 'auth_user', - 'menu_type' => 1, - 'icon' => 'iconfont-iconyonghu', - 'api_url' => 'site/user', - 'router_path' => 'user', - 'view_path' => 'auth/user', - 'methods' => 'get', - 'sort' => 80, - 'status' => 1, - 'is_show' => 1, - 'children' => [ - [ - 'menu_name' => '新增', - 'menu_key' => 'auth_user_add', - 'menu_type' => 2, - 'icon' => '', - 'api_url' => 'site/user', - 'router_path' => '', - 'view_path' => '', - 'methods' => 'post', - 'sort' => 1, - 'status' => 1, - 'is_show' => 1, - ], - [ - 'menu_name' => '编辑', - 'menu_key' => 'auth_user_update', - 'menu_type' => 2, - 'icon' => '', - 'api_url' => 'site/user/', - 'router_path' => '', - 'view_path' => '', - 'methods' => 'put', - 'sort' => 1, - 'status' => 1, - 'is_show' => 1, - ], - [ - 'menu_name' => '删除', - 'menu_key' => 'auth_user_del', - 'menu_type' => 2, - 'icon' => '', - 'api_url' => 'site/user/', - 'router_path' => '', - 'view_path' => '', - 'methods' => 'delete', - 'sort' => 1, - 'status' => 1, - 'is_show' => 1, - ], - [ - 'menu_name' => '详情', - 'menu_key' => 'auth_user_info', - 'menu_type' => 2, - 'icon' => '', - 'api_url' => 'sys/user/', - 'router_path' => '', - 'view_path' => '', - 'methods' => 'get', - 'sort' => 0, - 'status' => 1, - 'is_show' => 1, ], ], - ], - [ - 'menu_name' => '角色管理', - 'menu_key' => 'auth_role', - 'menu_type' => 1, - 'icon' => 'iconfont-iconhuiyuanliebiao', - 'api_url' => 'sys/role', - 'router_path' => 'role', - 'view_path' => 'auth/role', - 'methods' => 'get', - 'sort' => 70, - 'status' => 1, - 'is_show' => 1, - 'children' => [ - [ - 'menu_name' => '新增', - 'menu_key' => 'auth_role_add', - 'menu_type' => 2, - 'icon' => '', - 'api_url' => 'sys/role', - 'router_path' => '', - 'view_path' => '', - 'methods' => 'post', - 'sort' => 1, - 'status' => 1, - 'is_show' => 1, - ], - [ - 'menu_name' => '编辑', - 'menu_key' => 'auth_role_update', - 'menu_type' => 2, - 'icon' => '', - 'api_url' => 'sys/role/', - 'router_path' => '', - 'view_path' => '', - 'methods' => 'put', - 'sort' => 1, - 'status' => 1, - 'is_show' => 1, - ], - [ - 'menu_name' => '删除', - 'menu_key' => 'auth_role_del', - 'menu_type' => 2, - 'icon' => '', - 'api_url' => 'sys/role/', - 'router_path' => '', - 'view_path' => '', - 'methods' => 'delete', - 'sort' => 1, - 'status' => 1, - 'is_show' => 1, + [ + 'menu_name' => '站点菜单', + 'menu_key' => 'auth_site_menu', + 'menu_type' => 1, + 'icon' => '', + 'api_url' => 'sys/menu', + 'router_path' => 'site', + 'view_path' => 'auth/site_menu', + 'methods' => 'get', + 'sort' => 90, + 'status' => 1, + 'is_show' => 1, + 'children' => [ + [ + 'menu_name' => '新增', + 'menu_key' => 'auth_site_menu_add', + 'menu_type' => 2, + 'icon' => '', + 'api_url' => 'sys/menu', + 'router_path' => '', + 'view_path' => '', + 'methods' => 'post', + 'sort' => 1, + 'status' => 1, + 'is_show' => 1, + ], + [ + 'menu_name' => '编辑', + 'menu_key' => 'auth_site_menu_update', + 'menu_type' => 2, + 'icon' => '', + 'api_url' => 'sys/menu/', + 'router_path' => '', + 'view_path' => '', + 'methods' => 'put', + 'sort' => 1, + 'status' => 1, + 'is_show' => 1, + ], + [ + 'menu_name' => '删除', + 'menu_key' => 'auth_site_menu_del', + 'menu_type' => 2, + 'icon' => '', + 'api_url' => 'sys/menu', + 'router_path' => '', + 'view_path' => '', + 'methods' => 'delete', + 'sort' => 1, + 'status' => 1, + 'is_show' => 1, + ], + [ + 'menu_name' => '详情', + 'menu_key' => 'auth_site_menu_info', + 'menu_type' => 2, + 'icon' => '', + 'api_url' => 'sys/menu/', + 'router_path' => '', + 'view_path' => '', + 'methods' => 'get', + 'sort' => 0, + 'status' => 1, + 'is_show' => 1, + ], ], ] - ], - [ - 'menu_name' => '操作日志', - 'menu_key' => 'auth_log', - 'menu_type' => 1, - 'icon' => 'element-Document', - 'api_url' => 'sys/log', - 'router_path' => 'log', - 'view_path' => 'auth/log', - 'methods' => 'get', - 'sort' => 60, - 'status' => 1, - 'is_show' => 1, - ], - ] - ], + ] + ], + [ - [ - 'menu_name' => '系统设置', - 'menu_key' => 'setting', - 'menu_type' => 0, - 'icon' => 'element-Setting', - 'api_url' => '', - 'router_path' => 'setting', - 'view_path' => '', - 'methods' => '', - 'sort' => 20, - 'status' => 1, - 'is_show' => 1, - 'children' => [ - [ - 'menu_name' => '网站设置', - 'menu_key' => 'setting_system', - 'menu_type' => 1, - 'icon' => 'element-Basketball', - 'api_url' => 'sys/config/website', - 'router_path' => 'system', - 'view_path' => 'setting/system', - 'methods' => 'get', - 'sort' => 100, - 'status' => 1, - 'is_show' => 1, + 'menu_name' => '平台管理员', + 'menu_key' => 'auth_user', + 'menu_type' => 1, + 'icon' => 'iconfont-iconyonghu', + 'api_url' => 'site/user', + 'router_path' => 'user', + 'view_path' => 'auth/user', + 'methods' => 'get', + 'sort' => 80, + 'status' => 1, + 'is_show' => 1, + 'children' => [ + [ + 'menu_name' => '新增', + 'menu_key' => 'auth_user_add', + 'menu_type' => 2, + 'icon' => '', + 'api_url' => 'site/user', + 'router_path' => '', + 'view_path' => '', + 'methods' => 'post', + 'sort' => 1, + 'status' => 1, + 'is_show' => 1, + ], + [ + 'menu_name' => '编辑', + 'menu_key' => 'auth_user_update', + 'menu_type' => 2, + 'icon' => '', + 'api_url' => 'site/user/', + 'router_path' => '', + 'view_path' => '', + 'methods' => 'put', + 'sort' => 1, + 'status' => 1, + 'is_show' => 1, + ], + [ + 'menu_name' => '删除', + 'menu_key' => 'auth_user_del', + 'menu_type' => 2, + 'icon' => '', + 'api_url' => 'site/user/', + 'router_path' => '', + 'view_path' => '', + 'methods' => 'delete', + 'sort' => 1, + 'status' => 1, + 'is_show' => 1, + ], + [ + 'menu_name' => '详情', + 'menu_key' => 'auth_user_info', + 'menu_type' => 2, + 'icon' => '', + 'api_url' => 'sys/user/', + 'router_path' => '', + 'view_path' => '', + 'methods' => 'get', + 'sort' => 0, + 'status' => 1, + 'is_show' => 1, + ], ], - [ - 'menu_name' => '版权设置', - 'menu_key' => 'setting_copyright', - 'menu_type' => 1, - 'icon' => 'iconfont-iconbanquan1', - 'api_url' => 'sys/config/copyright', - 'router_path' => 'copyright', - 'view_path' => 'setting/copyright', - 'methods' => 'get', - 'sort' => 90, - 'status' => 1, - 'is_show' => 1, - ], - [ - 'menu_name' => '登录设置', - 'menu_key' => 'setting_login', - 'menu_type' => 1, - 'icon' => 'iconfont-iconzhuceshezhi', - 'api_url' => 'sys/config/login', - 'router_path' => 'adminlogin', - 'view_path' => 'setting/adminlogin', - 'methods' => 'get', - 'sort' => 80, - 'status' => 1, - 'is_show' => 1, - ], - [ - 'menu_name' => '存储设置', - 'menu_key' => 'setting_storage', - 'menu_type' => 1, - 'icon' => 'element-FolderChecked', - 'api_url' => 'sys/storage', - 'router_path' => 'storage', - 'view_path' => 'setting/storage', - 'methods' => 'get', - 'sort' => 30, - 'status' => 1, - 'is_show' => 1, - ], - [ - 'menu_name' => '微信开放平台', - 'menu_key' => 'setting_oplatform', - 'menu_type' => 1, - 'icon' => 'iconfont-iconweixin', - 'api_url' => 'sys/wxoplatform', - 'router_path' => 'oplatform', - 'view_path' => 'setting/wxoplatform', - 'methods' => 'get', - 'sort' => 20, - 'status' => 1, - 'is_show' => 1, + ], + [ + 'menu_name' => '角色管理', + 'menu_key' => 'auth_role', + 'menu_type' => 1, + 'icon' => 'iconfont-iconhuiyuanliebiao', + 'api_url' => 'sys/role', + 'router_path' => 'role', + 'view_path' => 'auth/role', + 'methods' => 'get', + 'sort' => 70, + 'status' => 1, + 'is_show' => 1, + 'children' => [ + [ + 'menu_name' => '新增', + 'menu_key' => 'auth_role_add', + 'menu_type' => 2, + 'icon' => '', + 'api_url' => 'sys/role', + 'router_path' => '', + 'view_path' => '', + 'methods' => 'post', + 'sort' => 1, + 'status' => 1, + 'is_show' => 1, + ], + [ + 'menu_name' => '编辑', + 'menu_key' => 'auth_role_update', + 'menu_type' => 2, + 'icon' => '', + 'api_url' => 'sys/role/', + 'router_path' => '', + 'view_path' => '', + 'methods' => 'put', + 'sort' => 1, + 'status' => 1, + 'is_show' => 1, + ], + [ + 'menu_name' => '删除', + 'menu_key' => 'auth_role_del', + 'menu_type' => 2, + 'icon' => '', + 'api_url' => 'sys/role/', + 'router_path' => '', + 'view_path' => '', + 'methods' => 'delete', + 'sort' => 1, + 'status' => 1, + 'is_show' => 1, + ], + ] + ], + [ + 'menu_name' => '操作日志', + 'menu_key' => 'auth_log', + 'menu_type' => 1, + 'icon' => 'element-Document', + 'api_url' => 'sys/log', + 'router_path' => 'log', + 'view_path' => 'auth/log', + 'methods' => 'get', + 'sort' => 60, + 'status' => 1, + 'is_show' => 1, + ], + ] + ], + + [ + 'menu_name' => '系统设置', + 'menu_key' => 'setting', + 'menu_type' => 0, + 'icon' => 'element-Setting', + 'api_url' => '', + 'router_path' => 'setting', + 'view_path' => '', + 'methods' => '', + 'sort' => 20, + 'status' => 1, + 'is_show' => 1, + 'children' => [ + [ + 'menu_name' => '网站设置', + 'menu_key' => 'setting_system', + 'menu_type' => 1, + 'icon' => 'element-Basketball', + 'api_url' => 'sys/config/website', + 'router_path' => 'system', + 'view_path' => 'setting/system', + 'methods' => 'get', + 'sort' => 100, + 'status' => 1, + 'is_show' => 1, + ], + [ + 'menu_name' => '版权设置', + 'menu_key' => 'setting_copyright', + 'menu_type' => 1, + 'icon' => 'iconfont-iconbanquan1', + 'api_url' => 'sys/config/copyright', + 'router_path' => 'copyright', + 'view_path' => 'setting/copyright', + 'methods' => 'get', + 'sort' => 90, + 'status' => 1, + 'is_show' => 1, + ], + [ + 'menu_name' => '登录设置', + 'menu_key' => 'setting_login', + 'menu_type' => 1, + 'icon' => 'iconfont-iconzhuceshezhi', + 'api_url' => 'sys/config/login', + 'router_path' => 'adminlogin', + 'view_path' => 'setting/adminlogin', + 'methods' => 'get', + 'sort' => 80, + 'status' => 1, + 'is_show' => 1, + ], + [ + 'menu_name' => '存储设置', + 'menu_key' => 'setting_storage', + 'menu_type' => 1, + 'icon' => 'element-FolderChecked', + 'api_url' => 'sys/storage', + 'router_path' => 'storage', + 'view_path' => 'setting/storage', + 'methods' => 'get', + 'sort' => 30, + 'status' => 1, + 'is_show' => 1, + ], + [ + 'menu_name' => '微信开放平台', + 'menu_key' => 'setting_oplatform', + 'menu_type' => 1, + 'icon' => 'iconfont-iconweixin', + 'api_url' => 'sys/wxoplatform', + 'router_path' => 'oplatform', + 'view_path' => 'setting/wxoplatform', + 'methods' => 'get', + 'sort' => 20, + 'status' => 1, + 'is_show' => 1, + ], + [ + 'menu_name' => '小程序平台', + 'menu_key' => 'setting_weapp_oplatform', + 'menu_type' => 1, + 'icon' => 'iconfont-iconweixin', + 'api_url' => 'sys/weapp', + 'router_path' => 'weapp', + 'view_path' => 'setting/weapp', + 'methods' => 'get', + 'sort' => 20, + 'status' => 1, + 'is_show' => 1, + ] + ] + ], + [ + 'menu_name' => '开发工具', + 'menu_key' => 'tool', + 'menu_type' => 0, + 'icon' => 'element-Edit', + 'api_url' => '', + 'router_path' => 'tools', + 'view_path' => '', + 'methods' => '', + 'sort' => 10, + 'status' => 1, + 'is_show' => 1, + 'children' => [ + [ + 'menu_name' => '代码生成', + 'menu_key' => 'code', + 'menu_type' => 1, + 'icon' => 'iconfont-iconyuandaima', + 'api_url' => 'generator/generator', + 'router_path' => 'code', + 'view_path' => 'tools/code/index', + 'methods' => 'get', + 'sort' => 100, + 'status' => 1, + 'is_show' => 1, + ], + [ + 'menu_name' => '数据表编辑', + 'menu_key' => 'code_edit', + 'menu_type' => 1, + 'icon' => '', + 'api_url' => '', + 'router_path' => 'code/edit', + 'view_path' => 'tools/code/edit', + 'methods' => '', + 'sort' => 80, + 'status' => 1, + 'is_show' => 0, + ], + [ + 'menu_name' => '更新缓存', + 'menu_key' => 'tools_Update_cache', + 'menu_type' => 1, + 'icon' => 'iconfont-icongengxinhuancun', + 'api_url' => '', + 'router_path' => 'update', + 'view_path' => 'tools/updatecache', + 'methods' => '', + 'sort' => 60, + 'status' => 1, + 'is_show' => 1, + ], + [ + 'menu_name' => '环境检测', + 'menu_key' => 'tools_check_environment', + 'menu_type' => 1, + 'icon' => 'element-SetUp', + 'api_url' => '', + 'router_path' => 'detection', + 'view_path' => 'tools/detection', + 'methods' => '', + 'sort' => 50, + 'status' => 1, + 'is_show' => 1, + ], + [ + 'menu_name' => '计划任务', + 'menu_key' => 'tools_schedule', + 'menu_type' => 1, + 'icon' => 'element-SetUp', + 'api_url' => 'sys/schedule/list', + 'router_path' => 'schedule', + 'view_path' => 'tools/schedule', + 'methods' => '', + 'sort' => 40, + 'status' => 1, + 'is_show' => 1, + 'children' => [ + [ + 'menu_name' => '新增', + 'menu_key' => 'schedule_add', + 'menu_type' => 2, + 'icon' => '', + 'api_url' => 'sys/schedule', + 'router_path' => '', + 'view_path' => '', + 'methods' => 'post', + 'sort' => 4, + 'status' => 1, + 'is_show' => 1, + ], + [ + 'menu_name' => '编辑', + 'menu_key' => 'schedule_update', + 'menu_type' => 2, + 'icon' => '', + 'api_url' => 'sys/schedule/', + 'router_path' => '', + 'view_path' => '', + 'methods' => 'put', + 'sort' => 3, + 'status' => 1, + 'is_show' => 1, + ], + [ + 'menu_name' => '设置状态', + 'menu_key' => 'schedule_set_status', + 'menu_type' => 2, + 'icon' => '', + 'api_url' => 'schedule/modify/status/', + 'router_path' => '', + 'view_path' => '', + 'methods' => 'put', + 'sort' => 2, + 'status' => 1, + 'is_show' => 1, + ], + [ + 'menu_name' => '删除', + 'menu_key' => 'schedule_del', + 'menu_type' => 2, + 'icon' => '', + 'api_url' => 'sys/schedule/', + 'router_path' => '', + 'view_path' => '', + 'methods' => 'delete', + 'sort' => 1, + 'status' => 1, + 'is_show' => 1, + ], ] ] - ], - [ - 'menu_name' => '开发工具', - 'menu_key' => 'tool', - 'menu_type' => 0, - 'icon' => 'element-Edit', - 'api_url' => '', - 'router_path' => 'tools', - 'view_path' => '', - 'methods' => '', - 'sort' => 10, - 'status' => 1, - 'is_show' => 1, - 'children' => [ - [ - 'menu_name' => '代码生成', - 'menu_key' => 'code', - 'menu_type' => 1, - 'icon' => 'iconfont-iconyuandaima', - 'api_url' => 'generator/generator', - 'router_path' => 'code', - 'view_path' => 'tools/code/index', - 'methods' => 'get', - 'sort' => 100, - 'status' => 1, - 'is_show' => 1, - ], - [ - 'menu_name' => '数据表编辑', - 'menu_key' => 'code_edit', - 'menu_type' => 1, - 'icon' => '', - 'api_url' => '', - 'router_path' => 'code/edit', - 'view_path' => 'tools/code/edit', - 'methods' => '', - 'sort' => 80, - 'status' => 1, - 'is_show' => 0, - ], - [ - 'menu_name' => '更新缓存', - 'menu_key' => 'tools_Update_cache', - 'menu_type' => 1, - 'icon' => 'iconfont-icongengxinhuancun', - 'api_url' => '', - 'router_path' => 'update', - 'view_path' => 'tools/updatecache', - 'methods' => '', - 'sort' => 60, - 'status' => 1, - 'is_show' => 1, - ], - [ - 'menu_name' => '环境检测', - 'menu_key' => 'tools_check_environment', - 'menu_type' => 1, - 'icon' => 'element-SetUp', - 'api_url' => '', - 'router_path' => 'detection', - 'view_path' => 'tools/detection', - 'methods' => '', - 'sort' => 50, - 'status' => 1, - 'is_show' => 1, - ], - [ - 'menu_name' => '计划任务', - 'menu_key' => 'tools_schedule', - 'menu_type' => 1, - 'icon' => 'element-SetUp', - 'api_url' => '', - 'router_path' => 'schedule', - 'view_path' => 'tools/schedule', - 'methods' => '', - 'sort' => 40, - 'status' => 1, - 'is_show' => 1, - ] - ] - ], - [ - 'menu_name' => '应用市场', - 'menu_key' => 'app_store', - 'menu_type' => 1, - 'icon' => 'element-ShoppingBag', - 'api_url' => 'addon/local', - 'router_path' => 'app_store', - 'view_path' => 'app/store', - 'methods' => 'get', - 'sort' => 0, - 'status' => 1, - 'is_show' => 1, - ], - ]; \ No newline at end of file + ] + ], + [ + 'menu_name' => '授权信息', + 'menu_key' => 'app_auth', + 'menu_type' => 1, + 'icon' => 'element-ShoppingBag', + 'api_url' => 'niucloud/authinfo', + 'router_path' => 'authorize', + 'view_path' => 'app/authorize', + 'methods' => 'get', + 'sort' => 0, + 'status' => 1, + 'is_show' => 1, + ], + [ + 'menu_name' => '应用市场', + 'menu_key' => 'app_store', + 'menu_type' => 1, + 'icon' => 'element-ShoppingBag', + 'api_url' => 'addon/local', + 'router_path' => 'app_store', + 'view_path' => 'app/store', + 'methods' => 'get', + 'sort' => 0, + 'status' => 1, + 'is_show' => 1, + ], + ]; \ No newline at end of file diff --git a/niucloud/app/dict/menu/site.php b/niucloud/app/dict/menu/site.php index 4bb857ed5..ac9b4f42a 100644 --- a/niucloud/app/dict/menu/site.php +++ b/niucloud/app/dict/menu/site.php @@ -497,6 +497,60 @@ return 'status' => 1, 'is_show' => 1, ], + [ + 'menu_name' => '线下支付', + 'menu_key' => 'site_pay_offlinepay', + 'menu_type' => 1, + 'icon' => 'element-Postcard', + 'api_url' => 'pay/offlinepay', + 'router_path' => 'pay/offlinepay', + 'view_path' => 'finance/offlinepay', + 'methods' => 'get', + 'sort' => 99, + 'status' => 1, + 'is_show' => 1, + 'children' => [ + [ + 'menu_name' => '通过', + 'menu_key' => 'site_pay_audit_pass', + 'menu_type' => 2, + 'icon' => '', + 'api_url' => 'pay/pass/:out_trade_no', + 'router_path' => '', + 'view_path' => '', + 'methods' => 'put', + 'sort' => 99, + 'status' => 1, + 'is_show' => 1, + ], + [ + 'menu_name' => '拒绝', + 'menu_key' => 'site_pay_audit_refuse', + 'menu_type' => 2, + 'icon' => '', + 'api_url' => 'pay/refuse/:out_trade_no', + 'router_path' => '', + 'view_path' => '', + 'methods' => 'put', + 'sort' => 99, + 'status' => 1, + 'is_show' => 1, + ], + ] + ], + [ + 'menu_name' => '支付单据详情', + 'menu_key' => 'site_pay_detail', + 'menu_type' => 1, + 'icon' => 'element-Postcard', + 'api_url' => 'pay/detail', + 'router_path' => 'pay/detail', + 'view_path' => 'finance/pay_detail', + 'methods' => 'get', + 'sort' => 98, + 'status' => 1, + 'is_show' => 0, + ], [ 'menu_name' => '会员提现', 'menu_key' => 'cash_out_list', @@ -506,7 +560,7 @@ return 'router_path' => 'cash_out', 'view_path' => 'finance/cash_out', 'methods' => 'get', - 'sort' => 99, + 'sort' => 97, 'status' => 1, 'is_show' => 1, ], @@ -703,6 +757,19 @@ return 'sort' => 90, 'status' => 1, 'is_show' => 1, + ], + [ + 'menu_name' => '小程序代码', + 'menu_key' => 'weapp_code', + 'menu_type' => 1, + 'icon' => '', + 'api_url' => 'weapp/code', + 'router_path' => 'code', + 'view_path' => 'channel/weapp/code', + 'methods' => 'get', + 'sort' => 90, + 'status' => 1, + 'is_show' => 1, ] ] ], diff --git a/niucloud/app/dict/notice/NoticeDict.php b/niucloud/app/dict/notice/NoticeDict.php index 5f362a664..8883272e2 100644 --- a/niucloud/app/dict/notice/NoticeDict.php +++ b/niucloud/app/dict/notice/NoticeDict.php @@ -27,11 +27,11 @@ class NoticeDict public static function getNotice(string $key = '') { $addon_load = new DictLoader('Notice'); - $notice = $addon_load->load([ 'type' => 'notice' ]); + $notice = $addon_load->load(['type' => 'notice']); $notice_type = NoticeTypeDict::getType(); foreach ($notice_type as $k => $v) { $var_name = $k . '_notice'; - $$var_name = $addon_load->load([ 'type' => $k ]); + $$var_name = $addon_load->load(['type' => $k]); } foreach ($notice as $k => $v) { @@ -39,14 +39,14 @@ class NoticeDict foreach ($notice_type as $notice_type_k => $notice_type_v) { $var_name = $notice_type_k . '_notice'; if (array_key_exists($k, $$var_name)) { - $notice[ $k ][ $notice_type_k ] = $$var_name[ $k ]; + $notice[$k][$notice_type_k] = $$var_name[$k]; $support_type[] = $notice_type_k; } } - $notice[ $k ][ 'support_type' ] = $support_type; + $notice[$k]['support_type'] = $support_type; } if (!empty($key)) { - return $notice[ $key ] ?? []; + return $notice[$key] ?? []; } return $notice; } diff --git a/niucloud/app/dict/notice/NoticeTypeDict.php b/niucloud/app/dict/notice/NoticeTypeDict.php index e7b5b7abe..27ad9f978 100644 --- a/niucloud/app/dict/notice/NoticeTypeDict.php +++ b/niucloud/app/dict/notice/NoticeTypeDict.php @@ -14,18 +14,19 @@ namespace app\dict\notice; class NoticeTypeDict { //短信 - const SMS = 'sms'; + public const SMS = 'sms'; //微信公众号 - const WECHAT = 'wechat'; + public const WECHAT = 'wechat'; //微信小程序 - const WEAPP = 'weapp'; + public const WEAPP = 'weapp'; /** * 获取消息类型 * @return array */ - public static function getType(){ + public static function getType() + { return [ self::SMS => get_lang('dict_notice.type_sms'),//短信 self::WECHAT => get_lang('dict_notice.type_wechat'),//微信公众号 diff --git a/niucloud/app/dict/notice/notice.php b/niucloud/app/dict/notice/notice.php index 85b8da2b3..df6aaca35 100644 --- a/niucloud/app/dict/notice/notice.php +++ b/niucloud/app/dict/notice/notice.php @@ -6,7 +6,7 @@ return [ 'name' => '手机验证码', 'title' => '管理端验证码登录', 'async' => false, - 'variable' =>[ + 'variable' => [ 'code' => '验证码' ], ], @@ -17,7 +17,7 @@ return [ 'name' => '手机验证码', 'title' => '前端验证码登录,注册,手机验证', 'async' => false, - 'variable' =>[ + 'variable' => [ 'code' => '验证码' ], ], @@ -29,7 +29,7 @@ return [ 'name' => '充值成功通知', 'title' => '会员充值成功后发送', 'async' => true, - 'variable' =>[ + 'variable' => [ 'price' => '充值金额', 'balance' => '充值后账户', 'time' => '充值时间', diff --git a/niucloud/app/dict/order/RechargeOrderDict.php b/niucloud/app/dict/order/RechargeOrderDict.php index ad372e601..71f3abf2f 100644 --- a/niucloud/app/dict/order/RechargeOrderDict.php +++ b/niucloud/app/dict/order/RechargeOrderDict.php @@ -98,7 +98,7 @@ class RechargeOrderDict if ($status == '') { return $data; } - return $data[ $status ] ?? ''; + return $data[$status] ?? ''; } /** @@ -126,7 +126,7 @@ class RechargeOrderDict if ($status == '') { return $data; } - return $data[ $status ] ?? ''; + return $data[$status] ?? ''; } } \ No newline at end of file diff --git a/niucloud/app/dict/pay/OnlinePayDict.php b/niucloud/app/dict/pay/OnlinePayDict.php index e783f3d3d..661787177 100644 --- a/niucloud/app/dict/pay/OnlinePayDict.php +++ b/niucloud/app/dict/pay/OnlinePayDict.php @@ -14,31 +14,33 @@ namespace app\dict\pay; class OnlinePayDict { //上传方式 图片 - const SUCCESS = 'SUCCESS';//支付成功 + public const SUCCESS = 'SUCCESS';//支付成功 //上传方式 视频 - const REFUND = 'REFUND';//转入退款 - const NOTPAY = 'NOTPAY';//未支付 - const CLOSED = 'CLOSED';//已关闭 - const REVOKED = 'REVOKED';//已撤销(仅付款码支付会返回) - const USERPAYING = 'USERPAYING';//用户支付中(仅付款码支付会返回) - const PAYERROR = 'PAYERROR';//支付失败(仅付款码支付会返回) - const TRADE_FINISHED = 'TRADE_FINISHED'; + public const REFUND = 'REFUND';//转入退款 + public const NOTPAY = 'NOTPAY';//未支付 + public const CLOSED = 'CLOSED';//已关闭 + public const REVOKED = 'REVOKED';//已撤销(仅付款码支付会返回) + public const USERPAYING = 'USERPAYING';//用户支付中(仅付款码支付会返回) + public const PAYERROR = 'PAYERROR';//支付失败(仅付款码支付会返回) + public const TRADE_FINISHED = 'TRADE_FINISHED'; - public static function getAliPayStatus(string $status = ''){ - $list = [ - 'WAIT_BUYER_PAY' => self::NOTPAY,//交易创建,等待买家付款 - 'TRADE_CLOSED' => self::CLOSED,//未付款交易超时关闭,或支付完成后全额退款 - 'TRADE_SUCCESS' => self::SUCCESS,//交易支付成功 - 'TRADE_FINISHED' => self::TRADE_FINISHED,//交易结束,不可退款 - ]; - if(!empty($status)) - return $list[$status]; + public static function getAliPayStatus(string $status = '') + { + $list = [ + 'WAIT_BUYER_PAY' => self::NOTPAY,//交易创建,等待买家付款 + 'TRADE_CLOSED' => self::CLOSED,//未付款交易超时关闭,或支付完成后全额退款 + 'TRADE_SUCCESS' => self::SUCCESS,//交易支付成功 + 'TRADE_FINISHED' => self::TRADE_FINISHED,//交易结束,不可退款 + ]; + if (!empty($status)) + return $list[$status]; - return $list; + return $list; } - public static function getWechatPayStatus(string $status = ''){ + public static function getWechatPayStatus(string $status = '') + { $list = [ 'NOTPAY' => self::NOTPAY,//交易创建,等待买家付款 'CLOSED' => self::CLOSED,//已关闭 @@ -48,7 +50,7 @@ class OnlinePayDict 'USERPAYING' => self::USERPAYING,//用户支付中(仅付款码支付会返回) 'PAYERROR' => self::PAYERROR,//支付失败(仅付款码支付会返回) ]; - if(!empty($status)) + if (!empty($status)) return $list[$status]; return $list; diff --git a/niucloud/app/dict/pay/OnlineRefundDict.php b/niucloud/app/dict/pay/OnlineRefundDict.php index 09c26b755..8bd435437 100644 --- a/niucloud/app/dict/pay/OnlineRefundDict.php +++ b/niucloud/app/dict/pay/OnlineRefundDict.php @@ -14,12 +14,12 @@ namespace app\dict\pay; class OnlineRefundDict { - const SUCCESS = 'SUCCESS';//退款成功 + public const SUCCESS = 'SUCCESS';//退款成功 - const CLOSED = 'CLOSED';//退款关闭 + public const CLOSED = 'CLOSED';//退款关闭 - const PROCESSING = 'PROCESSING';//退款处理中 - const ABNORMAL = 'ABNORMAL';//退款异常 + public const PROCESSING = 'PROCESSING';//退款处理中 + public const ABNORMAL = 'ABNORMAL';//退款异常 /** @@ -30,18 +30,20 @@ class OnlineRefundDict * 未返回该字段表示退款请求未收到或者退款失败; * 注:如果退款查询发起时间早于退款时间,或者间隔退款发起时间太短,可能出现退款查询时还没处理成功,后面又处理成功的情况,建议商户在退款发起后间隔10秒以上再发起退款查询请求。 */ - public static function getAliRefundStatus(string $status = ''){ + public static function getAliRefundStatus(string $status = '') + { $list = [ 'REFUND_SUCCESS ' => self::SUCCESS,//退款处理成功 'REFUND_FAIL ' => self::ABNORMAL,//表示退款请求未收到或者退款失败 ]; - if(!empty($status)) + if (!empty($status)) return $list[$status]; return $list; } - public static function getWechatRefundStatus(string $status = ''){ + public static function getWechatRefundStatus(string $status = '') + { $list = [ 'SUCCESS' => self::SUCCESS,//退款成功 'CLOSED' => self::CLOSED,//退款关闭 @@ -49,7 +51,7 @@ class OnlineRefundDict 'ABNORMAL' => self::ABNORMAL,//退款异常 ]; - if(!empty($status)) + if (!empty($status)) return $list[$status]; return $list; diff --git a/niucloud/app/dict/pay/PayChannelDict.php b/niucloud/app/dict/pay/PayChannelDict.php index 7af1d98b7..fe477a741 100644 --- a/niucloud/app/dict/pay/PayChannelDict.php +++ b/niucloud/app/dict/pay/PayChannelDict.php @@ -21,7 +21,8 @@ class PayChannelDict * 支付渠道类型 * @return array */ - public static function getPayChannel(array $types = []){ + public static function getPayChannel(array $types = []) + { $channel = ChannelDict::getType(); $list = []; $pay_type = PayDict::getPayType(); @@ -32,11 +33,11 @@ class PayChannelDict // $pay_type[$k]['is_template'] = true; // } // } - foreach($channel as $k => $v){ + foreach ($channel as $k => $v) { $list[$k] = [ 'name' => $v, 'key' => $k, - 'pay_type' => $pay_type + 'pay_type' => $k == ChannelDict::PC ? $pay_type : array_diff_key($pay_type, [ PayDict::OFFLINEPAY => '']) ]; } return $list; diff --git a/niucloud/app/dict/pay/PayDict.php b/niucloud/app/dict/pay/PayDict.php index e0c47832f..1c0c40197 100644 --- a/niucloud/app/dict/pay/PayDict.php +++ b/niucloud/app/dict/pay/PayDict.php @@ -14,38 +14,44 @@ namespace app\dict\pay; class PayDict { //上传方式 图片 - const WECHATPAY = 'wechatpay';//微信支付 + public const WECHATPAY = 'wechatpay';//微信支付 //上传方式 视频 - const ALIPAY = 'alipay';//支付宝支付 + public const ALIPAY = 'alipay';//支付宝支付 //const UNIPAY = 'unipay';//银联 - const OFFLINEPAY = 'offlinepay';//线下支付 - const BALANCEPAY = 'balancepay';//线下支付 + public const OFFLINEPAY = 'offlinepay';//线下支付 + public const BALANCEPAY = 'balancepay';//线下支付 - const ON = '1'; - const OFF = '0'; + public const ON = '1'; + public const OFF = '0'; //图标根目录 - const PAY_ICON_PATH = 'static'.'/'.'resource'.'/'.'icon'.'/'.'pay_icon'.'/'; - const WECHATPAY_ICON = self::PAY_ICON_PATH.'wechatpay.png';//微信支付 + public const PAY_ICON_PATH = 'static' . '/' . 'resource' . '/' . 'icon' . '/' . 'pay_icon' . '/'; + public const WECHATPAY_ICON = self::PAY_ICON_PATH . 'wechatpay.png';//微信支付 //上传方式 视频 - const ALIPAY_ICON = self::PAY_ICON_PATH.'alipay.png';//支付宝支付 + public const ALIPAY_ICON = self::PAY_ICON_PATH . 'alipay.png';//支付宝支付 + + public const BALANCEPAY_ICON = self::PAY_ICON_PATH . 'balancepay.png';//支付宝支付 + + public const OFFLINEPAY_ICON = self::PAY_ICON_PATH . 'offlinepay.png';//线下支付 - const BALANCEPAY_ICON = self::PAY_ICON_PATH.'balancepay.png';//支付宝支付 //支付状态 - const STATUS_WAIT = '0';//待支付 - const STATUS_ING = '1';//支付中 - const STATUS_ED = '2';//已支付 - const STATUS_CALCLE = '-1';//已取消 + public const STATUS_WAIT = '0';//待支付 + public const STATUS_ING = '1';//支付中 + public const STATUS_ED = '2';//已支付 - const MEMBER = 'member'; - const USER = 'user'; + public const STATUS_AUDIT = '3';//待审核 + public const STATUS_CALCLE = '-1';//已取消 + + public const MEMBER = 'member'; + public const USER = 'user'; /** * 支付类型 * @return array */ - public static function getPayType(array $types = []){ + public static function getPayType(array $types = []) + { $list = [ self::WECHATPAY => [ 'name' => get_lang('dict_pay.type_wechatpay'), @@ -62,11 +68,11 @@ class PayDict // 'key' => self::UNIPAY, // 'icon' => self::UNIPAY_ICON // ],//银联支付 -// self::OFFLINEPAY => [ -// 'name' => get_lang('dict_pay.type_offline'), -// 'key' => self::OFFLINEPAY, -// 'icon' => self::OFFLINEPAY_ICON -// ],//线下支付 + self::OFFLINEPAY => [ + 'name' => get_lang('dict_pay.type_offline'), + 'key' => self::OFFLINEPAY, + 'icon' => self::OFFLINEPAY_ICON + ],//线下支付 self::BALANCEPAY => [ 'name' => get_lang('dict_pay.type_balancepay'), 'key' => self::BALANCEPAY, @@ -77,9 +83,9 @@ class PayDict // self::OFFLINEPAY => get_lang('dict_pay.type_offline'),//线下支付 // self::BALANCEPAY => get_lang('dict_pay.type_balancepay'),//余额支付 ]; - if(!empty($types)){ - foreach($list as $k => $v){ - if(!in_array($k, $types)){ + if (!empty($types)) { + foreach ($list as $k => $v) { + if (!in_array($k, $types)) { unset($list[$k]); } } @@ -91,14 +97,15 @@ class PayDict * 获取状态 * @return array */ - public static function getStatus(){ - $list = [ + public static function getStatus() + { + return [ self::STATUS_WAIT => get_lang('dict_pay.status_wait'), self::STATUS_ING => get_lang('dict_pay.status_ing'), self::STATUS_ED => get_lang('dict_pay.status_ed'), self::STATUS_CALCLE => get_lang('dict_pay.status_cancle'), + self::STATUS_AUDIT => get_lang('dict_pay.status_audit') ]; - return $list; } } \ No newline at end of file diff --git a/niucloud/app/dict/pay/RefundDict.php b/niucloud/app/dict/pay/RefundDict.php index 2c2545dfa..ceaaa7dfb 100644 --- a/niucloud/app/dict/pay/RefundDict.php +++ b/niucloud/app/dict/pay/RefundDict.php @@ -29,21 +29,22 @@ class RefundDict * 获取状态 * @return array */ - public static function getStatus(){ - $list = [ + public static function getStatus() + { + return [ self::WAIT => get_lang('dict_pay_refund.status_wait'), self::DEALING => get_lang('dict_pay_refund.status_dealing'), self::SUCCESS => get_lang('dict_pay_refund.status_success'), self::FAIL => get_lang('dict_pay_refund.status_fail'), ]; - return $list; } /** * 获取退款方式 * @return array */ - public static function getType(){ + public static function getType() + { return [ self::WECHATPAY => get_lang('dict_pay_refund.wechatpay'), self::ALIPAY => get_lang('dict_pay_refund.alipay'), diff --git a/niucloud/app/dict/pay/TransferDict.php b/niucloud/app/dict/pay/TransferDict.php index 421db169e..ae39eba23 100644 --- a/niucloud/app/dict/pay/TransferDict.php +++ b/niucloud/app/dict/pay/TransferDict.php @@ -14,39 +14,40 @@ namespace app\dict\pay; class TransferDict { - const WECHAT = 'wechat';//微信支付 + public const WECHAT = 'wechat';//微信支付 - const ALIPAY = 'alipay';//支付宝支付 + public const ALIPAY = 'alipay';//支付宝支付 - const OFFLINE = 'offline';//线下转账 + public const OFFLINE = 'offline';//线下转账 - const BANK = 'bank';//银行卡转账 + public const BANK = 'bank';//银行卡转账 //转账状态 - const SUCCESS = 'success';//转账成功 - const DEALING = 'dealing';//处理中 - const WAIT = 'wait';//待转账 - const FAIL = 'fail';//失败 + public const SUCCESS = 'success';//转账成功 + public const DEALING = 'dealing';//处理中 + public const WAIT = 'wait';//待转账 + public const FAIL = 'fail';//失败 - - - public static function getPayTypeByTransfer(string $type = ''){ + public static function getPayTypeByTransfer(string $type = '') + { $list = array( self::WECHAT => PayDict::WECHATPAY, self::ALIPAY => PayDict::ALIPAY, ); - if(empty($type)) + if (empty($type)) return $list; return $list[$type]; } + /** * 支付类型 * @return array */ - public static function getTransferType(array $types = [], $is_all = true){ + public static function getTransferType(array $types = [], $is_all = true) + { $list = [ self::WECHAT => [ 'name' => get_lang('dict_transfer.type_wechat'), @@ -64,16 +65,16 @@ class TransferDict 'is_online' => false ],//银行卡 ]; - if($is_all){ + if ($is_all) { $list[self::OFFLINE] = [ 'name' => get_lang('dict_transfer.type_offline'), 'key' => self::OFFLINE, 'is_online' => false ]; } - if(!empty($types)){ - foreach($list as $k => $v){ - if(!in_array($k, $types)){ + if (!empty($types)) { + foreach ($list as $k => $v) { + if (!in_array($k, $types)) { unset($list[$k]); } } @@ -85,14 +86,14 @@ class TransferDict * 获取状态 * @return array */ - public static function getStatus(){ - $list = [ + public static function getStatus() + { + return [ self::WAIT => get_lang('dict_transfer.status_wait'), self::DEALING => get_lang('dict_transfer.status_dealing'), self::SUCCESS => get_lang('dict_transfer.status_success'), self::FAIL => get_lang('dict_transfer.status_fail'), ]; - return $list; } } \ No newline at end of file diff --git a/niucloud/app/dict/scan/ScanDict.php b/niucloud/app/dict/scan/ScanDict.php index f6b5e9ba7..bab930d3d 100644 --- a/niucloud/app/dict/scan/ScanDict.php +++ b/niucloud/app/dict/scan/ScanDict.php @@ -21,10 +21,7 @@ class ScanDict const FAIL = 'fail'; - const WECHAT_LOGIN = 'wechat_login';//微信登录 - - } \ No newline at end of file diff --git a/niucloud/app/dict/schedule/ScheduleDict.php b/niucloud/app/dict/schedule/ScheduleDict.php index 99b5f1cec..1eb11adf2 100644 --- a/niucloud/app/dict/schedule/ScheduleDict.php +++ b/niucloud/app/dict/schedule/ScheduleDict.php @@ -14,46 +14,48 @@ namespace app\dict\schedule; class ScheduleDict { - const CRON = 'cron';//定时任务 - const CROND = 'crond';//周期任务 - - const ON = 1; - const OFF = 2; + public const CRON = 'cron';//定时任务 + public const CROND = 'crond';//周期任务 + public const ON = 1; + public const OFF = 2; + public const MIN = 'min'; + public const HOUR = 'hour'; + public const DAY = 'day';//每隔几分钟 + public const WEEK = 'week';//每隔几小时 + public const MONTH = 'month';//每隔几天 /** * 任务模式 * @return array */ - public static function getType(){ + public static function getType() + { return [ self::CRON => get_lang('dict_schedule.type_cron'),//定时任务 - self::CROND => get_lang('dict_schedule.type_crond'),//周期任务 + self::CROND => get_lang('dict_schedule.type_crond'),//周期任务 ]; - } + }//每周 /** * 任务启用状态 * @return array */ - public static function getStatus(){ + public static function getStatus() + { return [ self::ON => get_lang('dict_schedule.on'),//启用 - self::OFF => get_lang('dict_schedule.off'),//关闭 + self::OFF => get_lang('dict_schedule.off'),//关闭 ]; - } + }//每月 - const MIN = 'min';//每隔几分钟 - const HOUR = 'hour';//每隔几小时 - const DAY = 'day';//每隔几天 - const WEEK = 'week';//每周 - const MONTH = 'month';//每月 - public static function getDateType(){ + public static function getDateType() + { return [ self::MIN => get_lang('dict_schedule.min'), - self::HOUR => get_lang('dict_schedule.hour'), + self::HOUR => get_lang('dict_schedule.hour'), self::DAY => get_lang('dict_schedule.day'), - self::WEEK => get_lang('dict_schedule.week'), + self::WEEK => get_lang('dict_schedule.week'), self::MONTH => get_lang('dict_schedule.month'), ]; } diff --git a/niucloud/app/dict/site/SiteAccountLogDict.php b/niucloud/app/dict/site/SiteAccountLogDict.php index 0bf013f4b..44f210868 100644 --- a/niucloud/app/dict/site/SiteAccountLogDict.php +++ b/niucloud/app/dict/site/SiteAccountLogDict.php @@ -21,11 +21,12 @@ class SiteAccountLogDict * 站点状态 * @return array */ - public static function getType(){ + public static function getType() + { return [ self::PAY => get_lang('dict_site.pay'),//支付 - self::REFUND => get_lang('dict_site.refund'),//退款 - self::TRANSFER => get_lang('dict_site.transfer'),//转账 + self::REFUND => get_lang('dict_site.refund'),//退款 + self::TRANSFER => get_lang('dict_site.transfer'),//转账 ]; } diff --git a/niucloud/app/dict/site/SiteDict.php b/niucloud/app/dict/site/SiteDict.php index b6afdcae2..1f23e3067 100644 --- a/niucloud/app/dict/site/SiteDict.php +++ b/niucloud/app/dict/site/SiteDict.php @@ -13,21 +13,22 @@ namespace app\dict\site; class SiteDict { - const EXPIRE = 2;//过期 + public const EXPIRE = 2;//过期 - const ON = 1;//正常 - const CLOSE = 3;//停止 + public const ON = 1;//正常 + public const CLOSE = 3;//停止 /** * 站点状态 * @return array */ - public static function getStatus(){ + public static function getStatus() + { return [ self::ON => get_lang('dict_site.status_on'),//正常 - self::EXPIRE => get_lang('dict_site.status_expire'),//过期 - self::CLOSE => get_lang('dict_site.status_close'),//停止 + self::EXPIRE => get_lang('dict_site.status_expire'),//过期 + self::CLOSE => get_lang('dict_site.status_close'),//停止 ]; } diff --git a/niucloud/app/dict/sys/AgreementDict.php b/niucloud/app/dict/sys/AgreementDict.php index 1457743fe..99a99d73e 100644 --- a/niucloud/app/dict/sys/AgreementDict.php +++ b/niucloud/app/dict/sys/AgreementDict.php @@ -27,7 +27,8 @@ class AgreementDict * 获取协议类型 * @return string[] */ - public static function getType(){ + public static function getType() + { return [ self::SERVICE => get_lang('dict_agreement.service'),//服务协议, self::PRIVACY => get_lang('dict_agreement.privacy'),//隐私协议 diff --git a/niucloud/app/dict/sys/AppTypeDict.php b/niucloud/app/dict/sys/AppTypeDict.php index 538d295cf..e55e24113 100644 --- a/niucloud/app/dict/sys/AppTypeDict.php +++ b/niucloud/app/dict/sys/AppTypeDict.php @@ -14,20 +14,21 @@ namespace app\dict\sys; class AppTypeDict { - const ADMIN = 'admin';//平台管理端 + public const ADMIN = 'admin';//平台管理端 - const SITE = 'site';//站点管理端 - const API = 'api';//手机网页端 + public const SITE = 'site';//站点管理端 + public const API = 'api';//手机网页端 /** * 附件类型 * @return array */ - public static function getAppType(){ + public static function getAppType() + { return [ self::ADMIN => get_lang('dict_app.type_admin'),//平台管理端 - self::SITE => get_lang('dict_app.type_site'),//站点管理端 - self::API => get_lang('dict_app.type_api'),//客户端 + self::SITE => get_lang('dict_app.type_site'),//站点管理端 + self::API => get_lang('dict_app.type_api'),//客户端 ]; } diff --git a/niucloud/app/dict/sys/ConfigKeyDict.php b/niucloud/app/dict/sys/ConfigKeyDict.php index a8b433b00..3344dde99 100644 --- a/niucloud/app/dict/sys/ConfigKeyDict.php +++ b/niucloud/app/dict/sys/ConfigKeyDict.php @@ -13,21 +13,21 @@ namespace app\dict\sys; class ConfigKeyDict { + public const NIUCLOUD_CONFIG = 'NIUCLOUD_CONFIG';//牛云配置 + public const WECHAT = 'WECHAT';//微信公众号 - const WECHAT = 'WECHAT';//微信公众号 + public const WEAPP = 'weapp';//微信小程序 + public const WECHAT_PAY = 'wechat_pay';//微信支付 + public const ALIPAY = 'alipay';//支付宝支付 + public const OFFLINE_PAY = 'offline_pay';//线下支付 + public const UPLOAD = 'upload';//上传配置 + public const DIY_BOTTOM = 'diy_bottom';//底部导航配置 - const WEAPP = 'weapp';//微信小程序 - const WECHAT_PAY = 'wechat_pay';//微信支付 - const ALIPAY = 'alipay';//支付宝支付 - const OFFLINE_PAY = 'offline_pay';//线下支付 - const UPLOAD = 'upload';//上传配置 - const DIY_BOTTOM = 'diy_bottom';//底部导航配置 + public const MEMBER_CASH_OUT = 'member_cash_out';//会员提现 - const MEMBER_CASH_OUT = 'member_cash_out';//会员提现 + public const ADMIN_LOGIN = 'admin_login';//管理端登录注册设置 + public const ALIAPP = 'aliapp';//支付宝小程序 - const ADMIN_LOGIN = 'admin_login';//管理端登录注册设置 - const ALIAPP = 'aliapp';//支付宝小程序 - - const H5 = 'h5';//h5 + public const H5 = 'h5';//h5 } \ No newline at end of file diff --git a/niucloud/app/dict/sys/DateDict.php b/niucloud/app/dict/sys/DateDict.php index a23c783d5..0a4928e1c 100644 --- a/niucloud/app/dict/sys/DateDict.php +++ b/niucloud/app/dict/sys/DateDict.php @@ -17,39 +17,41 @@ namespace app\dict\sys; class DateDict { - const MON = 1; - const TUE = 2; - const WED = 3; - const THUR = 4; - const FRI = 5; - const SAT = 6; - const SUN = 0; + public const MON = 1; + public const TUE = 2; + public const WED = 3; + public const THUR = 4; + public const FRI = 5; + public const SAT = 6; + public const SUN = 0; - CONST JAN = 1; - CONST FEB = 2; - CONST MAR = 3; - CONST APR = 4; - CONST MAY = 5; - CONST JUN = 6; - CONST JUL = 7; - CONST AUG = 8; - CONST SEPT = 9; - CONST OCT = 10; - CONST NOV = 11; - CONST DEC = 12; + public const JAN = 1; + public const FEB = 2; + public const MAR = 3; + public const APR = 4; + public const MAY = 5; + public const JUN = 6; + public const JUL = 7; + public const AUG = 8; + public const SEPT = 9; + public const OCT = 10; + public const NOV = 11; + public const DEC = 12; + /** * 星期 * @return array */ - public static function getWeek(){ + public static function getWeek() + { return [ self::MON => get_lang('dict_date.mon'),//周一 - self::TUE => get_lang('dict_date.tue'),//周二 + self::TUE => get_lang('dict_date.tue'),//周二 self::WED => get_lang('dict_date.wed'),//周三 - self::THUR => get_lang('dict_date.thur'),//周四 + self::THUR => get_lang('dict_date.thur'),//周四 self::FRI => get_lang('dict_date.fri'),//周五 - self::SAT => get_lang('dict_date.sat'),//周六 + self::SAT => get_lang('dict_date.sat'),//周六 self::SUN => get_lang('dict_date.sun'),//周日 ]; } @@ -58,14 +60,15 @@ class DateDict * 月份 * @return array */ - public function getMonth(){ + public function getMonth() + { return [ self::JAN => get_lang('dict_date.jan'),//1月 - self::FEB => get_lang('dict_date.feb'),//2月 + self::FEB => get_lang('dict_date.feb'),//2月 self::MAR => get_lang('dict_date.mar'),//3月 - self::APR => get_lang('dict_date.apr'),//4月 + self::APR => get_lang('dict_date.apr'),//4月 self::MAY => get_lang('dict_date.may'),//5月 - self::JUN => get_lang('dict_date.jun'),//6月 + self::JUN => get_lang('dict_date.jun'),//6月 self::JUL => get_lang('dict_date.jul'),//7月 self::AUG => get_lang('dict_date.aug'),//8月 self::SEPT => get_lang('dict_date.sept'),//9月 diff --git a/niucloud/app/dict/sys/FileDict.php b/niucloud/app/dict/sys/FileDict.php index a65adadab..9f08f48fb 100644 --- a/niucloud/app/dict/sys/FileDict.php +++ b/niucloud/app/dict/sys/FileDict.php @@ -14,24 +14,31 @@ namespace app\dict\sys; class FileDict { //上传方式 图片 - const IMAGE = 'image'; + public const IMAGE = 'image'; //上传方式 视频 - const VIDEO = 'video'; + public const VIDEO = 'video'; //上传方式 文件 - const DOCUMENT = 'document'; + public const DOCUMENT = 'document'; + + public const LOCAL = 'local';//本地存储 + public const QINIU = 'qiniu';//七牛云 + public const ALIYUN = 'aliyun';//阿里云 + public const QCLOUD = 'qcloud';//腾讯云 + public const WECHAT = 'wechat'; + public const APPLET = 'applet'; + public const BIG = 'big';//微信支付 + public const MID = 'mid';//小程序上传 + public const SMALL = 'small'; - const LOCAL = 'local';//本地存储 - const QINIU = 'qiniu';//七牛云 - const ALIYUN = 'aliyun';//阿里云 - const QCLOUD = 'qcloud';//腾讯云 /** * 附件类型 * @return array */ - public static function getType(){ + public static function getType() + { return [ self::IMAGE => get_lang('dict_file.type_image'),//图片 - self::VIDEO => get_lang('dict_file.type_video'),//视频 + self::VIDEO => get_lang('dict_file.type_video'),//视频 ]; } @@ -39,24 +46,22 @@ class FileDict * 存储方式 * @return array */ - public static function getStorageType(){ + public static function getStorageType() + { return [ self::LOCAL => get_lang('dict_file.storage_type_local'),//本地存储 - self::QINIU => get_lang('dict_file.storage_type_qiniu'),//七牛云 + self::QINIU => get_lang('dict_file.storage_type_qiniu'),//七牛云 self::ALIYUN => get_lang('dict_file.storage_type_image'),//阿里云 - self::QCLOUD => get_lang('dict_file.storage_type_qcloud'),//腾讯云 + self::QCLOUD => get_lang('dict_file.storage_type_qcloud'),//腾讯云 ]; } - - const WECHAT = 'wechat';//微信支付 - const APPLET = 'applet';//小程序上传 - /** * 获取上传的场景 * @return array */ - public static function getSceneType(){ + public static function getSceneType() + { return [ self::WECHAT,//微信相关上传 self::ALIYUN,//阿里云相关上传 @@ -66,15 +71,12 @@ class FileDict ]; } - const BIG = 'big'; - const MID = 'mid'; - const SMALL = 'small'; - /** * 缩略图规格 * @return string[] */ - public static function getThumbType(){ + public static function getThumbType() + { return [ self::BIG,//微信相关上传 self::MID,//阿里云相关上传 diff --git a/niucloud/app/dict/sys/IconDict.php b/niucloud/app/dict/sys/IconDict.php index 9e553da5a..69d0963c3 100644 --- a/niucloud/app/dict/sys/IconDict.php +++ b/niucloud/app/dict/sys/IconDict.php @@ -24,8 +24,7 @@ class IconDict public static function getIcon($params = []) { $system_pages = []; - $pages = ( new DictLoader("Icon") )->load($system_pages); - return $pages; + return (new DictLoader("Icon"))->load($system_pages); } } \ No newline at end of file diff --git a/niucloud/app/dict/sys/MenuDict.php b/niucloud/app/dict/sys/MenuDict.php index 496655a01..493aa9c25 100644 --- a/niucloud/app/dict/sys/MenuDict.php +++ b/niucloud/app/dict/sys/MenuDict.php @@ -14,18 +14,19 @@ namespace app\dict\sys; class MenuDict { - const ON = 1; - const OFF = 0; + public const ON = 1; + public const OFF = 0; /** * 菜单状态 * @return array */ - public static function getStatus(){ + public static function getStatus() + { return [ self::ON => get_lang('dict_menu.status_on'),//展示 - self::OFF => get_lang('dict_menu.status_off'),//隐藏 + self::OFF => get_lang('dict_menu.status_off'),//隐藏 ]; } diff --git a/niucloud/app/dict/sys/MenuTypeDict.php b/niucloud/app/dict/sys/MenuTypeDict.php index bf409ccc1..983298c79 100644 --- a/niucloud/app/dict/sys/MenuTypeDict.php +++ b/niucloud/app/dict/sys/MenuTypeDict.php @@ -14,15 +14,16 @@ namespace app\dict\sys; class MenuTypeDict { - const LIST = '0'; - const MENU = '1'; - const BUTTON = '2'; + public const LIST = '0'; + public const MENU = '1'; + public const BUTTON = '2'; - public static function getMenuType(){ + public static function getMenuType() + { return [ self::LIST => get_lang('dict_menu.type_list'),//目录 - self::MENU => get_lang('dict_menu.type_menu'),//菜单 - self::BUTTON => get_lang('dict_menu.type_button'),//接口 + self::MENU => get_lang('dict_menu.type_menu'),//菜单 + self::BUTTON => get_lang('dict_menu.type_button'),//接口 ]; } diff --git a/niucloud/app/dict/sys/MethodDict.php b/niucloud/app/dict/sys/MethodDict.php index 1b901f938..d9ac7a674 100644 --- a/niucloud/app/dict/sys/MethodDict.php +++ b/niucloud/app/dict/sys/MethodDict.php @@ -14,12 +14,13 @@ namespace app\dict\sys; class MethodDict { - const GET = 'get'; - const POST = 'post'; - const DELETE = 'delete'; - const PUT = 'put'; + public const GET = 'get'; + public const POST = 'post'; + public const DELETE = 'delete'; + public const PUT = 'put'; - public static function getMethodType(){ + public static function getMethodType() + { return [ self::GET => 'GET', self::POST => 'POST', diff --git a/niucloud/app/dict/sys/RoleStatusDict.php b/niucloud/app/dict/sys/RoleStatusDict.php index c2e3e4d09..651a78df5 100644 --- a/niucloud/app/dict/sys/RoleStatusDict.php +++ b/niucloud/app/dict/sys/RoleStatusDict.php @@ -22,10 +22,11 @@ class RoleStatusDict * 角色状态 * @return array */ - public static function getStatus(){ + public static function getStatus() + { return [ self::ON => get_lang('dict_role.status_on'),//启用 - self::OFF => get_lang('dict_role.status_off'),//关闭 + self::OFF => get_lang('dict_role.status_off'),//关闭 ]; } diff --git a/niucloud/app/dict/sys/SmsDict.php b/niucloud/app/dict/sys/SmsDict.php index 68ac9cd6e..5574b02f7 100644 --- a/niucloud/app/dict/sys/SmsDict.php +++ b/niucloud/app/dict/sys/SmsDict.php @@ -19,11 +19,25 @@ namespace app\dict\sys; class SmsDict { //阿里云短信 - const ALISMS = 'aliyun'; + public const ALISMS = 'aliyun'; //腾讯云短信 - const TENCENTSMS = 'tencent'; + public const TENCENTSMS = 'tencent'; + public const SENDING = 'sending'; + public const SUCCESS = 'success'; + public const FAIL = 'fail'; + public const LOGIN = 'login'; + public const REGISTER = 'register'; + public const BIND_MOBILE = 'bind_mobile'; + public const FIND_PASS = 'find_pass'; + public const SCENE_TYPE = [ + self::LOGIN, + self::REGISTER, + self::BIND_MOBILE, + self::FIND_PASS + ]; - public static function getType(){ + public static function getType() + { return [ self::ALISMS => [ 'name' => '阿里云短信', @@ -48,12 +62,10 @@ class SmsDict ]; } + //支持的短信场景 - const SENDING = 'sending'; - const SUCCESS = 'success'; - const FAIL = 'fail'; - - public static function getStatusType(){ + public static function getStatusType() + { return [ self::SENDING => 'dict_sms.status_sending', self::SUCCESS => 'dict_sms.status_success', @@ -61,18 +73,4 @@ class SmsDict ]; } - const LOGIN = 'login'; - const REGISTER = 'register'; - const BIND_MOBILE = 'bind_mobile'; - - - const FIND_PASS = 'find_pass'; - //支持的短信场景 - const SCENE_TYPE = [ - self::LOGIN, - self::REGISTER, - self::BIND_MOBILE, - self::FIND_PASS - ]; - } \ No newline at end of file diff --git a/niucloud/app/dict/sys/StorageDict.php b/niucloud/app/dict/sys/StorageDict.php index 1b06d4499..f2e99c935 100644 --- a/niucloud/app/dict/sys/StorageDict.php +++ b/niucloud/app/dict/sys/StorageDict.php @@ -19,22 +19,23 @@ namespace app\dict\sys; class StorageDict { //本地存储 - const LOCAL = 'local'; + public const LOCAL = 'local'; //七牛云存储 - const QINIU = 'qiniu'; + public const QINIU = 'qiniu'; //阿里云存储 - const ALI = 'aliyun'; + public const ALI = 'aliyun'; //腾讯云存储 - const TENCENT = 'tencent'; + public const TENCENT = 'tencent'; - const ON = '1';//开启 - const OFF = '0';//关闭 + public const ON = '1';//开启 + public const OFF = '0';//关闭 - public static function getType(){ + public static function getType() + { return [ self::LOCAL => [ 'name' => '本地存储', @@ -50,7 +51,7 @@ class StorageDict 'bucket' => '存储空间', 'access_key' => 'ACCESS_KEY', 'secret_key' => 'SECRET_KEY', - 'domain' => '空间域名' + 'domain' => '空间域名' ] ], @@ -61,8 +62,8 @@ class StorageDict 'bucket' => '存储空间', 'access_key' => 'ACCESS_KEY_ID', 'secret_key' => 'ACCESS_KEY_SECRET', - 'endpoint' => 'Endpoint', - 'domain' => '空间域名' + 'endpoint' => 'Endpoint', + 'domain' => '空间域名' ] ], @@ -74,7 +75,7 @@ class StorageDict 'region' => 'REGION', 'access_key' => 'SECRET_ID', 'secret_key' => 'SECRET_KEY', - 'domain' => '空间域名' + 'domain' => '空间域名' ] ], diff --git a/niucloud/app/dict/sys/UserDict.php b/niucloud/app/dict/sys/UserDict.php index 876286a93..2c9dc3896 100644 --- a/niucloud/app/dict/sys/UserDict.php +++ b/niucloud/app/dict/sys/UserDict.php @@ -21,10 +21,11 @@ class UserDict * 用户状态 * @return array */ - public static function getStatus(){ + public static function getStatus() + { return [ self::ON => get_lang('dict_user.status_on'),//正常 - self::OFF => get_lang('dict_user.status_off'),//无效 + self::OFF => get_lang('dict_user.status_off'),//无效 ]; } diff --git a/niucloud/app/event.php b/niucloud/app/event.php index 6b32f7289..e25e3e9a2 100644 --- a/niucloud/app/event.php +++ b/niucloud/app/event.php @@ -1,18 +1,17 @@ 1, 'bind' => [ ], - 'listen' => [ - /** * 系统事件 */ - 'AppInit' => [ 'app\listener\system\AppInitListener' ], + 'AppInit' => ['app\listener\system\AppInitListener'], 'HttpRun' => [], 'HttpEnd' => [], 'LogLevel' => [], @@ -20,33 +19,27 @@ $system_event = [ /** * 会员相关事件 */ - //会员注册事件 - 'MemberRegister' => [ 'app\listener\member\MemberRegisterListener' ], + 'MemberRegister' => ['app\listener\member\MemberRegisterListener'], //会员登录事件 - 'MemberLogin' => [ 'app\listener\member\MemberLoginListener' ], + 'MemberLogin' => ['app\listener\member\MemberLoginListener'], //会员账户变化事件 - 'MemberAccount' => [ 'app\listener\member\MemberAccountListener' ], + 'MemberAccount' => ['app\listener\member\MemberAccountListener'], //扫码事件 - 'Scan' => [ 'app\listener\scan\ScanListener' ], - 'AddSiteAfter' => [ 'app\listener\site\AddSiteAfterListener' ], - + 'Scan' => ['app\listener\scan\ScanListener'], + 'AddSiteAfter' => ['app\listener\site\AddSiteAfterListener'], /** * 支付相关事件 */ + 'PayCreate' => ['app\listener\pay\PayCreateListener'], //支付成功 - 'PaySuccess' => [ 'app\listener\pay\PaySuccessListener' ], + 'PaySuccess' => ['app\listener\pay\PaySuccessListener'], //退款成功 - 'RefundSuccess' => [ 'app\listener\pay\RefundSuccessListener' ], + 'RefundSuccess' => ['app\listener\pay\RefundSuccessListener'], //转账成功 - 'TransferSuccess' => [ 'app\listener\pay\TransferSuccessListener' ], - 'SiteIndex' => [ - 'app\listener\system\SiteIndexListener' - ], - - + 'TransferSuccess' => ['app\listener\pay\TransferSuccessListener'], // 任务失败统一回调,有四种定义方式 - 'queue_failed'=> [ + 'queue_failed' => [ ['app\listener\job\QueueFailedLoggerListener', 'report'], ], //系统应用管理加载 @@ -54,9 +47,17 @@ $system_event = [ 'app\listener\system\AppManageListener' ], //站点首页加载 - 'siteIndex' => [ + 'SiteIndex' => [ 'app\listener\system\SiteIndexListener' ], + // 站点端布局 + 'SiteLayout' => [ + 'app\listener\system\SiteLayout' + ], + //平台首页加载 + 'AdminIndex' => [ + 'app\listener\system\AdminIndexListener' + ], //消息模板数据内容 'NoticeData' => [ 'app\listener\notice_template\VerifyCode',//手机验证码 @@ -68,9 +69,12 @@ $system_event = [ 'app\listener\notice\Sms',//短信 'app\listener\notice\Wechat',//公众号模板消息 'app\listener\notice\Weapp',//小程序订阅消息 + ], + //小程序包替换 + 'AppletReplace' => [ + 'app\listener\applet\WeappListener',//微信小程序 ] ], - 'subscribe' => [ ], ]; diff --git a/niucloud/app/install/controller/BaseInstall.php b/niucloud/app/install/controller/BaseInstall.php index b717e3955..dbaf0c9bd 100644 --- a/niucloud/app/install/controller/BaseInstall.php +++ b/niucloud/app/install/controller/BaseInstall.php @@ -30,7 +30,7 @@ class BaseInstall extends BaseController * @access protected * @param string $template 模板文件名 * @param array $vars 模板输出变量 - * @return mixed + * @return string */ protected function fetch($template = '', $vars = []) { @@ -41,7 +41,7 @@ class BaseInstall extends BaseController * @access protected * @param mixed $name 要显示的模板变量 * @param mixed $value 变量的值 - * @return $this + * @return void */ protected function assign($name, $value = '') { @@ -50,7 +50,7 @@ class BaseInstall extends BaseController public function setInstallRoot() { - $this->install_root = realpath(__DIR__ . '/../' ); + $this->install_root = dirname(__DIR__) . '/'; } public function str_replace_first($search, $replace, $subject) diff --git a/niucloud/app/install/controller/Index.php b/niucloud/app/install/controller/Index.php index b9751c23d..f1ab4e7c8 100644 --- a/niucloud/app/install/controller/Index.php +++ b/niucloud/app/install/controller/Index.php @@ -9,9 +9,11 @@ use app\service\admin\install\InstallSystemService; use app\service\admin\site\SiteGroupService; use app\service\admin\site\SiteService; use app\service\core\schedule\CoreScheduleInstallService; +use Exception; use think\facade\Cache; use think\facade\Db; use think\facade\View; +use think\Response; class Index extends BaseInstall @@ -30,14 +32,14 @@ class Index extends BaseInstall } elseif ($step == 2) { //系统变量 $system_variables = []; - $phpv = phpversion(); + $phpv = PHP_VERSION; $os = PHP_OS; $server = $_SERVER[ 'SERVER_SOFTWARE' ]; $host = ( empty($_SERVER[ 'REMOTE_ADDR' ]) ? $_SERVER[ 'REMOTE_HOST' ] : $_SERVER[ 'REMOTE_ADDR' ] ); $name = $_SERVER[ 'SERVER_NAME' ]; - $verison = version_compare(PHP_VERSION, '8.0.0') == -1 ? false : true; + $verison = !(version_compare(PHP_VERSION, '8.0.0') == -1); //pdo $pdo = extension_loaded('pdo') && extension_loaded('pdo_mysql'); $system_variables[] = [ "name" => "pdo", "need" => "开启", "status" => $pdo ]; @@ -54,7 +56,7 @@ class Index extends BaseInstall $fileinfo = extension_loaded('fileinfo'); $system_variables[] = [ "name" => "fileinfo", "need" => "开启", "status" => $fileinfo ]; - $root_path = str_replace("\\", DIRECTORY_SEPARATOR, dirname(dirname(dirname(dirname(__FILE__))))); + $root_path = str_replace("\\", DIRECTORY_SEPARATOR, dirname(__FILE__, 4)); $root_path = str_replace("../", DIRECTORY_SEPARATOR, $root_path); $dirs_list = [ [ "path" => $root_path . DIRECTORY_SEPARATOR, "path_name" => "niucloud/", "name" => "网站目录" ], @@ -72,7 +74,7 @@ class Index extends BaseInstall $is_write = is_write($v[ "path" ]); $dirs_list[ $k ][ "is_readable" ] = $is_readable; $dirs_list[ $k ][ "is_write" ] = $is_write; - if ($is_readable == false || $is_write == false) { + if (!$is_readable || !$is_write) { $is_dir = false; } } @@ -103,7 +105,7 @@ class Index extends BaseInstall { Cache::delete('install_data'); Cache::delete('install_status'); - return $this->fetch('index/step-4', [], $this->replace); + return $this->fetch('index/step-4'); } /** @@ -169,7 +171,7 @@ class Index extends BaseInstall } return success($result); - } catch (\Exception $e) { + } catch ( Exception $e) { $result = [ "status" => -1, "message" => $e->getMessage() @@ -197,7 +199,7 @@ class Index extends BaseInstall $sqls = explode("\n", trim($sql)); $sqls = array_filter($sqls); foreach ($sqls as $query) { - $str1 = substr($query, 0, 1); + $str1 = $query[0] ?? ''; if ($str1 != '#' && $str1 != '-') $sql_query[ $num ] .= $query; } @@ -276,7 +278,7 @@ class Index extends BaseInstall Cache::set('install_status', 1);//成功 return success(); - } catch (\Exception $e) { + } catch ( Exception $e) { $this->setSuccessLog([ '安装失败' . $e->getMessage(), 'error' ]); return fail('安装失败' . $e->getMessage()); } @@ -357,10 +359,10 @@ class Index extends BaseInstall 'password' => $site_password, ]; (new SiteService())->add($data); - $fp = fopen($this->lock_file, "w"); - if ($fp == false) { - $this->setSuccessLog([ "写入失败,请检查目录" . dirname(dirname(__FILE__)) . "是否可写入!'", 'error' ]); - return fail("写入失败,请检查目录" . dirname(dirname(__FILE__)) . "是否可写入!'"); + $fp = fopen($this->lock_file, 'wb'); + if (!$fp) { + $this->setSuccessLog([ "写入失败,请检查目录" . dirname(__FILE__, 2) . "是否可写入!'", 'error' ]); + return fail("写入失败,请检查目录" . dirname(__FILE__, 2) . "是否可写入!'"); } $this->setSuccessLog([ '初始化成功', 'success' ]); fwrite($fp, '已安装'); @@ -368,7 +370,7 @@ class Index extends BaseInstall Cache::set('install_status', 2);//成功 // Cache::tag(MenuService::$cache_tag_name)->clear(); return success(); - } catch (\Exception $e) { + } catch ( Exception $e) { $this->setSuccessLog([ '安装失败' . $e->getMessage(), 'error' ]); return fail('安装失败' . $e->getMessage()); } @@ -376,8 +378,8 @@ class Index extends BaseInstall /** * 安装sql - * @param $data - * @return \think\Response + * @param array $data + * @return Response */ public function installSql(array $data) { @@ -428,13 +430,13 @@ class Index extends BaseInstall for ($i = 0; $i < $query_count; $i++) { $sql = trim($sql_query[ $i ]); $is_write = false; - if (strstr($sql, 'CREATE TABLE')) { + if (str_contains($sql, 'CREATE TABLE')) { $match_item = preg_match('/CREATE TABLE [`]?(\\w+)[`]?/is', $sql, $match_data); $is_write = true; - } elseif (strstr($sql, 'ALTER TABLE')) { + } elseif (str_contains($sql, 'ALTER TABLE')) { $match_item = preg_match('/ALTER TABLE [`]?(\\w+)[`]?/is', $sql, $match_data); - } elseif (strstr($sql, 'INSERT INTO')) { + } elseif (str_contains($sql, 'INSERT INTO')) { $match_item = preg_match('/INSERT INTO [`]?(\\w+)[`]?/is', $sql, $match_data); } else { $match_item = 0; @@ -446,7 +448,7 @@ class Index extends BaseInstall $sql_item = $this->str_replace_first($table_name, $new_table_name, $sql); @mysqli_query($conn, $sql_item); if ($is_write) $this->setSuccessLog([ '创建表' . $table_name, 'success' ]); - } catch (\Exception $e) { + } catch ( Exception $e) { $this->setSuccessLog([ $e->getMessage(), 'error' ]); return fail('数据库解析失败' . $e->getMessage()); } @@ -459,14 +461,13 @@ class Index extends BaseInstall /** * 配置设置 - * @param $path - * @param $data - * @return \think\Response + * @param array $data + * @return Response */ public function installConfig(array $data) { $this->checkLock(); - $root_path = str_replace("\\", DIRECTORY_SEPARATOR, dirname(dirname(dirname(dirname(__FILE__))))); + $root_path = str_replace("\\", DIRECTORY_SEPARATOR, dirname(__FILE__, 4)); $root_path = str_replace("../", DIRECTORY_SEPARATOR, $root_path); $env_dir = $root_path . DIRECTORY_SEPARATOR . ".env"; $example_env = $root_path . DIRECTORY_SEPARATOR . ".example.env"; diff --git a/niucloud/app/install/source/database.php b/niucloud/app/install/source/database.php index 375b72cbd..e0e817877 100644 --- a/niucloud/app/install/source/database.php +++ b/niucloud/app/install/source/database.php @@ -1,5 +1,4 @@ $site_id, 'key' => $key, 'data' => $data, 'template' => $template]); $notice_data = array_values(array_filter($result))[0] ?? []; - if(empty($notice_data)) throw new NoticeException('NOTICE_TEMPLATE_IS_NOT_EXIST'); + if (empty($notice_data)) throw new NoticeException('NOTICE_TEMPLATE_IS_NOT_EXIST'); event('Notice', ['site_id' => $site_id, 'key' => $key, 'to' => $notice_data['to'], 'vars' => $notice_data['vars'], 'template' => $template]); return true; } diff --git a/niucloud/app/job/pay/PayReturnTo.php b/niucloud/app/job/pay/PayReturnTo.php index 2666d403c..3d1ca0f1c 100644 --- a/niucloud/app/job/pay/PayReturnTo.php +++ b/niucloud/app/job/pay/PayReturnTo.php @@ -29,7 +29,7 @@ class PayReturnTo extends BaseJob protected function doJob($data) { - Log::write('pay_log_'.json_encode($data)); + Log::write('pay_log_' . json_encode($data)); $res = (new CorePayService())->returnTo($data['site_id'], $data['out_trade_no']); return true; } diff --git a/niucloud/app/job/schedule/OrderClose.php b/niucloud/app/job/schedule/OrderClose.php index db74b975b..281d02747 100644 --- a/niucloud/app/job/schedule/OrderClose.php +++ b/niucloud/app/job/schedule/OrderClose.php @@ -21,7 +21,7 @@ class OrderClose extends BaseJob { public function doJob() { - Log::write('订单关闭计划任务'.date('Y-m-d h:i:s')); + Log::write('订单关闭计划任务' . date('Y-m-d h:i:s')); return true; } } diff --git a/niucloud/app/job/schedule/SiteExpireClose.php b/niucloud/app/job/schedule/SiteExpireClose.php index 0204238dc..f3fdf0653 100644 --- a/niucloud/app/job/schedule/SiteExpireClose.php +++ b/niucloud/app/job/schedule/SiteExpireClose.php @@ -24,12 +24,12 @@ class SiteExpireClose extends BaseJob { $core_site_service = new CoreSiteService(); $list = $core_site_service->getExpireSiteList(); - if(!empty($list)){ - foreach($list as $k => $v){ + if (!empty($list)) { + foreach ($list as $k => $v) { $core_site_service->expire($v['site_id']); } } - Log::write('站点到期自动关闭'.date('Y-m-d h:i:s')); + Log::write('站点到期自动关闭' . date('Y-m-d h:i:s')); return true; } } diff --git a/niucloud/app/job/sys/AddonInstall.php b/niucloud/app/job/sys/AddonInstall.php index fbf421e2d..234ae4d62 100644 --- a/niucloud/app/job/sys/AddonInstall.php +++ b/niucloud/app/job/sys/AddonInstall.php @@ -13,7 +13,6 @@ namespace app\job\sys; use app\service\core\addon\CoreAddonInstallService; use core\base\BaseJob; -use think\queue\Job; /** * 队列异步执行插件安装任务 @@ -25,7 +24,8 @@ class AddonInstall extends BaseJob (new CoreAddonInstallService($addon))->executeTask($task); } - public function failed($data){ + public function failed($data) + { } } diff --git a/niucloud/app/job/sys/CheckJob.php b/niucloud/app/job/sys/CheckJob.php index c8b90b986..aa3be9bd0 100644 --- a/niucloud/app/job/sys/CheckJob.php +++ b/niucloud/app/job/sys/CheckJob.php @@ -22,7 +22,7 @@ class CheckJob extends BaseJob { file_put_contents($file, time()); //todo 部署一个十五秒后再校验一次删除这个文件 - CheckDeleteJob::invoke(['file' => $file], secs:8); + CheckDeleteJob::invoke(['file' => $file], secs: 8); return true; } } diff --git a/niucloud/app/lang/en/validate.php b/niucloud/app/lang/en/validate.php index e64687380..8112e5b27 100644 --- a/niucloud/app/lang/en/validate.php +++ b/niucloud/app/lang/en/validate.php @@ -77,6 +77,7 @@ return [ 'is_auth_register_between' => 'is_auth_register must be 0 or 1', 'is_bind_mobile_number' => 'is_bind_mobile must be a number', 'is_bind_mobile_between' => 'is_bind_mobile must be 0 or 1', + 'username_cannot_pure_number' => 'The account cannot be a pure number' ], 'validate_article' => [ 'title_require' => 'title is require', diff --git a/niucloud/app/lang/zh-cn/api.php b/niucloud/app/lang/zh-cn/api.php index 3b9022993..7eddb65d3 100644 --- a/niucloud/app/lang/zh-cn/api.php +++ b/niucloud/app/lang/zh-cn/api.php @@ -39,7 +39,12 @@ return [ 'ADDON_INSTALL_EXECUTED' => '插件安装任务已执行', 'INSTALL_CHECK_NOT_PASS' => '安装校验未通过', 'SITE_INDEX_VIEW_PATH_NOT_EXIST' => '当前首页路径不存在', - + 'ADMIN_INDEX_VIEW_PATH_NOT_EXIST' => '当前首页路径不存在', + 'ADDON_SQL_FAIL' => '插件sql执行失败', + 'ADDON_DIR_FAIL' => '插件文件操作失败', + 'LAYOUT_NOT_EXIST' => '该布局不存在', + 'ZIP_FILE_NOT_FOUND' => '找不到可用的压缩文件', + 'DOWNLOAD_SUCCESS' => '下载成功', //登录注册重置账号.... 'LOGIN_SUCCESS' => '登录成功', @@ -92,6 +97,9 @@ return [ 'OSS_FILE_URL_NOT_EXIST' => '远程资源文件地址不能为空', 'BASE_IMAGE_FILE_NOT_EXIST' => 'base图片资源不能为空', 'UPLOAD_TYPE_NOT_SUPPORT' => '不支持的上传类型', + 'FILE_ERROE' => '无效的资源', + 'UPLOAD_STORAGE_TYPE_ALL_CLOSE' => '至少要有一个启用的存储方式', + 'STORAGE_NOT_HAS_HTTP_OR_HTTPS' => '空间域名请补全http://或https://', //消息管理 @@ -185,12 +193,17 @@ return [ 'TEMPLATE_NOT_EXIST' => '模板不存在', 'IS_EXIST_TEMPLATE_NOT_MODIFY' => '已存在的支付模板不支持修改支付类型', 'ONLY_PAYING_CAN_PAY' => '只有待支付的订单可以支付', + 'VOUCHER_NOT_EMPTY' => '支付单据不能为空', + 'ONLY_PAYING_CAN_AUDIT' => '只有待支付的订单才可以操作', + 'ONLY_OFFLINEPAY_CAN_AUDIT' => '只有线下支付的单据才可以审核', //退款相关 'REFUND_NOT_EXIST' => '退款单据不存在', //订单相关 8*** 'ORDER_NOT_EXIST' => '订单不存在', 'ORDER_CLOSED' => '订单已关闭', 'DOCUMENT_IS_PAID' => '单据已支付', + 'REFUND_IS_CHANGE' => '退款状态已发生变化', + 'TRANFER_IS_CHANGE' => '转账状态已发生变化', // 退款相关 'NOT_ALLOW_APPLY_REFUND' => '该订单不允许退款', @@ -207,9 +220,11 @@ return [ //任务队列相关 'JOB_NOT_EXISTS' => '任务类不存在', 'JOB_CREATE_FAIL' => '任务创建失败', - + 'SCHEDULE_NOT_EXISTS' => '人物不存在', //小程序版本 'APPLET_VERSION_NOT_EXISTS' => '小程序版本不存在', - + 'APPLET_VERSION_PACKAGE_NOT_EXIST' => '小程序版本包不存在', + //验证码 + 'CAPTCHA_INVALID' => '无效的验证码', ]; diff --git a/niucloud/app/lang/zh-cn/dict.php b/niucloud/app/lang/zh-cn/dict.php index 673538b8d..5cad5c256 100644 --- a/niucloud/app/lang/zh-cn/dict.php +++ b/niucloud/app/lang/zh-cn/dict.php @@ -52,6 +52,11 @@ return [ //站点类型 'system' => '框架首页', ], + // 平台首页 + 'dict_admin_index' => [ + //站点类型 + 'system' => '框架首页', + ], 'dict_notice' => [ 'type_sms' => '短信', 'type_wechat' => '微信公众号', @@ -93,15 +98,15 @@ return [ 'login_mobile' => '手机验证码登录', 'login_wechat' => '微信公众号授权登录', 'login_weapp' => '微信小程序授权登录', - 'account_point_adjust' => '积分调整', + 'account_point_adjust' => '账户调整', 'account_point_recharge_give' => '充值赠送', - 'account_balance_adjust' => '余额调整', - 'account_balance_recharge' => '余额充值', + 'account_balance_adjust' => '账户调整', + 'account_balance_recharge' => '账户充值', 'account_money_award' => '活动奖励', - 'account_money_cash_out' => '余额提现', - 'account_money_adjust' => '零钱调整', + 'account_money_cash_out' => '账户提现', + 'account_money_adjust' => '账户调整', 'account_commission_award' => '活动奖励', - 'account_commission_cash_out' => '佣金提现', + 'account_commission_cash_out' => '账户提现', 'status_on' => '正常', 'status_off' => '锁定', 'account_balance_recharge_refund' => '充值订单退款', @@ -158,6 +163,7 @@ return [ 'status_ing' => '支付中', 'status_ed' => '已支付', 'status_cancle' => '已取消', + 'status_audit' => '待审核' ], //转账相关 'dict_transfer' => [ @@ -301,5 +307,7 @@ return [ 'dec' => '12月', ], - + 'dict_site_layout' => [ + 'default' => '默认' + ] ]; diff --git a/niucloud/app/lang/zh-cn/validate.php b/niucloud/app/lang/zh-cn/validate.php index 0400581fd..928c60238 100644 --- a/niucloud/app/lang/zh-cn/validate.php +++ b/niucloud/app/lang/zh-cn/validate.php @@ -85,12 +85,14 @@ return [ 'cash_out_is_auto_verify_in' => '是否启用审核必须是0或1', 'cash_out_is_auto_transfer_in' => '是否启用转账必须是0或1', 'status_require' => '会员状态必须填写', - 'not_exit_status' => '不存在的会员状态' + 'not_exit_status' => '不存在的会员状态', + 'username_cannot_pure_number' => '账号不能是纯数字' ], 'validate_member_config' => [ 'length_number' => '会员编码必须是整数', 'length_min' => '会员编码长度不能小于10', 'length_max' => '会员编码长度不能大于于20', + 'length_between' => '会员编码长度去除前缀后最少不能低于4位,最多不能超过30位', ], 'validate_article' => [ 'title_require' => '文章标题必须填写', diff --git a/niucloud/app/listener/applet/WeappListener.php b/niucloud/app/listener/applet/WeappListener.php new file mode 100644 index 000000000..49251115f --- /dev/null +++ b/niucloud/app/listener/applet/WeappListener.php @@ -0,0 +1,45 @@ + 'utils/request.js', + 'variable' => [ + '{{$baseUrl}}' => (string)url('/api/', [], '', true), + '{{$siteId}}' => $site_id + ], + ], + [ + 'path' => 'utils/common.js', + 'variable' => [ + '{{$imgUrl}}' => (string)url('/', [], '', true), + ], + ] + ]; + } + } +} \ No newline at end of file diff --git a/niucloud/app/listener/job/QueueFailedLoggerListener.php b/niucloud/app/listener/job/QueueFailedLoggerListener.php index 2940060a9..c25c1632f 100644 --- a/niucloud/app/listener/job/QueueFailedLoggerListener.php +++ b/niucloud/app/listener/job/QueueFailedLoggerListener.php @@ -6,27 +6,24 @@ class QueueFailedLoggerListener { const SHOULD_RUN_HOOK_CALLBACK = true; + /** - * * 错误报告 - * @param $jobObject \think\queue\Job //任务对象,保存了该任务的执行情况和业务数据 + * @param $job * @return bool true //是否需要删除任务并触发其failed() 方法 */ - - public function report(&$job){ - + public function report(&$job) + { $failedJobLog = [ - 'jobHandlerClassName' => $job->getName(), // 'application\index\job\Hello' - 'queueName' => $job->getQueue(),// 'helloJobQueue' - 'jobData' => $job->getRawBody()['data'], // '{'a': 1 }' - 'attempts' => $job->attempts(), // 3 + 'jobHandlerClassName' => $job->getName(), + 'queueName' => $job->getQueue(), + 'jobData' => $job->getRawBody()['data'], + 'attempts' => $job->attempts(), ]; - var_export(json_encode($failedJobLog,true)); - + var_export(json_encode($failedJobLog, true)); // $job->release(); //重发任务 $job->delete(); //删除任务 //$job->failed(); //通知消费者类任务执行失败 - return self::SHOULD_RUN_HOOK_CALLBACK; } } \ No newline at end of file diff --git a/niucloud/app/listener/member/MemberAccountListener.php b/niucloud/app/listener/member/MemberAccountListener.php index 6b91707dc..179980d3c 100644 --- a/niucloud/app/listener/member/MemberAccountListener.php +++ b/niucloud/app/listener/member/MemberAccountListener.php @@ -25,6 +25,6 @@ class MemberAccountListener */ public function handle(array $account_log) { - return ; + return; } } \ No newline at end of file diff --git a/niucloud/app/listener/member/MemberLoginListener.php b/niucloud/app/listener/member/MemberLoginListener.php index 929578d9f..1e773270e 100644 --- a/niucloud/app/listener/member/MemberLoginListener.php +++ b/niucloud/app/listener/member/MemberLoginListener.php @@ -24,7 +24,7 @@ class MemberLoginListener */ public function handle(object $member) { - return ; + return; } } \ No newline at end of file diff --git a/niucloud/app/listener/member/MemberRegisterListener.php b/niucloud/app/listener/member/MemberRegisterListener.php index 85fc806f6..a4087d8c5 100644 --- a/niucloud/app/listener/member/MemberRegisterListener.php +++ b/niucloud/app/listener/member/MemberRegisterListener.php @@ -24,6 +24,6 @@ class MemberRegisterListener */ public function handle($member) { - return ; + return; } } \ No newline at end of file diff --git a/niucloud/app/listener/notice/Sms.php b/niucloud/app/listener/notice/Sms.php index 616050330..104ed9b88 100644 --- a/niucloud/app/listener/notice/Sms.php +++ b/niucloud/app/listener/notice/Sms.php @@ -21,26 +21,26 @@ class Sms $mobile = $to['mobile'] ?? ''; //完全信任消息的设置, 不再依赖support_type if ($template['is_sms']) { - $sms_id = $template['sms_id'];//发送模板id - $content = $template['sms_content']; - $member_id = $to['member_id'] ?? 0; - $uid = $to['uid'] ?? 0; - if (!$mobile) { - //会员的 - if ($member_id > 0) {//查询openid - $info = (new CoreMemberService())->getInfoByMemberId($site_id, $member_id); - $mobile = $info['mobile'] ?? ''; - $nickname = $info['nickname'] ?? ''; - } + $sms_id = $template['sms_id'];//发送模板id + $content = $template['sms_content']; + $member_id = $to['member_id'] ?? 0; + $uid = $to['uid'] ?? 0; + if (!$mobile) { + //会员的 + if ($member_id > 0) {//查询openid + $info = (new CoreMemberService())->getInfoByMemberId($site_id, $member_id); + $mobile = $info['mobile'] ?? ''; + $nickname = $info['nickname'] ?? ''; } + } - try{ + try { if (empty($mobile)) throw new NoticeException('NOTICE_SMS_EMPTY');//没有手机号不能发送短信 $core_sms_service = new CoreSmsService(); //消息日志 $log_data = array( 'key' => $key, - 'message_type' => NoticeTypeDict::SMS, + 'notice_type' => NoticeTypeDict::SMS, 'uid' => $uid ?? 0, 'member_id' => $member_id ?? 0, 'nickname' => $nickname ?? '', diff --git a/niucloud/app/listener/notice/Weapp.php b/niucloud/app/listener/notice/Weapp.php index b85ddf57e..13ae7d3c4 100644 --- a/niucloud/app/listener/notice/Weapp.php +++ b/niucloud/app/listener/notice/Weapp.php @@ -20,29 +20,29 @@ class Weapp $to = $data['to'];//发送对象主题 //完全信任消息的设置, 不再依赖support_type - if($template['is_weapp']) { + if ($template['is_weapp']) { $member_id = $to['member_id'] ?? 0; - if($member_id > 0){//查询openid + if ($member_id > 0) {//查询openid $info = (new CoreMemberService())->getInfoByMemberId($site_id, $member_id); $openid = $info['weapp_openid'] ?? ''; $nickname = $info['nickname'] ?? ''; } - if(!empty($openid)) { + if (!empty($openid)) { $weapp_template_id = $template['weapp_template_id']; $weapp = $template['weapp']; $weapp_content = $weapp['content']; $weapp_data = []; - foreach($weapp_content as $k => $v){ + foreach ($weapp_content as $k => $v) { $search_content = $v[1]; - foreach($vars as $item_k => $item_v){ - $search_content = str_replace('{'.$item_k.'}', $item_v, $search_content); + foreach ($vars as $item_k => $item_v) { + $search_content = str_replace('{' . $item_k . '}', $item_v, $search_content); } $weapp_data[$v[2]]['value'] = $search_content; } $url = $vars['__weapp_page'] ?? ''; $log_data = array( 'key' => $key, - 'message_type' => NoticeTypeDict::WEAPP, + 'notice_type' => NoticeTypeDict::WEAPP, 'uid' => $data['uid'] ?? 0, 'member_id' => $member_id, 'nickname' => $nickname ?? '', diff --git a/niucloud/app/listener/notice/Wechat.php b/niucloud/app/listener/notice/Wechat.php index 706ffb50d..65596aadc 100644 --- a/niucloud/app/listener/notice/Wechat.php +++ b/niucloud/app/listener/notice/Wechat.php @@ -51,7 +51,7 @@ class Wechat //消息日志 $log_data = array( 'key' => $key, - 'message_type' => NoticeTypeDict::WECHAT, + 'notice_type' => NoticeTypeDict::WECHAT, 'uid' => $data['uid'] ?? 0, 'member_id' => $member_id, 'nickname' => $nickname ?? '', diff --git a/niucloud/app/listener/notice_template/BaseNoticeTemplate.php b/niucloud/app/listener/notice_template/BaseNoticeTemplate.php index 1a74f9464..f3b4f0c6b 100644 --- a/niucloud/app/listener/notice_template/BaseNoticeTemplate.php +++ b/niucloud/app/listener/notice_template/BaseNoticeTemplate.php @@ -9,7 +9,8 @@ class BaseNoticeTemplate * @param $to 发送对象 * @return array */ - public function toReturn($vars, $to){ + public function toReturn($vars, $to) + { return [ 'vars' => $vars, 'to' => $to, diff --git a/niucloud/app/listener/notice_template/MemberVerifySuccess.php b/niucloud/app/listener/notice_template/MemberVerifySuccess.php index f55a9263d..beae9c875 100644 --- a/niucloud/app/listener/notice_template/MemberVerifySuccess.php +++ b/niucloud/app/listener/notice_template/MemberVerifySuccess.php @@ -13,7 +13,7 @@ class MemberVerifySuccess extends BaseNoticeTemplate public function handle(array $params) { - if ($this->key == $params['key']){ + if ($this->key == $params['key']) { $data = $params['data']; return $this->toReturn( [ diff --git a/niucloud/app/listener/notice_template/RechargeSuccess.php b/niucloud/app/listener/notice_template/RechargeSuccess.php index 2ad9915dd..25c6e5e22 100644 --- a/niucloud/app/listener/notice_template/RechargeSuccess.php +++ b/niucloud/app/listener/notice_template/RechargeSuccess.php @@ -19,7 +19,7 @@ class RechargeSuccess extends BaseNoticeTemplate $core_order_service = new CoreRechargeOrderService(); $order = $core_order_service->orderInfo($site_id, $order_id); - if (!empty($order)){ + if (!empty($order)) { $member = (new CoreMemberService())->getInfoByMemberId($site_id, $order['member_id']); //通过订单id查询订单信息 return $this->toReturn( diff --git a/niucloud/app/listener/notice_template/VerifyCode.php b/niucloud/app/listener/notice_template/VerifyCode.php index eb1e04b1f..d50dbc205 100644 --- a/niucloud/app/listener/notice_template/VerifyCode.php +++ b/niucloud/app/listener/notice_template/VerifyCode.php @@ -15,7 +15,7 @@ class VerifyCode extends BaseNoticeTemplate // public $name = ''; public function handle(array $params) { - if ($this->key == $params['key']){ + if ($this->key == $params['key']) { $data = $params['data']; return $this->toReturn( [ diff --git a/niucloud/app/listener/pay/PayCreateListener.php b/niucloud/app/listener/pay/PayCreateListener.php new file mode 100644 index 000000000..2b9a9d549 --- /dev/null +++ b/niucloud/app/listener/pay/PayCreateListener.php @@ -0,0 +1,45 @@ +orderInfo($site_id, $trade_id); + if ($order_info['order_status'] != RechargeOrderDict::WAIT_PAY) throw new CommonException('ONLY_PAYING_CAN_PAY'); + //添加订单支付表 + return [ + 'site_id' => $order_info['site_id'], + 'main_type' => PayDict::MEMBER, + 'main_id' => $order_info['member_id'],//买家id + 'money' => $order_info['order_money'],//订单金额 + 'trade_type' => 'recharge',//业务类型 + 'trade_id' => $trade_id, + 'body' => get_lang("dict_order.trade_type_recharge") + ]; + } + + + } +} \ No newline at end of file diff --git a/niucloud/app/listener/pay/PayNotifyListener.php b/niucloud/app/listener/pay/PayNotifyListener.php index 48111aa20..aa82fbe2e 100644 --- a/niucloud/app/listener/pay/PayNotifyListener.php +++ b/niucloud/app/listener/pay/PayNotifyListener.php @@ -20,6 +20,6 @@ class PayNotifyListener { public function handle($member) { - return ; + return; } } \ No newline at end of file diff --git a/niucloud/app/listener/pay/PaySuccessListener.php b/niucloud/app/listener/pay/PaySuccessListener.php index ab637f9d8..8a511ea86 100644 --- a/niucloud/app/listener/pay/PaySuccessListener.php +++ b/niucloud/app/listener/pay/PaySuccessListener.php @@ -22,8 +22,7 @@ class PaySuccessListener public function handle(array $pay_info) { $trade_type = $pay_info['trade_type'] ?? ''; - if($trade_type == 'recharge') - { + if ($trade_type == 'recharge') { (new CoreRechargeOrderService())->pay($pay_info); } //账单记录添加 diff --git a/niucloud/app/listener/pay/RefundSuccessListener.php b/niucloud/app/listener/pay/RefundSuccessListener.php index c453b0c8e..0a64867bd 100644 --- a/niucloud/app/listener/pay/RefundSuccessListener.php +++ b/niucloud/app/listener/pay/RefundSuccessListener.php @@ -11,8 +11,6 @@ namespace app\listener\pay; -use app\model\site\SiteAccountLog; -use app\service\core\order\recharge\CoreRechargeOrderService; use app\service\core\order\recharge\CoreRechargeRefundService; use app\service\core\site\CoreSiteAccountService; @@ -27,8 +25,7 @@ class RefundSuccessListener (new CoreSiteAccountService())->addRefundLog($refund_info['site_id'], $refund_info['refund_no']); //交易单据处理 $trade_type = $refund_info['trade_type'] ?? ''; - if($trade_type == 'recharge') - { + if ($trade_type == 'recharge') { (new CoreRechargeRefundService())->refundComplete($refund_info['refund_no']); } diff --git a/niucloud/app/listener/pay/TransferSuccessListener.php b/niucloud/app/listener/pay/TransferSuccessListener.php index 48701ffe1..077253a2c 100644 --- a/niucloud/app/listener/pay/TransferSuccessListener.php +++ b/niucloud/app/listener/pay/TransferSuccessListener.php @@ -25,8 +25,7 @@ class TransferSuccessListener //添加账单记录 (new CoreSiteAccountService())->addTransferLog($info['site_id'], $info['transfer_no']); //会员零钱提现 - if($info['trade_type'] == CashOutTypeDict::MEMBER_CASH_OUT) - { + if ($info['trade_type'] == CashOutTypeDict::MEMBER_CASH_OUT) { return (new CoreMemberCashOutService())->transferFinish($info['site_id'], $info['transfer_no']); } } diff --git a/niucloud/app/listener/scan/ScanListener.php b/niucloud/app/listener/scan/ScanListener.php index ad2bd4aaa..f746ee783 100644 --- a/niucloud/app/listener/scan/ScanListener.php +++ b/niucloud/app/listener/scan/ScanListener.php @@ -13,6 +13,7 @@ namespace app\listener\scan; use app\dict\scan\ScanDict; use app\service\api\wechat\WechatAuthService; +use Throwable; /** * 支付异步回调事件 @@ -24,13 +25,13 @@ class ScanListener public function handle(array $data) { $action = $data['action']; - switch($action){ + switch ($action) { case ScanDict::WECHAT_LOGIN: try { $wechat_auth_service = new WechatAuthService(); $data['login_data'] = $wechat_auth_service->login($data['openid']); $data['status'] = ScanDict::SUCCESS; - }catch(\Throwable $e){ + } catch ( Throwable $e ) { $data['status'] = ScanDict::FAIL; $data['fail_reason'] = get_lang($e->getMessage()); } diff --git a/niucloud/app/listener/site/AddSiteAfterListener.php b/niucloud/app/listener/site/AddSiteAfterListener.php index 154f3372c..84bdaf453 100644 --- a/niucloud/app/listener/site/AddSiteAfterListener.php +++ b/niucloud/app/listener/site/AddSiteAfterListener.php @@ -11,7 +11,6 @@ namespace app\listener\site; -use app\service\admin\install\InstallArticleService; /** * 添加站点成功后事件 @@ -26,10 +25,5 @@ class AddSiteAfterListener */ public function handle($data) { - - // 初始化文章数据 -// ( new InstallArticleService() )->install([ 'site_id' => $data[ 'site_id' ] ]); - //加载插件语言包 - return; } } \ No newline at end of file diff --git a/niucloud/app/listener/system/AdminIndexListener.php b/niucloud/app/listener/system/AdminIndexListener.php new file mode 100644 index 000000000..bd84e1b6e --- /dev/null +++ b/niucloud/app/listener/system/AdminIndexListener.php @@ -0,0 +1,30 @@ + get_lang("dict_admin_index.system"), + "view_path" => "index/index" + ] + ]; + } +} \ No newline at end of file diff --git a/niucloud/app/listener/system/AppInitListener.php b/niucloud/app/listener/system/AppInitListener.php index c67890738..a35482d17 100644 --- a/niucloud/app/listener/system/AppInitListener.php +++ b/niucloud/app/listener/system/AppInitListener.php @@ -21,6 +21,6 @@ class AppInitListener public function handle() { //加载插件语言包 - return ; + return; } } \ No newline at end of file diff --git a/niucloud/app/listener/system/AppManageListener.php b/niucloud/app/listener/system/AppManageListener.php index 22aa56f0a..ea8002b9f 100644 --- a/niucloud/app/listener/system/AppManageListener.php +++ b/niucloud/app/listener/system/AppManageListener.php @@ -21,7 +21,7 @@ class AppManageListener public function handle() { return [ - "category" =>[ + "category" => [ [ "key" => "basic", diff --git a/niucloud/app/listener/system/SiteLayout.php b/niucloud/app/listener/system/SiteLayout.php new file mode 100644 index 000000000..8761e3f2c --- /dev/null +++ b/niucloud/app/listener/system/SiteLayout.php @@ -0,0 +1,30 @@ + get_lang("dict_site_layout.default"), + "key" => "default", + "image" => "static/resource/images/system/layout-default.png", + "sort" => 0 + ]; + } +} \ No newline at end of file diff --git a/niucloud/app/model/addon/Addon.php b/niucloud/app/model/addon/Addon.php index 8df9e59fe..68ab3b875 100644 --- a/niucloud/app/model/addon/Addon.php +++ b/niucloud/app/model/addon/Addon.php @@ -45,11 +45,12 @@ class Addon extends BaseModel */ public function getStatusNameAttr($value, $data) { - return AddonDict::getStatus()[ $data[ 'status' ]] ?? ''; + return AddonDict::getStatus()[$data['status']] ?? ''; } /** * 插件名称搜索器 + * @param $query * @param $value * @param $data */ diff --git a/niucloud/app/model/applet/AppletSiteVersion.php b/niucloud/app/model/applet/AppletSiteVersion.php index 9620cb53a..6e4d34a86 100644 --- a/niucloud/app/model/applet/AppletSiteVersion.php +++ b/niucloud/app/model/applet/AppletSiteVersion.php @@ -11,8 +11,8 @@ namespace app\model\applet; -use app\model\article\Article; use core\base\BaseModel; +use think\model\relation\HasOne; /** * 小程序包 站点版本模型 @@ -34,12 +34,12 @@ class AppletSiteVersion extends BaseModel /** * 版本主表 - * @return \think\model\relation\HasOne + * @return HasOne */ public function appletVersion() { - return $this->hasOne( AppletVersion::class, 'id', 'version_id')->joinType('left') + return $this->hasOne(AppletVersion::class, 'id', 'version_id')->joinType('left') ->withField('desc, status, version, version_num, release_version') - ->bind([ 'desc', 'status', 'version', 'version_num', 'release_version']); + ->bind(['desc', 'status', 'version', 'version_num', 'release_version']); } } diff --git a/niucloud/app/model/applet/AppletVersion.php b/niucloud/app/model/applet/AppletVersion.php index 80b68555b..408109e65 100644 --- a/niucloud/app/model/applet/AppletVersion.php +++ b/niucloud/app/model/applet/AppletVersion.php @@ -11,7 +11,6 @@ namespace app\model\applet; -use app\model\article\Article; use core\base\BaseModel; /** @@ -33,6 +32,4 @@ class AppletVersion extends BaseModel protected $name = 'applet_version'; - - } diff --git a/niucloud/app/model/article/Article.php b/niucloud/app/model/article/Article.php index 86086e152..cb59cfada 100644 --- a/niucloud/app/model/article/Article.php +++ b/niucloud/app/model/article/Article.php @@ -12,7 +12,6 @@ namespace app\model\article; use app\dict\sys\FileDict; -use app\model\site\Site; use core\base\BaseModel; use think\db\Query; use think\model\relation\HasOne; @@ -44,8 +43,10 @@ class Article extends BaseModel { return $this->hasOne(ArticleCategory::class, 'category_id', 'category_id')->joinType('left')->withField('category_id, name')->bind(['category_name' => 'name']); } + /** * 文章分类搜索器 + * @param $query * @param $value * @param $data */ @@ -58,31 +59,33 @@ class Article extends BaseModel /** * 文章标题搜索器 + * @param $query * @param $value * @param $data */ public function searchTitleAttr($query, $value, $data) { - if($value) { + if ($value) { $query->where('title', 'like', '%' . $value . '%'); } } /** * 文章标题搜索器 + * @param $query * @param $value * @param $data */ public function searchIsShowAttr($query, $value, $data) { - if($value != '') { + if ($value != '') { $query->where('is_show', $value); } } public function searchIdsAttr(Query $query, $value, $data) { - if(!empty($value)) { + if (!empty($value)) { $query->whereIn('id', $data['ids']); } } @@ -90,41 +93,46 @@ class Article extends BaseModel /** * 文章标题搜索器 + * @param $query * @param $value * @param $data */ public function searchSortAttr($query, $value, $data) { - if($value) { + if ($value) { $query->where('sort', $value); } } - public function getArticleUrlAttr($value, $data) { + public function getArticleUrlAttr($value, $data) + { $wap_domain = !empty(env("system.wap_domain")) ? preg_replace('#/$#', '', env("system.wap_domain")) : request()->domain(); $web_domain = !empty(env("system.web_domain")) ? preg_replace('#/$#', '', env("system.web_domain")) : request()->domain(); - return [ + return [ 'wap_url' => $wap_domain . "/wap/" . $data['site_id'] . "/pages/article/detail?id={$data['id']}", 'web_url' => $web_domain . "/web/" . $data['site_id'] . "/article/detail?id={$data['id']}" ]; } - public function getImageThumbBigAttr($value, $data) { - if($data['image'] != ''){ + public function getImageThumbBigAttr($value, $data) + { + if ($data['image'] != '') { return get_thumb_images($data['site_id'], $data['image'], FileDict::BIG); } } - public function getImageThumbMidAttr($value, $data) { - if($data['image'] != ''){ + public function getImageThumbMidAttr($value, $data) + { + if ($data['image'] != '') { return get_thumb_images($data['site_id'], $data['image'], FileDict::MID); } } - public function getImageThumbSmallAttr($value, $data) { - if($data['image'] != ''){ + public function getImageThumbSmallAttr($value, $data) + { + if ($data['image'] != '') { return get_thumb_images($data['site_id'], $data['image'], FileDict::SMALL); } } diff --git a/niucloud/app/model/article/ArticleCategory.php b/niucloud/app/model/article/ArticleCategory.php index e6e8e3079..989f8cf1d 100644 --- a/niucloud/app/model/article/ArticleCategory.php +++ b/niucloud/app/model/article/ArticleCategory.php @@ -35,13 +35,14 @@ class ArticleCategory extends BaseModel /** * 文章分类名称搜索器 + * @param $query * @param $value * @param $data */ public function searchNameAttr($query, $value, $data) { if ($value) { - $query->where([ ['name', 'like', "%$value%" ]]); + $query->where([['name', 'like', "%$value%"]]); } } @@ -51,5 +52,4 @@ class ArticleCategory extends BaseModel } - } diff --git a/niucloud/app/model/diy/Diy.php b/niucloud/app/model/diy/Diy.php index b2fb6dbd0..c598952eb 100644 --- a/niucloud/app/model/diy/Diy.php +++ b/niucloud/app/model/diy/Diy.php @@ -43,12 +43,13 @@ class Diy extends BaseModel /** * 状态字段转化 * @param $value + * @param $data * @return mixed */ public function getTypeNameAttr($value, $data) { - if (!empty($data[ 'type' ])) { - return TemplateDict::getTemplate([ 'type' => $data[ 'type' ] ])[ $data[ 'type' ] ][ 'title' ] ?? ''; + if (!empty($data['type'])) { + return TemplateDict::getTemplate(['type' => $data['type']])[$data['type']]['title'] ?? ''; } return ''; } @@ -56,28 +57,30 @@ class Diy extends BaseModel /** * 状态字段转化 * @param $value + * @param $data * @return mixed */ public function getShareAttr($value, $data) { - if (empty($data[ 'share' ])) { - $data[ 'share' ] = json_encode([ + if (empty($data['share'])) { + $data['share'] = json_encode([ 'wechat' => [ - 'title' => $data[ 'title' ], + 'title' => $data['title'], 'desc' => '', 'url' => '' ], 'weapp' => [ - 'title' => $data[ 'title' ], + 'title' => $data['title'], 'url' => '' ] ]); } - return $data[ 'share' ] ?? ''; + return $data['share'] ?? ''; } /** * 搜索器:自定义页面 + * @param $query * @param $value * @param $data */ @@ -90,6 +93,7 @@ class Diy extends BaseModel /** * 搜索器:自定义页面站点id + * @param $query * @param $value * @param $data */ @@ -102,6 +106,7 @@ class Diy extends BaseModel /** * 搜索器:自定义页面名称 + * @param $query * @param $value * @param $data */ @@ -114,6 +119,7 @@ class Diy extends BaseModel /** * 搜索器:自定义页面标识 + * @param $query * @param $value * @param $data */ @@ -126,6 +132,7 @@ class Diy extends BaseModel /** * 搜索器:自定义页面模板 + * @param $query * @param $value * @param $data */ @@ -138,6 +145,7 @@ class Diy extends BaseModel /** * 搜索器:页面展示模式,diy:自定义,fixed:固定 + * @param $query * @param $value * @param $data */ @@ -150,6 +158,7 @@ class Diy extends BaseModel /** * 搜索器:自定义页面数据,json格式 + * @param $query * @param $value * @param $data */ @@ -162,6 +171,7 @@ class Diy extends BaseModel /** * 搜索器:自定义页面是否默认页面,1:是,0:否 + * @param $query * @param $value * @param $data */ @@ -174,6 +184,7 @@ class Diy extends BaseModel /** * 搜索器:自定义页面访问量 + * @param $query * @param $value * @param $data */ @@ -186,6 +197,7 @@ class Diy extends BaseModel /** * 搜索器:自定义页面访问量 + * @param $query * @param $value * @param $data */ @@ -198,6 +210,7 @@ class Diy extends BaseModel /** * 搜索器:自定义页面创建时间 + * @param $query * @param $value * @param $data */ @@ -210,6 +223,7 @@ class Diy extends BaseModel /** * 搜索器:自定义页面更新时间 + * @param $query * @param $value * @param $data */ diff --git a/niucloud/app/model/diy/DiyRoute.php b/niucloud/app/model/diy/DiyRoute.php index 66a8dc936..f0358f098 100644 --- a/niucloud/app/model/diy/DiyRoute.php +++ b/niucloud/app/model/diy/DiyRoute.php @@ -36,6 +36,7 @@ class DiyRoute extends BaseModel /** * 搜索器:自定义路由表 + * @param $query * @param $value * @param $data */ @@ -48,6 +49,7 @@ class DiyRoute extends BaseModel /** * 搜索器:自定义路由表页面名称 + * @param $query * @param $value * @param $data */ @@ -60,6 +62,7 @@ class DiyRoute extends BaseModel /** * 搜索器:自定义路由表页面标识 + * @param $query * @param $value * @param $data */ @@ -72,6 +75,7 @@ class DiyRoute extends BaseModel /** * 搜索器:自定义路由表页面路径 + * @param $query * @param $value * @param $data */ @@ -84,6 +88,7 @@ class DiyRoute extends BaseModel /** * 搜索器:自定义路由表分享内容 + * @param $query * @param $value * @param $data */ @@ -93,8 +98,10 @@ class DiyRoute extends BaseModel $query->where("share", $value); } } + /** * 搜索器:自定义路由表是否支持分享 + * @param $query * @param $value * @param $data */ diff --git a/niucloud/app/model/generator/GenerateColumn.php b/niucloud/app/model/generator/GenerateColumn.php index 61f6d986f..f3b5fdf41 100644 --- a/niucloud/app/model/generator/GenerateColumn.php +++ b/niucloud/app/model/generator/GenerateColumn.php @@ -35,5 +35,4 @@ class GenerateColumn extends BaseModel protected $name = 'generate_column'; - } diff --git a/niucloud/app/model/generator/GenerateTable.php b/niucloud/app/model/generator/GenerateTable.php index 73898ae20..c6de1b35f 100644 --- a/niucloud/app/model/generator/GenerateTable.php +++ b/niucloud/app/model/generator/GenerateTable.php @@ -37,25 +37,27 @@ class GenerateTable extends BaseModel /** * 表名搜索器 + * @param $query * @param $value * @param $data */ public function searchTableNameAttr($query, $value, $data) { if ($value) { - $query->where('table_name', 'like', '%'.$value.'%'); + $query->where('table_name', 'like', '%' . $value . '%'); } } /** * 描述搜索器 + * @param $query * @param $value * @param $data */ public function searchTableContentAttr($query, $value, $data) { if ($value) { - $query->where('table_content', 'like', '%'.$value.'%'); + $query->where('table_content', 'like', '%' . $value . '%'); } } diff --git a/niucloud/app/model/member/Member.php b/niucloud/app/model/member/Member.php index 883a5fa74..862f1239e 100644 --- a/niucloud/app/model/member/Member.php +++ b/niucloud/app/model/member/Member.php @@ -31,8 +31,9 @@ class Member extends BaseModel use SoftDelete; + protected $type = [ - 'last_visit_time' => 'timestamp', + 'last_visit_time' => 'timestamp', 'login_time' => 'timestamp', 'last_consum_time' => 'timestamp', ]; @@ -61,67 +62,73 @@ class Member extends BaseModel protected $defaultSoftDelete = 0; // 设置json类型字段 - protected $json = [ 'member_label' ]; + protected $json = ['member_label']; // 设置JSON数据返回数组 protected $jsonAssoc = true; /** * 状态字段转化 * @param $value + * @param $data * @return mixed */ public function getStatusNameAttr($value, $data) { - if(empty($data['status'])) + if (empty($data['status'])) return ''; return MemberDict::getStatus()[$data['status']] ?? ''; } + /** * 注册来源字段转化 * @param $value + * @param $data * @return mixed */ public function getRegisterChannelNameAttr($value, $data) { - if(empty($data['register_channel'])) + if (empty($data['register_channel'])) return ''; - return MemberRegisterChannelDict::getType()[ $data[ 'register_channel' ]] ?? ''; + return MemberRegisterChannelDict::getType()[$data['register_channel']] ?? ''; } /** * 注册方式字段转化 * @param $value + * @param $data * @return mixed */ public function getRegisterTypeNameAttr($value, $data) { - if(empty($data['register_type'])) + if (empty($data['register_type'])) return ''; - return MemberRegisterTypeDict::getType()[ $data[ 'register_type' ]] ?? ''; + return MemberRegisterTypeDict::getType()[$data['register_type']] ?? ''; } /** * 登录渠道字段转化 * @param $value + * @param $data * @return mixed */ public function getLoginChannelNameAttr($value, $data) { - if(empty($data['login_channel'])) + if (empty($data['login_channel'])) return ''; - return ChannelDict::getType()[ $data[ 'login_channel' ]] ?? ''; + return ChannelDict::getType()[$data['login_channel']] ?? ''; } /** * 登录方式字段转化 * @param $value + * @param $data * @return mixed */ public function getLoginTypeNameAttr($value, $data) { - if(empty($data['login_type'])) + if (empty($data['login_type'])) return ''; - return MemberLoginTypeDict::getType()[ $data[ 'login_type' ]] ?? ''; + return MemberLoginTypeDict::getType()[$data['login_type']] ?? ''; } /** @@ -132,14 +139,14 @@ class Member extends BaseModel */ public function getSexNameAttr($value, $data) { - if(empty($data['sex'])) + if (empty($data['sex'])) return ''; - return CommonDict::getSexType()[ $data[ 'sex' ]] ?? ''; + return CommonDict::getSexType()[$data['sex']] ?? ''; } /** * 是否删除搜索器 - * @param $value + * @param $query */ public function searchIsDelAttr($query) { @@ -172,6 +179,7 @@ class Member extends BaseModel $query->where('register_type', '=', $value); } } + /** * 注册渠道搜索 * @param $query @@ -202,34 +210,39 @@ class Member extends BaseModel /** * 创建时间搜索器 + * @param Query $query * @param $value + * @param $data */ public function searchCreateTimeAttr(Query $query, $value, $data) { - $start_time = empty($value[ 0 ]) ? 0 : strtotime($value[ 0 ]); - $end_time = empty($value[ 1 ]) ? 0 : strtotime($value[ 1 ]); + $start_time = empty($value[0]) ? 0 : strtotime($value[0]); + $end_time = empty($value[1]) ? 0 : strtotime($value[1]); if ($start_time > 0 && $end_time > 0) { $query->whereBetweenTime('create_time', $start_time, $end_time); } else if ($start_time > 0 && $end_time == 0) { - $query->where([ [ 'create_time', '>=', $start_time ] ]); + $query->where([['create_time', '>=', $start_time]]); } else if ($start_time == 0 && $end_time > 0) { - $query->where([ [ 'create_time', '<=', $end_time ] ]); + $query->where([['create_time', '<=', $end_time]]); } } + /** * 创建时间搜索器 + * @param Query $query * @param $value + * @param $data */ public function searchJoinCreateTimeAttr(Query $query, $value, $data) { - $start_time = empty($value[ 0 ]) ? 0 : strtotime($value[ 0 ]); - $end_time = empty($value[ 1 ]) ? 0 : strtotime($value[ 1 ]); + $start_time = empty($value[0]) ? 0 : strtotime($value[0]); + $end_time = empty($value[1]) ? 0 : strtotime($value[1]); if ($start_time > 0 && $end_time > 0) { $query->whereBetweenTime('member.create_time', $start_time, $end_time); } else if ($start_time > 0 && $end_time == 0) { - $query->where([ [ 'member.create_time', '>=', $start_time ] ]); + $query->where([['member.create_time', '>=', $start_time]]); } else if ($start_time == 0 && $end_time > 0) { - $query->where([ [ 'member.create_time', '<=', $end_time ] ]); + $query->where([['member.create_time', '<=', $end_time]]); } } diff --git a/niucloud/app/model/member/MemberAccountLog.php b/niucloud/app/model/member/MemberAccountLog.php index 45f7c707b..14d9bd4ad 100644 --- a/niucloud/app/model/member/MemberAccountLog.php +++ b/niucloud/app/model/member/MemberAccountLog.php @@ -14,6 +14,7 @@ namespace app\model\member; use app\dict\member\MemberAccountChangeTypeDict; use app\dict\member\MemberAccountTypeDict; use core\base\BaseModel; +use think\model\relation\HasOne; /** * 会员账户流水(账单)模型 @@ -42,31 +43,31 @@ class MemberAccountLog extends BaseModel * @param $data * @return string */ - public function getAccountTypeNameAttr($value,$data) + public function getAccountTypeNameAttr($value, $data) { - if(empty($data['account_type'])) + if (empty($data['account_type'])) return ''; return MemberAccountTypeDict::getType()[$data['account_type']] ?? ''; } /** * 会员信息 - * @return \think\model\relation\HasOne + * @return HasOne */ public function memberInfo() { - return $this->hasOne( Member::class, 'member_id', 'member_id')->joinType('left') + return $this->hasOne(Member::class, 'member_id', 'member_id')->joinType('left') ->withField('member_id,member_no, username, mobile, nickname, headimg') ->bind(['username', 'mobile', 'nickname', 'headimg']); } /** * 会员关联 - * @return \think\model\relation\HasOne + * @return HasOne */ public function member() { - return $this->hasOne( Member::class, 'member_id', 'member_id')->withField('member_id, member_no, username, mobile, nickname, headimg')->joinType('inner'); + return $this->hasOne(Member::class, 'member_id', 'member_id')->withField('member_id, member_no, username, mobile, nickname, headimg')->joinType('inner'); } /** @@ -75,9 +76,9 @@ class MemberAccountLog extends BaseModel * @param $data * @return int */ - public function getAccountDataAttr($value,$data) + public function getAccountDataAttr($value, $data) { - if($data['account_type'] == 'point'|| $data['account_type'] == 'growth') + if ($data['account_type'] == 'point' || $data['account_type'] == 'growth') return (int)$data['account_data']; else return $data['account_data']; @@ -89,9 +90,9 @@ class MemberAccountLog extends BaseModel * @param $data * @return int */ - public function getAccountSumAttr($value,$data) + public function getAccountSumAttr($value, $data) { - if($data['account_type'] == 'point'|| $data['account_type'] == 'growth') + if ($data['account_type'] == 'point' || $data['account_type'] == 'growth') return (int)$data['account_sum']; else return $data['account_sum']; @@ -103,15 +104,17 @@ class MemberAccountLog extends BaseModel * @param $data * @return array|mixed|string */ - public function getFromTypeNameAttr($value,$data) + public function getFromTypeNameAttr($value, $data) { - if(isset($data['from_type'])&& isset($data['account_type'])) + if (isset($data['from_type'], $data['account_type'])) return MemberAccountChangeTypeDict::getType($data['account_type'])[$data['from_type']]['name']; else return ''; } + /** * 会员搜索 + * @param $query * @param $value * @param $data */ @@ -124,6 +127,7 @@ class MemberAccountLog extends BaseModel /** * 会员搜索(用于关联表查询) + * @param $query * @param $value * @param $data */ @@ -136,6 +140,7 @@ class MemberAccountLog extends BaseModel /** * 类型搜索 + * @param $query * @param $value * @param $data */ @@ -145,8 +150,10 @@ class MemberAccountLog extends BaseModel $query->where('from_type', $value); } } + /** * 账户类型搜索 + * @param $query * @param $value * @param $data */ @@ -156,36 +163,41 @@ class MemberAccountLog extends BaseModel $query->where('account_type', $value); } } + /** * 创建时间搜索器 + * @param $query * @param $value + * @param $data */ public function searchCreateTimeAttr($query, $value, $data) { - $start_time = empty($value[0]) ? 0 : strtotime($value[0]) ; - $end_time = empty($value[1]) ? 0 : strtotime($value[1]) ; - if($start_time > 0 && $end_time > 0){ + $start_time = empty($value[0]) ? 0 : strtotime($value[0]); + $end_time = empty($value[1]) ? 0 : strtotime($value[1]); + if ($start_time > 0 && $end_time > 0) { $query->whereBetweenTime('create_time', $start_time, $end_time); - }else if($start_time > 0 && $end_time == 0){ + } else if ($start_time > 0 && $end_time == 0) { $query->where([['create_time', '>=', $start_time]]); - }else if($start_time == 0 && $end_time > 0){ + } else if ($start_time == 0 && $end_time > 0) { $query->where([['create_time', '<=', $end_time]]); } } /** * 创建关联表时间搜索器 + * @param $query * @param $value + * @param $data */ public function searchJoinCreateTimeAttr($query, $value, $data) { - $start_time = empty($value[0]) ? 0 : strtotime($value[0]) ; - $end_time = empty($value[1]) ? 0 : strtotime($value[1]) ; - if($start_time > 0 && $end_time > 0){ + $start_time = empty($value[0]) ? 0 : strtotime($value[0]); + $end_time = empty($value[1]) ? 0 : strtotime($value[1]); + if ($start_time > 0 && $end_time > 0) { $query->whereBetweenTime('member_account_log.create_time', $start_time, $end_time); - }else if($start_time > 0 && $end_time == 0){ + } else if ($start_time > 0 && $end_time == 0) { $query->where([['member_account_log.create_time', '>=', $start_time]]); - }else if($start_time == 0 && $end_time > 0){ + } else if ($start_time == 0 && $end_time > 0) { $query->where([['member_account_log.create_time', '<=', $end_time]]); } } diff --git a/niucloud/app/model/member/MemberCashOut.php b/niucloud/app/model/member/MemberCashOut.php index c535b4248..1848ea436 100644 --- a/niucloud/app/model/member/MemberCashOut.php +++ b/niucloud/app/model/member/MemberCashOut.php @@ -16,6 +16,7 @@ use app\dict\member\MemberCashOutDict; use app\dict\pay\TransferDict; use app\model\pay\Transfer; use core\base\BaseModel; +use think\model\relation\HasOne; /** * 会员提现 @@ -35,33 +36,33 @@ class MemberCashOut extends BaseModel */ protected $name = 'member_cash_out'; protected $type = [ - 'audit_time' => 'timestamp', + 'audit_time' => 'timestamp', 'transfer_time' => 'timestamp', ]; /** * 会员信息 - * @return \think\model\relation\HasOne + * @return HasOne */ public function memberInfo() { - return $this->hasOne( Member::class, 'member_id', 'member_id')->joinType('left') + return $this->hasOne(Member::class, 'member_id', 'member_id')->joinType('left') ->withField('member_id, member_no, username, mobile, nickname, headimg') ->bind(['username', 'mobile', 'nickname', 'headimg', 'member_no']); } /** * 会员信息关联列表查询 - * @return \think\model\relation\HasOne + * @return HasOne */ public function member() { - return $this->hasOne( Member::class, 'member_id', 'member_id')->joinType('left'); + return $this->hasOne(Member::class, 'member_id', 'member_id')->joinType('left'); } /** * 转账信息 - * @return \think\model\relation\HasOne + * @return HasOne */ public function transfer() { @@ -75,22 +76,26 @@ class MemberCashOut extends BaseModel * @param $data * @return mixed|string */ - public function getAccountTypeNameAttr($value, $data){ - if(empty($data['account_type'])) + public function getAccountTypeNameAttr($value, $data) + { + if (empty($data['account_type'])) return ''; - return MemberAccountTypeDict::getType()[ $data[ 'account_type' ]] ?? ''; + return MemberAccountTypeDict::getType()[$data['account_type']] ?? ''; } + /** * 提现状态名称 * @param $value * @param $data * @return mixed|string */ - public function getStatusNameAttr($value, $data){ - if(empty($data[ 'status' ])) + public function getStatusNameAttr($value, $data) + { + if (empty($data['status'])) return ''; - return MemberCashOutDict::getStatus()[ $data[ 'status' ]] ?? ''; + return MemberCashOutDict::getStatus()[$data['status']] ?? ''; } + /** * 转账方式名称 * @param $value @@ -99,9 +104,9 @@ class MemberCashOut extends BaseModel */ public function getTransferTypeNameAttr($value, $data) { - if(empty($data[ 'transfer_type' ])) + if (empty($data['transfer_type'])) return ''; - $temp = TransferDict::getTransferType()[ $data[ 'transfer_type' ]] ?? []; + $temp = TransferDict::getTransferType()[$data['transfer_type']] ?? []; return $temp['name'] ?? ''; } @@ -111,13 +116,16 @@ class MemberCashOut extends BaseModel * @param $data * @return mixed|string */ - public function getTransferStatusNameAttr($value, $data){ - if(empty($data[ 'transfer_status' ])) + public function getTransferStatusNameAttr($value, $data) + { + if (empty($data['transfer_status'])) return ''; - return TransferDict::getStatus()[ $data[ 'transfer_status' ]] ?? ''; + return TransferDict::getStatus()[$data['transfer_status']] ?? ''; } + /** * 会员搜索 + * @param $query * @param $value * @param $data */ @@ -130,6 +138,7 @@ class MemberCashOut extends BaseModel /** * 状态搜索 + * @param $query * @param $value * @param $data */ @@ -142,6 +151,7 @@ class MemberCashOut extends BaseModel /** * + * @param $query * @param $value * @param $data */ @@ -154,6 +164,7 @@ class MemberCashOut extends BaseModel /** * + * @param $query * @param $value * @param $data */ @@ -166,68 +177,76 @@ class MemberCashOut extends BaseModel /** * 创建时间搜索器 + * @param $query * @param $value + * @param $data */ public function searchCreateTimeAttr($query, $value, $data) { - $start_time = empty($value[0]) ? 0 : strtotime($value[0]) ; - $end_time = empty($value[1]) ? 0 : strtotime($value[1]) ; - if($start_time > 0 && $end_time > 0){ + $start_time = empty($value[0]) ? 0 : strtotime($value[0]); + $end_time = empty($value[1]) ? 0 : strtotime($value[1]); + if ($start_time > 0 && $end_time > 0) { $query->whereBetweenTime('create_time', $start_time, $end_time); - }else if($start_time > 0 && $end_time == 0){ + } else if ($start_time > 0 && $end_time == 0) { $query->where([['create_time', '>=', $start_time]]); - }else if($start_time == 0 && $end_time > 0){ + } else if ($start_time == 0 && $end_time > 0) { $query->where([['create_time', '<=', $end_time]]); } } /** * 创建时间搜索器 + * @param $query * @param $value + * @param $data */ public function searchJoinCreateTimeAttr($query, $value, $data) { - $start_time = empty($value[0]) ? 0 : strtotime($value[0]) ; - $end_time = empty($value[1]) ? 0 : strtotime($value[1]) ; - if($start_time > 0 && $end_time > 0){ + $start_time = empty($value[0]) ? 0 : strtotime($value[0]); + $end_time = empty($value[1]) ? 0 : strtotime($value[1]); + if ($start_time > 0 && $end_time > 0) { $query->whereBetweenTime('member_cash_out.create_time', $start_time, $end_time); - }else if($start_time > 0 && $end_time == 0){ + } else if ($start_time > 0 && $end_time == 0) { $query->where([['member_cash_out.create_time', '>=', $start_time]]); - }else if($start_time == 0 && $end_time > 0){ + } else if ($start_time == 0 && $end_time > 0) { $query->where([['member_cash_out.create_time', '<=', $end_time]]); } } /** * 审核时间搜索器 + * @param $query * @param $value + * @param $data */ public function searchAuditTimeAttr($query, $value, $data) { - $start_time = empty($value[0]) ? 0 : strtotime($value[0]) ; - $end_time = empty($value[1]) ? 0 : strtotime($value[1]) ; - if($start_time > 0 && $end_time > 0){ + $start_time = empty($value[0]) ? 0 : strtotime($value[0]); + $end_time = empty($value[1]) ? 0 : strtotime($value[1]); + if ($start_time > 0 && $end_time > 0) { $query->whereBetweenTime('audit_time', $start_time, $end_time); - }else if($start_time > 0 && $end_time == 0){ + } else if ($start_time > 0 && $end_time == 0) { $query->where([['audit_time', '>=', $start_time]]); - }else if($start_time == 0 && $end_time > 0){ + } else if ($start_time == 0 && $end_time > 0) { $query->where([['audit_time', '<=', $end_time]]); } } /** * 审核时间搜索器 + * @param $query * @param $value + * @param $data */ public function searchTransferTimeAttr($query, $value, $data) { - $start_time = empty($value[0]) ? 0 : strtotime($value[0]) ; - $end_time = empty($value[1]) ? 0 : strtotime($value[1]) ; - if($start_time > 0 && $end_time > 0){ + $start_time = empty($value[0]) ? 0 : strtotime($value[0]); + $end_time = empty($value[1]) ? 0 : strtotime($value[1]); + if ($start_time > 0 && $end_time > 0) { $query->whereBetweenTime('transfer_time', $start_time, $end_time); - }else if($start_time > 0 && $end_time == 0){ + } else if ($start_time > 0 && $end_time == 0) { $query->where([['transfer_time', '>=', $start_time]]); - }else if($start_time == 0 && $end_time > 0){ + } else if ($start_time == 0 && $end_time > 0) { $query->where([['transfer_time', '<=', $end_time]]); } } diff --git a/niucloud/app/model/member/MemberCashOutAccount.php b/niucloud/app/model/member/MemberCashOutAccount.php index c1e22a690..1d070e717 100644 --- a/niucloud/app/model/member/MemberCashOutAccount.php +++ b/niucloud/app/model/member/MemberCashOutAccount.php @@ -38,26 +38,29 @@ class MemberCashOutAccount extends BaseModel * @param $data * @return mixed|string */ - public function getAccountTypeNameAttr($value, $data){ - if(empty($data[ 'transfer_type' ])) + public function getAccountTypeNameAttr($value, $data) + { + if (empty($data['transfer_type'])) return ''; - $temp = TransferDict::getTransferType()[ $data[ 'transfer_type' ]] ?? []; + $temp = TransferDict::getTransferType()[$data['transfer_type']] ?? []; return $temp['name'] ?? ''; } /** * 创建时间搜索器 + * @param $query * @param $value + * @param $data */ public function searchCreateTimeAttr($query, $value, $data) { - $start_time = empty($value[0]) ? 0 : strtotime($value[0]) ; - $end_time = empty($value[1]) ? 0 : strtotime($value[1]) ; - if($start_time > 0 && $end_time > 0){ + $start_time = empty($value[0]) ? 0 : strtotime($value[0]); + $end_time = empty($value[1]) ? 0 : strtotime($value[1]); + if ($start_time > 0 && $end_time > 0) { $query->whereBetweenTime('create_time', $start_time, $end_time); - }else if($start_time > 0 && $end_time == 0){ + } else if ($start_time > 0 && $end_time == 0) { $query->where([['create_time', '>=', $start_time]]); - }else if($start_time == 0 && $end_time > 0){ + } else if ($start_time == 0 && $end_time > 0) { $query->where([['create_time', '<=', $end_time]]); } } diff --git a/niucloud/app/model/member/MemberLabel.php b/niucloud/app/model/member/MemberLabel.php index a0b8d2bdc..e6a18feef 100644 --- a/niucloud/app/model/member/MemberLabel.php +++ b/niucloud/app/model/member/MemberLabel.php @@ -12,6 +12,7 @@ namespace app\model\member; use core\base\BaseModel; +use think\db\exception\DbException; /** * 会员标签模型 @@ -36,26 +37,28 @@ class MemberLabel extends BaseModel /** * 获取对应标签的会员数量 * @param $value - * @return mixed + * @param $data + * @return int + * @throws DbException */ public function getMemberNumAttr($value, $data) { - if(isset($data['label_id'])) - { - return (new Member())->where([['member_label', 'like', '%"' . $data['label_id'] . '"%' ]])->count(); - }else + if (isset($data['label_id'])) { + return (new Member())->where([['member_label', 'like', '%"' . $data['label_id'] . '"%']])->count(); + } else return 0; } /** * 会员标签 + * @param $query * @param $value * @param $data */ public function searchLabelNameAttr($query, $value, $data) { if ($value) { - $query->where('label_name','like', '%'.$value.'%'); + $query->where('label_name', 'like', '%' . $value . '%'); } } diff --git a/niucloud/app/model/order/RechargeOrder.php b/niucloud/app/model/order/RechargeOrder.php index 94ca027e9..24ca792f6 100644 --- a/niucloud/app/model/order/RechargeOrder.php +++ b/niucloud/app/model/order/RechargeOrder.php @@ -15,6 +15,8 @@ use app\dict\common\ChannelDict; use app\model\member\Member; use app\model\pay\Pay; use core\base\BaseModel; +use think\model\relation\HasMany; +use think\model\relation\HasOne; /** * 充值订单模型 @@ -38,20 +40,20 @@ class RechargeOrder extends BaseModel //类型 protected $type = [ - 'pay_time' => 'timestamp', - 'close_time' => 'timestamp', + 'pay_time' => 'timestamp', + 'close_time' => 'timestamp', ]; /** * 登录渠道字段转化 * @param $value + * @param $data * @return mixed */ public function getOrderFromNameAttr($value, $data) { - if(isset($data['order_from'])) - { + if (isset($data['order_from'])) { return ChannelDict::getType()[$data['order_from']] ?? ''; } @@ -132,7 +134,7 @@ class RechargeOrder extends BaseModel public function searchOrderMoneyAttr($query, $value, $data) { if (!empty($data['start_money']) && !empty($data['end_money'])) { - $money = [ $data['start_money'], $data['end_money'] ]; + $money = [$data['start_money'], $data['end_money']]; sort($money); $query->where('order_money', 'between', $money); } else if (!empty($data['start_money'])) { @@ -154,19 +156,22 @@ class RechargeOrder extends BaseModel $query->where('order_status', '=', $value); } } + /** * 创建时间搜索器 + * @param $query * @param $value + * @param $data */ public function searchCreateTimeAttr($query, $value, $data) { - $start_time = empty($value[0]) ? 0 : strtotime($value[0]) ; - $end_time = empty($value[1]) ? 0 : strtotime($value[1]) ; - if($start_time > 0 && $end_time > 0){ + $start_time = empty($value[0]) ? 0 : strtotime($value[0]); + $end_time = empty($value[1]) ? 0 : strtotime($value[1]); + if ($start_time > 0 && $end_time > 0) { $query->whereBetweenTime('create_time', $start_time, $end_time); - }else if($start_time > 0 && $end_time == 0){ + } else if ($start_time > 0 && $end_time == 0) { $query->where([['create_time', '>=', $start_time]]); - }else if($start_time == 0 && $end_time > 0){ + } else if ($start_time == 0 && $end_time > 0) { $query->where([['create_time', '<=', $end_time]]); } } @@ -180,40 +185,41 @@ class RechargeOrder extends BaseModel */ public function searchPayTimeAttr($query, $value, $data) { - $start_time = empty($value[0]) ? 0 : strtotime($value[0]) ; - $end_time = empty($value[1]) ? 0 : strtotime($value[1]) ; - if($start_time > 0 && $end_time > 0){ + $start_time = empty($value[0]) ? 0 : strtotime($value[0]); + $end_time = empty($value[1]) ? 0 : strtotime($value[1]); + if ($start_time > 0 && $end_time > 0) { $query->whereBetweenTime('pay_time', $start_time, $end_time); - }else if($start_time > 0 && $end_time == 0){ + } else if ($start_time > 0 && $end_time == 0) { $query->where([['pay_time', '>=', $start_time]]); - }else if($start_time == 0 && $end_time > 0){ + } else if ($start_time == 0 && $end_time > 0) { $query->where([['pay_time', '<=', $end_time]]); } } /** * 订单项目 - * @return \think\model\relation\HasMany + * @return HasMany */ public function item() { - return $this->hasMany(RechargeOrderItem::class,'order_id', 'order_id'); + return $this->hasMany(RechargeOrderItem::class, 'order_id', 'order_id'); } /** * 订单会员 - * @return \think\model\relation\HasOne + * @return HasOne */ public function member() { - return $this->hasOne(Member::class,'member_id', 'member_id'); + return $this->hasOne(Member::class, 'member_id', 'member_id'); } /** * 支付记录 - * @return \think\model\relation\HasOne + * @return HasOne */ - public function pay() { - return $this->hasOne(Pay::class,'out_trade_no', 'out_trade_no')->bind(['pay_type_name' => 'type_name']); + public function pay() + { + return $this->hasOne(Pay::class, 'out_trade_no', 'out_trade_no')->bind(['pay_type_name' => 'type_name']); } } diff --git a/niucloud/app/model/order/RechargeOrderItem.php b/niucloud/app/model/order/RechargeOrderItem.php index 1545df97b..2b8b2422a 100644 --- a/niucloud/app/model/order/RechargeOrderItem.php +++ b/niucloud/app/model/order/RechargeOrderItem.php @@ -12,6 +12,7 @@ namespace app\model\order; use core\base\BaseModel; +use think\model\relation\HasOne; /** * 订单项目模型 @@ -40,24 +41,26 @@ class RechargeOrderItem extends BaseModel { return $this->hasOne(RechargeOrder::class, 'order_id', 'order_id')->joinType('left')->withField('order_id, order_no')->bind(['order_no' => 'order_no']); } + /** * 数量字段处理 * @param $value - * @return mixed + * @param $data + * @return string|void */ public function getNumAttr($value, $data) { - if(isset($data['num'])) - { - return number_format($data['num'], 0); + if (isset($data['num'])) { + return number_format($data['num']); } } /** * 关联订单主表 - * @return void + * @return HasOne */ - public function ordermain(){ + public function ordermain() + { return $this->hasOne(RechargeOrder::class, 'order_id')->joinType('inner'); } } diff --git a/niucloud/app/model/order/RechargeOrderItemRefund.php b/niucloud/app/model/order/RechargeOrderItemRefund.php index 0b991459f..76ae1792d 100644 --- a/niucloud/app/model/order/RechargeOrderItemRefund.php +++ b/niucloud/app/model/order/RechargeOrderItemRefund.php @@ -15,6 +15,7 @@ use app\dict\order\RechargeOrderDict; use app\model\member\Member; use app\model\pay\Refund; use core\base\BaseModel; +use think\model\relation\HasOne; /** * 订单项目模型 @@ -25,9 +26,9 @@ class RechargeOrderItemRefund extends BaseModel { //类型 protected $type = [ - 'create_time' => 'timestamp', - 'audit_time' => 'timestamp', - 'transfer_time' => 'timestamp', + 'create_time' => 'timestamp', + 'audit_time' => 'timestamp', + 'transfer_time' => 'timestamp', ]; /** @@ -45,39 +46,42 @@ class RechargeOrderItemRefund extends BaseModel /** * 退款状态字段处理 * @param $value + * @param $data * @return mixed */ public function getStatusNameAttr($value, $data) { - if(empty($data['status'])) + if (empty($data['status'])) return ''; $temp = RechargeOrderDict::getRefundStatus()[$data['status']] ?? []; - return $temp['name'] ?? ''; + return $temp['name'] ?? ''; } /** * - * @return \think\model\relation\HasOne + * @return HasOne */ - public function item() { + public function item() + { return $this->hasOne(RechargeOrderItem::class, 'order_item_id', 'order_item_id')->joinType('inner'); } /** * 订单会员 - * @return \think\model\relation\HasOne + * @return HasOne */ public function member() { - return $this->hasOne( Member::class, 'member_id', 'member_id')->withField('member_id, username, mobile, nickname, headimg')->joinType('left'); + return $this->hasOne(Member::class, 'member_id', 'member_id')->withField('member_id, username, mobile, nickname, headimg')->joinType('left'); } /** * 关联退款支付记录表 - * @return \think\model\relation\HasOne + * @return HasOne */ - public function payrefund(){ - return $this->hasOne(Refund::class,'refund_no', 'refund_no'); + public function payrefund() + { + return $this->hasOne(Refund::class, 'refund_no', 'refund_no'); } /** @@ -174,34 +178,38 @@ class RechargeOrderItemRefund extends BaseModel /** * 创建时间搜索器 + * @param $query * @param $value + * @param $data */ public function searchCreateTimeAttr($query, $value, $data) { - $start_time = empty($value[0]) ? 0 : strtotime($value[0]) ; - $end_time = empty($value[1]) ? 0 : strtotime($value[1]) ; - if($start_time > 0 && $end_time > 0){ + $start_time = empty($value[0]) ? 0 : strtotime($value[0]); + $end_time = empty($value[1]) ? 0 : strtotime($value[1]); + if ($start_time > 0 && $end_time > 0) { $query->whereBetweenTime('create_time', $start_time, $end_time); - }else if($start_time > 0 && $end_time == 0){ + } else if ($start_time > 0 && $end_time == 0) { $query->where([['create_time', '>=', $start_time]]); - }else if($start_time == 0 && $end_time > 0){ + } else if ($start_time == 0 && $end_time > 0) { $query->where([['create_time', '<=', $end_time]]); } } /** * 创建时间搜索器 + * @param $query * @param $value + * @param $data */ public function searchJoinCreateTimeAttr($query, $value, $data) { - $start_time = empty($value[0]) ? 0 : strtotime($value[0]) ; - $end_time = empty($value[1]) ? 0 : strtotime($value[1]) ; - if($start_time > 0 && $end_time > 0){ + $start_time = empty($value[0]) ? 0 : strtotime($value[0]); + $end_time = empty($value[1]) ? 0 : strtotime($value[1]); + if ($start_time > 0 && $end_time > 0) { $query->whereBetweenTime('recharge_order_item_refund.create_time', $start_time, $end_time); - }else if($start_time > 0 && $end_time == 0){ + } else if ($start_time > 0 && $end_time == 0) { $query->where([['recharge_order_item_refund.create_time', '>=', $start_time]]); - }else if($start_time == 0 && $end_time > 0){ + } else if ($start_time == 0 && $end_time > 0) { $query->where([['recharge_order_item_refund.create_time', '<=', $end_time]]); } } diff --git a/niucloud/app/model/pay/Pay.php b/niucloud/app/model/pay/Pay.php index 40fe79096..6c51c4802 100644 --- a/niucloud/app/model/pay/Pay.php +++ b/niucloud/app/model/pay/Pay.php @@ -11,6 +11,7 @@ namespace app\model\pay; +use app\dict\common\ChannelDict; use app\dict\pay\PayDict; use core\base\BaseModel; @@ -39,35 +40,93 @@ class Pay extends BaseModel //类型 protected $type = [ - 'pay_time' => 'timestamp', - 'close_time' => 'timestamp', + 'pay_time' => 'timestamp', + 'close_time' => 'timestamp', ]; protected $json = ['allow_type']; protected $jsonAssoc = true; + /** * 状态字段转化 * @param $value + * @param $data * @return mixed */ public function getStatusNameAttr($value, $data) { - if(empty($data['status'])) + if (empty($data['status'])) return ''; return PayDict::getStatus()[$data['status']] ?? ''; } + /** * 支付方式字段转化 * @param $value + * @param $data * @return mixed */ public function getTypeNameAttr($value, $data) { - if(empty($data['type'])) + if (empty($data['type'])) return ''; $temp = PayDict::getPayType()[$data['type']] ?? []; return $temp['name'] ?? ''; } + /** + * 创建时间搜索器 + * @param $query + * @param $value + * @param $data + */ + public function searchCreateTimeAttr($query, $value, $data) + { + $start_time = empty($value[0]) ? 0 : strtotime($value[0]); + $end_time = empty($value[1]) ? 0 : strtotime($value[1]); + if ($start_time > 0 && $end_time > 0) { + $query->whereBetweenTime('create_time', $start_time, $end_time); + } else if ($start_time > 0 && $end_time == 0) { + $query->where([['create_time', '>=', $start_time]]); + } else if ($start_time == 0 && $end_time > 0) { + $query->where([['create_time', '<=', $end_time]]); + } + } + + /** + * 查询交易流水号 + * @param $query + * @param $value + * @return void + */ + public function searchOutTradeNoAttr($query, $value) { + if (!empty($value)) { + $query->where([['out_trade_no', '=', $value]]); + } + } + + /** + * 查询交易状态 + * @param $query + * @param $value + * @return void + */ + public function searchStatusAttr($query, $value) { + if ($value != '') { + $query->where([['status', '=', $value]]); + } + } + + /** + * 支付渠道 + * @param $value + * @param $data + * @return array|mixed|string|void + */ + public function getChannelNameAttr($value, $data){ + if (isset($data['channel'])) { + return ChannelDict::getType($data['channel']); + } + } } diff --git a/niucloud/app/model/pay/PayChannel.php b/niucloud/app/model/pay/PayChannel.php index da24a7864..583d968a5 100644 --- a/niucloud/app/model/pay/PayChannel.php +++ b/niucloud/app/model/pay/PayChannel.php @@ -43,11 +43,12 @@ class PayChannel extends BaseModel /** * 支付方式字段转化 * @param $value + * @param $data * @return mixed */ public function getTypeNameAttr($value, $data) { - if(empty($data['type'])) return ''; + if (empty($data['type'])) return ''; $temp = PayDict::getPayType()[$data['type']] ?? []; return $temp['name'] ?? ''; } @@ -55,11 +56,12 @@ class PayChannel extends BaseModel /** * 渠道字段转化 * @param $value + * @param $data * @return mixed */ public function getChannelNameAttr($value, $data) { - if(empty($data['channel'])) return ''; + if (empty($data['channel'])) return ''; return ChannelDict::getType()[$data['channel']] ?? ''; } diff --git a/niucloud/app/model/pay/Refund.php b/niucloud/app/model/pay/Refund.php index 446c3dcc4..740a61018 100644 --- a/niucloud/app/model/pay/Refund.php +++ b/niucloud/app/model/pay/Refund.php @@ -35,30 +35,31 @@ class Refund extends BaseModel //类型 protected $type = [ - 'create_time' => 'timestamp', - 'refund_time' => 'timestamp', - 'close_time' => 'timestamp', + 'refund_time' => 'timestamp', + 'close_time' => 'timestamp', ]; /** * 状态字段转化 * @param $value + * @param $data * @return mixed */ public function getStatusNameAttr($value, $data) { - if(empty($data['status'])) return ''; + if (empty($data['status'])) return ''; return RefundDict::getStatus()[$data['status']] ?? ''; } /** * 支付方式字段转化 * @param $value + * @param $data * @return mixed */ public function getTypeNameAttr($value, $data) { - if(empty($data['type'])) return ''; + if (empty($data['type'])) return ''; return RefundDict::getType()[$data['type']] ?? ''; } diff --git a/niucloud/app/model/pay/Transfer.php b/niucloud/app/model/pay/Transfer.php index eb5edfa40..1e859b8e1 100644 --- a/niucloud/app/model/pay/Transfer.php +++ b/niucloud/app/model/pay/Transfer.php @@ -37,18 +37,19 @@ class Transfer extends BaseModel //类型 protected $type = [ - 'transfer_time' => 'timestamp', + 'transfer_time' => 'timestamp', 'finish_time' => 'timestamp', ]; /** * 状态字段转化 * @param $value + * @param $data * @return mixed */ public function getTransferStatusNameAttr($value, $data) { - if(empty($data['transfer_status'])) return ''; + if (empty($data['transfer_status'])) return ''; return TransferDict::getStatus()[$data['transfer_status']] ?? ''; } @@ -56,11 +57,12 @@ class Transfer extends BaseModel /** * 转账方式字段转化 * @param $value + * @param $data * @return mixed */ public function getTransferTypeNameAttr($value, $data) { - if(empty($data['transfer_type'])) return ''; + if (empty($data['transfer_type'])) return ''; $temp = TransferDict::getTransferType()[$data['transfer_type']] ?? []; return $temp['name'] ?? ''; } diff --git a/niucloud/app/model/site/Site.php b/niucloud/app/model/site/Site.php index 285a1b1d4..51d1748b4 100644 --- a/niucloud/app/model/site/Site.php +++ b/niucloud/app/model/site/Site.php @@ -14,6 +14,7 @@ namespace app\model\site; use app\dict\site\SiteDict; use core\base\BaseModel; use think\db\Query; +use think\model\relation\HasOne; /** * 站点模型 @@ -24,7 +25,7 @@ class Site extends BaseModel { protected $type = [ - 'expire_time' => 'timestamp', + 'expire_time' => 'timestamp', ]; /** * 数据表主键 @@ -42,14 +43,16 @@ class Site extends BaseModel /** * 状态字段转化 * @param $value + * @param $data * @return mixed */ public function getStatusNameAttr($value, $data) { - if(empty($data['status'])) + if (empty($data['status'])) return ''; return SiteDict::getStatus()[$data['status']] ?? ''; } + /** * 关键字搜索 * @param $query @@ -91,45 +94,49 @@ class Site extends BaseModel /** * 分组名称 - * @return \think\model\relation\HasOne + * @return HasOne */ public function groupName() { - return $this->hasOne( SiteGroup::class, 'group_id', 'group_id')->joinType('left')->withField('group_id, group_name')->bind(['group_name' => 'group_name']); + return $this->hasOne(SiteGroup::class, 'group_id', 'group_id')->joinType('left')->withField('group_id, group_name')->bind(['group_name' => 'group_name']); } /** * 创建时间搜索器 + * @param Query $query * @param $value + * @param $data */ public function searchCreateTimeAttr(Query $query, $value, $data) { - $start_time = empty($value[ 0 ]) ? 0 : strtotime($value[ 0 ]); - $end_time = empty($value[ 1 ]) ? 0 : strtotime($value[ 1 ]); + $start_time = empty($value[0]) ? 0 : strtotime($value[0]); + $end_time = empty($value[1]) ? 0 : strtotime($value[1]); if ($start_time > 0 && $end_time > 0) { $query->whereBetweenTime('create_time', $start_time, $end_time); } else if ($start_time > 0 && $end_time == 0) { - $query->where([ [ 'create_time', '>=', $start_time ] ]); + $query->where([['create_time', '>=', $start_time]]); } else if ($start_time == 0 && $end_time > 0) { - $query->where([ [ 'create_time', '<=', $end_time ] ]); + $query->where([['create_time', '<=', $end_time]]); } } /** * 到期时间搜索器 + * @param Query $query * @param $value + * @param $data */ public function searchExpireTimeAttr(Query $query, $value, $data) { - $start_time = empty($value[ 0 ]) ? 0 : strtotime($value[ 0 ]); - $end_time = empty($value[ 1 ]) ? 0 : strtotime($value[ 1 ]); + $start_time = empty($value[0]) ? 0 : strtotime($value[0]); + $end_time = empty($value[1]) ? 0 : strtotime($value[1]); if ($start_time > 0 && $end_time > 0) { $query->whereBetweenTime('expire_time', $start_time, $end_time); } else if ($start_time > 0 && $end_time == 0) { - $query->where([ [ 'expire_time', '>=', $start_time ] ]); + $query->where([['expire_time', '>=', $start_time]]); } else if ($start_time == 0 && $end_time > 0) { - $query->where([ [ 'expire_time', '<=', $end_time ] ]); + $query->where([['expire_time', '<=', $end_time]]); } } diff --git a/niucloud/app/model/site/SiteAccountLog.php b/niucloud/app/model/site/SiteAccountLog.php index 6f795bbe7..3cce7a2b1 100644 --- a/niucloud/app/model/site/SiteAccountLog.php +++ b/niucloud/app/model/site/SiteAccountLog.php @@ -12,7 +12,6 @@ namespace app\model\site; use app\dict\site\SiteAccountLogDict; -use app\dict\site\SiteDict; use app\model\pay\Pay; use app\model\pay\Refund; use app\model\pay\Transfer; @@ -43,6 +42,7 @@ class SiteAccountLog extends BaseModel /** * 状态字段转化 * @param $value + * @param $data * @return mixed */ public function getTypeNameAttr($value, $data) @@ -54,63 +54,63 @@ class SiteAccountLog extends BaseModel * 获取相关支付单据信息 * @param $value * @param $data + * @return array */ public function getPayInfoAttr($value, $data) { - switch ($data['type']){ - case 'pay' : - return (new Pay())->where([['out_trade_no', '=', $data['trade_no']]])->append(['type_name'])->findOrEmpty()->toArray(); - break; - case 'refund' : - return (new Refund())->where([['refund_no', '=', $data['trade_no']]])->findOrEmpty()->toArray(); - break; - case 'transfer': - return (new Transfer())->where([['transfer_no', '=', $data['trade_no']]])->findOrEmpty()->toArray(); - break; - default: - return []; - } + return match ($data['type']) { + 'pay' => (new Pay())->where([['out_trade_no', '=', $data['trade_no']]])->append(['type_name'])->findOrEmpty()->toArray(), + 'refund' => (new Refund())->where([['refund_no', '=', $data['trade_no']]])->findOrEmpty()->toArray(), + 'transfer' => (new Transfer())->where([['transfer_no', '=', $data['trade_no']]])->findOrEmpty()->toArray(), + default => [], + }; } + /** * 状态字段转化 + * @param $query * @param $value - * @return mixed + * @param $data + * @return void */ public function searchTypeAttr($query, $value, $data) { if ($value) { - $query->where('type', '=', $value ); + $query->where('type', '=', $value); } } /** * 金额转化 * @param $value + * @param $data * @return mixed */ public function getMoneyAttr($value, $data) { - if(strpos($data['money'], "-") !== false){ + if (str_contains($data['money'], "-")) { return $data['money']; - }else{ - return "+".$data['money']; + } else { + return "+" . $data['money']; } } /** * 创建时间搜索器 + * @param Query $query * @param $value + * @param $data */ public function searchCreateTimeAttr(Query $query, $value, $data) { - $start_time = empty($value[ 0 ]) ? 0 : strtotime($value[ 0 ]); - $end_time = empty($value[ 1 ]) ? 0 : strtotime($value[ 1 ]); + $start_time = empty($value[0]) ? 0 : strtotime($value[0]); + $end_time = empty($value[1]) ? 0 : strtotime($value[1]); if ($start_time > 0 && $end_time > 0) { $query->whereBetweenTime('create_time', $start_time, $end_time); } else if ($start_time > 0 && $end_time == 0) { - $query->where([ [ 'create_time', '>=', $start_time ] ]); + $query->where([['create_time', '>=', $start_time]]); } else if ($start_time == 0 && $end_time > 0) { - $query->where([ [ 'create_time', '<=', $end_time ] ]); + $query->where([['create_time', '<=', $end_time]]); } } diff --git a/niucloud/app/model/site/SiteGroup.php b/niucloud/app/model/site/SiteGroup.php index a721f1d47..7ec1b5e45 100644 --- a/niucloud/app/model/site/SiteGroup.php +++ b/niucloud/app/model/site/SiteGroup.php @@ -37,6 +37,7 @@ class SiteGroup extends BaseModel * @var string */ protected $name = 'site_group'; + /** * 关键字搜索 * @param $query diff --git a/niucloud/app/model/sys/SysAgreement.php b/niucloud/app/model/sys/SysAgreement.php index c41f2c9f8..f227a1009 100644 --- a/niucloud/app/model/sys/SysAgreement.php +++ b/niucloud/app/model/sys/SysAgreement.php @@ -12,7 +12,6 @@ namespace app\model\sys; use app\dict\sys\AgreementDict; -use app\dict\sys\StorageDict; use core\base\BaseModel; /** @@ -42,11 +41,12 @@ class SysAgreement extends BaseModel /** * 字段转化 * @param $value - * @return mixed + * @param $data + * @return string */ public function getAgreementKeyNameAttr($value, $data) { - if(empty($data['agreement_key'])) return ''; + if (empty($data['agreement_key'])) return ''; return AgreementDict::getType()[$data['agreement_key']] ?? ''; } } diff --git a/niucloud/app/model/sys/SysArea.php b/niucloud/app/model/sys/SysArea.php index 50b69901a..aaca9c03b 100644 --- a/niucloud/app/model/sys/SysArea.php +++ b/niucloud/app/model/sys/SysArea.php @@ -34,5 +34,4 @@ class SysArea extends BaseModel protected $name = 'sys_area'; - } diff --git a/niucloud/app/model/sys/SysMenu.php b/niucloud/app/model/sys/SysMenu.php index 9710ecfe0..eb290c09b 100644 --- a/niucloud/app/model/sys/SysMenu.php +++ b/niucloud/app/model/sys/SysMenu.php @@ -24,6 +24,7 @@ use think\model\concern\SoftDelete; class SysMenu extends BaseModel { use SoftDelete; + /** * 数据表主键 * @var string @@ -58,9 +59,9 @@ class SysMenu extends BaseModel * @param $data * @return string */ - public function getMenuTypeNameAttr($value,$data) + public function getMenuTypeNameAttr($value, $data) { - if(empty($data['menu_type'])) + if (empty($data['menu_type'])) return ''; return MenuTypeDict::getMenuType()[$data['menu_type']] ?? ''; } @@ -71,9 +72,9 @@ class SysMenu extends BaseModel * @param $data * @return string */ - public function getStatusNameAttr($value,$data) + public function getStatusNameAttr($value, $data) { - if(empty($data['status'])) + if (empty($data['status'])) return ''; return MenuDict::getStatus()[$data['status']] ?? ''; } diff --git a/niucloud/app/model/sys/SysNoticeLog.php b/niucloud/app/model/sys/SysNoticeLog.php index 4354d4fba..054140c44 100644 --- a/niucloud/app/model/sys/SysNoticeLog.php +++ b/niucloud/app/model/sys/SysNoticeLog.php @@ -13,7 +13,6 @@ namespace app\model\sys; use app\dict\notice\NoticeDict; use app\dict\notice\NoticeTypeDict; -use app\dict\sys\SmsDict; use core\base\BaseModel; use think\db\Query; @@ -38,7 +37,7 @@ class SysNoticeLog extends BaseModel protected $name = 'sys_notice_log'; protected $type = [ - 'send_time' => 'timestamp', + 'send_time' => 'timestamp', ]; // 设置json类型字段 @@ -52,30 +51,12 @@ class SysNoticeLog extends BaseModel * @param $data * @return string */ - public function getContentAttr($value,$data) + public function getContentAttr($value, $data) { - if($value){ + if ($value) { $temp = json_decode($value, true); } - if(!$temp){ - $temp = $value; - } - return $temp; - } - /** - * 名称 - * @param $value - * @param $data - * @return string - */ - public function getNameAttr($value,$data) - { - $name = ''; - if(!empty($data['key'])){ - $temp = NoticeDict::getNotice()[$data['key']] ?? []; - $name = $temp['name'] ?? ''; - } - return $name; + return $temp ?? $value; } /** @@ -84,7 +65,23 @@ class SysNoticeLog extends BaseModel * @param $data * @return string */ - public function getNoticeTypeNameAttr($value,$data) + public function getNameAttr($value, $data) + { + $name = ''; + if (!empty($data['key'])) { + $temp = NoticeDict::getNotice()[$data['key']] ?? []; + $name = $temp['name'] ?? ''; + } + return $name; + } + + /** + * 名称 + * @param $value + * @param $data + * @return string + */ + public function getNoticeTypeNameAttr($value, $data) { $name = ''; if (!empty($data['notice_type'])) { @@ -93,10 +90,12 @@ class SysNoticeLog extends BaseModel } return $name; } + /** * 消息类型 + * @param $query * @param $value - * @return mixed + * @return void */ public function searchKeyAttr($query, $value) { @@ -107,8 +106,9 @@ class SysNoticeLog extends BaseModel /** * 接收人 + * @param $query * @param $value - * @return mixed + * @return void */ public function searchReceiverAttr($query, $value) { @@ -119,17 +119,19 @@ class SysNoticeLog extends BaseModel /** * 创建时间搜索器 + * @param Query $query * @param $value + * @param $data */ public function searchCreateTimeAttr(Query $query, $value, $data) { - $start_time = empty($value[0]) ? 0 : strtotime($value[0]) ; - $end_time = empty($value[1]) ? 0 : strtotime($value[1]) ; - if($start_time > 0 && $end_time > 0){ + $start_time = empty($value[0]) ? 0 : strtotime($value[0]); + $end_time = empty($value[1]) ? 0 : strtotime($value[1]); + if ($start_time > 0 && $end_time > 0) { $query->whereBetweenTime('create_time', $start_time, $end_time); - }else if($start_time > 0 && $end_time == 0){ + } else if ($start_time > 0 && $end_time == 0) { $query->where([['create_time', '>=', $start_time]]); - }else if($start_time == 0 && $end_time > 0){ + } else if ($start_time == 0 && $end_time > 0) { $query->where([['create_time', '<=', $end_time]]); } } diff --git a/niucloud/app/model/sys/SysNoticeSmsLog.php b/niucloud/app/model/sys/SysNoticeSmsLog.php index 110191131..27414d85b 100644 --- a/niucloud/app/model/sys/SysNoticeSmsLog.php +++ b/niucloud/app/model/sys/SysNoticeSmsLog.php @@ -100,15 +100,16 @@ class SysNoticeSmsLog extends BaseModel */ public function getSmsTypesNameAttr($value, $data) { - if(empty($data['sms_type'])) return ''; + if (empty($data['sms_type'])) return ''; $temp = SmsDict::getType()[$data['sms_type']] ?? []; return $temp['name'] ?? ''; } /** * 消息标识 + * @param $query * @param $value - * @return mixed + * @return void */ public function searchKeyAttr($query, $value) { @@ -119,8 +120,9 @@ class SysNoticeSmsLog extends BaseModel /** * 短信方式 + * @param $query * @param $value - * @return mixed + * @return void */ public function searchSmsTypeAttr($query, $value) { @@ -131,8 +133,9 @@ class SysNoticeSmsLog extends BaseModel /** * 手机号 + * @param $query * @param $value - * @return mixed + * @return void */ public function searchMobileAttr($query, $value) { diff --git a/niucloud/app/model/sys/SysRole.php b/niucloud/app/model/sys/SysRole.php index 194cd660f..7d68cd932 100644 --- a/niucloud/app/model/sys/SysRole.php +++ b/niucloud/app/model/sys/SysRole.php @@ -44,8 +44,9 @@ class SysRole extends BaseModel * @param $data * @return string */ - public function getStatusNameAttr($value, $data){ - if(empty($data['status'])) return ''; + public function getStatusNameAttr($value, $data) + { + if (empty($data['status'])) return ''; return RoleStatusDict::getStatus()[$data['status']] ?? ''; } diff --git a/niucloud/app/model/sys/SysSchedule.php b/niucloud/app/model/sys/SysSchedule.php index e97eb7bd5..d74536113 100644 --- a/niucloud/app/model/sys/SysSchedule.php +++ b/niucloud/app/model/sys/SysSchedule.php @@ -34,9 +34,9 @@ class SysSchedule extends BaseModel protected $name = 'sys_schedule'; protected $type = [ - 'last_time' => 'timestamp', - 'next_time' => 'timestamp', - 'update_time' => 'timestamp', + 'last_time' => 'timestamp', + 'next_time' => 'timestamp', + 'update_time' => 'timestamp', ]; // 设置json类型字段 @@ -48,16 +48,20 @@ class SysSchedule extends BaseModel /** * 启用状态 * @param $value + * @param $data * @return mixed */ public function getStatusNameAttr($value, $data) { - if(empty($data['status'])) return ''; + if (empty($data['status'])) return ''; return ScheduleDict::getStatus()[$data['status']] ?? ''; } + /** * 任务类型搜索器 + * @param Query $query * @param $value + * @param $data */ public function searchKeyAttr(Query $query, $value, $data) { @@ -83,17 +87,19 @@ class SysSchedule extends BaseModel /** * 执行时间搜索器 + * @param $query * @param $value + * @param $data */ public function searchLastTimeAttr($query, $value, $data) { - $start_time = empty($value[0]) ? 0 : strtotime($value[0]) ; - $end_time = empty($value[1]) ? 0 : strtotime($value[1]) ; - if($start_time > 0 && $end_time > 0){ + $start_time = empty($value[0]) ? 0 : strtotime($value[0]); + $end_time = empty($value[1]) ? 0 : strtotime($value[1]); + if ($start_time > 0 && $end_time > 0) { $query->whereBetweenTime('last_time', $start_time, $end_time); - }else if($start_time > 0 && $end_time == 0){ + } else if ($start_time > 0 && $end_time == 0) { $query->where([['last_time', '>=', $start_time]]); - }else if($start_time == 0 && $end_time > 0){ + } else if ($start_time == 0 && $end_time > 0) { $query->where([['last_time', '<=', $end_time]]); } } diff --git a/niucloud/app/model/sys/SysUser.php b/niucloud/app/model/sys/SysUser.php index 8aaabd3fb..e615166a6 100644 --- a/niucloud/app/model/sys/SysUser.php +++ b/niucloud/app/model/sys/SysUser.php @@ -14,6 +14,7 @@ namespace app\model\sys; use app\dict\sys\UserDict; use core\base\BaseModel; use think\model\concern\SoftDelete; +use think\model\relation\HasMany; /** * 系统用户模型 @@ -26,7 +27,7 @@ class SysUser extends BaseModel use SoftDelete; protected $type = [ - 'last_time' => 'timestamp', + 'last_time' => 'timestamp', ]; /** * 数据表主键 @@ -58,7 +59,7 @@ class SysUser extends BaseModel /** * 权限组 - * @return mixed + * @return HasMany */ public function roles() { @@ -68,11 +69,12 @@ class SysUser extends BaseModel /** * 状态字段转化 * @param $value + * @param $data * @return mixed */ public function getStatusNameAttr($value, $data) { - if(empty($data['status'])) return ''; + if (empty($data['status'])) return ''; return UserDict::getStatus()[$data['status']] ?? ''; } @@ -83,31 +85,33 @@ class SysUser extends BaseModel /** * 账号搜索器 + * @param $query * @param $value */ public function searchUsernameAttr($query, $value) { if ($value) { - $query->whereLike('username', '%'.$value.'%'); + $query->whereLike('username', '%' . $value . '%'); } } /** * 用户实际姓名搜索器 + * @param $query * @param $value */ public function searchRealnameAttr($query, $value) { if ($value) { - $query->whereLike('real_name', '%'.$value.'%'); + $query->whereLike('real_name', '%' . $value . '%'); } } /** * 是否删除搜索器 - * @param $value + * @param $query */ public function searchIsDelAttr($query) { @@ -116,6 +120,7 @@ class SysUser extends BaseModel /** * 状态搜索器 + * @param $query * @param $value */ public function searchStatusAttr($query, $value) @@ -126,17 +131,19 @@ class SysUser extends BaseModel /** * 创建时间搜索器 + * @param $query * @param $value + * @param $data */ public function searchCreateTimeAttr($query, $value, $data) { - $start_time = empty($value[0]) ? 0 : strtotime($value[0]) ; - $end_time = empty($value[1]) ? 0 : strtotime($value[1]) ; - if($start_time > 0 && $end_time > 0){ + $start_time = empty($value[0]) ? 0 : strtotime($value[0]); + $end_time = empty($value[1]) ? 0 : strtotime($value[1]); + if ($start_time > 0 && $end_time > 0) { $query->whereBetweenTime('sys_user.create_time', $start_time, $end_time); - }else if($start_time > 0 && $end_time == 0){ + } else if ($start_time > 0 && $end_time == 0) { $query->where([['sys_user.create_time', '>=', $start_time]]); - }else if($start_time == 0 && $end_time > 0){ + } else if ($start_time == 0 && $end_time > 0) { $query->where([['sys_user.create_time', '<=', $end_time]]); } } diff --git a/niucloud/app/model/sys/SysUserLog.php b/niucloud/app/model/sys/SysUserLog.php index 761f345e8..3d446059b 100644 --- a/niucloud/app/model/sys/SysUserLog.php +++ b/niucloud/app/model/sys/SysUserLog.php @@ -39,9 +39,12 @@ class SysUserLog extends BaseModel protected $json = ['params']; protected $jsonAssoc = true; + /** * 用户id搜索器 + * @param Query $query * @param $value + * @param $data */ public function searchUidAttr(Query $query, $value, $data) { @@ -49,19 +52,25 @@ class SysUserLog extends BaseModel $query->where('uid', $value); } } + /** * 用户名搜索器 + * @param Query $query * @param $value + * @param $data */ public function searchUsernameAttr(Query $query, $value, $data) { if ($value) { - $query->whereLike('username', '%'.$value.'%'); + $query->whereLike('username', '%' . $value . '%'); } } + /** * 请求方式搜索器 + * @param Query $query * @param $value + * @param $data */ public function searchTypeAttr(Query $query, $value, $data) { @@ -72,39 +81,45 @@ class SysUserLog extends BaseModel /** * 链接搜索器 + * @param Query $query * @param $value + * @param $data */ public function searchUrlAttr(Query $query, $value, $data) { if ($value) { - $query->whereLike('url', '%'.$value.'%'); + $query->whereLike('url', '%' . $value . '%'); } } /** * ip搜索器 + * @param Query $query * @param $value + * @param $data */ public function searchIpAttr(Query $query, $value, $data) { if ($value) { - $query->whereLike('ip', '%'.$value.'%'); + $query->whereLike('ip', '%' . $value . '%'); } } /** * 创建时间搜索器 + * @param $query * @param $value + * @param $data */ public function searchCreateTimeAttr($query, $value, $data) { - $start_time = empty($value[0]) ? 0 : strtotime($value[0]) ; - $end_time = empty($value[1]) ? 0 : strtotime($value[1]) ; - if($start_time > 0 && $end_time > 0){ + $start_time = empty($value[0]) ? 0 : strtotime($value[0]); + $end_time = empty($value[1]) ? 0 : strtotime($value[1]); + if ($start_time > 0 && $end_time > 0) { $query->whereBetweenTime('create_time', $start_time, $end_time); - }else if($start_time > 0 && $end_time == 0){ + } else if ($start_time > 0 && $end_time == 0) { $query->where([['create_time', '>=', $start_time]]); - }else if($start_time == 0 && $end_time > 0){ + } else if ($start_time == 0 && $end_time > 0) { $query->where([['create_time', '<=', $end_time]]); } } diff --git a/niucloud/app/model/sys/SysUserRole.php b/niucloud/app/model/sys/SysUserRole.php index 5b344e545..47b757f78 100644 --- a/niucloud/app/model/sys/SysUserRole.php +++ b/niucloud/app/model/sys/SysUserRole.php @@ -13,6 +13,7 @@ namespace app\model\sys; use app\model\site\Site; use core\base\BaseModel; +use think\model\relation\HasOne; /** * 用户角色模型 @@ -41,23 +42,23 @@ class SysUserRole extends BaseModel /** * 关联查询用户信息 - * @return \think\model\relation\HasOne + * @return HasOne */ public function userinfo() { - return $this->hasOne( SysUser::class, 'uid', 'uid')->joinType('left') + return $this->hasOne(SysUser::class, 'uid', 'uid')->joinType('left') ->withField('uid,username,head_img,real_name,last_ip,last_time,login_count,status,create_time') - ->bind(['username','head_img','real_name','last_ip','last_time','login_count','status']); + ->bind(['username', 'head_img', 'real_name', 'last_ip', 'last_time', 'login_count', 'status']); } /** * 关联查询站点信息 - * @return \think\model\relation\HasOne + * @return HasOne */ public function siteInfo() { - return $this->hasOne( Site::class, 'site_id', 'site_id')->joinType('inner') + return $this->hasOne(Site::class, 'site_id', 'site_id')->joinType('inner') ->withField('site_id, site_name, app_type, status, expire_time') - ->bind(['site_name','app_type','status','expire_time']); + ->bind(['site_name', 'app_type', 'status', 'expire_time']); } } diff --git a/niucloud/app/model/wechat/WechatFans.php b/niucloud/app/model/wechat/WechatFans.php index 1a379f9da..02a501baa 100644 --- a/niucloud/app/model/wechat/WechatFans.php +++ b/niucloud/app/model/wechat/WechatFans.php @@ -34,5 +34,4 @@ class WechatFans extends BaseModel protected $name = 'wechat_fans'; - } diff --git a/niucloud/app/model/wechat/WechatMedia.php b/niucloud/app/model/wechat/WechatMedia.php index 852631cef..ffd2524a1 100644 --- a/niucloud/app/model/wechat/WechatMedia.php +++ b/niucloud/app/model/wechat/WechatMedia.php @@ -34,5 +34,4 @@ class WechatMedia extends BaseModel protected $name = 'wechat_media'; - } diff --git a/niucloud/app/model/wechat/WechatReply.php b/niucloud/app/model/wechat/WechatReply.php index c55263837..96d246157 100644 --- a/niucloud/app/model/wechat/WechatReply.php +++ b/niucloud/app/model/wechat/WechatReply.php @@ -41,7 +41,7 @@ class WechatReply extends BaseModel * @param $data * @return string */ - public function getContentAttr($value,$data) + public function getContentAttr($value, $data) { return $data['content_type'] == ReplyDict::CONTENT_TYPE_TEXT ? $value : json_decode($value, true); diff --git a/niucloud/app/service/admin/addon/AddonService.php b/niucloud/app/service/admin/addon/AddonService.php index f7e67a1d8..ac54bdd3c 100644 --- a/niucloud/app/service/admin/addon/AddonService.php +++ b/niucloud/app/service/admin/addon/AddonService.php @@ -12,9 +12,13 @@ namespace app\service\admin\addon; +use app\service\core\addon\CoreAddonDownloadService; use app\service\core\addon\CoreAddonInstallService; use app\service\core\addon\CoreAddonService; +use app\service\core\niucloud\CoreModuleService; use core\base\BaseAdminService; +use Exception; +use think\Response; /** @@ -27,6 +31,9 @@ class AddonService extends BaseAdminService parent::__construct(); } + public function getList(){ + return (new CoreAddonService())->getLocalAddonList(); + } /** * 获取当前站点消息 @@ -40,14 +47,14 @@ class AddonService extends BaseAdminService /** * 安装插件 * @param string $addon - * @return true + * @return Response */ public function install(string $addon) { try { $data = (new CoreAddonInstallService($addon))->install(); return success('SUCCESS', $data); - } catch (\Exception $e) { + } catch ( Exception $e) { return fail($e->getMessage()); } } @@ -55,13 +62,13 @@ class AddonService extends BaseAdminService /** * 执行安装 * @param string $addon - * @return \think\Response + * @return Response */ public function executeInstall(string $addon) { try { $data = (new CoreAddonInstallService($addon))->executeInstall(); return success('SUCCESS', $data); - } catch (\Exception $e) { + } catch ( Exception $e) { return fail($e->getMessage()); } } @@ -69,7 +76,7 @@ class AddonService extends BaseAdminService /** * 安装插件检测安装环境 * @param string $addon - * @return \think\Response + * @return Response */ public function installCheck(string $addon) { $data = (new CoreAddonInstallService($addon))->installCheck(); @@ -79,6 +86,7 @@ class AddonService extends BaseAdminService /** * 获取插件安装状态 * @param string $addon + * @param string $key * @return mixed */ public function getInstallState(string $addon, string $key) @@ -99,7 +107,7 @@ class AddonService extends BaseAdminService /** * 获取插件列表 * @param array $where - * @param string $order + * @return array */ public function getPage(array $where = []) { @@ -109,6 +117,7 @@ class AddonService extends BaseAdminService /** * 获取插件信息 * @param int $id + * @return array */ public function getInfo(int $id) { @@ -125,5 +134,22 @@ class AddonService extends BaseAdminService return (new CoreAddonService())->setStatus($id, $status); } + /** + * 下载应用 + * @param string $app_key + * @return true + */ + public function download(string $app_key){ + return (new CoreAddonDownloadService())->download($app_key); + } + + /** + * 更新应用 + * @param string $app_key + * @return null + */ + public function update(string $app_key){ + return (new CoreAddonDownloadService())->update($app_key); + } } \ No newline at end of file diff --git a/niucloud/app/service/admin/aliapp/AliappConfigService.php b/niucloud/app/service/admin/aliapp/AliappConfigService.php index 5014da58f..6ef814f39 100644 --- a/niucloud/app/service/admin/aliapp/AliappConfigService.php +++ b/niucloud/app/service/admin/aliapp/AliappConfigService.php @@ -11,8 +11,10 @@ namespace app\service\admin\aliapp; +use app\model\sys\SysConfig; use app\service\core\aliapp\CoreAliappConfigService; use core\base\BaseAdminService; +use think\Model; /** * 支付宝小程序设置 @@ -33,7 +35,7 @@ class AliappConfigService extends BaseAdminService /** * 设置配置 * @param array $data - * @return \app\model\sys\SysConfig|bool|\think\Model + * @return SysConfig|bool|Model */ public function setAliappConfig(array $data){ return (new CoreAliappConfigService())->setAliappConfig($this->site_id, $data); diff --git a/niucloud/app/service/admin/applet/AppletDownloadService.php b/niucloud/app/service/admin/applet/AppletDownloadService.php index d08298168..0a2ec504e 100644 --- a/niucloud/app/service/admin/applet/AppletDownloadService.php +++ b/niucloud/app/service/admin/applet/AppletDownloadService.php @@ -11,10 +11,9 @@ namespace app\service\admin\applet; -use app\model\article\Article; use app\service\core\applet\CoreAppletDownloadService; -use app\service\core\applet\CoreAppletVersionService; use core\base\BaseAdminService; +use think\response\File; /** * 小程序下载服务层 @@ -32,7 +31,7 @@ class AppletDownloadService extends BaseAdminService /** * 小程序下载 * @param int $id - * @return \think\response\File + * @return File */ public function download(int $id) { diff --git a/niucloud/app/service/admin/applet/AppletVersionService.php b/niucloud/app/service/admin/applet/AppletVersionService.php index 5e6946411..e7f56a3ec 100644 --- a/niucloud/app/service/admin/applet/AppletVersionService.php +++ b/niucloud/app/service/admin/applet/AppletVersionService.php @@ -14,10 +14,10 @@ namespace app\service\admin\applet; use app\dict\applet\AppletlDict; use app\dict\sys\FileDict; use app\model\applet\AppletVersion; -use app\model\article\Article; use app\service\core\applet\CoreAppletVersionService; use app\service\core\upload\CoreUploadService; use core\base\BaseAdminService; +use Exception; /** * 文章服务层 @@ -39,7 +39,7 @@ class AppletVersionService extends BaseAdminService /** * 获取列表 * @param array $where - * @param string $order + * @return array */ public function getPage(array $where = []) { @@ -49,6 +49,7 @@ class AppletVersionService extends BaseAdminService /** * 获取信息 * @param int $id + * @return array */ public function getInfo(int $id) { @@ -71,8 +72,8 @@ class AppletVersionService extends BaseAdminService /** * 上传小程序包 * @param $file - * @return true - * @throws \Exception + * @return array + * @throws Exception */ public function upload($file){ $core_upload_service = new CoreUploadService(); @@ -83,7 +84,7 @@ class AppletVersionService extends BaseAdminService /** * 设置版本状态 - * @param $id + * @param int $id * @param $status * @return true */ @@ -97,10 +98,12 @@ class AppletVersionService extends BaseAdminService $this->model->where($where)->update($data); return true; } + /** * 编辑 * @param int $id * @param array $data + * @return true */ public function edit(int $id, array $data) { diff --git a/niucloud/app/service/admin/applet/AppletVersionSiteService.php b/niucloud/app/service/admin/applet/AppletVersionSiteService.php index 46b3b8caa..9ffbb1064 100644 --- a/niucloud/app/service/admin/applet/AppletVersionSiteService.php +++ b/niucloud/app/service/admin/applet/AppletVersionSiteService.php @@ -11,13 +11,11 @@ namespace app\service\admin\applet; -use app\dict\applet\AppletlDict; -use app\dict\sys\FileDict; -use app\model\article\Article; use app\service\core\applet\CoreAppletSiteVersionService; -use app\service\core\applet\CoreAppletVersionService; -use app\service\core\upload\CoreUploadService; use core\base\BaseAdminService; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; /** * 文章服务层 @@ -36,7 +34,7 @@ class AppletVersionSiteService extends BaseAdminService /** * 获取列表 * @param array $where - * @return mixed + * @return array */ public function getPage(array $where = []) { @@ -57,6 +55,9 @@ class AppletVersionSiteService extends BaseAdminService * 查询最后一个下载或升级的版本 * @param string $type * @return mixed|string + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function getLastVersion(string $type){ return $this->core_applet_site_version_service->getLastVersion($this->site_id, $type); diff --git a/niucloud/app/service/admin/article/ArticleCategoryService.php b/niucloud/app/service/admin/article/ArticleCategoryService.php index ffe610e87..407d96876 100644 --- a/niucloud/app/service/admin/article/ArticleCategoryService.php +++ b/niucloud/app/service/admin/article/ArticleCategoryService.php @@ -31,6 +31,7 @@ class ArticleCategoryService extends BaseAdminService /** * 获取文章分类列表 * @param array $where + * @return array */ public function getPage(array $where = []) { @@ -55,6 +56,7 @@ class ArticleCategoryService extends BaseAdminService /** * 获取文章分类信息 * @param int $id + * @return array */ public function getInfo(int $id) { @@ -66,6 +68,7 @@ class ArticleCategoryService extends BaseAdminService /** * 添加文章分类 * @param array $data + * @return mixed */ public function add(array $data) { @@ -79,6 +82,7 @@ class ArticleCategoryService extends BaseAdminService * 文章分类编辑 * @param int $id * @param array $data + * @return true */ public function edit(int $id, array $data) { @@ -90,6 +94,7 @@ class ArticleCategoryService extends BaseAdminService /** * 删除文章分类 * @param int $id + * @return bool */ public function del(int $id) { diff --git a/niucloud/app/service/admin/article/ArticleService.php b/niucloud/app/service/admin/article/ArticleService.php index 473d09a14..a9db91794 100644 --- a/niucloud/app/service/admin/article/ArticleService.php +++ b/niucloud/app/service/admin/article/ArticleService.php @@ -31,7 +31,7 @@ class ArticleService extends BaseAdminService /** * 获取文章列表 * @param array $where - * @param string $order + * @return array */ public function getPage(array $where = []) { @@ -45,6 +45,7 @@ class ArticleService extends BaseAdminService /** * 获取文章信息 * @param int $id + * @return array */ public function getInfo(int $id) { @@ -56,6 +57,7 @@ class ArticleService extends BaseAdminService /** * 添加文章 * @param array $data + * @return mixed */ public function add(array $data) { @@ -70,6 +72,7 @@ class ArticleService extends BaseAdminService * 文章编辑 * @param int $id * @param array $data + * @return true */ public function edit(int $id, array $data) { @@ -81,6 +84,7 @@ class ArticleService extends BaseAdminService /** * 删除文章 * @param int $id + * @return bool */ public function del(int $id) { diff --git a/niucloud/app/service/admin/auth/AuthService.php b/niucloud/app/service/admin/auth/AuthService.php index 58173cd48..bc8ba0ebf 100644 --- a/niucloud/app/service/admin/auth/AuthService.php +++ b/niucloud/app/service/admin/auth/AuthService.php @@ -13,7 +13,6 @@ namespace app\service\admin\auth; use app\dict\site\SiteDict; use app\Request; -use app\service\admin\site\SiteService; use app\service\admin\site\SiteUserService; use app\service\admin\sys\MenuService; use app\service\admin\sys\RoleService; @@ -33,7 +32,8 @@ class AuthService extends BaseAdminService { /** * 校验用户和传入站点是否存在从属关系 - * @param $site_id + * @param Request $request + * @return true */ public function checkSiteAuth(Request $request){ $site_id = $request->adminSiteId(); @@ -59,8 +59,8 @@ class AuthService extends BaseAdminService */ public function checkRole(Request $request){ - $rule = trim(strtolower($request->rule()->getRule())); - $method = trim(strtolower($request->method())); + $rule = strtolower(trim($request->rule()->getRule())); + $method = strtolower(trim($request->method())); $site_info = (new AuthSiteService())->getSiteInfo(); if($method != 'get'){ if($site_info['status'] == SiteDict::EXPIRE) throw new AuthException('SITE_EXPIRE_NOT_ALLOW'); @@ -78,7 +78,7 @@ class AuthService extends BaseAdminService if(!empty($auth_role_list[$method]) && in_array($rule, $auth_role_list[$method])) return true; - throw new Exception('NO_PERMISSION'); + throw new AuthException('NO_PERMISSION'); } @@ -147,6 +147,7 @@ class AuthService extends BaseAdminService * 修改用户权限 * @param string $field * @param $data + * @return bool */ public function modifyAuth(string $field, $data){ return (new SiteUserService())->modify($this->uid, $field, $data); diff --git a/niucloud/app/service/admin/auth/AuthSiteService.php b/niucloud/app/service/admin/auth/AuthSiteService.php index 09ef67db8..aeb619022 100644 --- a/niucloud/app/service/admin/auth/AuthSiteService.php +++ b/niucloud/app/service/admin/auth/AuthSiteService.php @@ -13,13 +13,15 @@ namespace app\service\admin\auth; use app\dict\sys\AppTypeDict; -use app\dict\sys\MenuDict; use app\dict\sys\MenuTypeDict; use app\model\site\Site; use app\model\sys\SysMenu; use app\service\admin\site\SiteService; use core\base\BaseAdminService; -use think\facade\Cache; +use think\Collection; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; /** * 用户服务层 @@ -63,7 +65,8 @@ class AuthSiteService extends BaseAdminService /** * 通过站点id获取菜单列表 - * @param int $site_id + * @param int $is_tree + * @param int|string $status * @return mixed */ public function getMenuList(int $is_tree, int|string $status){ @@ -72,7 +75,7 @@ class AuthSiteService extends BaseAdminService /** * 通过站点id获取菜单列表 - * @param int $site_id + * @param int|string $status * @return mixed */ public function getApiList(int|string $status){ @@ -81,10 +84,10 @@ class AuthSiteService extends BaseAdminService /** * 查询当前站点可以单独显示的菜单(仅支持站点端调用) - * @return SysMenu[]|array|\think\Collection - * @throws \think\db\exception\DataNotFoundException - * @throws \think\db\exception\DbException - * @throws \think\db\exception\ModelNotFoundException + * @return array|SysMenu[] + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function getShowMenuList(){ $menu_keys = (new SiteService())->getMenuIdsBySiteId($this->site_id, 1); diff --git a/niucloud/app/service/admin/auth/ConfigService.php b/niucloud/app/service/admin/auth/ConfigService.php index 1d21743f3..e91caec89 100644 --- a/niucloud/app/service/admin/auth/ConfigService.php +++ b/niucloud/app/service/admin/auth/ConfigService.php @@ -32,7 +32,7 @@ class ConfigService extends BaseAdminService /** * 获取注册与登录设置 - * @param $site_id + * @return array */ public function getConfig() { @@ -47,9 +47,8 @@ class ConfigService extends BaseAdminService /** * 注册与登录设置 - * @param $site_id - * @param $data - * @return SysConfig|bool|Model + * @param array $data + * @return true */ public function setConfig(array $data) { diff --git a/niucloud/app/service/admin/auth/LoginService.php b/niucloud/app/service/admin/auth/LoginService.php index eab3f884d..e148eb74f 100644 --- a/niucloud/app/service/admin/auth/LoginService.php +++ b/niucloud/app/service/admin/auth/LoginService.php @@ -17,10 +17,12 @@ use app\service\admin\captcha\CaptchaService; use app\service\admin\site\SiteService; use app\service\admin\user\UserRoleService; use app\service\admin\user\UserService; +use app\service\core\sys\CoreConfigService; use core\base\BaseAdminService; use core\exception\AuthException; use core\util\TokenAuth; use Exception; +use Throwable; /** * 登录服务层 @@ -40,13 +42,12 @@ class LoginService extends BaseAdminService * 用户登录 * @param string $username * @param string $password + * @param string $app_type * @return array|bool - * @throws AuthException */ public function login(string $username, string $password, string $app_type) { - - if(!in_array($app_type, array_keys(AppTypeDict::getAppType()))) throw new AuthException('APP_TYPE_NOT_EXIST'); + if(!array_key_exists($app_type, AppTypeDict::getAppType())) throw new AuthException('APP_TYPE_NOT_EXIST'); $config = (new ConfigService())->getConfig(); switch($app_type){ @@ -77,7 +78,8 @@ class LoginService extends BaseAdminService }else if($app_type == AppTypeDict::SITE){ $default_site_id = (new UserRoleService())->getUserDefaultSiteId($userinfo->uid); if(!($default_site_id > 0)) throw new AuthException('ADMIN_USER_CAN_NOT_LOGIN_IN_SITE'); - + }else{ + throw new AuthException('APP_TYPE_NOT_EXIST'); } //修改用户登录信息 $userinfo->last_time = time(); @@ -98,12 +100,15 @@ class LoginService extends BaseAdminService 'site_id' => $default_site_id, ]; $data['site_info'] = (new SiteService())->getInfo($data['site_id']); + // 获取站点布局 + $layout_config = (new CoreConfigService())->getConfig($data['site_id'], 'SITE_LAYOUT'); + $data['layout'] = empty($layout_config) ? 'default' : $layout_config['value']['key']; return $data; } /** * 登陆退出(当前账户) (todo 这儿应该登出当前token, (登出一个账号还是全端口登出)) - * @return void + * @return true */ public function logout() { @@ -113,20 +118,21 @@ class LoginService extends BaseAdminService /** * 创建token - * @param $userinfo + * @param SysUser $userinfo + * @param string $app_type * @return array */ public function createToken(SysUser $userinfo, string $app_type) { $expire_time = env('system.admin_token_expire_time') ?? 3600; - $token_info = TokenAuth::createToken($userinfo->uid, AppTypeDict::ADMIN, ['uid' => $userinfo->uid, 'username' => $userinfo->username], $expire_time); - return $token_info; + return TokenAuth::createToken($userinfo->uid, AppTypeDict::ADMIN, ['uid' => $userinfo->uid, 'username' => $userinfo->username], $expire_time); } /** * 清理token - * @param $uid - * @param string $type + * @param int $uid + * @param string|null $type + * @param string|null $token */ public static function clearToken(int $uid, ?string $type = '', ?string $token = '') { @@ -141,9 +147,8 @@ class LoginService extends BaseAdminService /** * 解析token - * @param string $token - * @return mixed - * @throws Exception + * @param string|null $token + * @return array */ public function parseToken(?string $token) { @@ -154,7 +159,7 @@ class LoginService extends BaseAdminService //暴力操作,截停所有异常覆盖为token失效 try { $token_info = TokenAuth::parseToken($token, AppTypeDict::ADMIN); - } catch ( \Throwable $e ) { + } catch ( Throwable $e ) { // if(env('app_debug', false)){ // throw new AuthException($e->getMessage(), 401); // }else{ diff --git a/niucloud/app/service/admin/captcha/CaptchaService.php b/niucloud/app/service/admin/captcha/CaptchaService.php index 248557ebe..700d53afe 100644 --- a/niucloud/app/service/admin/captcha/CaptchaService.php +++ b/niucloud/app/service/admin/captcha/CaptchaService.php @@ -28,7 +28,6 @@ class CaptchaService extends BaseAdminService /** * 创建验证码 - * @param array|null $data * @return array|null */ public function create(){ diff --git a/niucloud/app/service/admin/channel/H5Service.php b/niucloud/app/service/admin/channel/H5Service.php index cd3cf3160..88138af77 100644 --- a/niucloud/app/service/admin/channel/H5Service.php +++ b/niucloud/app/service/admin/channel/H5Service.php @@ -42,8 +42,7 @@ class H5Service extends BaseAdminService $data = [ 'is_open' => $value['is_open'] ]; - $res = $this->core_config_service->setConfig($this->site_id,ConfigKeyDict::H5, $data); - return $res; + return $this->core_config_service->setConfig($this->site_id,ConfigKeyDict::H5, $data); } /** diff --git a/niucloud/app/service/admin/diy/DiyConfigService.php b/niucloud/app/service/admin/diy/DiyConfigService.php index 7a374d725..d5e82b856 100644 --- a/niucloud/app/service/admin/diy/DiyConfigService.php +++ b/niucloud/app/service/admin/diy/DiyConfigService.php @@ -11,8 +11,10 @@ namespace app\service\admin\diy; +use app\model\sys\SysConfig; use app\service\core\diy\CoreDiyConfigService; use core\base\BaseAdminService; +use think\Model; /** * 自定义页面相关配置服务层 @@ -34,7 +36,7 @@ class DiyConfigService extends BaseAdminService /** * 底部导航配置 * @param $data - * @return \app\model\sys\SysConfig|bool|\think\Model + * @return SysConfig|bool|Model */ public function setBottomConfig($data) { diff --git a/niucloud/app/service/admin/diy/DiyRouteService.php b/niucloud/app/service/admin/diy/DiyRouteService.php index 907004176..6b4932990 100644 --- a/niucloud/app/service/admin/diy/DiyRouteService.php +++ b/niucloud/app/service/admin/diy/DiyRouteService.php @@ -43,7 +43,7 @@ class DiyRouteService extends BaseAdminService if (!empty($v[ 'child_list' ])) { foreach ($v[ 'child_list' ] as $ck => $cv) { if (!empty($cv[ 'url' ])) { - if (empty($where[ 'title' ]) || ( !empty($where[ 'title' ]) && strpos($cv[ 'title' ], $where[ 'title' ]) !== false )) { + if (empty($where[ 'title' ]) || ( !empty($where[ 'title' ]) && str_contains($cv['title'], $where['title']))) { $diy_route_list[] = [ 'title' => $cv[ 'title' ], 'name' => $cv[ 'name' ], @@ -71,8 +71,7 @@ class DiyRouteService extends BaseAdminService $order = ''; $search_model = $this->model->where([ [ 'site_id', '=', $this->site_id ] ])->withSearch([ "title" ], $where)->field($field)->order($order); - $list = $this->pageQuery($search_model); - return $list; + return $this->pageQuery($search_model); } /** @@ -84,8 +83,7 @@ class DiyRouteService extends BaseAdminService { $field = 'title,name,page,share,is_share,sort'; - $info = $this->model->field($field)->where([ [ 'id', '=', $id ], [ 'site_id', '=', $this->site_id ] ])->findOrEmpty()->toArray(); - return $info; + return $this->model->field($field)->where([ [ 'id', '=', $id ], [ 'site_id', '=', $this->site_id ] ])->findOrEmpty()->toArray(); } /** @@ -96,8 +94,7 @@ class DiyRouteService extends BaseAdminService public function getInfoByName(string $name) { $field = 'id,title,name,page,share,is_share,sort'; - $info = $this->model->field($field)->where([ [ 'name', '=', $name ], [ 'site_id', '=', $this->site_id ] ])->findOrEmpty()->toArray(); - return $info; + return $this->model->field($field)->where([ [ 'name', '=', $name ], [ 'site_id', '=', $this->site_id ] ])->findOrEmpty()->toArray(); } /** @@ -131,8 +128,7 @@ class DiyRouteService extends BaseAdminService */ public function del(int $id) { - $res = $this->model->where([ [ 'id', '=', $id ], [ 'site_id', '=', $this->site_id ] ])->delete(); - return $res; + return $this->model->where([ [ 'id', '=', $id ], [ 'site_id', '=', $this->site_id ] ])->delete(); } /** diff --git a/niucloud/app/service/admin/diy/DiyService.php b/niucloud/app/service/admin/diy/DiyService.php index 0046e21a9..f45c0c28b 100644 --- a/niucloud/app/service/admin/diy/DiyService.php +++ b/niucloud/app/service/admin/diy/DiyService.php @@ -18,7 +18,11 @@ use app\dict\diy\TemplateDict; use app\model\diy\Diy; use app\service\admin\sys\SystemService; use core\base\BaseAdminService; +use core\exception\AdminException; use Exception; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; use think\facade\Db; /** @@ -46,8 +50,7 @@ class DiyService extends BaseAdminService $field = 'id,site_id,title,name,template,type,mode,is_default,share,visit_count,create_time,update_time'; $order = "update_time desc"; $search_model = $this->model->where([ [ 'site_id', '=', $this->site_id ] ])->withSearch([ "title", "type", 'mode' ], $where)->field($field)->order($order)->append([ 'type_name' ]); - $list = $this->pageQuery($search_model); - return $list; + return $this->pageQuery($search_model); } /** @@ -55,15 +58,14 @@ class DiyService extends BaseAdminService * @param array $where * @param string $field * @return array - * @throws \think\db\exception\DataNotFoundException - * @throws \think\db\exception\DbException - * @throws \think\db\exception\ModelNotFoundException + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function getList(array $where = [], $field = 'id,site_id,title,name,template,type,mode,is_default,share,visit_count,create_time,update_time') { $order = "update_time desc"; - $list = $this->model->where([ [ [ 'site_id', '=', $this->site_id ] ] ])->withSearch([ "title", "type", 'mode' ], $where)->field($field)->select()->order($order)->toArray(); - return $list; + return $this->model->where([ [ [ 'site_id', '=', $this->site_id ] ] ])->withSearch([ "title", "type", 'mode' ], $where)->field($field)->select()->order($order)->toArray(); } /** @@ -74,22 +76,20 @@ class DiyService extends BaseAdminService public function getInfo(int $id) { $field = 'id,site_id,title,name,template,type,mode,value,is_default,is_change,share,visit_count'; - $info = $this->model->field($field)->where([ [ 'id', '=', $id ], [ 'site_id', '=', $this->site_id ] ])->findOrEmpty()->toArray(); - return $info; + return $this->model->field($field)->where([ [ 'id', '=', $id ], [ 'site_id', '=', $this->site_id ] ])->findOrEmpty()->toArray(); } public function getInfoByName(string $name) { $field = 'id,site_id,title,name,template,type,mode,value,is_default,is_change,share,visit_count'; - $info = $this->model->field($field)->where([ [ 'name', '=', $name ], [ 'site_id', '=', $this->site_id ], [ 'is_default', '=', 1 ] ])->findOrEmpty()->toArray(); - return $info; + return $this->model->field($field)->where([ [ 'name', '=', $name ], [ 'site_id', '=', $this->site_id ], [ 'is_default', '=', 1 ] ])->findOrEmpty()->toArray(); } /** * 查询数量 * @param array $where * @return int - * @throws \think\db\exception\DbException + * @throws DbException */ public function getCount(array $where = []) { @@ -140,8 +140,7 @@ class DiyService extends BaseAdminService */ public function del(int $id) { - $res = $this->model->where([ [ 'id', '=', $id ], [ 'site_id', '=', $this->site_id ] ])->delete(); - return $res; + return $this->model->where([ [ 'id', '=', $id ], [ 'site_id', '=', $this->site_id ] ])->delete(); } /** @@ -162,9 +161,9 @@ class DiyService extends BaseAdminService $this->model->where([ [ 'id', '=', $id ], [ 'site_id', '=', $this->site_id ] ])->update([ 'is_default' => 1, 'update_time' => time() ]); Db::commit(); return true; - } catch (\Exception $e) { + } catch ( Exception $e) { Db::rollback(); - throw new Exception($e->getMessage()); + throw new AdminException($e->getMessage()); } } @@ -172,6 +171,7 @@ class DiyService extends BaseAdminService * 页面加载初始化 * @param array $params * @return array + * @throws DbException */ public function getInit(array $params = []) { @@ -195,8 +195,8 @@ class DiyService extends BaseAdminService } else { // 新页面赋值 - $title = $params[ 'title' ] ? $params[ 'title' ] : '页面' . $time; - $type = $params[ 'type' ] ? $params[ 'type' ] : 'DIY_PAGE'; + $title = $params[ 'title' ] ?: '页面' . $time; + $type = $params[ 'type' ] ?: 'DIY_PAGE'; $name = $type == 'DIY_PAGE' ? 'DIY_PAGE_RANDOM_' . $time : $type; $type_name = ''; $template_name = $params[ 'template' ] ?? ''; // 页面模板名称 @@ -280,8 +280,7 @@ class DiyService extends BaseAdminService } $sort_arr [] = $cv[ 'sort' ]; - unset($data[ $k ][ 'list' ][ $ck ][ 'sort' ]); - unset($data[ $k ][ 'list' ][ $ck ][ 'support_page' ]); + unset($data[$k]['list'][$ck]['sort'], $data[$k]['list'][$ck]['support_page']); } array_multisort($sort_arr, SORT_ASC, $data[ $k ][ 'list' ]); //排序,根据 sort 排序 } @@ -292,6 +291,9 @@ class DiyService extends BaseAdminService /** * 获取自定义链接 * @return array + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function getLink() { @@ -341,7 +343,7 @@ class DiyService extends BaseAdminService /** * 获取页面模板 * @param array $params - * @return array|string + * @return array */ public function getTemplate($params = []) { @@ -366,10 +368,7 @@ class DiyService extends BaseAdminService public function getPageData($type, $name) { $pages = PagesDict::getPages([ 'type' => $type ]); - if (isset($pages[ $name ])) { - return $pages[ $name ]; - } - return []; + return $pages[$name] ?? []; } /** @@ -392,7 +391,10 @@ class DiyService extends BaseAdminService /** * 获取页面装修列表 - * @return array|string|null + * @return array + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function getDecoratePage() { @@ -463,7 +465,7 @@ class DiyService extends BaseAdminService /** * 切换模板 * @param array $params - * @return array|mixed + * @return array * @throws Exception */ public function changeTemplate(array $params = []) diff --git a/niucloud/app/service/admin/generator/Generate.php b/niucloud/app/service/admin/generator/Generate.php index 7b2de0754..06c6f3022 100644 --- a/niucloud/app/service/admin/generator/Generate.php +++ b/niucloud/app/service/admin/generator/Generate.php @@ -62,7 +62,7 @@ class Generate public function delOutFiles() { // 删除runtime目录制定文件夹 - !is_dir($this->outPath) && mkdirs($this->outPath, 0777, true); + !is_dir($this->outPath) && mkdirs($this->outPath); del_target_dir($this->outPath, false); } diff --git a/niucloud/app/service/admin/generator/GenerateService.php b/niucloud/app/service/admin/generator/GenerateService.php index bd24e3676..3d820da34 100644 --- a/niucloud/app/service/admin/generator/GenerateService.php +++ b/niucloud/app/service/admin/generator/GenerateService.php @@ -35,15 +35,14 @@ class GenerateService extends BaseAdminService /** * 获取代码生成列表 * @param array $where - * @return HasOne + * @return array */ public function getPage(array $where = []) { $field = 'id,table_name,table_content,class_name,edit_type,create_time'; $order = 'create_time desc'; $search_model = (new GenerateTable())->withSearch(['table_name', 'table_content'], $where)->field($field)->order($order); - $list = $this->pageQuery($search_model); - return $list; + return $this->pageQuery($search_model); } /** @@ -129,7 +128,7 @@ class GenerateService extends BaseAdminService return $table_id; } catch ( Exception $e) { Db::rollback(); - throw new Exception($e->getMessage()); + throw new AdminException($e->getMessage()); } } @@ -225,7 +224,7 @@ class GenerateService extends BaseAdminService $flag = array_unique(array_column($table_info, 'table_name')); $flag = implode(',', $flag); - $generator->setFlag(md5($flag . time()), false); + $generator->setFlag(md5($flag . time())); $generator->generate($table_info); @@ -272,7 +271,7 @@ class GenerateService extends BaseAdminService */ public static function getDbFieldType(string $type): string { - if (0 === strpos($type, 'set') || 0 === strpos($type, 'dict')) { + if (str_starts_with($type, 'set') || str_starts_with($type, 'dict')) { $result = 'string'; } elseif (preg_match('/(double|float|decimal|real|numeric)/is', $type)) { $result = 'float'; @@ -280,11 +279,11 @@ class GenerateService extends BaseAdminService $result = 'int'; } elseif (preg_match('/bool/is', $type)) { $result = 'bool'; - } elseif (0 === strpos($type, 'timestamp')) { + } elseif (str_starts_with($type, 'timestamp')) { $result = 'timestamp'; - } elseif (0 === strpos($type, 'datetime')) { + } elseif (str_starts_with($type, 'datetime')) { $result = 'datetime'; - } elseif (0 === strpos($type, 'date')) { + } elseif (str_starts_with($type, 'date')) { $result = 'date'; } else { $result = 'string'; @@ -306,8 +305,7 @@ class GenerateService extends BaseAdminService if (!empty($params['comment'])) { $sql .= "AND comment LIKE '%" . $params['comment'] . "%'"; } - $table = Db::query($sql); - return $table; + return Db::query($sql); } } \ No newline at end of file diff --git a/niucloud/app/service/admin/generator/core/AdminApiRouteGenerator.php b/niucloud/app/service/admin/generator/core/AdminApiRouteGenerator.php index f37a68059..9e9502668 100644 --- a/niucloud/app/service/admin/generator/core/AdminApiRouteGenerator.php +++ b/niucloud/app/service/admin/generator/core/AdminApiRouteGenerator.php @@ -22,7 +22,7 @@ class AdminApiRouteGenerator extends BaseGenerator { /** * 替换模板中的变量 - * @return mixed|void + * @return void */ public function replaceText() { diff --git a/niucloud/app/service/admin/generator/core/BaseGenerator.php b/niucloud/app/service/admin/generator/core/BaseGenerator.php index 6647e00fc..bb2d75b82 100644 --- a/niucloud/app/service/admin/generator/core/BaseGenerator.php +++ b/niucloud/app/service/admin/generator/core/BaseGenerator.php @@ -312,11 +312,12 @@ abstract class BaseGenerator /** * 获取缺省值 - * @param $type + * @param string $type + * @return int|string */ public function getDefault(string $type) { - if (0 === strpos($type, 'set') || 0 === strpos($type, 'dict')) { + if (str_starts_with($type, 'set') || str_starts_with($type, 'dict')) { $result = '""'; } elseif (preg_match('/(int|serial|bit)/is', $type)) { $result = '0'; @@ -324,11 +325,11 @@ abstract class BaseGenerator $result = '0.00'; } elseif (preg_match('/bool/is', $type)) { $result = 'false'; - } elseif (0 === strpos($type, 'timestamp')) { + } elseif (str_starts_with($type, 'timestamp')) { $result = time(); - } elseif (0 === strpos($type, 'datetime')) { + } elseif (str_starts_with($type, 'datetime')) { $result = date('Y-m-d H:i:s'); - } elseif (0 === strpos($type, 'date')) { + } elseif (str_starts_with($type, 'date')) { $result = date('Y-m-d H:i:s'); } else { $result = '""'; @@ -348,7 +349,7 @@ abstract class BaseGenerator /** * 代码生成备注时间 - * @return false|string + * @return string */ public function getNoteDate() { diff --git a/niucloud/app/service/admin/generator/core/ControllerGenerator.php b/niucloud/app/service/admin/generator/core/ControllerGenerator.php index 92e7d3d62..25a103592 100644 --- a/niucloud/app/service/admin/generator/core/ControllerGenerator.php +++ b/niucloud/app/service/admin/generator/core/ControllerGenerator.php @@ -22,7 +22,7 @@ class ControllerGenerator extends BaseGenerator { /** * 替换模板中的变量 - * @return mixed|void + * @return void */ public function replaceText() { @@ -80,7 +80,7 @@ class ControllerGenerator extends BaseGenerator /** * 代码验证 - * @return false|string + * @return string */ public function getValidate() { @@ -89,14 +89,14 @@ class ControllerGenerator extends BaseGenerator /** * 添加字段 - * @return false|string + * @return string */ public function getAddField() { $str = ''; $last_field = end($this->table['fields'])['column_name']; - foreach ($this->table['fields'] as $k => $v){ + foreach ($this->table['fields'] as $v){ if(!$v['is_pk'] && $v['is_insert']){ $str .= ' ["'.$v['column_name'].'",'.$this->getDefault($v['column_type']).']'; if($last_field != $v['column_name']) $str .= ','.PHP_EOL; @@ -107,13 +107,13 @@ class ControllerGenerator extends BaseGenerator /** * 编辑字段 - * @return false|string + * @return string */ public function getEditField() { $str = ''; $last_field = end($this->table['fields'])['column_name']; - foreach ($this->table['fields'] as $k => $v){ + foreach ($this->table['fields'] as $v){ if(!$v['is_pk'] && $v['is_update']){ $str .= ' ["'.$v['column_name'].'",'.$this->getDefault($v['column_type']).']'; if($last_field != $v['column_name']) $str .= ','.PHP_EOL; @@ -130,7 +130,7 @@ class ControllerGenerator extends BaseGenerator { $str = ''; $last_field = end($this->table['fields'])['column_name']; - foreach ($this->table['fields'] as $k => $v){ + foreach ($this->table['fields'] as $v){ if(!$v['is_pk'] && $v['is_search']){ if($v['view_type'] == 'datetime'){ $str .= ' ["'.$v['column_name'].'",'.'["",""]'.']'; diff --git a/niucloud/app/service/admin/generator/core/ModelGenerator.php b/niucloud/app/service/admin/generator/core/ModelGenerator.php index f06f036dc..dc53677c4 100644 --- a/niucloud/app/service/admin/generator/core/ModelGenerator.php +++ b/niucloud/app/service/admin/generator/core/ModelGenerator.php @@ -26,7 +26,7 @@ class ModelGenerator extends BaseGenerator /** * 替换模板中的变量 - * @return mixed|void + * @return void */ public function replaceText() { @@ -132,7 +132,7 @@ class ModelGenerator extends BaseGenerator public function getSearchContent(array $column_info){ $type = $column_info['query_type']; - $result = match ($type) { + return match ($type) { '<>' => '"' . $column_info['column_name'] . '", "<>", $value', '!=' => '"' . $column_info['column_name'] . '", "<>", $value', '>' => '"' . $column_info['column_name'] . '", ">", $value', @@ -143,8 +143,6 @@ class ModelGenerator extends BaseGenerator 'BETWEEN' => '"' . $column_info['column_name'] . '", $value[0], $value[1] ', default => '"' . $column_info['column_name'] . '", $value', }; - - return $result; } /** diff --git a/niucloud/app/service/admin/generator/core/ServiceGenerator.php b/niucloud/app/service/admin/generator/core/ServiceGenerator.php index e93bd1b88..99f92e004 100644 --- a/niucloud/app/service/admin/generator/core/ServiceGenerator.php +++ b/niucloud/app/service/admin/generator/core/ServiceGenerator.php @@ -24,7 +24,7 @@ class ServiceGenerator extends BaseGenerator /** * 替换模板中的变量 - * @return mixed|void + * @return void */ public function replaceText() { diff --git a/niucloud/app/service/admin/generator/core/ValidateGenerator.php b/niucloud/app/service/admin/generator/core/ValidateGenerator.php index 3a93ccafb..afbd997a8 100644 --- a/niucloud/app/service/admin/generator/core/ValidateGenerator.php +++ b/niucloud/app/service/admin/generator/core/ValidateGenerator.php @@ -24,7 +24,7 @@ class ValidateGenerator extends BaseGenerator /** * 替换模板中的变量 - * @return mixed|void + * @return void */ public function replaceText() { @@ -59,7 +59,7 @@ class ValidateGenerator extends BaseGenerator /** * 验证规则 - * @return mixed|string + * @return string */ public function getRule() { @@ -76,7 +76,7 @@ class ValidateGenerator extends BaseGenerator /** * 验证提示 - * @return mixed|string + * @return string */ public function getMessage() { @@ -85,7 +85,7 @@ class ValidateGenerator extends BaseGenerator /** * 验证字段 - * @return mixed|string + * @return string */ public function getScene() { diff --git a/niucloud/app/service/admin/generator/core/WebApiGenerator.php b/niucloud/app/service/admin/generator/core/WebApiGenerator.php index 8e7626b9c..79e383f4d 100644 --- a/niucloud/app/service/admin/generator/core/WebApiGenerator.php +++ b/niucloud/app/service/admin/generator/core/WebApiGenerator.php @@ -26,7 +26,7 @@ class WebApiGenerator extends BaseGenerator /** * 替换模板中的变量 - * @return mixed|void + * @return void */ public function replaceText() { @@ -35,6 +35,7 @@ class WebApiGenerator extends BaseGenerator '{NOTES}', '{UCASE_CLASS_NAME}', '{LCASE_CLASS_NAME}', + '{ROUTE_NAME}', '{PK}', '{UCASE_NAME}', '{MODULE_NAME}', @@ -43,7 +44,8 @@ class WebApiGenerator extends BaseGenerator $new = [ $this->table['table_content'], $this->getUCaseClassName(), - $this->getLCaseClassName(), + strtolower($this->getLCaseClassName()), + $this->getRouteName(), $this->getPk(), $this->getUCaseName(), $this->moduleName, @@ -54,10 +56,22 @@ class WebApiGenerator extends BaseGenerator $this->setText($text); } - + /** + * 路由名称 + * @return string + */ + public function getRouteName() + { + //如果是某个模块下的功能,公用一个路由 + if($this->moduleName && ($this->getLCaseTableName() != $this->moduleName) && $this->className){ + return Str::lower($this->className); + }else{ + return $this->getLCaseTableName(); + } + } /** * 获取文件生成到模块的文件夹路径 - * @return mixed|void + * @return string */ public function getModuleOutDir() { diff --git a/niucloud/app/service/admin/generator/core/WebEditGenerator.php b/niucloud/app/service/admin/generator/core/WebEditGenerator.php index 2f76c04f4..37dd25158 100644 --- a/niucloud/app/service/admin/generator/core/WebEditGenerator.php +++ b/niucloud/app/service/admin/generator/core/WebEditGenerator.php @@ -26,7 +26,7 @@ class WebEditGenerator extends BaseGenerator /** * 替换模板中的变量 - * @return mixed|void + * @return false|void */ public function replaceText() { @@ -122,8 +122,8 @@ class WebEditGenerator extends BaseGenerator if (in_array($column['column_type'], $intFieldValue)) { $vmItemValue = 'parseInt(item.value)'; } - array_push($old, '{ITEM_VALUE}'); - array_push($new, $vmItemValue); + $old[] = '{ITEM_VALUE}'; + $new[] = $vmItemValue; } $content .= $this->replaceFileText($old, $new, $vmPath) . PHP_EOL; @@ -134,8 +134,7 @@ class WebEditGenerator extends BaseGenerator $content = substr($content, 0, -1); } - $content = $this->setBlankSpace($content, ' '); - return $content; + return $this->setBlankSpace($content, ' '); } @@ -172,7 +171,7 @@ class WebEditGenerator extends BaseGenerator /** * 表单验证内容 - * @return false|string + * @return string */ public function getFormValidate() { @@ -210,14 +209,13 @@ class WebEditGenerator extends BaseGenerator $isExist[] = $column['column_name']; } - $content = substr($content, 0, -2); - return $content; + return substr($content, 0, -2); } /** * 获取文件生成到模块的文件夹路径 - * @return mixed|void + * @return string */ public function getModuleOutDir() { diff --git a/niucloud/app/service/admin/generator/core/WebEditLangGenerator.php b/niucloud/app/service/admin/generator/core/WebEditLangGenerator.php index 51695d371..bf88992f5 100644 --- a/niucloud/app/service/admin/generator/core/WebEditLangGenerator.php +++ b/niucloud/app/service/admin/generator/core/WebEditLangGenerator.php @@ -26,7 +26,7 @@ class WebEditLangGenerator extends BaseGenerator /** * 替换模板中的变量 - * @return mixed|void + * @return void */ public function replaceText() { @@ -70,7 +70,7 @@ class WebEditLangGenerator extends BaseGenerator /** * 获取文件生成到模块的文件夹路径 - * @return mixed|void + * @return string */ public function getModuleOutDir() { @@ -108,9 +108,9 @@ class WebEditLangGenerator extends BaseGenerator return ''; } if($this->className){ - return $this->moduleName.'.'.Str::lower($this->className).'.edit.json'; + return $this->moduleName.'.'.Str::lower($this->className).'_edit.json'; } - return $this->moduleName.'.edit.json'; + return $this->moduleName.'.'.'edit.json'; } } \ No newline at end of file diff --git a/niucloud/app/service/admin/generator/core/WebEditPageGenerator.php b/niucloud/app/service/admin/generator/core/WebEditPageGenerator.php index 0dfbd7796..657612f41 100644 --- a/niucloud/app/service/admin/generator/core/WebEditPageGenerator.php +++ b/niucloud/app/service/admin/generator/core/WebEditPageGenerator.php @@ -25,7 +25,7 @@ class WebEditPageGenerator extends BaseGenerator /** * 替换模板中的变量 - * @return mixed|void + * @return false|void */ public function replaceText() { @@ -126,8 +126,8 @@ class WebEditPageGenerator extends BaseGenerator if (in_array($column['column_type'], $intFieldValue)) { $vmItemValue = 'parseInt(item.value)'; } - array_push($old, '{ITEM_VALUE}'); - array_push($new, $vmItemValue); + $old[] = '{ITEM_VALUE}'; + $new[] = $vmItemValue; } $content .= $this->replaceFileText($old, $new, $vmPath) . PHP_EOL; @@ -138,8 +138,7 @@ class WebEditPageGenerator extends BaseGenerator $content = substr($content, 0, -1); } - $content = $this->setBlankSpace($content, ' '); - return $content; + return $this->setBlankSpace($content, ' '); } @@ -178,7 +177,7 @@ class WebEditPageGenerator extends BaseGenerator /** * 表单验证内容 - * @return false|string + * @return string */ public function getFormValidate() { @@ -216,14 +215,13 @@ class WebEditPageGenerator extends BaseGenerator $isExist[] = $column['column_name']; } - $content = substr($content, 0, -2); - return $content; + return substr($content, 0, -2); } /** * 获取文件生成到模块的文件夹路径 - * @return mixed|void + * @return string */ public function getModuleOutDir() { @@ -265,7 +263,7 @@ class WebEditPageGenerator extends BaseGenerator if($this->className){ return Str::lower($this->className).'_edit.vue'; } - return Str::lower($this->getTableName()).'_edit.vue'; + return 'edit.vue'; } } \ No newline at end of file diff --git a/niucloud/app/service/admin/generator/core/WebIndexGenerator.php b/niucloud/app/service/admin/generator/core/WebIndexGenerator.php index 040b996e5..e8e3f87e0 100644 --- a/niucloud/app/service/admin/generator/core/WebIndexGenerator.php +++ b/niucloud/app/service/admin/generator/core/WebIndexGenerator.php @@ -27,7 +27,7 @@ class WebIndexGenerator extends BaseGenerator /** * 替换模板中的变量 - * @return mixed|void + * @return void */ public function replaceText() { @@ -195,8 +195,7 @@ class WebIndexGenerator extends BaseGenerator $content = substr($content, 0, -1); } - $content = $this->setBlankSpace($content, ' '); - return $content; + return $this->setBlankSpace($content, ' '); } /** @@ -295,7 +294,7 @@ class WebIndexGenerator extends BaseGenerator /** * 获取文件生成到模块的文件夹路径 - * @return mixed|void + * @return string */ public function getModuleOutDir() { @@ -325,8 +324,8 @@ class WebIndexGenerator extends BaseGenerator */ public function getFileName() { - if($this->className) return Str::lower($this->className).'.vue'; - return Str::lower($this->getTableName()).'.vue'; + if($this->className) return Str::lower($this->className).'_list.vue'; + return 'list.vue'; } diff --git a/niucloud/app/service/admin/generator/core/WebLangGenerator.php b/niucloud/app/service/admin/generator/core/WebLangGenerator.php index 7f3def4eb..63ac08e96 100644 --- a/niucloud/app/service/admin/generator/core/WebLangGenerator.php +++ b/niucloud/app/service/admin/generator/core/WebLangGenerator.php @@ -26,7 +26,7 @@ class WebLangGenerator extends BaseGenerator /** * 替换模板中的变量 - * @return mixed|void + * @return void */ public function replaceText() { @@ -51,11 +51,11 @@ class WebLangGenerator extends BaseGenerator } if($this->table['edit_type'] == 1 && ($column['is_insert'] || $column['is_update'])){ - if(strpos($lang, '"'.Str::camel($column['column_name']).'"') === false){ + if(!str_contains($lang, '"' . Str::camel($column['column_name']) . '"')){ $lang .= '"' . Str::camel($column['column_name']) . '":"' . $column['column_comment'] . '",' . PHP_EOL; } $placeholder_text = '请输入'; - if(strpos($lang, '"'.Str::camel($column['column_name']).'Placeholder"') === false){ + if(!str_contains($lang, '"' . Str::camel($column['column_name']) . 'Placeholder"')){ $lang .= '"'.Str::camel($column['column_name']) .'Placeholder":"'.$placeholder_text.$column['column_comment'].'",'.PHP_EOL; } @@ -71,7 +71,7 @@ class WebLangGenerator extends BaseGenerator /** * 获取文件生成到模块的文件夹路径 - * @return mixed|void + * @return string */ public function getModuleOutDir() { @@ -100,7 +100,7 @@ class WebLangGenerator extends BaseGenerator public function getFileName() { if($this->className){ - return $this->moduleName.'.'.Str::lower($this->className).'.json'; + return $this->moduleName.'.'.Str::lower($this->className).'_list.json'; } return $this->moduleName.'.list.json'; } diff --git a/niucloud/app/service/admin/generator/vm/web_api.vm b/niucloud/app/service/admin/generator/vm/web_api.vm index abc6bd53b..a52005eb4 100644 --- a/niucloud/app/service/admin/generator/vm/web_api.vm +++ b/niucloud/app/service/admin/generator/vm/web_api.vm @@ -8,7 +8,7 @@ import request from '@/utils/request' * @returns */ export function get{UCASE_NAME}List(params: Record) { - return request.get(`{MODULE_NAME}/{LCASE_CLASS_NAME}`, {params}) + return request.get(`{MODULE_NAME}/{ROUTE_NAME}`, {params}) } /** @@ -17,7 +17,7 @@ export function get{UCASE_NAME}List(params: Record) { * @returns */ export function get{UCASE_NAME}Info({PK}: number) { - return request.get(`{MODULE_NAME}/{LCASE_CLASS_NAME}/${{PK}}`); + return request.get(`{MODULE_NAME}/{ROUTE_NAME}/${{PK}}`); } /** @@ -26,7 +26,7 @@ export function get{UCASE_NAME}Info({PK}: number) { * @returns */ export function add{UCASE_NAME}(params: Record) { - return request.post('{MODULE_NAME}/{LCASE_CLASS_NAME}', params, { showErrorMessage: true, showSuccessMessage: true }) + return request.post('{MODULE_NAME}/{ROUTE_NAME}', params, { showErrorMessage: true, showSuccessMessage: true }) } /** @@ -36,7 +36,7 @@ export function add{UCASE_NAME}(params: Record) { * @returns */ export function edit{UCASE_NAME}(params: Record) { - return request.put(`{MODULE_NAME}/{LCASE_CLASS_NAME}/${params.{PK}}`, params, { showErrorMessage: true, showSuccessMessage: true }) + return request.put(`{MODULE_NAME}/{ROUTE_NAME}/${params.{PK}}`, params, { showErrorMessage: true, showSuccessMessage: true }) } /** @@ -45,6 +45,6 @@ export function edit{UCASE_NAME}(params: Record) { * @returns */ export function delete{UCASE_NAME}({PK}: number) { - return request.delete(`{MODULE_NAME}/{LCASE_CLASS_NAME}/${{PK}}`, { showErrorMessage: true, showSuccessMessage: true }) + return request.delete(`{MODULE_NAME}/{ROUTE_NAME}/${{PK}}`, { showErrorMessage: true, showSuccessMessage: true }) } diff --git a/niucloud/app/service/admin/generator/vm/web_edit_page.vm b/niucloud/app/service/admin/generator/vm/web_edit_page.vm index 4993925eb..c3ce648e8 100644 --- a/niucloud/app/service/admin/generator/vm/web_edit_page.vm +++ b/niucloud/app/service/admin/generator/vm/web_edit_page.vm @@ -67,7 +67,7 @@ const onSave = async (formEl: FormInstance | undefined) => { loading.value = true let data = formData - const save = id ? update{UCASE_NAME} : add{UCASE_NAME} + const save = id ? edit{UCASE_NAME} : add{UCASE_NAME} save(data).then(res => { loading.value = false history.back() diff --git a/niucloud/app/service/admin/generator/vm/web_index.vm b/niucloud/app/service/admin/generator/vm/web_index.vm index abe1cc53b..fd9e36840 100644 --- a/niucloud/app/service/admin/generator/vm/web_index.vm +++ b/niucloud/app/service/admin/generator/vm/web_index.vm @@ -5,7 +5,7 @@
{{pageName}} - {{ t('addArticle') }} + {{ t('add{UCASE_NAME}') }}
diff --git a/niucloud/app/service/admin/install/InstallSystemService.php b/niucloud/app/service/admin/install/InstallSystemService.php index 040c9b504..082c295ef 100644 --- a/niucloud/app/service/admin/install/InstallSystemService.php +++ b/niucloud/app/service/admin/install/InstallSystemService.php @@ -101,11 +101,11 @@ class InstallSystemService extends BaseAdminService $refer = $value; if (isset($refer[ 'children' ])) { unset($refer[ 'children' ]); - array_push($this->menu_list, $item); + $this->menu_list[] = $item; $p_key = $refer[ 'menu_key' ]; $this->menuTreeToList($value[ 'children' ], $p_key, $app_type); } else { - array_push($this->menu_list, $item); + $this->menu_list[] = $item; } } } diff --git a/niucloud/app/service/admin/member/MemberAccountService.php b/niucloud/app/service/admin/member/MemberAccountService.php index b695016fb..c09df64ca 100644 --- a/niucloud/app/service/admin/member/MemberAccountService.php +++ b/niucloud/app/service/admin/member/MemberAccountService.php @@ -35,7 +35,7 @@ class MemberAccountService extends BaseAdminService /** * 会员账户流水列表 * @param array $where - * @return mixed + * @return array */ public function getPage(array $where = []) { @@ -49,8 +49,7 @@ class MemberAccountService extends BaseAdminService $query->field("member.nickname, member.headimg, member.mobile, member.member_id, member.member_no"); } ])->where($member_where)->field($field)->order('create_time desc')->append([ 'from_type_name', 'account_type_name' ]); - $list = $this->pageQuery($search_model); - return $list; + return $this->pageQuery($search_model); } /** @@ -71,8 +70,7 @@ class MemberAccountService extends BaseAdminService */ public function adjustPoint(array $data) { - $res = ( new CoreMemberAccountService() )->addLog($this->site_id, $data[ 'member_id' ], 'point', $data[ 'account_data' ], 'adjust', $data[ 'memo' ], 0); - return $res; + return ( new CoreMemberAccountService() )->addLog($this->site_id, $data[ 'member_id' ], 'point', $data[ 'account_data' ], 'adjust', $data[ 'memo' ]); } /** @@ -82,14 +80,12 @@ class MemberAccountService extends BaseAdminService */ public function adjustBalance(array $data) { - $res = ( new CoreMemberAccountService() )->addLog($this->site_id, $data[ 'member_id' ], 'balance', $data[ 'account_data' ], 'adjust', $data[ 'memo' ], 0); - return $res; + return ( new CoreMemberAccountService() )->addLog($this->site_id, $data[ 'member_id' ], 'balance', $data[ 'account_data' ], 'adjust', $data[ 'memo' ]); } public function adjustMoney(array $data) { - $res = ( new CoreMemberAccountService() )->addLog($this->site_id, $data[ 'member_id' ], MemberAccountTypeDict::MONEY, $data[ 'account_data' ], 'adjust', $data[ 'memo' ], 0); - return $res; + return ( new CoreMemberAccountService() )->addLog($this->site_id, $data[ 'member_id' ], MemberAccountTypeDict::MONEY, $data[ 'account_data' ], 'adjust', $data[ 'memo' ]); } /** @@ -100,8 +96,7 @@ class MemberAccountService extends BaseAdminService public function getFromType($account_type) { if (!array_key_exists($account_type, MemberAccountTypeDict::getType())) throw new AdminException('MEMBER_TYPE_NOT_EXIST'); - $res = MemberAccountChangeTypeDict::getType($account_type); - return $res; + return MemberAccountChangeTypeDict::getType($account_type); } /** @@ -110,8 +105,7 @@ class MemberAccountService extends BaseAdminService */ public function getSumAccount(string $account_type) { - $sum = $this->model->where([ [ 'site_id', '=', $this->site_id ], [ 'account_type', '=', $account_type ] ])->sum('account_data'); - return $sum; + return $this->model->where([ [ 'site_id', '=', $this->site_id ], [ 'account_type', '=', $account_type ] ])->sum('account_data'); } /** @@ -138,8 +132,7 @@ class MemberAccountService extends BaseAdminService ]; if (!empty($member_id)) $condition[] = [ 'member_id', '=', $member_id ]; - $sum = $this->model->where($condition)->sum('account_data'); - return $sum; + return $this->model->where($condition)->sum('account_data'); } /** @@ -155,8 +148,7 @@ class MemberAccountService extends BaseAdminService ]; if (!empty($member_id)) $condition[] = [ 'member_id', '=', $member_id ]; - $sum = $this->model->where($condition)->sum('account_data'); - return $sum; + return $this->model->where($condition)->sum('account_data'); } } \ No newline at end of file diff --git a/niucloud/app/service/admin/member/MemberCashOutService.php b/niucloud/app/service/admin/member/MemberCashOutService.php index 60f0bd520..765cc1b32 100644 --- a/niucloud/app/service/admin/member/MemberCashOutService.php +++ b/niucloud/app/service/admin/member/MemberCashOutService.php @@ -30,7 +30,7 @@ class MemberCashOutService extends BaseAdminService /** * 会员提现列表 * @param array $where - * @return mixed + * @return array */ public function getPage(array $where = []) { @@ -44,8 +44,7 @@ class MemberCashOutService extends BaseAdminService $search_model = $this->model->where([['member_cash_out.site_id', '=', $this->site_id]])->withSearch(['member_id','status', 'join_create_time' => 'create_time', 'audit_time', 'transfer_time', 'transfer_type', 'cash_out_no'],$where)->with(['transfer'])->withJoin(["member" => function($query){ $query->field("member.nickname, member.headimg, member.mobile, member.member_id, member.member_no"); }])->where($member_where)->field($field)->order('create_time desc')->append(['status_name', 'transfer_status_name', 'transfer_type_name', 'account_type_name']); - $list = $this->pageQuery($search_model); - return $list; + return $this->pageQuery($search_model); } /** @@ -61,8 +60,9 @@ class MemberCashOutService extends BaseAdminService /** * @param int $id + * @param string $action * @param $data - * @return void + * @return true|null */ public function audit(int $id, string $action, $data){ $core_member_cash_out_service = new CoreMemberCashOutService(); @@ -72,8 +72,8 @@ class MemberCashOutService extends BaseAdminService /** * 转账 - * @param $id - * @param $data + * @param int $id + * @param array $data * @return true */ public function transfer(int $id, array $data){ diff --git a/niucloud/app/service/admin/member/MemberConfigService.php b/niucloud/app/service/admin/member/MemberConfigService.php index caa2d0a2f..9b6efbf2f 100644 --- a/niucloud/app/service/admin/member/MemberConfigService.php +++ b/niucloud/app/service/admin/member/MemberConfigService.php @@ -11,8 +11,10 @@ namespace app\service\admin\member; +use app\model\sys\SysConfig; use app\service\core\member\CoreMemberConfigService; use core\base\BaseAdminService; +use think\Model; /** * 会员设置 @@ -31,7 +33,8 @@ class MemberConfigService extends BaseAdminService /** * 注册登录设置 - * @param $data + * @param array $data + * @return true */ public function setLoginConfig(array $data){ return (new CoreMemberConfigService())->setLoginConfig($this->site_id, $data); @@ -46,7 +49,8 @@ class MemberConfigService extends BaseAdminService /** * 提现设置 - * @param $data + * @param array $data + * @return true */ public function setCashOutConfig(array $data){ return (new CoreMemberConfigService())->setCashOutConfig($this->site_id, $data); @@ -61,7 +65,8 @@ class MemberConfigService extends BaseAdminService /** * 会员设置 - * @param $data + * @param array $data + * @return true */ public function setMemberConfig(array $data){ return (new CoreMemberConfigService())->setMemberConfig($this->site_id, $data); diff --git a/niucloud/app/service/admin/member/MemberLabelService.php b/niucloud/app/service/admin/member/MemberLabelService.php index a455fe3ca..7fe1b5627 100644 --- a/niucloud/app/service/admin/member/MemberLabelService.php +++ b/niucloud/app/service/admin/member/MemberLabelService.php @@ -14,6 +14,10 @@ namespace app\service\admin\member; use app\model\member\MemberLabel; use app\service\core\member\CoreMemberLabelService; use core\base\BaseAdminService; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; +use think\Response; /** * 会员标签 @@ -32,40 +36,42 @@ class MemberLabelService extends BaseAdminService * 获取会员标签列表 * @param array $where * @param string $order + * @return array */ public function getPage(array $where = [], string $order = 'create_time desc') { $field = 'label_id, site_id, label_name, memo, sort, create_time, update_time'; $search_model = $this->model->where([ [ 'site_id', '=', $this->site_id ] ])->withSearch([ 'label_name'], $where)->field($field)->append(["member_num"])->order($order); - $list = $this->pageQuery($search_model); - return $list; + return $this->pageQuery($search_model); } /** * 获取会员标签信息 * @param int $label_id + * @return array */ public function getInfo(int $label_id) { $field = 'label_id, site_id, label_name, memo, sort, create_time, update_time'; - $info = $this->model->field($field)->where([['label_id', '=', $label_id], ['site_id', '=', $this->site_id]])->findOrEmpty()->toArray(); - return $info; + return $this->model->field($field)->where([['label_id', '=', $label_id], ['site_id', '=', $this->site_id]])->findOrEmpty()->toArray(); } /** * 获取标签 * @return array - * @throws \think\db\exception\DataNotFoundException - * @throws \think\db\exception\DbException - * @throws \think\db\exception\ModelNotFoundException + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function getAll(){ return (new CoreMemberLabelService())->getAll($this->site_id); } + /** * 添加会员标签 * @param array $data + * @return mixed */ public function add(array $data) { @@ -80,6 +86,7 @@ class MemberLabelService extends BaseAdminService * 会员标签编辑 * @param int $label_id * @param array $data + * @return true */ public function edit(int $label_id, array $data) { @@ -92,6 +99,7 @@ class MemberLabelService extends BaseAdminService /** * 删除会员标签 * @param int $label_id + * @return bool */ public function del(int $label_id) { @@ -103,7 +111,10 @@ class MemberLabelService extends BaseAdminService /** * 通过标签id获取标签列表 * @param array $label_ids - * @return \think\Response + * @return Response + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function getMemberLabelListByLabelIds(array $label_ids){ return (new CoreMemberLabelService())->getMemberLabelListByLabelIds($this->site_id, $label_ids); diff --git a/niucloud/app/service/admin/member/MemberService.php b/niucloud/app/service/admin/member/MemberService.php index 572d764fa..4e7bc9930 100644 --- a/niucloud/app/service/admin/member/MemberService.php +++ b/niucloud/app/service/admin/member/MemberService.php @@ -17,7 +17,9 @@ use app\model\member\Member; use app\service\core\member\CoreMemberService; use core\base\BaseAdminService; use core\exception\AdminException; +use think\db\exception\DataNotFoundException; use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; /** * 会员服务层 @@ -35,17 +37,16 @@ class MemberService extends BaseAdminService /** * 会员列表 * @param array $where - * @return mixed + * @return array */ public function getPage(array $where = []) { $field = 'member_id, member_no, site_id, username, mobile, password, register_channel, register_type, nickname, headimg, member_level, member_label, wx_openid, weapp_openid, wx_unionid, ali_openid, douyin_openid, login_ip, login_type, login_channel, login_count, login_time, create_time, last_visit_time, last_consum_time, sex, status, birthday, point, point_get, balance, balance_get, growth, growth_get, is_member, member_time, is_del, province_id, city_id, district_id, address, location, delete_time, money, money_get, commission, commission_get, commission_cash_outing'; $search_model = $this->model->where([['site_id', '=', $this->site_id]])->withSearch(['keyword','register_type', 'create_time', 'is_del', 'member_label', 'register_channel'],$where)->field($field)->order('member_id desc')->append(['register_channel_name', 'register_type_name', 'sex_name', 'login_channel_name', 'login_type_name', 'status_name']); - $data = $this->pageQuery($search_model, function ($item, $key) { + return $this->pageQuery($search_model, function ($item, $key) { $item = $this->makeUp($item); }); - return $data; } /** @@ -53,8 +54,8 @@ class MemberService extends BaseAdminService * @param array $where * @return array * @throws DbException - * @throws \think\db\exception\DataNotFoundException - * @throws \think\db\exception\ModelNotFoundException + * @throws DataNotFoundException + * @throws ModelNotFoundException */ public function getList(array $where = []) { @@ -64,7 +65,7 @@ class MemberService extends BaseAdminService /** * 会员详情 * @param int $member_id - * @return array + * @return array|null */ public function getInfo(int $member_id) { @@ -90,7 +91,7 @@ class MemberService extends BaseAdminService throw new AdminException('MEMBER_NO_IS_EXIST'); }else{ if(!$this->model->where([['site_id', '=', $this->site_id], ['member_no', '=', $data['member_no']]])->findOrEmpty()->isEmpty()){ - $data['member_no'] = $this->getMemberNo($this->site_id); + $data['member_no'] = $this->getMemberNo(); } } @@ -191,13 +192,12 @@ class MemberService extends BaseAdminService */ public function getSum($field) { - $sum = $this->model->where([['site_id', '=', $this->site_id] ])->sum($field); - return $sum; + return $this->model->where([['site_id', '=', $this->site_id] ])->sum($field); } /** * 创建会员编码 - * @return string|void + * @return string|null */ public function getMemberNo() { @@ -207,6 +207,7 @@ class MemberService extends BaseAdminService /** * 删除会员 * @param int $member_id + * @return true */ public function deleteMember(int $member_id) { diff --git a/niucloud/app/service/admin/niucloud/NiucloudService.php b/niucloud/app/service/admin/niucloud/NiucloudService.php new file mode 100644 index 000000000..55a8151b6 --- /dev/null +++ b/niucloud/app/service/admin/niucloud/NiucloudService.php @@ -0,0 +1,63 @@ +core_config_service = new CoreConfigService(); + + } + + /** + * 设置 授权信息 + * @param $data + * @return \app\model\sys\SysConfig|bool|\think\Model + */ + public function setAuthorize($data){ + + $data = [ + 'auth_code' => $data['auth_code'], + 'auth_secret' => $data['auth_secret'] + ]; + return $this->core_config_service->setConfig(0,ConfigKeyDict::NIUCLOUD_CONFIG, $data); + } + + /** + * 获取授权信息 + * @return mixed|string[] + */ + public function getAuthorize(){ + $info = $this->core_config_service->getConfig(0, ConfigKeyDict::NIUCLOUD_CONFIG); + if(empty($info)) + { + $info = []; + $info['value'] = [ + 'auth_code' => '', + 'auth_secret' => '' + ]; + } + return $info['value']; + } + +} \ No newline at end of file diff --git a/niucloud/app/service/admin/notice/NoticeLogService.php b/niucloud/app/service/admin/notice/NoticeLogService.php index 3584453ea..75cde2023 100644 --- a/niucloud/app/service/admin/notice/NoticeLogService.php +++ b/niucloud/app/service/admin/notice/NoticeLogService.php @@ -29,7 +29,7 @@ class NoticeLogService extends BaseAdminService /** * 消息发送记录 * @param $where - * @return mixed + * @return array */ public function getPage($where) { diff --git a/niucloud/app/service/admin/notice/NoticeService.php b/niucloud/app/service/admin/notice/NoticeService.php index a39cb361c..7bdb6d3ff 100644 --- a/niucloud/app/service/admin/notice/NoticeService.php +++ b/niucloud/app/service/admin/notice/NoticeService.php @@ -17,6 +17,7 @@ use app\model\sys\SysNotice; use app\service\core\notice\CoreNoticeService; use core\base\BaseAdminService; use core\exception\AdminException; +use think\Response; /** * 消息管理服务层 @@ -41,6 +42,7 @@ class NoticeService extends BaseAdminService /** * 获取消息内容 * @param string $key + * @return array */ public function getInfo(string $key) { @@ -52,7 +54,7 @@ class NoticeService extends BaseAdminService * @param string $key * @param string $field_type * @param $value - * @return void + * @return bool */ public function modify(string $key, string $field_type, $value){ $data = array( @@ -66,7 +68,7 @@ class NoticeService extends BaseAdminService * @param string $key * @param string $type * @param int $status - * @return \think\Response + * @return Response */ public function editMessageStatus(string $key, string $type, int $status) { @@ -80,7 +82,7 @@ class NoticeService extends BaseAdminService * @param string $key * @param string $type * @param array $data - * @return \think\Response + * @return Response */ public function edit(string $key, string $type, array $data) { diff --git a/niucloud/app/service/admin/notice/NoticeSmsLogService.php b/niucloud/app/service/admin/notice/NoticeSmsLogService.php index 8f5da5fe9..ca0abac8b 100644 --- a/niucloud/app/service/admin/notice/NoticeSmsLogService.php +++ b/niucloud/app/service/admin/notice/NoticeSmsLogService.php @@ -12,7 +12,6 @@ namespace app\service\admin\notice; use app\model\sys\SysNoticeLog; -use app\service\core\notice\CoreNoticeLogService; use app\service\core\notice\CoreNoticeSmsLogService; use core\base\BaseAdminService; @@ -38,7 +37,8 @@ class NoticeSmsLogService extends BaseAdminService /** * 获取消息内容 - * @param string $key + * @param int $id + * @return array */ public function getInfo(int $id) { diff --git a/niucloud/app/service/admin/notice/SmsService.php b/niucloud/app/service/admin/notice/SmsService.php index 59ef891d0..ea43b3e7f 100644 --- a/niucloud/app/service/admin/notice/SmsService.php +++ b/niucloud/app/service/admin/notice/SmsService.php @@ -61,8 +61,8 @@ class SmsService extends BaseAdminService /** * 获取短信配置 - * @param $sms_type - * @return array|Response + * @param string $sms_type + * @return array */ public function getConfig(string $sms_type) { @@ -93,7 +93,7 @@ class SmsService extends BaseAdminService /** * 短信配置 - * @param $sms_type + * @param string $sms_type * @param array $data * @return bool */ @@ -121,8 +121,7 @@ class SmsService extends BaseAdminService $config[$sms_type][$k_param] = $data[$k_param] ?? ''; } - $res = (new CoreConfigService())->setConfig($this->site_id, 'SMS', $config); - return $res; + return (new CoreConfigService())->setConfig($this->site_id, 'SMS', $config); } diff --git a/niucloud/app/service/admin/order/RechargeOrderRefundService.php b/niucloud/app/service/admin/order/RechargeOrderRefundService.php index 5cbebfa06..54de19758 100644 --- a/niucloud/app/service/admin/order/RechargeOrderRefundService.php +++ b/niucloud/app/service/admin/order/RechargeOrderRefundService.php @@ -15,6 +15,7 @@ use app\dict\order\RechargeOrderDict; use app\model\order\RechargeOrderItemRefund; use app\service\core\order\recharge\CoreRechargeRefundService; use core\base\BaseAdminService; +use Exception; /** * 充值订单 @@ -33,7 +34,7 @@ class RechargeOrderRefundService extends BaseAdminService try { (new CoreRechargeRefundService())->create($this->site_id, $order_id); return true; - } catch (\Exception $e) { + } catch ( Exception $e) { return $e->getMessage(); } } @@ -41,7 +42,7 @@ class RechargeOrderRefundService extends BaseAdminService /** * 查询退款列表 * @param array $where - * @return mixed + * @return array */ public function getPage(array $where) { @@ -64,27 +65,25 @@ class RechargeOrderRefundService extends BaseAdminService /** * 查询退款详情 * @param int $refund_id - * @return void + * @return array */ public function getDetail(int $refund_id) { $field = 'refund_id,num,money,refund_no,status,create_time,audit_time,transfer_time,item_type,order_item_id, order_id,member_id'; - $detail = $this->model->where([ ['site_id', '=', $this->site_id], ['refund_id', '=', $refund_id]])->field($field)->with(['item' => function($query) { + return $this->model->where([ ['site_id', '=', $this->site_id], ['refund_id', '=', $refund_id]])->field($field)->with(['item' => function($query) { $query->field('order_item_id, item_name, item_image'); }, 'member' => function($query) { $query->field('member_id, nickname, mobile, headimg'); }, 'payrefund' => function($query) { $query->field('refund_no'); }])->append(['status_name', 'payrefund.type_name'])->findOrEmpty()->toArray(); - return $detail; } /** * 获取退款状态 - * @return void + * @return array|array[]|string */ public function getStatus(){ - $status = RechargeOrderDict::getRefundStatus(); - return $status; + return RechargeOrderDict::getRefundStatus(); } /** @@ -95,7 +94,7 @@ class RechargeOrderRefundService extends BaseAdminService $status = RechargeOrderDict::getRefundStatus(); $all = 0; $have = 0; - foreach ($status as $k => $v) + foreach ($status as $k => &$v) { $money = $this->model->where([['status', '=', $v['status']], ['site_id', '=', $this->site_id]])->sum("money"); if($money == null) @@ -103,10 +102,10 @@ class RechargeOrderRefundService extends BaseAdminService $money = 0; } if($k == 1 || $k == 2){ - $have = $have + $money; + $have += $money; } - $status[$k]['money'] = number_format($money, 2); - $all = $all + $money; + $v['money'] = number_format($money, 2); + $all += $money; } $status['all'] = [ 'name' => get_lang('dict_refund.all'), diff --git a/niucloud/app/service/admin/order/RechargeOrderService.php b/niucloud/app/service/admin/order/RechargeOrderService.php index 327aaa213..500afa56f 100644 --- a/niucloud/app/service/admin/order/RechargeOrderService.php +++ b/niucloud/app/service/admin/order/RechargeOrderService.php @@ -31,7 +31,7 @@ class RechargeOrderService extends BaseAdminService /** * 充值订单分页列表 * @param array $where - * @return mixed + * @return array */ public function getPage(array $where) { @@ -58,8 +58,8 @@ class RechargeOrderService extends BaseAdminService /** * 充值订单详情 - * @param array $where - * @return mixed + * @param int $order_id + * @return array */ public function getDetail(int $order_id) { @@ -90,7 +90,8 @@ class RechargeOrderService extends BaseAdminService /** * 充值订单 - * @return array|array[]|string + * @param array $data + * @return int[] */ public function stat(array $data = []) { diff --git a/niucloud/app/service/admin/pay/PayChannelService.php b/niucloud/app/service/admin/pay/PayChannelService.php index 594e26297..1fdff43f7 100644 --- a/niucloud/app/service/admin/pay/PayChannelService.php +++ b/niucloud/app/service/admin/pay/PayChannelService.php @@ -18,6 +18,9 @@ use app\model\pay\PayChannel; use app\service\core\pay\CorePayChannelService; use core\base\BaseAdminService; use core\exception\PayException; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; /** * 支付配置服务层 @@ -36,7 +39,10 @@ class PayChannelService extends BaseAdminService /** * 添加模板 + * @param string $channel + * @param string $type * @param array $data + * @return true */ public function set(string $channel, string $type, array $data) { @@ -44,9 +50,9 @@ class PayChannelService extends BaseAdminService 'type' => $type, 'channel' => $channel ); - if (!in_array($type, array_keys(PayDict::getPayType()))) throw new PayException('PATMENT_METHOD_INVALID'); + if (!array_key_exists($type, PayDict::getPayType())) throw new PayException('PATMENT_METHOD_INVALID'); if ($channel != 'transfer') { - if (!in_array($channel, array_keys(ChannelDict::getType()))) throw new PayException('CHANNEL_MARK_INVALID'); + if (!array_key_exists($channel, ChannelDict::getType())) throw new PayException('CHANNEL_MARK_INVALID'); } $pay_channel = $this->core_pay_channel_service->find($this->site_id, $where); if ($pay_channel->isEmpty()) { @@ -64,7 +70,10 @@ class PayChannelService extends BaseAdminService /** * 用于后端支付渠道 - * @return void + * @return array + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function getChannelList() { @@ -99,9 +108,9 @@ class PayChannelService extends BaseAdminService * 通过渠道获取配置 * @param string $channel * @return array - * @throws \think\db\exception\DataNotFoundException - * @throws \think\db\exception\DbException - * @throws \think\db\exception\ModelNotFoundException + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function getListByChannel(string $channel) { @@ -139,6 +148,14 @@ class PayChannelService extends BaseAdminService 'alipay_root_cert_path' => $data['alipay_root_cert_path'] ?? '',// 必填-支付宝根证书 路径 ]; break; + case PayDict::OFFLINEPAY: + $config = [ + 'collection_name' => $data['collection_name'] ?? '',// 必填-收款账户名称 + 'collection_bank' => $data['collection_bank'] ?? '',//必填-收款银行 + 'collection_account' => $data['collection_account'] ?? '',//必填-收款账号 + 'collection_desc' => $data['collection_desc'] ?? '',// 必填-转账说明 + ]; + break; } return $config; } diff --git a/niucloud/app/service/admin/pay/PayService.php b/niucloud/app/service/admin/pay/PayService.php new file mode 100644 index 000000000..0747339ce --- /dev/null +++ b/niucloud/app/service/admin/pay/PayService.php @@ -0,0 +1,85 @@ +model = new Pay(); + } + + /** + * 待审核支付记录 + * @param array $where + * @return mixed + */ + public function getAuditPage(array $where){ + $field = 'id, out_trade_no, type, money, body, voucher, create_time, trade_id, trade_type, status'; + $search_model = $this->model->where([ [ 'site_id', '=', $this->site_id ], ['type', '=', PayDict::OFFLINEPAY] ])->withSearch([ 'create_time', 'out_trade_no', 'status' ], $where)->field($field)->append([ 'type_name' ])->order('create_time desc'); + return $this->pageQuery($search_model); + } + + /** + * 获取交易详情 + * @param int $id + * @return void + */ + public function getDetail(int $id){ + $field = 'id,out_trade_no,trade_type,trade_id,trade_no,body,money,voucher,status,create_time,pay_time,cancel_time,type,channel,fail_reason'; + return $this->model->where([ [ 'site_id', '=', $this->site_id ], ['id', '=', $id ] ]) + ->field($field) + ->append([ 'type_name', 'channel_name', 'status_name' ]) + ->findOrEmpty() + ->toArray(); + } + + /** + * 支付审核通过 + * @param string $out_trade_no + * @return null + */ + public function pass(string $out_trade_no) { + return (new CoreOfflineService())->pass($this->site_id, $out_trade_no); + } + + /** + * 支付审核未通过 + * @param string $out_trade_no + * @param string $reason + * @return void + */ + public function refuse(string $out_trade_no, string $reason) { + return (new CoreOfflineService())->refuse($this->site_id, $out_trade_no, $reason); + } + + /** + * 统计支付数据 + * @param $where + * @return int + * @throws \think\db\exception\DbException + */ + public function payCount($where) + { + return $this->model->where($where)->count(); + } +} diff --git a/niucloud/app/service/admin/schedule/ScheduleService.php b/niucloud/app/service/admin/schedule/ScheduleService.php index 4a0077a82..de3734f0a 100644 --- a/niucloud/app/service/admin/schedule/ScheduleService.php +++ b/niucloud/app/service/admin/schedule/ScheduleService.php @@ -33,8 +33,8 @@ class ScheduleService extends BaseAdminService /** * 获取自动任务列表 - * @param array $where - * @return mixed + * @param array $data + * @return array */ public function getPage(array $data = []) { @@ -63,6 +63,7 @@ class ScheduleService extends BaseAdminService /** * 添加 * @param array $data + * @return true */ public function add(array $data) { diff --git a/niucloud/app/service/admin/site/SiteAccountLogService.php b/niucloud/app/service/admin/site/SiteAccountLogService.php index 7d2b81d26..9762ea08d 100644 --- a/niucloud/app/service/admin/site/SiteAccountLogService.php +++ b/niucloud/app/service/admin/site/SiteAccountLogService.php @@ -11,16 +11,9 @@ namespace app\service\admin\site; -use app\dict\sys\AppTypeDict; -use app\model\site\Site; use app\model\site\SiteAccountLog; -use app\service\admin\sys\MenuService; -use app\service\admin\user\UserService; use core\base\BaseAdminService; -use core\exception\AdminException; -use Exception; -use think\facade\Cache; -use think\facade\Db; +use think\db\exception\DbException; /** * 站点账单服务层 @@ -39,16 +32,15 @@ class SiteAccountLogService extends BaseAdminService /** * 获取账单列表 * @param array $where - * @param string $order - * @return mixed + * @return array + * @throws DbException */ public function getPage(array $where = []) { $field = 'id, site_id, type, money, trade_no, create_time'; $search_model = $this->model->where([ [ 'site_id', '=', $this->site_id ] ])->withSearch([ 'create_time', 'type' ], $where)->field($field)->append([ 'type_name', 'pay_info', 'money' ])->order('create_time desc'); - $list = $this->pageQuery($search_model); - return $list; + return $this->pageQuery($search_model); } /** diff --git a/niucloud/app/service/admin/site/SiteGroupService.php b/niucloud/app/service/admin/site/SiteGroupService.php index caedec93f..8698ff231 100644 --- a/niucloud/app/service/admin/site/SiteGroupService.php +++ b/niucloud/app/service/admin/site/SiteGroupService.php @@ -17,6 +17,9 @@ use app\model\sys\SysMenu; use app\service\admin\sys\MenuService; use core\base\BaseAdminService; use core\exception\AdminException; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; use think\facade\Cache; /** @@ -37,19 +40,21 @@ class SiteGroupService extends BaseAdminService /** * 站点分组列表 * @param array $where - * @return \think\model\relation\HasOne + * @return array */ public function getPage(array $where = []) { $field = 'group_id, group_name, group_desc, group_roles, app_type, create_time, update_time'; $search_model = $this->model->withSearch(['keywords'],$where)->field($field)->order('create_time desc'); - $data = $this->pageQuery($search_model); - return $data; + return $this->pageQuery($search_model); } /** * 获取所有分组 * @return array + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function getAll() { @@ -85,7 +90,7 @@ class SiteGroupService extends BaseAdminService * 修改站点分组 * @param int $group_id * @param array $data - * @return SiteGroup + * @return true */ public function edit(int $group_id, array $data){ $this->model->update($data, [['group_id', '=', $group_id]]); @@ -99,6 +104,7 @@ class SiteGroupService extends BaseAdminService * 删除分组 * @param int $group_id * @return bool + * @throws DbException */ public function del(int $group_id) { diff --git a/niucloud/app/service/admin/site/SiteService.php b/niucloud/app/service/admin/site/SiteService.php index ccd000795..df08fbcb0 100644 --- a/niucloud/app/service/admin/site/SiteService.php +++ b/niucloud/app/service/admin/site/SiteService.php @@ -18,6 +18,9 @@ use app\service\admin\user\UserService; use core\base\BaseAdminService; use core\exception\AdminException; use Exception; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; use think\facade\Cache; use think\facade\Db; @@ -39,8 +42,8 @@ class SiteService extends BaseAdminService /** * 获取站点列表 * @param array $where - * @param string $order - * @return mixed + * @return array + * @throws DbException */ public function getPage(array $where = []) { @@ -48,8 +51,7 @@ class SiteService extends BaseAdminService $field = 'site_id, site_name, front_end_name, front_end_logo, app_type, keywords, logo, icon, `desc`, status, latitude, longitude, province_id, city_id, district_id, address, full_address, phone, business_hours, create_time, expire_time, group_id'; $search_model = $this->model->where([ [ 'app_type', '<>', 'admin' ] ])->withSearch([ 'create_time', 'expire_time', 'keywords', 'status', 'group_id' ], $where)->with('groupName')->field($field)->append([ 'status_name' ])->order('create_time desc'); - $list = $this->pageQuery($search_model); - return $list; + return $this->pageQuery($search_model); } /** @@ -69,7 +71,8 @@ class SiteService extends BaseAdminService * 添加站点(平台端添加站点,同时添加用户以及密码) * @param array $data * ['site_name' => '', 'username' => '', 'head_img' => '', 'real_name' => '', 'password' => ''] - * + * @return mixed + * @throws DbException */ public function add(array $data) { @@ -105,9 +108,9 @@ class SiteService extends BaseAdminService Db::commit(); return $site_id; - } catch (Exception $e) { + } catch ( Exception $e) { Db::rollback(); - throw new Exception($e->getMessage()); + throw new AdminException($e->getMessage()); } } @@ -128,7 +131,7 @@ class SiteService extends BaseAdminService /** * 站点数量 * @return int - * @throws \think\db\exception\DbException + * @throws DbException */ public function getCount(array $where = []) { @@ -160,7 +163,12 @@ class SiteService extends BaseAdminService /** * 通过站点id获取菜单列表 * @param int $site_id + * @param $is_tree + * @param $status * @return mixed + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function getMenuList(int $site_id, $is_tree, $status) { @@ -186,7 +194,6 @@ class SiteService extends BaseAdminService /** * 通过站点id获取站点菜单极限 * @param int $site_id - * @param $is_tree * @param $status * @return array|mixed|string|null */ @@ -211,6 +218,7 @@ class SiteService extends BaseAdminService /** * 通过站点id获取菜单列表 * @param int $site_id + * @param $status * @return mixed */ public function getApiList(int $site_id, $status) diff --git a/niucloud/app/service/admin/site/SiteUserService.php b/niucloud/app/service/admin/site/SiteUserService.php index a8aba6250..612fec98f 100644 --- a/niucloud/app/service/admin/site/SiteUserService.php +++ b/niucloud/app/service/admin/site/SiteUserService.php @@ -36,7 +36,7 @@ class SiteUserService extends BaseAdminService /** * 管理端获取用户列表(对应站点用户列表) * @param array $where - * @return mixed + * @return array */ public function getPage(array $where) { @@ -77,7 +77,7 @@ class SiteUserService extends BaseAdminService ['uid', '=', $uid], ); $field = 'uid, username, head_img, real_name, last_ip, last_time, create_time, login_count, status, is_del, delete_time, update_time'; - $user = $this->model::where($where)->field($field)->with(['userrole'])->findOrEmpty(); + $user = $this->model->where($where)->field($field)->with(['userrole'])->findOrEmpty(); if ($user->isEmpty()) return []; @@ -90,10 +90,8 @@ class SiteUserService extends BaseAdminService /** * 添加当前站点用户 - * @param int $site_id * @param array $data * @return bool - * @throws Exception */ public function add(array $data) { @@ -104,6 +102,7 @@ class SiteUserService extends BaseAdminService * 编辑站点用户 * @param int $uid * @param array $data + * @return true */ public function edit(int $uid, array $data) { @@ -130,7 +129,7 @@ class SiteUserService extends BaseAdminService /** * 删除 * @param int $uid - * @return mixed + * @return true */ public function del(int $uid) { diff --git a/niucloud/app/service/admin/site/UserLogService.php b/niucloud/app/service/admin/site/UserLogService.php index c62d5bf24..2163c95d8 100644 --- a/niucloud/app/service/admin/site/UserLogService.php +++ b/niucloud/app/service/admin/site/UserLogService.php @@ -33,15 +33,14 @@ class UserLogService extends BaseAdminService /** * 获取用户日志 * @param array $where - * @return mixed + * @return array */ public function getPage(array $where) { $field = 'id, ip, site_id, uid, username, url, params, type, create_time'; $order = 'create_time desc'; $search_model = $this->model->where([['site_id', '=', $this->site_id]])->withSearch(['username', 'create_time', 'uid', 'ip', 'type', 'url'], $where)->field($field)->order($order); - $list = $this->pageQuery($search_model); - return $list; + return $this->pageQuery($search_model); } /** @@ -55,8 +54,7 @@ class UserLogService extends BaseAdminService ['site_id', '=', $this->site_id] ); $field = 'id, ip, site_id, uid, username, url, params, type, create_time'; - $info = $this->model->where($where)->field($field)->findOrEmpty()->toArray(); - return $info; + return $this->model->where($where)->field($field)->findOrEmpty()->toArray(); } /** diff --git a/niucloud/app/service/admin/stat/SiteStatService.php b/niucloud/app/service/admin/stat/SiteStatService.php index c5b746b1f..2cd72258e 100644 --- a/niucloud/app/service/admin/stat/SiteStatService.php +++ b/niucloud/app/service/admin/stat/SiteStatService.php @@ -12,13 +12,9 @@ namespace app\service\admin\stat; use app\model\order\RechargeOrder; -use app\service\admin\member\MemberService; use app\service\admin\site\SiteService; -use app\service\admin\sys\SystemService; -use app\service\core\member\CoreMemberService; -use Carbon\Carbon; use core\base\BaseAdminService; -use think\facade\Db; +use think\db\exception\DbException; /** @@ -46,7 +42,7 @@ class SiteStatService extends BaseAdminService $data['site_info'] = (new SiteService())->getInfo($this->site_id); $site_create_time = strtotime($data['site_info']['create_time']); $site_expire_time = strtotime($data['site_info']['expire_time']); - $data['site_info']['mix'] = (number_format((time() - $site_create_time) / ($site_expire_time - $site_create_time), 2) * 100).'%'; ; + $data['site_info']['mix'] = (number_format((time() - $site_create_time) / ($site_expire_time - $site_create_time), 2) * 100).'%'; $data['site_info']['over_date'] = $site_expire_time - time() > 0 ? number_format(($site_expire_time - time())/ 86400, 2) : 0; return $data; @@ -56,6 +52,7 @@ class SiteStatService extends BaseAdminService * 订单金额 * @param $start_time * @param $end_time + * @return float */ public function orderMoney($start_time, $end_time) { @@ -64,14 +61,15 @@ class SiteStatService extends BaseAdminService ['order_status', '>', 0], ['create_time', 'between', [$start_time, $end_time]] ]; - $money = (new RechargeOrder())->where($where)->sum('order_money'); - return $money; + return (new RechargeOrder())->where($where)->sum('order_money'); } - /** + /** * 订单数量 * @param $start_time * @param $end_time + * @return int + * @throws DbException */ public function orderCount($start_time, $end_time) { @@ -80,8 +78,7 @@ class SiteStatService extends BaseAdminService ['order_status', '>', 0], ['create_time', 'between', [$start_time, $end_time]] ]; - $money = (new RechargeOrder())->where($where)->count('order_id'); - return $money; + return (new RechargeOrder())->where($where)->count('order_id'); } diff --git a/niucloud/app/service/admin/stat/StatService.php b/niucloud/app/service/admin/stat/StatService.php index 4cd689b2c..e2b82cb1a 100644 --- a/niucloud/app/service/admin/stat/StatService.php +++ b/niucloud/app/service/admin/stat/StatService.php @@ -17,6 +17,9 @@ use app\service\admin\sys\SystemService; use app\service\core\addon\CoreAddonService; use app\service\core\member\CoreMemberService; use core\base\BaseAdminService; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; /** @@ -35,6 +38,9 @@ class StatService extends BaseAdminService /** * 获取统计数据 * @return int[] + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function getIndexData() { @@ -79,7 +85,7 @@ class StatService extends BaseAdminService ] ]; - $day_start_time = strtotime(date('Y-m-d', time())); + $day_start_time = strtotime(date('Y-m-d')); //当天结束之间 $day_end_time = $day_start_time + 86400; $data['today_data']['total_member_count'] = (new CoreMemberService())->getCount(); diff --git a/niucloud/app/service/admin/sys/AppService.php b/niucloud/app/service/admin/sys/AppService.php index c10b81b6c..81b89b24a 100644 --- a/niucloud/app/service/admin/sys/AppService.php +++ b/niucloud/app/service/admin/sys/AppService.php @@ -34,7 +34,7 @@ class AppService extends BaseAdminService // $category_list = []; $list = []; - foreach ($data as $k => $v) + foreach ($data as $v) { if(isset($v['category'])) { @@ -51,7 +51,7 @@ class AppService extends BaseAdminService { $category_list[$k_category]['sort'] = $category['sort'] ?? 100; $category_list[$k_category]['app_list'] = []; - foreach ($list as $k => $app) + foreach ($list as $app) { $app_category = $app['category'] ?? "basic"; diff --git a/niucloud/app/service/admin/sys/AreaService.php b/niucloud/app/service/admin/sys/AreaService.php index 94beee2ae..c8f990418 100644 --- a/niucloud/app/service/admin/sys/AreaService.php +++ b/niucloud/app/service/admin/sys/AreaService.php @@ -13,7 +13,9 @@ namespace app\service\admin\sys; use app\model\sys\SysArea; use core\base\BaseAdminService; -use think\facade\Cache; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; /** * 地区服务层 @@ -33,6 +35,9 @@ class AreaService extends BaseAdminService * 获取地区信息 * @param int $pid //上级pid * @return mixed + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function getListByPid(int $pid = 0) { @@ -51,6 +56,9 @@ class AreaService extends BaseAdminService * 查询地区树列表 * @param int $level //层级1,2,3 * @return mixed + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function getAreaTree(int $level = 3) { @@ -59,7 +67,7 @@ class AreaService extends BaseAdminService $cache_name, function() use($level) { $list = $this->model->where([['level', '<=', $level]])->field('id, pid, name, shortname, longitude, latitude, level, sort, status')->select()->toArray(); - return list_to_tree($list, 'id', 'pid'); + return list_to_tree($list); }, [self::$cache_tag_name] ); diff --git a/niucloud/app/service/admin/sys/AttachmentService.php b/niucloud/app/service/admin/sys/AttachmentService.php index 690940b1c..c9b3df3ef 100644 --- a/niucloud/app/service/admin/sys/AttachmentService.php +++ b/niucloud/app/service/admin/sys/AttachmentService.php @@ -18,6 +18,9 @@ use app\model\sys\SysAttachmentCategory; use app\service\core\sys\CoreAttachmentService; use core\base\BaseAdminService; use core\exception\AdminException; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; /** * 附件服务层 @@ -37,7 +40,8 @@ class AttachmentService extends BaseAdminService /** * 新增素材 - * @param $params + * @param array $data + * @return mixed */ public function add(array $data) { @@ -49,8 +53,9 @@ class AttachmentService extends BaseAdminService * * /** * 编辑素材 + * @param int $att_id * @param array $data - * @param $where + * @return SysAttachment */ public function edit(int $att_id, array $data) { @@ -75,7 +80,7 @@ class AttachmentService extends BaseAdminService /** * 批量更新附件分组 - * @param $att_id + * @param $att_ids * @param $cate_id * @return bool */ @@ -92,7 +97,7 @@ class AttachmentService extends BaseAdminService /** * 删除素材 - * @param int $uid + * @param int $att_id * @return mixed */ public function del(int $att_id) @@ -113,7 +118,7 @@ class AttachmentService extends BaseAdminService /** * 管理端获取附件列表 * @param array $data - * @return mixed + * @return array */ public function getPage(array $data) { @@ -137,7 +142,8 @@ class AttachmentService extends BaseAdminService /** * 新增素材组 - * @param $params + * @param array $data + * @return mixed */ public function addCategory(array $data) { @@ -151,7 +157,8 @@ class AttachmentService extends BaseAdminService /** * 素材组模型对象 - * @param int $uid + * @param int $site_id + * @param int $id * @return mixed */ public function findCategory(int $site_id, int $id) @@ -169,8 +176,9 @@ class AttachmentService extends BaseAdminService /** * 编辑素材组 + * @param int $id * @param array $data - * @param $where + * @return SysAttachmentCategory */ public function editCategory(int $id, array $data) { @@ -184,8 +192,9 @@ class AttachmentService extends BaseAdminService /** * 删除素材组 - * @param int $uid + * @param int $id * @return mixed + * @throws DbException */ public function delCategory(int $id) { @@ -201,10 +210,9 @@ class AttachmentService extends BaseAdminService /** * 管理端获取附件组列表 - * @param array $where - * @param string $order - * @param int $limit - * @return mixed + * @param array $data + * @return array + * @throws DbException */ public function getCategoryPage(array $data) { @@ -223,7 +231,10 @@ class AttachmentService extends BaseAdminService /** * 获取分组列表 * @param array $data - * @return mixed + * @return array + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function getCategoryList(array $data) { @@ -249,12 +260,11 @@ class AttachmentService extends BaseAdminService $icon_list = IconDict::getIcon(); foreach ($icon_list as $k => $v) { unset($icon_list[ $k ][ 'glyphs' ]); - if (!empty($data[ 'name' ]) && strpos($v[ 'name' ], $data[ 'name' ]) === false) { + if (!empty($data[ 'name' ]) && !str_contains($v['name'], $data['name'])) { unset($icon_list[ $k ]); } } - $icon_list = array_values($icon_list); - return $icon_list; + return array_values($icon_list); } /** @@ -275,18 +285,18 @@ class AttachmentService extends BaseAdminService $temp_data = []; - foreach ($icon_list as $k => $v) { + foreach ($icon_list as $v) { - $icon = $icon_list[ $k ][ 'glyphs' ]; // 图标列表 + $icon = $v[ 'glyphs' ]; // 图标列表 foreach ($icon as $ck => $cv) { // 素材表中数据保持要一致 $icon[ $ck ][ 'att_id' ] = $cv[ 'icon_id' ]; - $icon[ $ck ][ 'url' ] = $icon_list[ $k ][ 'font_family' ] . '-' . $icon_list[ $k ][ 'css_prefix_text' ] . $cv[ 'font_class' ]; + $icon[ $ck ][ 'url' ] = $v[ 'font_family' ] . '-' . $v[ 'css_prefix_text' ] . $cv[ 'font_class' ]; $icon[ $ck ][ 'real_name' ] = $cv[ 'name' ]; // 查询名称 - if (!empty($data[ 'real_name' ]) && strpos($cv[ 'name' ], $data[ 'real_name' ]) === false) { + if (!empty($data[ 'real_name' ]) && !str_contains($cv['name'], $data['real_name'])) { unset($icon[ $ck ]); } } diff --git a/niucloud/app/service/admin/sys/ConfigService.php b/niucloud/app/service/admin/sys/ConfigService.php index 3e1482993..c265c7dfd 100644 --- a/niucloud/app/service/admin/sys/ConfigService.php +++ b/niucloud/app/service/admin/sys/ConfigService.php @@ -64,7 +64,7 @@ class ConfigService extends BaseAdminService /** * 获取网站信息 - * @return mixed + * @return array */ public function getWebSite() { @@ -167,13 +167,13 @@ class ConfigService extends BaseAdminService }else{ $result = event("SiteIndex"); $index_list = []; - foreach ($result as $k => $v) + foreach ($result as $v) { $index_list = empty($index_list) ? $v: array_merge($index_list, $v); } $tag = 0; $view_path = $config['value']['view_path']; - foreach ($index_list as $k => $v) + foreach ($index_list as $v) { $v_view_path = $v['view_path'] ?? ''; if($view_path == $v_view_path) @@ -196,7 +196,7 @@ class ConfigService extends BaseAdminService /** * 站点主页配置 * @param $data - * @return \app\model\sys\SysConfig|bool|\think\Model + * @return true */ public function setSiteIndexConfig($data) { @@ -206,7 +206,7 @@ class ConfigService extends BaseAdminService //检测是否路劲一个异常 $index_list = $this->getSiteIndexList(); $check_tag = 0; - foreach($index_list as $k => $v) + foreach($index_list as $v) { if($v['view_path'] == $data['view_path']) { @@ -226,7 +226,7 @@ class ConfigService extends BaseAdminService { $result = event("SiteIndex"); $index_list = []; - foreach ($result as $k => $v) + foreach ($result as $v) { $index_list = empty($index_list) ? $v: array_merge($index_list, $v); } @@ -274,4 +274,90 @@ class ConfigService extends BaseAdminService } return $menu; } + /** + * 获取平台主页配置 + * @return mixed|string[] + */ + public function getAdminIndexConfig() + { + $config = (new CoreConfigService())->getConfig($this->site_id, "admin_index"); + if(empty($config)) + { + $config['value'] = [ + 'view_path' => 'index/index' + ]; + }else{ + $result = event("AdminIndex"); + $index_list = []; + foreach ($result as $v) + { + $index_list = empty($index_list) ? $v: array_merge($index_list, $v); + } + $tag = 0; + $view_path = $config['value']['view_path']; + foreach ($index_list as $v) + { + $v_view_path = $v['view_path'] ?? ''; + if($view_path == $v_view_path) + { + $tag = 1; + break; + } + } + if($tag == 0) + { + $config['value'] = [ + 'view_path' => 'index/index' + ]; + } + + } + return $config['value']['view_path']; + } + + /** + * 站点主页配置 + * @param $data + * @return true + */ + public function setAdminIndexConfig($data) + { + $config = [ + 'view_path' => $data['view_path'] , + ]; + //检测是否路劲一个异常 + $index_list = $this->getAdminIndexList(); + $check_tag = 0; + foreach($index_list as $v) + { + if($v['view_path'] == $data['view_path']) + { + $check_tag = 1; + } + } + if($check_tag == 0) throw new AdminException('ADMIN_INDEX_VIEW_PATH_NOT_EXIST'); + (new CoreConfigService())->setConfig($this->site_id, "admin_index", $config); + return true; + } + + /** + * 获取站点配置的首页列表 + * @return array + */ + public function getAdminIndexList() + { + $result = event("AdminIndex"); + $index_list = []; + foreach ($result as $v) + { + $index_list = empty($index_list) ? $v: array_merge($index_list, $v); + } + $view_path = $this->getAdminIndexConfig(); + foreach ($index_list as $k => $v) + { + $v_view_path = $v['view_path'] ?? ''; + $index_list[$k]['is_use'] = ($v_view_path == $view_path) ? 1: 0; + } + return $index_list; + } } \ No newline at end of file diff --git a/niucloud/app/service/admin/sys/MenuService.php b/niucloud/app/service/admin/sys/MenuService.php index 0e8d54d1c..29ea5e615 100644 --- a/niucloud/app/service/admin/sys/MenuService.php +++ b/niucloud/app/service/admin/sys/MenuService.php @@ -15,8 +15,11 @@ use app\dict\sys\MenuTypeDict; use app\model\sys\SysMenu; use core\base\BaseAdminService; use core\exception\AdminException; -use think\Exception; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; use think\facade\Cache; +use think\Model; /** * 用户服务层 @@ -35,7 +38,8 @@ class MenuService extends BaseAdminService /** * 新增菜单接口 - * @param $params + * @param array $data + * @return SysMenu|Model */ public function add(array $data) { @@ -52,7 +56,7 @@ class MenuService extends BaseAdminService /** * 更新菜单 - * @param int $menu_key + * @param string $menu_key * @param array $data * @return SysMenu */ @@ -68,7 +72,7 @@ class MenuService extends BaseAdminService /** * 获取信息 - * @param int $menu_key + * @param string $menu_key * @return array */ public function get(string $menu_key){ @@ -76,8 +80,9 @@ class MenuService extends BaseAdminService } /** - * @param int $menu_key - * @return SysMenu|array|mixed|\think\Model + * @param string $menu_key + * @param string $app_type + * @return SysMenu|array|mixed|Model */ public function find(string $menu_key, string $app_type = ''){ $where = array( @@ -91,15 +96,17 @@ class MenuService extends BaseAdminService throw new AdminException('MENU_NOT_EXIST'); return $menu; } + /** * 菜单删除 - * @param int $menu_key - * @throws Exception + * @param string $menu_key + * @return bool + * @throws DbException */ public function del(string $menu_key){ //查询是否有下级菜单或按钮 $menu = $this->find($menu_key); - if($this->model::where([['parent_key', '=', $menu_key]])->count() > 0) + if($this->model->where([['parent_key', '=', $menu_key]])->count() > 0) throw new AdminException('MENU_NOT_ALLOW_DELETE'); $res = $menu->delete(); @@ -110,8 +117,12 @@ class MenuService extends BaseAdminService /** * 通过菜单menu_key获取 * @param array $menu_keys + * @param string $app_type * @param int $is_tree * @return mixed + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function getMenuListByMenuKeys(array $menu_keys, string $app_type, int $is_tree = 0) { @@ -127,26 +138,31 @@ class MenuService extends BaseAdminService if(!empty($app_type)){ $where[] = ['app_type', '=', $app_type]; } - $menu_list = $this->model->where($where)->order('sort', 'desc')->select()->toArray(); - return $menu_list; + return $this->model->where($where)->order('sort', 'desc')->select()->toArray(); }, self::$cache_tag_name ); - foreach ($menu_list as $k => $v) + foreach ($menu_list as &$v) { $lang_menu_key = "dict_menu_". $v['app_type']. '.'. $v['menu_key']; $lang_menu_name = get_lang("dict_menu_". $v['app_type']. '.'. $v['menu_key']); //语言已定义 if($lang_menu_key != $lang_menu_name) { - $menu_list[$k]['menu_name'] = $lang_menu_name; + $v['menu_name'] = $lang_menu_name; } //首页加载 if($v['menu_key'] == 'overview' && $v['app_type'] == 'site') { $view_path = (new ConfigService())->getSiteIndexConfig(); - $menu_list[$k]['view_path'] = $view_path; + $v['view_path'] = $view_path; + } + + if($v['menu_key'] == 'overview' && $v['app_type'] == 'admin') + { + $view_path = (new ConfigService())->getAdminIndexConfig(); + $v['view_path'] = $view_path; } } @@ -171,25 +187,30 @@ class MenuService extends BaseAdminService if ($status != 'all') { $where[] = ['status', '=', $status]; } - $menu_list = $this->model->where($where)->order('sort desc')->select()->toArray(); - return $menu_list; + return $this->model->where($where)->order('sort desc')->select()->toArray(); }, self::$cache_tag_name ); - foreach ($menu_list as $k => $v) + foreach ($menu_list as &$v) { $lang_menu_key = "dict_menu_". $v['app_type']. '.'. $v['menu_key']; $lang_menu_name = get_lang("dict_menu_". $v['app_type']. '.'. $v['menu_key']); //语言已定义 if($lang_menu_key != $lang_menu_name) { - $menu_list[$k]['menu_name'] = $lang_menu_name; + $v['menu_name'] = $lang_menu_name; } //首页加载 if($v['menu_key'] == 'overview' && $v['app_type'] == 'site') { $view_path = (new ConfigService())->getSiteIndexConfig(); - $menu_list[$k]['view_path'] = $view_path; + $v['view_path'] = $view_path; + } + + if($v['menu_key'] == 'overview' && $v['app_type'] == 'admin') + { + $view_path = (new ConfigService())->getAdminIndexConfig(); + $v['view_path'] = $view_path; } } @@ -202,6 +223,8 @@ class MenuService extends BaseAdminService /** * 通过菜单menu_key组获取接口数组 * @param array $menu_keys + * @param string $app_type + * @return mixed|string */ public function getApiListByMenuKeys(array $menu_keys, string $app_type = '') { @@ -227,10 +250,10 @@ class MenuService extends BaseAdminService } - /** * 通过菜单menu_key组获取按钮数组 * @param array $menu_keys + * @param string $app_type * @return mixed */ public function getButtonListBuMenuKeys(array $menu_keys, string $app_type = '') @@ -247,8 +270,7 @@ class MenuService extends BaseAdminService if(!empty($app_type)){ $where[] = ['app_type', '=', $app_type]; } - $menu_list = $this->model->where($where)->order('sort', 'desc')->column('menu_key'); - return $menu_list; + return $this->model->where($where)->order('sort', 'desc')->column('menu_key'); }, self::$cache_tag_name ); @@ -326,8 +348,7 @@ class MenuService extends BaseAdminService if ($status != 'all') { $where[] = ['status', '=', $status]; } - $menu_list = $this->model->where($where)->order('sort', 'desc')->column('menu_key'); - return $menu_list; + return $this->model->where($where)->order('sort', 'desc')->column('menu_key'); }, self::$cache_tag_name ); @@ -376,7 +397,7 @@ class MenuService extends BaseAdminService /** * 获取完整的路由地址 - * @param $menu + * @param $menu_key * @return string */ public function getFullRouterPath($menu_key){ diff --git a/niucloud/app/service/admin/sys/RoleService.php b/niucloud/app/service/admin/sys/RoleService.php index 9ba8ab04a..5be42ccc8 100644 --- a/niucloud/app/service/admin/sys/RoleService.php +++ b/niucloud/app/service/admin/sys/RoleService.php @@ -17,6 +17,9 @@ use app\model\sys\SysUserRole; use app\service\admin\site\SiteService; use core\base\BaseAdminService; use core\exception\AdminException; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; use think\facade\Cache; /** @@ -36,7 +39,7 @@ class RoleService extends BaseAdminService /** * 管理端获取角色列表 * @param array $data - * @return mixed + * @return array */ public function getPage(array $data) { @@ -46,13 +49,12 @@ class RoleService extends BaseAdminService } $field = 'role_id,role_name,status,create_time'; $search_model = $this->model->where($where)->field($field)->order('create_time desc')->append(['status_name']); - $list = $this->pageQuery($search_model); - return $list; + return $this->pageQuery($search_model); } /** * 获取权限信息 * @param int $role_id - * @return mixed + * @return array */ public function getInfo(int $role_id){ return $this->model->append(['status_name'])->findOrEmpty($role_id)->toArray(); @@ -60,7 +62,10 @@ class RoleService extends BaseAdminService /** * 获取站点下的所有权限 - * @return mixed + * @return array + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function getAll() { @@ -70,9 +75,11 @@ class RoleService extends BaseAdminService ); return $this->model->where($where)->field('role_id,role_name,status,create_time')->select()->toArray(); } + /** * 新增权限 * @param array $data + * @return true */ public function add(array $data){ $data['create_time'] = time(); @@ -87,6 +94,7 @@ class RoleService extends BaseAdminService * 更新权限 * @param int $role_id * @param array $data + * @return true */ public function edit(int $role_id, array $data){ $where = array( @@ -99,8 +107,10 @@ class RoleService extends BaseAdminService return true; } + /** * 获取模型对象 + * @param int $site_id * @param int $role_id * @return mixed */ @@ -119,7 +129,7 @@ class RoleService extends BaseAdminService * 删除权限(saas应该不允许删除) * @param int $role_id * @return mixed - * @throws \think\db\exception\DbException + * @throws DbException */ public function del(int $role_id){ $role = $this->find($this->site_id, $role_id); @@ -134,7 +144,7 @@ class RoleService extends BaseAdminService /** * 获取角色id为健名,角色名为键值的数据 * @param int $site_id - * @param string $app_type + * @return mixed|string */ public function getColumn(int $site_id){ $cache_name = 'role_column_'.$site_id; @@ -152,8 +162,12 @@ class RoleService extends BaseAdminService /** * 通过权限组id获取菜单id + * @param int $site_id * @param array $role_ids * @return array + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function getMenuIdsByRoleIds(int $site_id, array $role_ids){ $menu_keys = (new SiteService())->getMenuIdsBySiteId($site_id, 1); @@ -163,7 +177,7 @@ class RoleService extends BaseAdminService return cache_remember( $cache_name, function() use($role_ids, $menu_keys) { - $rules = $this->model::where([['role_id', 'IN', $role_ids], ['status', '=', RoleStatusDict::ON]])->field('rules')->select()->toArray(); + $rules = $this->model->where([['role_id', 'IN', $role_ids], ['status', '=', RoleStatusDict::ON]])->field('rules')->select()->toArray(); if(!empty($rules)){ $temp = []; foreach($rules as $k => $v){ @@ -172,8 +186,7 @@ class RoleService extends BaseAdminService $temp = array_unique($temp); if(empty($menu_keys)) return []; if(empty($temp)) return []; - $allow_menu_ids = array_intersect($temp, $menu_keys); - return $allow_menu_ids; + return array_intersect($temp, $menu_keys); } return []; }, diff --git a/niucloud/app/service/admin/sys/SystemService.php b/niucloud/app/service/admin/sys/SystemService.php index 7474ddfe0..8947e9d2c 100644 --- a/niucloud/app/service/admin/sys/SystemService.php +++ b/niucloud/app/service/admin/sys/SystemService.php @@ -12,9 +12,11 @@ namespace app\service\admin\sys; use app\job\sys\CheckJob; -use app\model\site\Site; +use app\service\core\sys\CoreConfigService; use core\base\BaseAdminService; +use core\exception\CommonException; use think\facade\Db; +use Throwable; /** * 系统信息服务层 @@ -30,17 +32,16 @@ class SystemService extends BaseAdminService /** * 获取版权信息(网站整体,不按照站点设置) - * @return array|mixed + * @return array */ public function getInfo() { - $data = [ + return [ 'os' => PHP_OS, 'environment' => $_SERVER[ 'SERVER_SOFTWARE' ], 'php_v' => PHP_VERSION, 'version' => config('version') ]; - return $data; } /** @@ -51,24 +52,23 @@ class SystemService extends BaseAdminService $wap_domain = !empty(env("system.wap_domain")) ? preg_replace('#/$#', '', env("system.wap_domain")) : request()->domain(); $web_domain = !empty(env("system.web_domain")) ? preg_replace('#/$#', '', env("system.web_domain")) : request()->domain(); - $data = [ + return [ 'wap_domain' => env("system.wap_domain"), 'wap_url' => $wap_domain . "/wap/" . $this->site_id, 'web_url' => $web_domain . "/web/" . $this->site_id, ]; - return $data; } /** * 获取系统信息 - * @return void + * @return array */ public function getSystemInfo() { $server = []; $server[] = [ "name" => get_lang('dict_setting.server_system'), "server" => PHP_OS ]; $server[] = [ "name" => get_lang('dict_setting.server_setting'), "server" => PHP_SAPI ]; - $server[] = [ "name" => get_lang('dict_setting.php_version'), "server" => phpversion() ]; + $server[] = [ "name" => get_lang('dict_setting.php_version'), "server" => PHP_VERSION]; //环境权限 $system_variables = []; @@ -88,7 +88,7 @@ class SystemService extends BaseAdminService $fileinfo = extension_loaded('fileinfo'); $system_variables[] = [ "name" => "fileinfo", "need" => get_lang('dict_setting.php_authority_ask'), "status" => $fileinfo ]; //目录权限 - $root_path = str_replace("\\", DIRECTORY_SEPARATOR, dirname(dirname(dirname(dirname(dirname(__FILE__)))))); + $root_path = str_replace("\\", DIRECTORY_SEPARATOR, dirname(__FILE__, 5)); $root_path = str_replace("../", DIRECTORY_SEPARATOR, $root_path); @@ -111,14 +111,13 @@ class SystemService extends BaseAdminService //获取环境版本 $server_version = []; $row = (array) Db::query("select VERSION() as verson"); - $server_version[] = [ "name" => get_lang('dict_setting.php_version'), "demand" => get_lang('dict_setting.php_ask'), "server" => phpversion() ]; + $server_version[] = [ "name" => get_lang('dict_setting.php_version'), "demand" => get_lang('dict_setting.php_ask'), "server" => PHP_VERSION]; $server_version[] = [ "name" => get_lang('dict_setting.mysql_version'), "demand" => get_lang('dict_setting.mysql_ask'), "server" => $row[ 0 ][ 'verson' ] ]; // 进程 $process[] = [ "name" => "php think queue:listen", "need" => get_lang('dict_setting.php_authority_ask'), "status" => ( new SystemService() )->checkJob() ]; - $data = [ "server" => $server, "dirs_list" => $dirs_list, 'system_variables' => $system_variables, 'server_version' => $server_version, 'process' => $process ]; - return $data; + return [ "server" => $server, "dirs_list" => $dirs_list, 'system_variables' => $system_variables, 'server_version' => $server_version, 'process' => $process ]; } /** @@ -135,15 +134,15 @@ class SystemService extends BaseAdminService /** *校验消息队列是否正常运行 - * @return void + * @return bool */ public function checkJob() { - $secret = uniqid(); + $secret = uniqid('', true); $file = root_path('runtime') . $secret . '.job'; try { CheckJob::invoke([ 'file' => $file ]); - } catch (\Throwable $e) { + } catch ( Throwable $e) { return false; } sleep(3); @@ -169,4 +168,16 @@ class SystemService extends BaseAdminService } return false; } + + /** + * 设置布局 + * @param string $key + * @return void + */ + public function setLayout(string $key) { + $layouts = array_column(event('SiteLayout'), 'key'); + if (!in_array($key, $layouts)) throw new CommonException('LAYOUT_NOT_EXIST'); + (new CoreConfigService())->setConfig($this->site_id, 'SITE_LAYOUT', [ 'key' => $key ]); + return true; + } } \ No newline at end of file diff --git a/niucloud/app/service/admin/upload/StorageConfigService.php b/niucloud/app/service/admin/upload/StorageConfigService.php index 5a1daa02a..da8d43218 100644 --- a/niucloud/app/service/admin/upload/StorageConfigService.php +++ b/niucloud/app/service/admin/upload/StorageConfigService.php @@ -11,6 +11,7 @@ namespace app\service\admin\upload; +use app\dict\sys\FileDict; use app\dict\sys\StorageDict; use app\service\core\upload\CoreStorageService; use app\service\core\sys\CoreConfigService; @@ -41,8 +42,8 @@ class StorageConfigService extends BaseAdminService /** * 获取存储配置 - * @param $storage_type - * @return array|Response + * @param string $storage_type + * @return array */ public function getStorageConfig(string $storage_type) { @@ -73,7 +74,7 @@ class StorageConfigService extends BaseAdminService /** * 云存储配置 - * @param $storage_type + * @param string $storage_type * @param array $data * @return bool */ @@ -81,6 +82,12 @@ class StorageConfigService extends BaseAdminService { $storage_type_list = StorageDict::getType(); if(!array_key_exists($storage_type, $storage_type_list)) throw new AdminException('OSS_TYPE_NOT_EXIST'); + if($storage_type != FileDict::LOCAL){ + $domain = $data['domain']; + if (!str_contains($domain, 'http://') && !str_contains($domain, 'https://')){ + throw new AdminException('STORAGE_NOT_HAS_HTTP_OR_HTTPS'); + } + } $info = (new CoreConfigService())->getConfig($this->site_id, 'STORAGE'); if(empty($info)) { @@ -101,8 +108,7 @@ class StorageConfigService extends BaseAdminService $config[$storage_type][$k_param] = $data[$k_param] ?? ''; } - $res = (new CoreConfigService())->setConfig($this->site_id, 'STORAGE', $config); - return $res; + return (new CoreConfigService())->setConfig($this->site_id, 'STORAGE', $config); } diff --git a/niucloud/app/service/admin/upload/UploadService.php b/niucloud/app/service/admin/upload/UploadService.php index 909c4162d..2eddf29df 100644 --- a/niucloud/app/service/admin/upload/UploadService.php +++ b/niucloud/app/service/admin/upload/UploadService.php @@ -16,6 +16,7 @@ use app\dict\sys\StorageDict; use app\service\core\upload\CoreUploadService; use core\base\BaseAdminService; use core\exception\UploadFileException; +use Exception; /** * 用户服务层 @@ -33,9 +34,9 @@ class UploadService extends BaseAdminService * @param int $cate_id * @return array */ - public function image($file, int $cate_id = 0){ + public function image($file, int $cate_id = 0, $is_attachment = true){ $dir = $this->root_path.'/'.'image'.'/'.$this->site_id.'/'.date('Ym').'/'.date('d'); - $core_upload_service = new CoreUploadService(true); + $core_upload_service = new CoreUploadService($is_attachment); //如果没有选择相册分组的话,就选择第一个相册分组 return $core_upload_service->image($file, $this->site_id, $dir, $cate_id); } @@ -57,6 +58,7 @@ class UploadService extends BaseAdminService * @param $file * @param string $type * @return array + * @throws Exception */ public function document($file, string $type){ if(!in_array($type, FileDict::getSceneType())) diff --git a/niucloud/app/service/admin/user/UserRoleService.php b/niucloud/app/service/admin/user/UserRoleService.php index 8a908f657..cb8db77f8 100644 --- a/niucloud/app/service/admin/user/UserRoleService.php +++ b/niucloud/app/service/admin/user/UserRoleService.php @@ -18,6 +18,7 @@ use app\service\admin\sys\RoleService; use core\base\BaseAdminService; use core\exception\AdminException; use think\facade\Cache; +use think\Model; /** * 用户服务层 @@ -98,7 +99,7 @@ class UserRoleService extends BaseAdminService ['uid', '=', $uid], ['site_id', '=', $site_id] ); - return $user_role_model::where($where)->findOrEmpty()->toArray(); + return $user_role_model->where($where)->findOrEmpty()->toArray(); }, [self::$role_cache_name, RoleService::$cache_tag_name.$this->site_id] ); @@ -107,7 +108,7 @@ class UserRoleService extends BaseAdminService /** * 获取用户默认站点(切勿用于平台管理端) * @param int $uid - * @return SysUserRole|array|mixed|\think\Model + * @return SysUserRole|array|mixed|Model */ public function getUserDefaultSiteId(int $uid){ $user_role_model = new SysUserRole(); @@ -117,8 +118,8 @@ class UserRoleService extends BaseAdminService /** * 通过角色id组获取角色 - * @param $role_ids - * @param $site_id + * @param array $role_ids + * @param int $site_id * @return mixed */ public function getRoleByUserRoleIds(array $role_ids, int $site_id){ diff --git a/niucloud/app/service/admin/user/UserService.php b/niucloud/app/service/admin/user/UserService.php index 600eb098e..b3fdce7db 100644 --- a/niucloud/app/service/admin/user/UserService.php +++ b/niucloud/app/service/admin/user/UserService.php @@ -18,7 +18,9 @@ use app\service\admin\auth\LoginService; use core\base\BaseAdminService; use core\exception\AdminException; use Exception; +use think\db\exception\DbException; use think\facade\Db; +use think\Model; /** * 用户服务层 @@ -36,7 +38,7 @@ class UserService extends BaseAdminService /** * 用户列表 * @param array $where - * @return mixed + * @return array */ public function getPage(array $where) { @@ -61,7 +63,7 @@ class UserService extends BaseAdminService /** * 获取用户列表(用于平台整体用户管理) * @param array $where - * @return mixed + * @return array */ public function getUserAdminPage(array $where) { @@ -73,18 +75,18 @@ class UserService extends BaseAdminService return $this->pageQuery($search_model); } + /** * 获取用户列表(用于平台整体用户管理) - * @param array $where - * @return mixed + * @param int $uid + * @return array */ public function getUserAdminInfo(int $uid) { $field = 'uid, username, head_img, real_name, last_ip, last_time, create_time, login_count, status, delete_time, update_time'; - $res = $this->model->where([['uid', '=', $uid]])->field($field)->with(['roles' => function($query) { + return $this->model->where([['uid', '=', $uid]])->field($field)->with(['roles' => function($query) { $query->field('uid, site_id, is_admin')->with('siteInfo'); }])->findOrEmpty()->toArray(); - return $res; } @@ -103,8 +105,7 @@ class UserService extends BaseAdminService 'password' => create_password($data['password']) ]; $user = $this->model->create($user_data); - $uid = $user?->uid; - return $uid; + return $user?->uid; } /** @@ -160,7 +161,7 @@ class UserService extends BaseAdminService * 检测用户名是否重复 * @param $username * @return bool - * @throws \think\db\exception\DbException + * @throws DbException */ public function checkUsername($username) { @@ -175,7 +176,7 @@ class UserService extends BaseAdminService /** * 用户模型对象 * @param int $uid - * @return SysUser|array|mixed|\think\Model + * @return SysUser|array|mixed|Model */ public function find(int $uid){ @@ -228,7 +229,7 @@ class UserService extends BaseAdminService /** * 删除 * @param int $uid - * @return mixed + * @return true */ public function del(int $uid){ $where = [ @@ -242,7 +243,7 @@ class UserService extends BaseAdminService /** * 通过账号获取管理员信息 * @param string $username - * @return SysUser|array|mixed|\think\Model + * @return SysUser|array|mixed|Model */ public function getUserInfoByUsername(string $username){ return $this->model->where([['username', '=',$username]])->findOrEmpty(); diff --git a/niucloud/app/service/admin/weapp/WeappConfigService.php b/niucloud/app/service/admin/weapp/WeappConfigService.php index 99f9492c0..f2a78c7b3 100644 --- a/niucloud/app/service/admin/weapp/WeappConfigService.php +++ b/niucloud/app/service/admin/weapp/WeappConfigService.php @@ -11,8 +11,10 @@ namespace app\service\admin\weapp; +use app\model\sys\SysConfig; use app\service\core\weapp\CoreWeappConfigService; use core\base\BaseAdminService; +use think\Model; /** * 微信小程序设置 @@ -28,15 +30,14 @@ class WeappConfigService extends BaseAdminService public function getWeappConfig() { $config_info = (new CoreWeappConfigService())->getWeappConfig($this->site_id); - $config_info = array_merge($config_info, $this->getWeappStaticInfo()); - return $config_info; + return array_merge($config_info, $this->getWeappStaticInfo()); } /** * 设置配置 * @param array $data - * @return \app\model\sys\SysConfig|bool|\think\Model + * @return SysConfig|bool|Model */ public function setWeappConfig(array $data){ return (new CoreWeappConfigService())->setWeappConfig($this->site_id, $data); diff --git a/niucloud/app/service/admin/weapp/WeappPackageService.php b/niucloud/app/service/admin/weapp/WeappPackageService.php index 84ae7dc53..fb12c5eaf 100644 --- a/niucloud/app/service/admin/weapp/WeappPackageService.php +++ b/niucloud/app/service/admin/weapp/WeappPackageService.php @@ -11,8 +11,6 @@ namespace app\service\admin\weapp; -use app\model\sys\SysMenu; -use app\service\core\weapp\CoreWeappConfigService; use core\base\BaseAdminService; /** diff --git a/niucloud/app/service/admin/weapp/WeappTemplateService.php b/niucloud/app/service/admin/weapp/WeappTemplateService.php index 50434361f..67c09b017 100644 --- a/niucloud/app/service/admin/weapp/WeappTemplateService.php +++ b/niucloud/app/service/admin/weapp/WeappTemplateService.php @@ -18,6 +18,9 @@ use core\base\BaseAdminService; use core\exception\NoticeException; use core\template\TemplateLoader; use EasyWeChat\Kernel\Exceptions\InvalidArgumentException; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; /** * easywechat主体提供 @@ -42,10 +45,14 @@ class WeappTemplateService extends BaseAdminService } return $template; } + /** * 同步微信公众号消息模板 * @param array $keys * @return true + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function syncAll(array $keys = []){ $site_id = $this->site_id; @@ -62,9 +69,6 @@ class WeappTemplateService extends BaseAdminService /** * @param $item * @return true - * @throws InvalidArgumentException - * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException - * @throws \GuzzleHttp\Exception\GuzzleException */ public function syncItem($item){ $key = $item['key'] ?? ''; diff --git a/niucloud/app/service/admin/wechat/WechatConfigService.php b/niucloud/app/service/admin/wechat/WechatConfigService.php index 08acb089b..5cdf30dd4 100644 --- a/niucloud/app/service/admin/wechat/WechatConfigService.php +++ b/niucloud/app/service/admin/wechat/WechatConfigService.php @@ -11,8 +11,10 @@ namespace app\service\admin\wechat; +use app\model\sys\SysConfig; use app\service\core\wechat\CoreWechatConfigService; use core\base\BaseAdminService; +use think\Model; /** * 微信配置模型 @@ -33,7 +35,7 @@ class WechatConfigService extends BaseAdminService /** * 设置配置 * @param array $data - * @return \app\model\sys\SysConfig|bool|\think\Model + * @return SysConfig|bool|Model */ public function setWechatConfig(array $data){ return (new CoreWechatConfigService())->setWechatConfig($this->site_id, $data); diff --git a/niucloud/app/service/admin/wechat/WechatMenuService.php b/niucloud/app/service/admin/wechat/WechatMenuService.php index 5a6f32a3e..342da6f15 100644 --- a/niucloud/app/service/admin/wechat/WechatMenuService.php +++ b/niucloud/app/service/admin/wechat/WechatMenuService.php @@ -17,6 +17,8 @@ use app\service\core\wechat\CoreWechatApiService; use core\base\BaseAdminService; use core\exception\WechatException; use EasyWeChat\Kernel\Exceptions\InvalidArgumentException; +use EasyWeChat\Kernel\Exceptions\InvalidConfigException; +use GuzzleHttp\Exception\GuzzleException; use think\Model; /** @@ -32,16 +34,16 @@ class WechatMenuService extends BaseAdminService */ public function getInfo(){ $core_config_service = new CoreConfigService(); - $menu = $core_config_service->getConfig($this->site_id, 'WECHAT_MENU')['value'] ?? []; - return $menu; + return $core_config_service->getConfig($this->site_id, 'WECHAT_MENU')['value'] ?? []; } /** * 更新微信菜单 - * @param $data + * @param array $data * @return SysConfig|bool|Model - * @throws InvalidArgumentException + * @throws GuzzleException + * @throws InvalidConfigException */ public function edit(array $data){ $core_wechat_api_service = new CoreWechatApiService(); diff --git a/niucloud/app/service/admin/wechat/WechatReplyService.php b/niucloud/app/service/admin/wechat/WechatReplyService.php index 8a168d7e8..af892571c 100644 --- a/niucloud/app/service/admin/wechat/WechatReplyService.php +++ b/niucloud/app/service/admin/wechat/WechatReplyService.php @@ -32,7 +32,7 @@ class WechatReplyService extends BaseAdminService /** *关键字回复列表 - * @return void + * @return array */ public function getKeywordPage(array $data = []){ @@ -41,7 +41,7 @@ class WechatReplyService extends BaseAdminService /** * 获取关键词回复信息 - * @param $id + * @param int $id * @return array */ public function getKeywordInfo(int $id){ @@ -50,8 +50,8 @@ class WechatReplyService extends BaseAdminService /** * 新增关键词回复 - * @param $data - * @return WechatReply + * @param array $data + * @return true */ public function addKeyword(array $data){ return $this->core_wechat_reply_service->addKeyword($this->site_id, $data); @@ -59,8 +59,9 @@ class WechatReplyService extends BaseAdminService /** * 更新关键词回复 - * @param $data - * @return void + * @param int $id + * @param array $data + * @return WechatReply */ public function editKeyword(int $id, array $data){ return $this->core_wechat_reply_service->editKeyword($this->site_id, $id, $data); @@ -68,7 +69,7 @@ class WechatReplyService extends BaseAdminService /** * 删除关键词回复 - * @return void + * @return void|null */ public function delKeyword(int $id){ return $this->core_wechat_reply_service->delKeyword($this->site_id, $id); @@ -76,7 +77,7 @@ class WechatReplyService extends BaseAdminService /** * 获取默认回复 - * @return void + * @return void|null */ public function getDefault(){ return $this->core_wechat_reply_service->delKeyword($this->site_id); @@ -84,8 +85,8 @@ class WechatReplyService extends BaseAdminService /** * 更新默认回复 - * @param $data - * @return void + * @param array $data + * @return void|null */ public function editDefault(array $data){ return $this->core_wechat_reply_service->editDefault($this->site_id, $data); @@ -94,7 +95,7 @@ class WechatReplyService extends BaseAdminService /** * 获取关注回复 - * @return void + * @return array */ public function getSubscribe(){ return $this->core_wechat_reply_service->getSubscribe($this->site_id); @@ -103,8 +104,8 @@ class WechatReplyService extends BaseAdminService /** * 更新关注回复 - * @param $data - * @return void + * @param array $data + * @return void|null */ public function editSubscribe(array $data){ return $this->core_wechat_reply_service->editSubscribe($this->site_id, $data); diff --git a/niucloud/app/service/admin/wechat/WechatTemplateService.php b/niucloud/app/service/admin/wechat/WechatTemplateService.php index 81ed77023..fc8a97e3c 100644 --- a/niucloud/app/service/admin/wechat/WechatTemplateService.php +++ b/niucloud/app/service/admin/wechat/WechatTemplateService.php @@ -18,6 +18,11 @@ use core\base\BaseAdminService; use core\exception\NoticeException; use core\template\TemplateLoader; use EasyWeChat\Kernel\Exceptions\InvalidArgumentException; +use EasyWeChat\Kernel\Exceptions\InvalidConfigException; +use GuzzleHttp\Exception\GuzzleException; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; /** * easywechat主体提供 @@ -32,6 +37,9 @@ class WechatTemplateService extends BaseAdminService * 同步微信公众号消息模板 * @param array $keys * @return true + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function syncAll(array $keys = []){ $site_id = $this->site_id; @@ -47,9 +55,6 @@ class WechatTemplateService extends BaseAdminService /** * @param $item * @return true - * @throws InvalidArgumentException - * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException - * @throws \GuzzleHttp\Exception\GuzzleException */ public function syncItem($item){ $key = $item['key'] ?? ''; diff --git a/niucloud/app/service/api/article/ArticleCategoryService.php b/niucloud/app/service/api/article/ArticleCategoryService.php index 827f30ed0..8d0c41882 100644 --- a/niucloud/app/service/api/article/ArticleCategoryService.php +++ b/niucloud/app/service/api/article/ArticleCategoryService.php @@ -30,6 +30,7 @@ class ArticleCategoryService extends BaseApiService /** * 获取文章分类列表 * @param array $where + * @return array */ public function getPage(array $where = []) { @@ -42,6 +43,7 @@ class ArticleCategoryService extends BaseApiService /** * 获取文章分类信息 * @param int $id + * @return array */ public function getInfo(int $id) { diff --git a/niucloud/app/service/api/article/ArticleService.php b/niucloud/app/service/api/article/ArticleService.php index 78eb0d7f4..63a0a2992 100644 --- a/niucloud/app/service/api/article/ArticleService.php +++ b/niucloud/app/service/api/article/ArticleService.php @@ -13,6 +13,9 @@ namespace app\service\api\article; use app\model\article\Article; use core\base\BaseApiService; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; /** * 文章服务层 @@ -31,7 +34,7 @@ class ArticleService extends BaseApiService /** * 获取文章列表 * @param array $where - * @param string $order + * @return array */ public function getPage(array $where = []) { @@ -45,10 +48,11 @@ class ArticleService extends BaseApiService /** * 文章列表 * @param array $where - * @return mixed - * @throws \think\db\exception\DataNotFoundException - * @throws \think\db\exception\DbException - * @throws \think\db\exception\ModelNotFoundException + * @param int $limit + * @return array + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function getAll(array $where = [], int $limit = 0){ $where[] = [ 'site_id', '=', $this->site_id ]; @@ -60,6 +64,7 @@ class ArticleService extends BaseApiService /** * 获取文章信息 * @param int $id + * @return array */ public function getInfo(int $id) { diff --git a/niucloud/app/service/api/captcha/CaptchaService.php b/niucloud/app/service/api/captcha/CaptchaService.php index e4a7022b2..8c211846a 100644 --- a/niucloud/app/service/api/captcha/CaptchaService.php +++ b/niucloud/app/service/api/captcha/CaptchaService.php @@ -32,7 +32,7 @@ class CaptchaService extends BaseApiService * @return array|null */ public function create(?array $data = []){ - return (new CoreCaptchaService())->create(0); + return (new CoreCaptchaService())->create(); } /** @@ -40,7 +40,7 @@ class CaptchaService extends BaseApiService * @return true */ public function check(){ - return (new CoreCaptchaService())->check(0); + return (new CoreCaptchaService())->check(); } } \ No newline at end of file diff --git a/niucloud/app/service/api/login/LoginService.php b/niucloud/app/service/api/login/LoginService.php index 0e31aa2bc..15ef3bf89 100644 --- a/niucloud/app/service/api/login/LoginService.php +++ b/niucloud/app/service/api/login/LoginService.php @@ -26,6 +26,7 @@ use core\util\TokenAuth; use Exception; use think\facade\Cache; use think\facade\Log; +use Throwable; /** * 登录服务层 @@ -55,7 +56,7 @@ class LoginService extends BaseApiService /** * 登录操作 * @param Member $member_info - * @param string $type 登录的操作终端类型 + * @param string $login_type * @return array */ public function login(Member $member_info, string $login_type) @@ -83,12 +84,12 @@ class LoginService extends BaseApiService * 账号登录 * @param string $username * @param string $password - * @return void + * @return array|false */ public function account(string $username, string $password) { $member_service = new MemberService(); - $member_info = $member_service->findMemberInfo(['username' => $username, 'site_id' => $this->site_id]); + $member_info = $member_service->findMemberInfo(['username|mobile' => $username, 'site_id' => $this->site_id]); if ($member_info->isEmpty()) throw new AuthException('MEMBER_NOT_EXIST');//账号不存在 if (!check_password($password, $member_info->password)) return false;//密码与账号不匹配 return $this->login($member_info, MemberLoginTypeDict::USERNAME); @@ -113,16 +114,16 @@ class LoginService extends BaseApiService return $this->login($member_info, MemberLoginTypeDict::MOBILE); } + /** * 生成token * @param $member_info - * @return array + * @return array|null */ public function createToken($member_info): ?array { $expire_time = env('system.api_token_expire_time') ?? 3600;//todo 不一定和管理端合用这个token时限 - $token_info = TokenAuth::createToken($member_info->member_id, AppTypeDict::API, ['member_id' => $member_info->member_id, 'username' => $member_info->username, 'site_id' => $member_info->site_id], $expire_time); - return $token_info; + return TokenAuth::createToken($member_info->member_id, AppTypeDict::API, ['member_id' => $member_info->member_id, 'username' => $member_info->username, 'site_id' => $member_info->site_id], $expire_time); } /** @@ -137,6 +138,8 @@ class LoginService extends BaseApiService /** * 清理token * @param int $member_id + * @param string|null $token + * @return bool|null */ public static function clearToken(int $member_id, ?string $token = ''): ?bool { @@ -147,9 +150,8 @@ class LoginService extends BaseApiService /** * 解析token - * @param string $token - * @return mixed - * @throws Exception + * @param string|null $token + * @return array */ public function parseToken(?string $token){ if(empty($token)) @@ -160,7 +162,7 @@ class LoginService extends BaseApiService try { $token_info = TokenAuth::parseToken($token, AppTypeDict::API); - } catch ( \Throwable $e ) { + } catch ( Throwable $e ) { // if(env('app_debug', false)){ // throw new AuthException($e->getMessage(), 401); // }else{ @@ -205,12 +207,11 @@ class LoginService extends BaseApiService $cache_tag_name = "mobile_key".$mobile.$type; Cache::tag($cache_tag_name)->clear(); } + /** * 校验手机验证码 - * @param $mobile - * @param $code - * @param $member_key - * @return void + * @param string $mobile + * @return true */ public function checkMobileCode(string $mobile){ if(empty($mobile)) throw new AuthException('MOBILE_NEEDED'); @@ -283,7 +284,9 @@ class LoginService extends BaseApiService $data = array( 'password' => $password_hash, ); - return $member_service->editByFind($member_info, $data); + $member_service->editByFind($member_info, $data); + self::clearToken($member_info['member_id'], $this->request->apiToken()); + return true; } public function loginScanCode(){ diff --git a/niucloud/app/service/api/login/RegisterService.php b/niucloud/app/service/api/login/RegisterService.php index 0bdc5413f..01d8fadf7 100644 --- a/niucloud/app/service/api/login/RegisterService.php +++ b/niucloud/app/service/api/login/RegisterService.php @@ -20,6 +20,9 @@ use app\service\api\member\MemberService; use app\service\core\member\CoreMemberService; use core\base\BaseApiService; use core\exception\AuthException; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; /** * 登录服务层 @@ -37,7 +40,14 @@ class RegisterService extends BaseApiService /** * 会员公共注册 + * @param string $mobile * @param $data + * @param string $type + * @param bool $is_verify_mobile + * @return array + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function register(string $mobile, $data, string $type, bool $is_verify_mobile = true) { @@ -73,8 +83,7 @@ class RegisterService extends BaseApiService } $member_info = $member_service->findMemberInfo([ 'member_id' => $member_id, 'site_id' => $this->site_id ]); if ($member_info->isEmpty()) throw new AuthException('MEMBER_NOT_EXIST');//账号已存在 - $result = ( new LoginService() )->login($member_info, $type); - return $result; + return ( new LoginService() )->login($member_info, $type); } /** @@ -87,7 +96,7 @@ class RegisterService extends BaseApiService $chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; $username = ''; for ($i = 0; $i < 6; $i++) { - $username .= $chars[ mt_rand(0, strlen($chars)) ]; + $username .= $chars[ random_int(0, strlen($chars)) ]; } return $microtime . strtoupper(base_convert(time() - 1420070400, 10, 36)) . $username; @@ -98,7 +107,8 @@ class RegisterService extends BaseApiService * 账号注册 * @param string $username * @param string $password - * @return void + * @param $mobile + * @return array */ public function account(string $username, string $password, $mobile) { @@ -119,14 +129,13 @@ class RegisterService extends BaseApiService 'username' => $username, 'password' => $password_hash, ); - $result = $this->register($mobile, $data, MemberRegisterTypeDict::USERNAME); - return $result; + return $this->register($mobile, $data, MemberRegisterTypeDict::USERNAME); } /** * 手机号注册 * @param $mobile - * @return Member|array|mixed|\think\Model + * @return array */ public function mobile($mobile) { @@ -142,8 +151,7 @@ class RegisterService extends BaseApiService $data = array ( 'mobile' => $mobile, ); - $result = $this->register($mobile, $data, MemberRegisterTypeDict::MOBILE); - return $result; + return $this->register($mobile, $data, MemberRegisterTypeDict::MOBILE); } /** diff --git a/niucloud/app/service/api/member/MemberAccountService.php b/niucloud/app/service/api/member/MemberAccountService.php index babecd302..9c01ad346 100644 --- a/niucloud/app/service/api/member/MemberAccountService.php +++ b/niucloud/app/service/api/member/MemberAccountService.php @@ -13,6 +13,7 @@ namespace app\service\api\member; use app\model\member\MemberAccountLog; use core\base\BaseApiService; +use think\db\exception\DbException; /** * 会员账户流水服务层(会员个人账户通过会员服务层查询) @@ -31,15 +32,14 @@ class MemberAccountService extends BaseApiService /** * 会员账户流水列表 * @param array $where - * @return mixed + * @return array */ public function getPage(array $where = []) { $where['member_id'] = $this->member_id; $field = 'id, member_id, site_id, account_type, account_data, from_type, related_id, create_time, memo'; $search_model = $this->model->where([['site_id', '=', $this->site_id]])->withSearch(['member_id','account_type', 'from_type', 'create_time'],$where)->field($field)->order('create_time desc')->append(['from_type_name', 'account_type_name']); - $list = $this->pageQuery($search_model); - return $list; + return $this->pageQuery($search_model); } /** * 账户流水详情 @@ -56,7 +56,7 @@ class MemberAccountService extends BaseApiService * 会员账户统计数量 * @param array $where * @return int - * @throws \think\db\exception\DbException + * @throws DbException */ public function getCount(array $where = []){ $where['member_id'] = $this->member_id; diff --git a/niucloud/app/service/api/member/MemberCashOutAccountService.php b/niucloud/app/service/api/member/MemberCashOutAccountService.php index d90a3b138..cb4564df9 100644 --- a/niucloud/app/service/api/member/MemberCashOutAccountService.php +++ b/niucloud/app/service/api/member/MemberCashOutAccountService.php @@ -28,7 +28,7 @@ class MemberCashOutAccountService extends BaseApiService /** * 会员提现账户列表 * @param array $where - * @return mixed + * @return array */ public function getPage(array $where = []) { @@ -37,8 +37,7 @@ class MemberCashOutAccountService extends BaseApiService $field = 'account_id,site_id,member_id,account_type,bank_name,realname,account_no'; $search_model = $this->model->where($where)->field($field)->order('create_time desc'); - $list = $this->pageQuery($search_model); - return $list; + return $this->pageQuery($search_model); } /** @@ -55,6 +54,8 @@ class MemberCashOutAccountService extends BaseApiService /** * 获取首条信息 * @param array $where + * @param string $order_field + * @param string $order * @return array */ public function getFirstInfo(array $where, $order_field = 'create_time', string $order = 'desc'){ @@ -93,8 +94,8 @@ class MemberCashOutAccountService extends BaseApiService /** * 删除 - * @param int $uid - * @return mixed + * @param int $account_id + * @return true */ public function del(int $account_id) { diff --git a/niucloud/app/service/api/member/MemberCashOutService.php b/niucloud/app/service/api/member/MemberCashOutService.php index f1a1df5af..f7cf0ee20 100644 --- a/niucloud/app/service/api/member/MemberCashOutService.php +++ b/niucloud/app/service/api/member/MemberCashOutService.php @@ -33,7 +33,7 @@ class MemberCashOutService extends BaseApiService /** * 会员提现列表 * @param array $where - * @return mixed + * @return array */ public function getPage(array $where = []) { @@ -42,8 +42,7 @@ class MemberCashOutService extends BaseApiService $field = 'id,site_id,cash_out_no,member_id,account_type,transfer_type,transfer_realname,transfer_mobile,transfer_bank,transfer_account,transfer_status,transfer_time,apply_money,rate,service_money,money,audit_time,status,remark,create_time,refuse_reason'; $search_model = $this->model->where($where)->withSearch(['member_id','status', 'create_time'],$where)->with(['memberInfo', 'transfer'])->field($field)->append(['account_type_name', 'transfer_type_name', 'status_name', 'transfer_status_name'])->order('create_time desc'); - $list = $this->pageQuery($search_model); - return $list; + return $this->pageQuery($search_model); } /** @@ -60,7 +59,7 @@ class MemberCashOutService extends BaseApiService /** * 申请提现 - * @param $data + * @param array $data * @return true */ public function apply(array $data){ @@ -71,8 +70,6 @@ class MemberCashOutService extends BaseApiService /** * 撤销提现申请 - * @param int $site_id - * @param int $member_id * @param int $id * @return true */ diff --git a/niucloud/app/service/api/member/MemberService.php b/niucloud/app/service/api/member/MemberService.php index c28dd2593..e1d77e4d8 100644 --- a/niucloud/app/service/api/member/MemberService.php +++ b/niucloud/app/service/api/member/MemberService.php @@ -15,6 +15,7 @@ use app\model\member\Member; use app\service\core\member\CoreMemberService; use core\base\BaseApiService; use core\exception\ApiException; +use core\util\Barcode; use think\db\exception\DataNotFoundException; use think\db\exception\DbException; use think\db\exception\ModelNotFoundException; @@ -44,7 +45,6 @@ class MemberService extends BaseApiService /** * 更新会员 - * @param int $member_id * @param array $data * @return true */ @@ -60,9 +60,6 @@ class MemberService extends BaseApiService /** * 获取会员信息 * @return array - * @throws DataNotFoundException - * @throws DbException - * @throws ModelNotFoundException */ public function getInfo() { @@ -101,13 +98,14 @@ class MemberService extends BaseApiService if(!empty($data['weapp_openid'])) $where[] = ['weapp_openid', '=', $data['weapp_openid']]; + if(!empty($data['username|mobile'])) + $where[] = ['username|mobile', '=', $data['username|mobile']]; if(empty($where)){ $where[] = ['member_id', '=', -1]; } if(isset($data['site_id']) ) $where[] = ['site_id', '=', $data['site_id']]; - $member = $this->model->where($where)->findOrEmpty(); - return $member; + return $this->model->where($where)->findOrEmpty(); } /** @@ -119,9 +117,9 @@ class MemberService extends BaseApiService public function editByFind($member, $data){ return $member->save($data); } + /** * 修改字段 - * @param int $member_id * @param string $field * @param $data * @return null @@ -131,4 +129,19 @@ class MemberService extends BaseApiService return (new CoreMemberService())->modify($this->site_id, $this->member_id, $field, $data); } + public function getQrcode(){ + // 生成会员二维码 + $qrcode_dir = 'upload/member/temp'; + if (!is_dir($qrcode_dir)) mkdir($qrcode_dir, intval('0755', 8), true); + $id = "member-".$this->member_id; + $qrcode_path = "{$qrcode_dir}/order_qrcode_{$this->member_id}.png"; + \core\util\QRcode::png($id, $qrcode_path, 'L', 16, 1); + + // 生成会员条形码 + $barcode_path = (new Barcode(14, $id))->generateBarcode($qrcode_dir, 2); + $detail = []; + $detail['verify_code_qrcode'] = image_to_base64($qrcode_path, true); + $detail['verify_code_barcode'] = image_to_base64($barcode_path); + return $detail; + } } \ No newline at end of file diff --git a/niucloud/app/service/api/notice/NoticeService.php b/niucloud/app/service/api/notice/NoticeService.php index 1aa8149e5..153d38a4c 100644 --- a/niucloud/app/service/api/notice/NoticeService.php +++ b/niucloud/app/service/api/notice/NoticeService.php @@ -40,11 +40,10 @@ class NoticeService extends BaseApiService /** * 获取微信小程序订阅消息模板id - * @param string $keywords - * @return void + * @param string $keys + * @return array */ public function getWeappNoticeTemplateId(string $keys) { - $column = (new SysNotice())->where([ ['site_id', '=', $this->site_id], ['key', 'in', explode(',', $keys) ], ['weapp_template_id', '<>', ''], ['is_weapp', '=', 1] ])->column('weapp_template_id'); - return $column; + return (new SysNotice())->where([ ['site_id', '=', $this->site_id], ['key', 'in', explode(',', $keys) ], ['weapp_template_id', '<>', ''], ['is_weapp', '=', 1] ])->column('weapp_template_id'); } } \ No newline at end of file diff --git a/niucloud/app/service/api/order/RechargeOrderService.php b/niucloud/app/service/api/order/RechargeOrderService.php index ab333287f..d8126af99 100644 --- a/niucloud/app/service/api/order/RechargeOrderService.php +++ b/niucloud/app/service/api/order/RechargeOrderService.php @@ -45,7 +45,7 @@ class RechargeOrderService extends BaseApiService /** * 充值订单分页列表 * @param array $where - * @return mixed + * @return array */ public function getPage(array $where) { @@ -68,8 +68,8 @@ class RechargeOrderService extends BaseApiService /** * 充值订单详情 - * @param array $where - * @return mixed + * @param int $order_id + * @return array */ public function getDetail(int $order_id) { diff --git a/niucloud/app/service/api/pay/PayService.php b/niucloud/app/service/api/pay/PayService.php index 2dbed2963..1a1bee3d1 100644 --- a/niucloud/app/service/api/pay/PayService.php +++ b/niucloud/app/service/api/pay/PayService.php @@ -15,7 +15,9 @@ use app\dict\common\ChannelDict; use app\service\core\member\CoreMemberService; use app\service\core\pay\CorePayService; use core\base\BaseApiService; -use Yansongda\Supports\Collection; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; /** * 支付业务 @@ -32,49 +34,48 @@ class PayService extends BaseApiService /** * 去支付 - * @param $site_id - * @param $type - * @param $out_trade_no - * @param $money - * @param $boby - * @param $channel - * @param $refund_url - * @param $quit_url - * @param $buyer_id + * @param string $type + * @param string $trade_type + * @param int $trade_id + * @param string $return_url + * @param string $quit_url + * @param string $buyer_id * @return mixed + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ - public function pay(string $type, string $out_trade_no, string $return_url = '', string $quit_url = '', string $buyer_id = ''){ + public function pay(string $type, string $trade_type, int $trade_id, string $return_url = '', string $quit_url = '', string $buyer_id = '', string $voucher = ''){ $member = (new CoreMemberService())->getInfoByMemberId($this->site_id, $this->member_id); switch ($this->channel) { case ChannelDict::WECHAT://公众号 $openid = $member['wx_openid'] ?? ''; - break; case ChannelDict::WEAPP://微信小程序 $openid = $member['weapp_openid'] ?? ''; break; } - return $this->core_pay_service->pay($this->site_id, $out_trade_no, $type, $this->channel, $openid ?? '', $return_url, $quit_url, $buyer_id); + return $this->core_pay_service->pay($this->site_id, $trade_type, $trade_id, $type, $this->channel, $openid ?? '', $return_url, $quit_url, $buyer_id, $voucher); } /** * 关闭支付 - * @param $site_id - * @param $type - * @param $out_trade_no + * @param string $type + * @param string $out_trade_no * @return null */ public function close(string $type, string $out_trade_no){ - return $this->core_pay_service->close($this->site_id, $type, $out_trade_no); + return $this->core_pay_service->close($this->site_id, $type); } /** * 支付异步通知 - * @param $site_id - * @param $type - * @return void + * @param string $channel + * @param string $type + * @param string $action + * @return void|null */ public function notify(string $channel, string $type, string $action){ return $this->core_pay_service->notify($this->site_id, $channel, $type, $action); @@ -83,9 +84,25 @@ class PayService extends BaseApiService /** * 通过交易流水号查询支付信息以及支付方式 * @param $out_trade_no - * @return mixed + * @return array */ public function getInfoByOutTradeNo($out_trade_no){ return $this->core_pay_service->getInfoByOutTradeNo($this->site_id, $out_trade_no, $this->channel); } + + public function getInfoByTrade(string $trade_type, int $trade_id){ + return $this->core_pay_service->getInfoByTrade($this->site_id, $trade_type, $trade_id, $this->channel); + } + + /** + * 获取支付方法 + * @param string $trade_type + * @return array|array[] + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException + */ + public function getPayTypeByTrade(string $trade_type){ + return $this->core_pay_service->getPayTypeByTrade($this->site_id, $trade_type, $this->channel); + } } \ No newline at end of file diff --git a/niucloud/app/service/api/scan/ScanService.php b/niucloud/app/service/api/scan/ScanService.php index 2511f9249..93dfdbc99 100644 --- a/niucloud/app/service/api/scan/ScanService.php +++ b/niucloud/app/service/api/scan/ScanService.php @@ -23,6 +23,7 @@ use core\base\BaseApiService; class ScanService extends BaseApiService { private $core_scan_service; + public function __construct() { parent::__construct(); @@ -35,7 +36,8 @@ class ScanService extends BaseApiService * @param string $key * @return mixed */ - public function checkScan(string $key){ + public function checkScan(string $key) + { return $this->core_scan_service->checkScan($this->site_id, $key); } diff --git a/niucloud/app/service/api/upload/Base64Service.php b/niucloud/app/service/api/upload/Base64Service.php index 669d0c56b..6f9582fed 100644 --- a/niucloud/app/service/api/upload/Base64Service.php +++ b/niucloud/app/service/api/upload/Base64Service.php @@ -13,6 +13,7 @@ namespace app\service\api\upload; use app\service\core\upload\CoreBase64Service; use core\base\BaseApiService; +use Exception; /** * 用户服务层 @@ -26,8 +27,9 @@ class Base64Service extends BaseApiService /** * 远程拉取图片 - * @param $url + * @param string $content * @return array + * @throws Exception */ public function image(string $content){ diff --git a/niucloud/app/service/api/upload/FetchService.php b/niucloud/app/service/api/upload/FetchService.php index 5a64bdb1c..96dab57ff 100644 --- a/niucloud/app/service/api/upload/FetchService.php +++ b/niucloud/app/service/api/upload/FetchService.php @@ -13,6 +13,7 @@ namespace app\service\api\upload; use app\service\core\upload\CoreFetchService; use core\base\BaseApiService; +use Exception; /** * 用户服务层 @@ -26,8 +27,9 @@ class FetchService extends BaseApiService /** * 远程拉取图片 - * @param $url + * @param string $url * @return array + * @throws Exception */ public function image(string $url){ diff --git a/niucloud/app/service/api/upload/UploadService.php b/niucloud/app/service/api/upload/UploadService.php index be58b7cb5..6c1e23bb0 100644 --- a/niucloud/app/service/api/upload/UploadService.php +++ b/niucloud/app/service/api/upload/UploadService.php @@ -16,6 +16,7 @@ use app\dict\sys\StorageDict; use app\service\core\upload\CoreUploadService; use core\base\BaseApiService; use core\exception\UploadFileException; +use Exception; /** * 用户服务层 @@ -29,9 +30,9 @@ class UploadService extends BaseApiService /** * 附件库上传图片 - * @param int $cate_id - * @param string $dir + * @param $file * @return array + * @throws Exception */ public function image($file) { @@ -43,8 +44,8 @@ class UploadService extends BaseApiService /** * 附件库上传视频 * @param $file - * @param int $cate_id * @return array + * @throws Exception */ public function video($file) { @@ -56,7 +57,9 @@ class UploadService extends BaseApiService /** * 文件上传 * @param $file + * @param string $type * @return array + * @throws Exception */ public function document($file, string $type = '') { diff --git a/niucloud/app/service/api/weapp/WeappAuthService.php b/niucloud/app/service/api/weapp/WeappAuthService.php index 95517fbdc..134357d66 100644 --- a/niucloud/app/service/api/weapp/WeappAuthService.php +++ b/niucloud/app/service/api/weapp/WeappAuthService.php @@ -13,6 +13,7 @@ namespace app\service\api\weapp; use app\dict\member\MemberLoginTypeDict; use app\dict\member\MemberRegisterTypeDict; +use app\model\member\Member; use app\service\api\login\LoginService; use app\service\api\login\RegisterService; use app\service\api\member\MemberConfigService; @@ -22,6 +23,12 @@ use core\base\BaseApiService; use core\exception\ApiException; use core\exception\AuthException; use EasyWeChat\Kernel\Exceptions\InvalidArgumentException; +use EasyWeChat\Kernel\Exceptions\InvalidConfigException; +use GuzzleHttp\Exception\GuzzleException; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; +use think\Model; /** @@ -42,10 +49,8 @@ class WeappAuthService extends BaseApiService /** * 通过code获取微信小程序用户信息 * @param string $code - * @param string $iv - * @param string $encrypted_data * @return array - * @throws InvalidArgumentException + * @throws InvalidConfigException */ public function getUserInfoByCode(string $code){ // $iv = $this->request->param('iv', ''); @@ -72,8 +77,7 @@ class WeappAuthService extends BaseApiService /** * 登录 * @param string $code - * @return \app\model\member\Member|array|mixed|\think\Model - * @throws InvalidArgumentException + * @return array */ public function login(string $code) { @@ -108,10 +112,15 @@ class WeappAuthService extends BaseApiService /** * 注册 - * @param string|array $data + * @param string $openid * @param string $mobile - * @return \app\model\member\Member|array|mixed|\think\Model - * @throws InvalidArgumentException + * @param string $mobile_code + * @return array + * @throws DataNotFoundException + * @throws DbException + * @throws GuzzleException + * @throws InvalidConfigException + * @throws ModelNotFoundException */ public function register(string $openid, string $mobile = '', string $mobile_code = ''){ @@ -136,14 +145,13 @@ class WeappAuthService extends BaseApiService if(!$member_info->isEmpty()) throw new AuthException('MEMBER_IS_EXIST');//账号已存在, 不能在注册 $register_service = new RegisterService(); - $result = $register_service->register($mobile ?? '', + return $register_service->register($mobile ?? '', [ 'weapp_openid' => $openid ], MemberRegisterTypeDict::WEAPP, $is_verify_mobile ?? false ); - return $result; } diff --git a/niucloud/app/service/api/wechat/WechatAuthService.php b/niucloud/app/service/api/wechat/WechatAuthService.php index 497959020..fc6d92ff8 100644 --- a/niucloud/app/service/api/wechat/WechatAuthService.php +++ b/niucloud/app/service/api/wechat/WechatAuthService.php @@ -26,6 +26,9 @@ use core\base\BaseApiService; use core\exception\ApiException; use core\exception\AuthException; use EasyWeChat\Kernel\Exceptions\InvalidArgumentException; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; /** @@ -46,10 +49,9 @@ class WechatAuthService extends BaseApiService /** * 网页授权 - * @param $url - * @param $scopes - * @return string - * @throws InvalidArgumentException + * @param string $url + * @param string $scopes + * @return array */ public function authorization(string $url = '', string $scopes = 'snsapi_base') { @@ -59,9 +61,8 @@ class WechatAuthService extends BaseApiService /** * 处理授权回调 - * @param $code - * @return string - * @throws InvalidArgumentException + * @param string $code + * @return array */ public function userFromCode(string $code) { @@ -87,17 +88,24 @@ class WechatAuthService extends BaseApiService * 登录通过code * @param string $code * @return array|string[]|null - * @throws InvalidArgumentException + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function loginByCode(string $code){ [$avatar, $nickname, $openid] = $this->userFromCode($code); return $this->login($openid, $nickname, $avatar); } + /** * 公众号登录 - * @param string $code + * @param string $openid + * @param string $nickname + * @param string $avatar * @return array|null - * @throws InvalidArgumentException + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function login(string $openid, string $nickname = '', string $avatar = '') { @@ -124,7 +132,6 @@ class WechatAuthService extends BaseApiService * 同步数据 * @param string $code * @return true - * @throws InvalidArgumentException */ public function sync(string $code) { @@ -142,9 +149,14 @@ class WechatAuthService extends BaseApiService /** * 注册 - * @param string|array $data - * @return void - * @throws InvalidArgumentException + * @param string $openid + * @param string $mobile + * @param string $nickname + * @param string $avatar + * @return array + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function register(string $openid, string $mobile = '', string $nickname = '', string $avatar = '') { @@ -152,7 +164,7 @@ class WechatAuthService extends BaseApiService $member_info = $member_service->findMemberInfo(['wx_openid' => $openid, 'site_id' => $this->site_id]); if (!$member_info->isEmpty()) throw new AuthException('MEMBER_IS_EXIST');//账号已存在, 不能在注册 $register_service = new RegisterService(); - $result = $register_service->register($mobile, + return $register_service->register($mobile, [ 'wx_openid' => $openid, 'nickname' => $nickname, @@ -160,7 +172,6 @@ class WechatAuthService extends BaseApiService ], MemberRegisterTypeDict::WECHAT ); - return $result; } diff --git a/niucloud/app/service/api/wechat/WechatServeService.php b/niucloud/app/service/api/wechat/WechatServeService.php index dfb3de938..b953794b1 100644 --- a/niucloud/app/service/api/wechat/WechatServeService.php +++ b/niucloud/app/service/api/wechat/WechatServeService.php @@ -18,6 +18,7 @@ use EasyWeChat\Kernel\Exceptions\InvalidArgumentException; use EasyWeChat\Kernel\Exceptions\RuntimeException; use Psr\Http\Message\ResponseInterface; use ReflectionException; +use Symfony\Component\HttpFoundation\Response; use Throwable; /** @@ -37,10 +38,9 @@ class WechatServeService extends BaseApiService /** * 消息与时间推送 - * @return ResponseInterface + * @return Response * @throws BadRequestException * @throws InvalidArgumentException - * @throws RuntimeException * @throws ReflectionException * @throws Throwable */ diff --git a/niucloud/app/service/core/addon/CoreAddonBaseService.php b/niucloud/app/service/core/addon/CoreAddonBaseService.php index 0dad616b7..67d6c6167 100644 --- a/niucloud/app/service/core/addon/CoreAddonBaseService.php +++ b/niucloud/app/service/core/addon/CoreAddonBaseService.php @@ -22,11 +22,12 @@ use core\exception\CommonException; class CoreAddonBaseService extends BaseCoreService { //系统整体根目录 - protected $root_path; - //插件整体目录 - protected $addon_path; - //插件整体缓存标识 public static $cache_tag_name = 'addon_cash'; + //插件整体目录 + protected $root_path; + //插件整体缓存标识 + protected $addon_path; + public function __construct() { parent::__construct(); @@ -42,13 +43,13 @@ class CoreAddonBaseService extends BaseCoreService public function getAddonConfig(string $addon) { $path = $this->addon_path . $addon . DIRECTORY_SEPARATOR . 'info.json'; - $resource_path = $this->addon_path . $addon . DIRECTORY_SEPARATOR.'resource'.DIRECTORY_SEPARATOR; + $resource_path = $this->addon_path . $addon . DIRECTORY_SEPARATOR . 'resource' . DIRECTORY_SEPARATOR; if (is_file($path)) { $json_string = file_get_contents($path); // 用参数true把JSON字符串强制转成PHP数组 $info = json_decode($json_string, true); - $info['icon'] = $resource_path.'icon.png'; - $info['cover'] = $resource_path.'cover.png'; + $info['icon'] = $resource_path . 'icon.png'; + $info['cover'] = $resource_path . 'cover.png'; } return $info ?? []; } @@ -60,7 +61,7 @@ class CoreAddonBaseService extends BaseCoreService */ public function getAddonConfigPath(string $addon) { - return $this->addon_path . $addon . DIRECTORY_SEPARATOR . 'config'. DIRECTORY_SEPARATOR; + return $this->addon_path . $addon . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR; } /** @@ -70,32 +71,34 @@ class CoreAddonBaseService extends BaseCoreService */ public function geAddonPackagePath(string $addon) { - return $this->addon_path . $addon . DIRECTORY_SEPARATOR . 'package'. DIRECTORY_SEPARATOR; + return $this->addon_path . $addon . DIRECTORY_SEPARATOR . 'package' . DIRECTORY_SEPARATOR; } /** * 读取json文件转化成数组返回 - * @param $json_file_path //json文件目录 + * @param $json_file_path //json文件目录 */ protected function jsonFileToArray(string $json_file_path) { if (file_exists($json_file_path)) { $content_json = @file_get_contents($json_file_path); return json_decode($content_json, true); - }else + } else return []; } /** * 读取json文件转化成数组返回 - * @param $json_file_path //json文件目录 + * @param array $content + * @param string $file_path + * @return true */ protected function writeArrayToJsonFile(array $content, string $file_path) { - $content_json = json_encode($content, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT); - $result = @file_put_contents($file_path, $content_json); + $content_json = json_encode($content, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT); + $result = @file_put_contents($file_path, $content_json); if (!$result) { - throw new CommonException($file_path.'文件不存在或者权限不足'); + throw new CommonException($file_path . '文件不存在或者权限不足'); } return true; } diff --git a/niucloud/app/service/core/addon/CoreAddonDownloadService.php b/niucloud/app/service/core/addon/CoreAddonDownloadService.php new file mode 100644 index 000000000..f5b118680 --- /dev/null +++ b/niucloud/app/service/core/addon/CoreAddonDownloadService.php @@ -0,0 +1,86 @@ +model = new Addon(); + $this->addon_download_path = 'upload/download/'; + } + + /** + * 下载文件 + * @param $app_key + * @return true + * @throws GuzzleException + * @throws GuzzleException + */ + public function download($app_key) + { + $app_path = $this->addon_path . $app_key . '/'; + //先判断当前的应用在本地是否存在 +// if(is_dir($app_path)) throw new NiucloudException(); + $app_download_path = $this->addon_download_path . $app_key . '/'; + //下载文件到本地 + $zip_file = (new CoreModuleService())->downloadModule($app_key, $app_download_path); + //解压到应用addon下 + //删除旧版本文件 + del_target_dir($app_path, true); + //解压文件 + $this->unzip($zip_file, $this->addon_path); + //删除压缩包 + @unlink($zip_file); + return true; + } + + /** + * 解压压缩包 + * @param $file + * @param $dir + * @return mixed|string + */ + public function unzip($file, $dir) + { + if (!file_exists($file)) throw new AddonException('ZIP_FILE_NOT_FOUND'); + $zip = new ZipArchive(); + if ($zip->open($file) === TRUE) { + // 对Zip文件进行解压缩操作 + $zip->extractTo($dir); + $zip->close(); + } else { + throw new AddonException('ZIP_FILE_NOT_FOUND'); + } + return $dir; + } + + public function update() + { + + } +} \ No newline at end of file diff --git a/niucloud/app/service/core/addon/CoreAddonInstallService.php b/niucloud/app/service/core/addon/CoreAddonInstallService.php index 7cf636f1f..7bb0edaa8 100644 --- a/niucloud/app/service/core/addon/CoreAddonInstallService.php +++ b/niucloud/app/service/core/addon/CoreAddonInstallService.php @@ -20,10 +20,12 @@ use app\service\core\schedule\CoreScheduleInstallService; use core\exception\AddonException; use core\exception\CommonException; use core\util\Terminal; +use think\db\exception\DbException; use think\db\exception\PDOException; use think\facade\Cache; use think\facade\Db; use think\helper\Str; +use think\Response; /** * 安装服务层 @@ -33,22 +35,22 @@ use think\helper\Str; class CoreAddonInstallService extends CoreAddonBaseService { use WapTrait; - private $files = [ - 'niucloud' => [], - 'admin' => [], - 'web' => [], - 'wap' => [], - 'resource' => [] - ]; + + const WAIT_INSTALL = 'wait_install'; // 安装流程 - private $flow_path = [ - 'file', - 'sql', - 'menu', - 'diy' - ]; + const DIR_INSTALLED = 'dir_installed'; + const SQL_INSTALLED = 'sql_installed'; + const MENU_INSTALLED = 'menu_installed'; + const SCHEDULE_INSTALLED = 'schedule_installed';// 待安装的插件目录 + // 对象实例 + const WAIT_DEPEND = 'wait_depend'; + + // 状态关键字 + const INSTALL_SUCCESS = 'install_success'; + const INSTALL_FAIL = 'install_fail'; + public static $instance; /** * 需要迁移的文件,用于检测是否冲突 * @var array[] @@ -58,30 +60,21 @@ class CoreAddonInstallService extends CoreAddonBaseService 'web' => [], 'wap' => [], ]; - + private $files = [ + 'niucloud' => [], + 'admin' => [], + 'web' => [], + 'wap' => [], + 'resource' => [] + ]; + private $flow_path = [ + 'file', + 'sql', + 'menu', + 'diy' + ]; private $addon; - private $install_addon_path;// 待安装的插件目录 - - // 对象实例 - public static $instance; - - // 状态关键字 - const WAIT_INSTALL = 'wait_install'; - - const DIR_INSTALLED = 'dir_installed'; - - const SQL_INSTALLED = 'sql_installed'; - - const MENU_INSTALLED = 'menu_installed'; - - const SCHEDULE_INSTALLED = 'schedule_installed'; - - const WAIT_DEPEND = 'wait_depend'; - - const INSTALL_SUCCESS = 'install_success'; - - const INSTALL_FAIL = 'install_fail'; - +private $install_addon_path; private $state; // 安装任务 @@ -89,19 +82,6 @@ class CoreAddonInstallService extends CoreAddonBaseService private $cache_key = ''; - /** - * 初始化实例 - * @param string $uid - * @return static - */ - public static function instance(string $addon) - { - if (is_null(self::$instance)) { - self::$instance = new static($addon); - } - return self::$instance; - } - public function __construct($addon) { parent::__construct(); @@ -112,9 +92,22 @@ class CoreAddonInstallService extends CoreAddonBaseService $this->task = Cache::get($this->cache_key, []); } + /** + * 初始化实例 + * @param string $addon + * @return static + */ + public static function instance(string $addon) + { + if (is_null(self::$instance)) { + self::$instance = new static($addon); + } + return self::$instance; + } + /** * 安装前检测 - * @return void + * @return array */ public function installCheck() { @@ -133,7 +126,7 @@ class CoreAddonInstallService extends CoreAddonBaseService $package_path = $this->install_addon_path . 'package' . DIRECTORY_SEPARATOR; $package_file = []; search_dir($package_path, $package_file); - $package_file = array_map(function($file) use ($package_path) { + $package_file = array_map(function ($file) use ($package_path) { return str_replace($package_path . DIRECTORY_SEPARATOR, '', $file); }, $package_file); @@ -147,38 +140,38 @@ class CoreAddonInstallService extends CoreAddonBaseService ], // 运行环境检测 'runtime' => [], - 'job_normal' => ( new SystemService() )->checkJob(), + 'job_normal' => (new SystemService())->checkJob(), 'conflict_files' => $this->dirCheck() ]; - if (is_dir($from_admin_dir)) array_push($data[ 'dir' ][ 'is_readable' ], [ 'dir' => str_replace(project_path(), '', $from_admin_dir), 'status' => is_readable($from_admin_dir) ]); - if (is_dir($from_web_dir)) array_push($data[ 'dir' ][ 'is_readable' ], [ 'dir' => str_replace(project_path(), '', $from_web_dir), 'status' => is_readable($from_web_dir) ]); - if (is_dir($from_wap_dir)) array_push($data[ 'dir' ][ 'is_readable' ], [ 'dir' => str_replace(project_path(), '', $from_wap_dir), 'status' => is_readable($from_wap_dir) ]); - if (is_dir($from_resource_dir)) array_push($data[ 'dir' ][ 'is_readable' ], [ 'dir' => str_replace(project_path(), '', $from_resource_dir), 'status' => is_readable($from_resource_dir) ]); + if (is_dir($from_admin_dir)) $data['dir']['is_readable'][] = ['dir' => str_replace(project_path(), '', $from_admin_dir), 'status' => is_readable($from_admin_dir)]; + if (is_dir($from_web_dir)) $data['dir']['is_readable'][] = ['dir' => str_replace(project_path(), '', $from_web_dir), 'status' => is_readable($from_web_dir)]; + if (is_dir($from_wap_dir)) $data['dir']['is_readable'][] = ['dir' => str_replace(project_path(), '', $from_wap_dir), 'status' => is_readable($from_wap_dir)]; + if (is_dir($from_resource_dir)) $data['dir']['is_readable'][] = ['dir' => str_replace(project_path(), '', $from_resource_dir), 'status' => is_readable($from_resource_dir)]; - if (is_dir($to_admin_dir)) array_push($data[ 'dir' ][ 'is_write' ], [ 'dir' => str_replace(project_path(), '', $to_admin_dir), 'status' => is_write($to_admin_dir) ]); - if (is_dir($to_web_dir)) array_push($data[ 'dir' ][ 'is_write' ], [ 'dir' => str_replace(project_path(), '', $to_web_dir), 'status' => is_write($to_web_dir) ]); - if (is_dir($to_wap_dir)) array_push($data[ 'dir' ][ 'is_write' ], [ 'dir' => str_replace(project_path(), '', $to_wap_dir), 'status' => is_write($to_wap_dir) ]); - if (is_dir($to_resource_dir)) array_push($data[ 'dir' ][ 'is_write' ], [ 'dir' => str_replace(project_path(), '', $to_resource_dir), 'status' => is_write($to_resource_dir) ]); + if (is_dir($to_admin_dir)) $data['dir']['is_write'][] = ['dir' => str_replace(project_path(), '', $to_admin_dir), 'status' => is_write($to_admin_dir)]; + if (is_dir($to_web_dir)) $data['dir']['is_write'][] = ['dir' => str_replace(project_path(), '', $to_web_dir), 'status' => is_write($to_web_dir)]; + if (is_dir($to_wap_dir)) $data['dir']['is_write'][] = ['dir' => str_replace(project_path(), '', $to_wap_dir), 'status' => is_write($to_wap_dir)]; + if (is_dir($to_resource_dir)) $data['dir']['is_write'][] = ['dir' => str_replace(project_path(), '', $to_resource_dir), 'status' => is_write($to_resource_dir)]; if (in_array('composer.json', $package_file)) { - array_push($data[ 'runtime' ], [ 'name' => 'composer', 'status' => Terminal::execute(root_path(), 'composer -V') === true ]); + $data['runtime'][] = ['name' => 'composer', 'status' => Terminal::execute(root_path(), 'composer -V') === true]; } if (in_array('admin-package.json', $package_file) || in_array('web-package.json', $package_file) || in_array('uni-app-package.json', $package_file)) { - array_push($data[ 'runtime' ], [ 'name' => 'npm', 'status' => Terminal::execute(root_path(), 'npm -v') === true ]); + $data['runtime'][] = ['name' => 'npm', 'status' => Terminal::execute(root_path(), 'npm -v') === true]; } $check_res = array_merge( - array_column($data[ 'dir' ][ 'is_readable' ], 'status'), - array_column($data[ 'dir' ][ 'is_write' ], 'status'), - array_column($data[ 'runtime' ], 'status'), - [ $data[ 'job_normal' ] ] + array_column($data['dir']['is_readable'], 'status'), + array_column($data['dir']['is_write'], 'status'), + array_column($data['runtime'], 'status'), + [$data['job_normal']] ); - if (count($data[ 'conflict_files' ])) array_push($check_res, false); + if (count($data['conflict_files'])) $check_res[] = false; // 是否通过校验 - $data[ 'is_pass' ] = !in_array(false, $check_res); - Cache::set($this->cache_key . '_install_check', $data[ 'is_pass' ], 120); + $data['is_pass'] = !in_array(false, $check_res); + Cache::set($this->cache_key . '_install_check', $data['is_pass'], 120); return $data; } @@ -200,8 +193,8 @@ class CoreAddonInstallService extends CoreAddonBaseService //检测admin文件 if (is_dir($from_admin_dir)) { - search_dir($from_admin_dir, $this->install_files[ "admin" ]); - foreach ($this->install_files[ 'admin' ] as $admin_file) { + search_dir($from_admin_dir, $this->install_files["admin"]); + foreach ($this->install_files['admin'] as $admin_file) { $file_path = str_replace($from_admin_dir, "", $admin_file); if (is_file($to_admin_dir . $file_path)) $conflict_files[] = str_replace(project_path(), '', $admin_file); @@ -210,8 +203,8 @@ class CoreAddonInstallService extends CoreAddonBaseService //检测web端文件 if (is_dir($from_web_dir)) { - search_dir($from_web_dir, $this->install_files[ "web" ]); - foreach ($this->install_files[ 'web' ] as $web_file) { + search_dir($from_web_dir, $this->install_files["web"]); + foreach ($this->install_files['web'] as $web_file) { $file_path = str_replace($from_web_dir, "", $web_file); if (is_file($to_web_dir . $file_path)) $conflict_files[] = str_replace(project_path(), '', $web_file); @@ -220,8 +213,8 @@ class CoreAddonInstallService extends CoreAddonBaseService //检测wap的uniapp文件 if (is_dir($from_wap_dir)) { - search_dir($from_wap_dir, $this->install_files[ "wap" ]); - foreach ($this->install_files[ 'wap' ] as $wap_file) { + search_dir($from_wap_dir, $this->install_files["wap"]); + foreach ($this->install_files['wap'] as $wap_file) { $file_path = str_replace($from_wap_dir, "", $wap_file); if (is_file($to_wap_dir . $file_path)) $conflict_files[] = str_replace(project_path(), '', $wap_file); @@ -231,6 +224,218 @@ class CoreAddonInstallService extends CoreAddonBaseService return $conflict_files; } + /** + * + * @return true + */ + public function executeInstall() + { + if (empty($this->task)) throw new CommonException('ADDON_INSTALL_NOT_EXIST'); + + $check_res = Cache::get($this->cache_key . '_install_check'); + if (!$check_res) throw new CommonException('INSTALL_CHECK_NOT_PASS'); + + if ($this->task['installDir']['state'] == AddonDict::INSTALL_UNEXECUTED) AddonInstall::invoke(['addon' => $this->addon, 'task' => 'installDir']); + return true; + } + + /** + * 执行任务 + * @param string $task + * @return Response + */ + public function executeTask(string $task) + { + if (empty($this->task) || !isset($this->task[$task])) throw new CommonException('ADDON_INSTALL_NOT_EXIST'); + if ($this->task[$task]['state'] != AddonDict::INSTALL_UNEXECUTED) throw new CommonException('ADDON_INSTALL_EXECUTED'); + + $this->setTaskState($task, AddonDict::INPROGRESS); + + $result = Terminal::execute(root_path(), $this->task[$task]['command']); + + // 变更任务状态 + if ($result === true) { + if ($task != 'installComplete') { + $this->setTaskState($task, AddonDict::INSTALL_SUCCESS); + $task_key = array_keys($this->task); + AddonInstall::invoke(['addon' => $this->addon, 'task' => $task_key[array_search($task, $task_key) + 1]]); + } else { + // 设置任务缓存30秒后失效 + $this->setTaskState($task, AddonDict::INSTALL_SUCCESS, '', 30); + } + } else { + // 设置任务缓存30秒后失效 + $this->setTaskState($task, AddonDict::INSTALL_FAIL, $result, 30); + } + return $result; + } + + /** + * 设置任务执行状态 + * @param string $task + * @param string $state + * @param $error + * @param int|null $ttl + * @return void + */ + public function setTaskState(string $task, string $state, $error = '', $ttl = null) + { + $this->task[$task]['state'] = $state; + if (!empty($error)) $this->task[$task]['error'] = $error; + Cache::set($this->cache_key, $this->task, $ttl); + } + + /** + * 获取安装任务 + * @return array + */ + public function getTask() + { + return $this->task; + } + + /** + * 获取任务执行状态 + * @param string $key + * @return array|mixed + */ + public function getInstallState(string $key) + { + return $this->task[$key] ?? []; + } + + /** + * 安装迁移复制文件 + * @return bool + */ + public function installDir() + { + $from_admin_dir = $this->install_addon_path . "admin" . DIRECTORY_SEPARATOR; + $from_web_dir = $this->install_addon_path . "web" . DIRECTORY_SEPARATOR; + $from_wap_dir = $this->install_addon_path . "uni-app" . DIRECTORY_SEPARATOR; + $from_resource_dir = $this->install_addon_path . "resource" . DIRECTORY_SEPARATOR; + + // 放入的文件 + $to_admin_dir = $this->root_path . "admin" . DIRECTORY_SEPARATOR; + $to_web_dir = $this->root_path . "web" . DIRECTORY_SEPARATOR; + $to_wap_dir = $this->root_path . "uni-app" . DIRECTORY_SEPARATOR; + $to_resource_dir = public_path() . "addon" . DIRECTORY_SEPARATOR . $this->addon . DIRECTORY_SEPARATOR; + + // 安装admin管理端 + if (file_exists($from_admin_dir)) { + dir_copy($from_admin_dir, $to_admin_dir, $this->files['admin']); + // 编译后台图标库文件 + $this->compileAdminIcon(); + } + + // 安装电脑端 + if (file_exists($from_web_dir)) { + dir_copy($from_web_dir, $to_web_dir, $this->files['web']); + } + + // 安装手机端 + if (file_exists($from_wap_dir)) { + dir_copy($from_wap_dir, $to_wap_dir, $this->files['wap']); + } + + //安装资源文件 + if (file_exists($from_resource_dir)) { + dir_copy($from_resource_dir, $to_resource_dir, $this->files['resource']); + } + + $this->state = self::DIR_INSTALLED; + return true; + } + + /** + * 编译后台图标库文件 + * 图标开发注意事项,不能占用 iconfont、icon 关键词(会跟系统图标冲突),建议增加业务前缀,比如 旅游业:tourism + * @return bool + */ + public function compileAdminIcon() + { + $compile_path = $this->root_path . str_replace('/', DIRECTORY_SEPARATOR, 'admin/src/styles/icon/'); + + $content = ""; + $root_path = $compile_path . 'addon'; // 插件图标根目录 + $file_arr = getFileMap($root_path); + if (!empty($file_arr)) { + foreach ($file_arr as $ck => $cv) { + if (str_contains($cv, '.css')) { + $path = str_replace($root_path . '/', '', $ck); + $path = str_replace('/.css', '', $path); + $content .= "@import \"addon/{$path}\";\n"; + } + } + } + file_put_contents($compile_path . 'addon-iconfont.css', $content); + return true; + } + + public function installSql() + { + $sql = $this->install_addon_path . 'sql' . DIRECTORY_SEPARATOR . 'install.sql'; + $this->executeSql($sql); + $this->state = self::SQL_INSTALLED; + return true; + } + + /** + * 执行sql + * @param string $sql_file + * @return bool + */ + public static function executeSql(string $sql_file): bool + { + if (is_file($sql_file)) { + $sql = file_get_contents($sql_file); + // 执行sql + $sql_arr = parse_sql($sql); + if (!empty($sql_arr)) { + $prefix = config('database.connections.mysql.prefix'); + Db::startTrans(); + try { + foreach ($sql_arr as $sql_line) { + $sql_line = trim($sql_line); + if (!empty($sql_line)) { + $sql_line = str_ireplace('{{prefix}}', $prefix, $sql_line); + $sql_line = str_ireplace('INSERT INTO ', 'INSERT IGNORE INTO ', $sql_line); + Db::execute($sql_line); + } + } + Db::commit(); + return true; + } catch ( PDOException $e ) { + Db::rollback(); + throw new AddonException($e->getMessage()); + } + } + } + return true; + } + + /** + * 执行插件install方法 + * @return true + */ + public function handleAddonInstall() + { + $core_addon_service = new CoreAddonService(); + $install_data = $this->getAddonConfig($this->addon); + $install_data['icon'] = $this->addon . 'icon.png'; + $core_addon_service->set($install_data); + //清理缓存 + Cache::tag(self::$cache_tag_name)->clear(); + Cache::set("local_install_addons", []); + //执行命令 + //执行插件安装方法 + $class = "addon\\" . $this->addon . "\\" . Str::studly($this->addon); + if (class_exists($class)) { + (new $class())->install(); + } + return true; + } + /** * 插件安装 * @return true @@ -246,7 +451,7 @@ class CoreAddonInstallService extends CoreAddonBaseService $package_path = $this->install_addon_path . 'package' . DIRECTORY_SEPARATOR; $package_file = []; search_dir($package_path, $package_file); - $package_file = array_map(function($file) use ($package_path) { + $package_file = array_map(function ($file) use ($package_path) { return str_replace($package_path . DIRECTORY_SEPARATOR, '', $file); }, $package_file); @@ -303,7 +508,7 @@ class CoreAddonInstallService extends CoreAddonBaseService ]; if (in_array('composer.json', $package_file)) { - $this->task[ 'updateComposer' ] = [ + $this->task['updateComposer'] = [ 'addon' => $this->addon, 'step' => 'updateComposer', 'command' => "php think addon:install {$this->addon} --step updateComposer", @@ -312,7 +517,7 @@ class CoreAddonInstallService extends CoreAddonBaseService ]; } if (in_array('admin-package.json', $package_file)) { - $this->task[ 'updateAdminDependencies' ] = [ + $this->task['updateAdminDependencies'] = [ 'addon' => $this->addon, 'step' => 'updateAdminDependencies', 'command' => "php think addon:install {$this->addon} --step updateAdminDependencies", @@ -321,7 +526,7 @@ class CoreAddonInstallService extends CoreAddonBaseService ]; } if (in_array('uni-app-package.json', $package_file)) { - $this->task[ 'updateWapDependencies' ] = [ + $this->task['updateWapDependencies'] = [ 'addon' => $this->addon, 'step' => 'updateWapDependencies', 'command' => "php think addon:install {$this->addon} --step updateWapDependencies", @@ -330,7 +535,7 @@ class CoreAddonInstallService extends CoreAddonBaseService ]; } if (in_array('web-package.json', $package_file)) { - $this->task[ 'updateWebDependencies' ] = [ + $this->task['updateWebDependencies'] = [ 'addon' => $this->addon, 'step' => 'updateWebDependencies', 'command' => "php think addon:install {$this->addon} --step updateWebDependencies", @@ -339,7 +544,7 @@ class CoreAddonInstallService extends CoreAddonBaseService ]; } - $this->task[ 'installComplete' ] = [ + $this->task['installComplete'] = [ 'addon' => $this->addon, 'step' => 'installComplete', 'command' => "php think addon:install {$this->addon} --step installComplete", @@ -351,201 +556,13 @@ class CoreAddonInstallService extends CoreAddonBaseService return $this->task; } - /** - * - * @return true - */ - public function executeInstall() - { - if (empty($this->task)) throw new CommonException('ADDON_INSTALL_NOT_EXIST'); - - $check_res = Cache::get($this->cache_key . '_install_check'); - if (!$check_res) throw new CommonException('INSTALL_CHECK_NOT_PASS'); - - if ($this->task[ 'installDir' ][ 'state' ] == AddonDict::INSTALL_UNEXECUTED) AddonInstall::invoke([ 'addon' => $this->addon, 'task' => 'installDir' ]); - return true; - } - - /** - * 执行任务 - * @param $task - * @return \think\Response - */ - public function executeTask(string $task) - { - if (empty($this->task) || !isset($this->task[ $task ])) throw new CommonException('ADDON_INSTALL_NOT_EXIST'); - if ($this->task[ $task ][ 'state' ] != AddonDict::INSTALL_UNEXECUTED) throw new CommonException('ADDON_INSTALL_EXECUTED'); - - $this->setTaskState($task, AddonDict::INPROGRESS); - - $result = Terminal::execute(root_path(), $this->task[ $task ][ 'command' ]); - - // 变更任务状态 - if ($result === true) { - if ($task != 'installComplete') { - $this->setTaskState($task, AddonDict::INSTALL_SUCCESS); - $task_key = array_keys($this->task); - AddonInstall::invoke([ 'addon' => $this->addon, 'task' => $task_key[ array_search($task, $task_key) + 1 ] ]); - } else { - // 设置任务缓存30秒后失效 - $this->setTaskState($task, AddonDict::INSTALL_SUCCESS, '', 30); - } - } else { - // 设置任务缓存30秒后失效 - $this->setTaskState($task, AddonDict::INSTALL_FAIL, $result, 30); - } - return $result; - } - - /** - * 设置任务执行状态 - * @param string $task - * @param string $state - * @param $error - * @param int|null $ttl - * @return void - */ - public function setTaskState(string $task, string $state, $error = '', $ttl = null) - { - $this->task[ $task ][ 'state' ] = $state; - if (!empty($error)) $this->task[ $task ][ 'error' ] = $error; - Cache::set($this->cache_key, $this->task, $ttl); - } - - /** - * 获取安装任务 - * @return array - */ - public function getTask() - { - return $this->task; - } - - /** - * 获取任务执行状态 - * @param string $key - * @return array|mixed - */ - public function getInstallState(string $key) - { - return $this->task[ $key ] ?? []; - } - - /** - * 安装迁移复制文件 - * @param $dir - * @return bool - */ - public function installDir() - { - $from_admin_dir = $this->install_addon_path . "admin" . DIRECTORY_SEPARATOR; - $from_web_dir = $this->install_addon_path . "web" . DIRECTORY_SEPARATOR; - $from_wap_dir = $this->install_addon_path . "uni-app" . DIRECTORY_SEPARATOR; - $from_resource_dir = $this->install_addon_path . "resource" . DIRECTORY_SEPARATOR; - - // 放入的文件 - $to_admin_dir = $this->root_path . "admin" . DIRECTORY_SEPARATOR; - $to_web_dir = $this->root_path . "web" . DIRECTORY_SEPARATOR; - $to_wap_dir = $this->root_path . "uni-app" . DIRECTORY_SEPARATOR; - $to_resource_dir = public_path() . "addon" . DIRECTORY_SEPARATOR . $this->addon . DIRECTORY_SEPARATOR; - - // 安装admin管理端 - if (file_exists($from_admin_dir)) { - dir_copy($from_admin_dir, $to_admin_dir, $this->files[ 'admin' ]); - // 编译后台图标库文件 - $this->compileAdminIcon(); - } - - // 安装电脑端 - if (file_exists($from_web_dir)) { - dir_copy($from_web_dir, $to_web_dir, $this->files[ 'web' ]); - } - - // 安装手机端 - if (file_exists($from_wap_dir)) { - dir_copy($from_wap_dir, $to_wap_dir, $this->files[ 'wap' ]); - } - - //安装资源文件 - if (file_exists($from_resource_dir)) { - dir_copy($from_resource_dir, $to_resource_dir, $this->files[ 'resource' ]); - } - - $this->state = self::DIR_INSTALLED; - return true; - } - - public function installSql() - { - $sql = $this->install_addon_path . 'sql' . DIRECTORY_SEPARATOR . 'install.sql'; - $this->executeSql($sql); - $this->state = self::SQL_INSTALLED; - return true; - } - - /** - * 执行sql - * @param string $sql_file - * @return bool - */ - public static function executeSql(string $sql_file) : bool - { - if (is_file($sql_file)) { - $sql = file_get_contents($sql_file); - // 执行sql - $sql_arr = parse_sql($sql); - if (!empty($sql_arr)) { - $prefix = config('database.connections.mysql.prefix'); - Db::startTrans(); - try { - foreach ($sql_arr as $sql_line) { - $sql_line = trim($sql_line); - if (!empty($sql_line)) { - $sql_line = str_ireplace('{{prefix}}', $prefix, $sql_line); - $sql_line = str_ireplace('INSERT INTO ', 'INSERT IGNORE INTO ', $sql_line); - Db::execute($sql_line); - } - } - Db::commit(); - return true; - } catch (PDOException $e) { - Db::rollback(); - throw new AddonException($e->getMessage()); - } - } - } - return true; - } - - /** - * 执行插件install方法 - * @return void - */ - public function handleAddonInstall() - { - $core_addon_service = new CoreAddonService(); - $install_data = $this->getAddonConfig($this->addon); - $install_data[ 'icon' ] = $this->addon . 'icon.png'; - $core_addon_service->set($install_data); - //清理缓存 - Cache::tag(self::$cache_tag_name)->clear(); - Cache::set("local_install_addons", []); - //执行命令 - //执行插件安装方法 - $class = "addon\\" . $this->addon . "\\" . Str::studly($this->addon); - if (class_exists($class)) { - ( new $class() )->install(); - } - return true; - } - /** * 合并依赖 * @return void */ public function installDepend() { - ( new CoreDependService() )->installDepend($this->addon); + (new CoreDependService())->installDepend($this->addon); } /** @@ -557,12 +574,12 @@ class CoreAddonInstallService extends CoreAddonBaseService //执行插件卸载方法 $class = "addon\\" . $this->addon . "\\" . Str::studly($this->addon); if (class_exists($class)) { - ( new $class() )->uninstall(); + (new $class())->uninstall(); } $core_addon_service = new CoreAddonService(); if (empty($core_addon_service->getInfoByKey($this->addon))) throw new AddonException('NOT_UNINSTALL'); - if (!$this->uninstallSql()) throw new AddonException(); - if (!$this->uninstallDir()) throw new AddonException(); + if (!$this->uninstallSql()) throw new AddonException('ADDON_SQL_FAIL'); + if (!$this->uninstallDir()) throw new AddonException('ADDON_DIR_FAIL'); // 卸载菜单 $this->uninstallMenu(); @@ -582,9 +599,19 @@ class CoreAddonInstallService extends CoreAddonBaseService return true; } + /** + * 卸载数据库 + * @return true + */ + public function uninstallSql() + { + $sql = $this->install_addon_path . 'sql' . DIRECTORY_SEPARATOR . 'uninstall.sql'; + $this->executeSql($sql); + return true; + } + /** * 卸载插件 - * @param $dir * @return true */ public function uninstallDir() @@ -632,42 +659,58 @@ class CoreAddonInstallService extends CoreAddonBaseService } /** - * 卸载数据库 - * @param $dir + * 卸载菜单 + * @return true + * @throws DbException + * @throws DbException + */ + public function uninstallMenu() + { + $core_menu_service = new CoreMenuService(); + $core_menu_service->deleteByAddon($this->addon); + Cache::tag(MenuService::$cache_tag_name)->clear(); + return true; + } + + /** + * 卸载计划任务 * @return true */ - public function uninstallSql() + public function uninstallSchedule() { - $sql = $this->install_addon_path . 'sql' . DIRECTORY_SEPARATOR . 'uninstall.sql'; - $this->executeSql($sql); + (new CoreScheduleInstallService())->uninstallAddonSchedule($this->addon); return true; } + /** + * 卸载手机端 + * @return void + */ + public function uninstallWap() + { + // 编译 diy-group 自定义组件代码文件 + $this->compileDiyComponentsCode($this->root_path . "uni-app" . DIRECTORY_SEPARATOR); + + // 编译 fixed-group 固定模板组件代码文件 + $this->compileFixedComponentsCode($this->root_path . "uni-app" . DIRECTORY_SEPARATOR); + + // 编译 pages.json 页面路由代码文件 + $this->uninstallPageCode($this->root_path . "uni-app" . DIRECTORY_SEPARATOR); + } + /** * 安装插件菜单 * @return true */ public function installMenu() { - ( new CoreMenuService )->refreshAddonMenu($this->addon); + (new CoreMenuService)->refreshAddonMenu($this->addon); Cache::tag(MenuService::$cache_tag_name)->clear(); $this->state = self::MENU_INSTALLED; return true; } - /** - * 卸载菜单 - * @return true - */ - public function uninstallMenu() - { - $core_menu_service = new CoreMenuService(); - $core_menu_service->deleteByAddon($this->addon); - Cache::tag(MenuService::$cache_tag_name)->clear(); - return true; - } - /** * 安装手机端 * @return void @@ -686,22 +729,6 @@ class CoreAddonInstallService extends CoreAddonBaseService } - /** - * 卸载手机端 - * @return void - */ - public function uninstallWap() - { - // 编译 diy-group 自定义组件代码文件 - $this->compileDiyComponentsCode($this->root_path . "uni-app" . DIRECTORY_SEPARATOR); - - // 编译 fixed-group 固定模板组件代码文件 - $this->compileFixedComponentsCode($this->root_path . "uni-app" . DIRECTORY_SEPARATOR); - - // 编译 pages.json 页面路由代码文件 - $this->uninstallPageCode($this->root_path . "uni-app" . DIRECTORY_SEPARATOR); - } - public function download() { @@ -714,7 +741,7 @@ class CoreAddonInstallService extends CoreAddonBaseService /** * 更新composer依赖 - * @return void + * @return true */ public function updateComposer() { @@ -727,7 +754,7 @@ class CoreAddonInstallService extends CoreAddonBaseService /** * 更新admin端依赖 - * @return void + * @return true */ public function updateAdminDependencies() { @@ -740,7 +767,7 @@ class CoreAddonInstallService extends CoreAddonBaseService /** * 更新手机端依赖 - * @return void + * @return true */ public function updateWapDependencies() { @@ -753,7 +780,7 @@ class CoreAddonInstallService extends CoreAddonBaseService /** * 更新web端依赖 - * @return void + * @return true */ public function updateWebDependencies() { @@ -766,58 +793,22 @@ class CoreAddonInstallService extends CoreAddonBaseService /** * 安装完成 销毁插件实例 - * @return void + * @return true */ public function installComplete() { return true; } - /** * 安装计划任务 * @return true */ public function installSchedule() { - ( new CoreScheduleInstallService() )->installAddonSchedule($this->addon); + (new CoreScheduleInstallService())->installAddonSchedule($this->addon); $this->state = self::SCHEDULE_INSTALLED; return true; } - /** - * 卸载计划任务 - * @return true - */ - public function uninstallSchedule() - { - ( new CoreScheduleInstallService() )->uninstallAddonSchedule($this->addon); - return true; - } - - /** - * 编译后台图标库文件 - * 图标开发注意事项,不能占用 iconfont、icon 关键词(会跟系统图标冲突),建议增加业务前缀,比如 旅游业:tourism - * @return bool - */ - public function compileAdminIcon() - { - $compile_path = $this->root_path . str_replace('/', DIRECTORY_SEPARATOR, 'admin/src/styles/icon/'); - - $content = ""; - $root_path = $compile_path . 'addon'; // 插件图标根目录 - $file_arr = getFileMap($root_path); - if (!empty($file_arr)) { - foreach ($file_arr as $ck => $cv) { - if (strpos($cv, '.css') !== false) { - $path = str_replace($root_path . '/', '', $ck); - $path = str_replace('/.css', '', $path); - $content .= "@import \"addon/{$path}\";\n"; - } - } - } - $res = file_put_contents($compile_path . 'addon-iconfont.css', $content); - return true; - } - } \ No newline at end of file diff --git a/niucloud/app/service/core/addon/CoreAddonLogService.php b/niucloud/app/service/core/addon/CoreAddonLogService.php index 8d69195ed..c28ecac00 100644 --- a/niucloud/app/service/core/addon/CoreAddonLogService.php +++ b/niucloud/app/service/core/addon/CoreAddonLogService.php @@ -32,7 +32,8 @@ class CoreAddonLogService extends CoreAddonBaseService * @param array $params * @return true */ - public function add(array $params){ + public function add(array $params) + { $data = array( 'type' => $params['type'], 'key' => $params['key'], diff --git a/niucloud/app/service/core/addon/CoreAddonService.php b/niucloud/app/service/core/addon/CoreAddonService.php index 1a1579231..7a00ab031 100644 --- a/niucloud/app/service/core/addon/CoreAddonService.php +++ b/niucloud/app/service/core/addon/CoreAddonService.php @@ -12,6 +12,9 @@ namespace app\service\core\addon; use app\model\addon\Addon; +use app\service\core\niucloud\CoreModuleService; +use think\db\exception\DbException; +use Throwable; /** * 安装服务层 @@ -33,26 +36,49 @@ class CoreAddonService extends CoreAddonBaseService */ public function getLocalAddonList() { - $files = get_files_by_dir($this->addon_path); $list = []; - if(!empty($files)){ - $install_addon_list = $this->model->append(['status_name'])->column('title, icon, key, desc, status, author, version, install_time, update_time, cover', 'key'); - foreach($files as $path) { + $online_app_list = []; + $install_addon_list = $this->model->append(['status_name'])->column('title, icon, key, desc, status, author, version, install_time, update_time, cover', 'key'); + try { + $niucloud_module_list = (new CoreModuleService())->getModuleList()['data'] ?? []; + foreach ($niucloud_module_list as $v) { + $data = array( + 'title' => $v['app']['app_name'], + 'desc' => $v['app']['app_desc'], + 'key' => $v['app']['app_key'] ?? '', + 'version' => $v['version'] ?? '', + 'author' => $v['app']['app_name'], + 'type' => $v['app']['app_type'], + 'support_app' => $v['app']['support_channel'] ?? [], + 'is_download' => false, + 'is_local' => false, + 'icon' => $v['app']['app_logo'], + 'cover' => $v['app']['window_logo'][0], + ); + $data['install_info'] = $install_addon_list[$v['app']['app_key']] ?? []; + $list[$v['app']['app_key']] = $data; + } + $online_app_list = array_column($list, 'key'); + } catch ( Throwable $e ) { + $error = $e->getMessage(); + } + $files = get_files_by_dir($this->addon_path); + if (!empty($files)) { + foreach ($files as $path) { $data = $this->getAddonConfig($path); - if(isset($data['key'])) - { - $icon = addon_resource($data['key'], "icon.png"); - $data['icon'] = is_file($icon) ? $icon : ''; - $cover = addon_resource($data['key'], "cover.png"); - $data['cover'] = is_file($cover) ? $cover : ''; + if (isset($data['key'])) { + $data['icon'] = is_file($data['icon']) ? image_to_base64($data['icon']) : ''; + $data['cover'] = is_file($data['cover']) ? image_to_base64($data['cover']) : ''; $key = $data['key']; $data['install_info'] = $install_addon_list[$key] ?? []; - $list[] = $data; + $data['is_download'] = true; + $data['is_local'] = in_array($data['key'], $online_app_list) ? false : true; + $list[$key] = $data; } } } - return $list; + return ['list' => $list, 'error' => $error ?? '']; } /** @@ -69,20 +95,25 @@ class CoreAddonService extends CoreAddonBaseService * 获取已安装插件数量 * @param array $where * @return int - * @throws \think\db\exception\DbException + * @throws DbException */ - public function getCount(array $where = []){ + public function getCount(array $where = []) + { return $this->model->where($where)->count(); } + /** * 安装的插件分页 * @param array $where - * @return mixed + * @return array + * @throws DbException + * @throws DbException */ - public function getPage(array $where){ + public function getPage(array $where) + { $field = 'id, title, key, desc, version, status, icon, create_time, install_time'; - $search_model = $this->model->where([])->withSearch(['title'],$where)->field($field)->order('id desc'); + $search_model = $this->model->where([])->withSearch(['title'], $where)->field($field)->order('id desc'); return $this->pageQuery($search_model); } @@ -91,7 +122,8 @@ class CoreAddonService extends CoreAddonBaseService * @param int $id * @return array */ - public function getInfo(int $id){ + public function getInfo(int $id) + { return $this->model->where([['id', '=', $id]])->findOrEmpty()->toArray(); } @@ -100,7 +132,8 @@ class CoreAddonService extends CoreAddonBaseService * @param array $params * @return true */ - public function set(array $params){ + public function set(array $params) + { $title = $params['title']; $key = $params['key']; $addon = $this->model->where([ @@ -117,10 +150,10 @@ class CoreAddonService extends CoreAddonBaseService 'icon' => $icon, 'key' => $key ); - if($addon->isEmpty()){ + if ($addon->isEmpty()) { $data['install_time'] = time(); $this->model->create($data); - }else{ + } else { $data['update_time'] = time(); $addon->save($data); } @@ -132,15 +165,18 @@ class CoreAddonService extends CoreAddonBaseService * @param string $key * @return array */ - public function getInfoByKey(string $key){ + public function getInfoByKey(string $key) + { return $this->model->where([['key', '=', $key]])->findOrEmpty()->toArray(); } + /** * 通过插件名删除插件 * @param string $key * @return true */ - public function delByKey(string $key){ + public function delByKey(string $key) + { $this->model->where([['key', '=', $key]])->delete(); return true; } @@ -149,14 +185,16 @@ class CoreAddonService extends CoreAddonBaseService * 修改插件状态 * @param int $id * @param int $status - * @return void + * @return true */ - public function setStatus(int $id, int $status){ + public function setStatus(int $id, int $status) + { $this->model->where([['id', '=', $id]])->update(['status' => $status]); return true; } - public function getAppList(){ + public function getAppList() + { return event('addon', []); } } \ No newline at end of file diff --git a/niucloud/app/service/core/addon/CoreDependService.php b/niucloud/app/service/core/addon/CoreDependService.php index 49a03795d..f0ab13d6e 100644 --- a/niucloud/app/service/core/addon/CoreDependService.php +++ b/niucloud/app/service/core/addon/CoreDependService.php @@ -24,10 +24,10 @@ class CoreDependService extends CoreAddonBaseService public function __construct() { parent::__construct(); - $this->server_composer_file = $this->root_path. 'niucloud'. DIRECTORY_SEPARATOR. 'composer.json'; - $this->admin_npm_file = $this->root_path. 'admin'. DIRECTORY_SEPARATOR. 'package.json'; - $this->web_npm_file = $this->root_path. 'web'. DIRECTORY_SEPARATOR. 'package.json'; - $this->wap_npm_file = $this->root_path. 'uni-app'. DIRECTORY_SEPARATOR. 'package.json'; + $this->server_composer_file = $this->root_path . 'niucloud' . DIRECTORY_SEPARATOR . 'composer.json'; + $this->admin_npm_file = $this->root_path . 'admin' . DIRECTORY_SEPARATOR . 'package.json'; + $this->web_npm_file = $this->root_path . 'web' . DIRECTORY_SEPARATOR . 'package.json'; + $this->wap_npm_file = $this->root_path . 'uni-app' . DIRECTORY_SEPARATOR . 'package.json'; } /** @@ -39,27 +39,23 @@ class CoreDependService extends CoreAddonBaseService { //composer文件扩展 $composer_content = $this->getComposerContent(); - $addon_composer_content = $this->getAddonComposerContent($addon); - if(isset($addon_composer_content['require'])) - { + $addon_composer_content = $this->getAddonComposerContent($addon); + if (isset($addon_composer_content['require'])) { $composer_content['require'] = array_merge($composer_content['require'], $addon_composer_content['require']); } - if(isset($addon_composer_content['require_dev'])) - { + if (isset($addon_composer_content['require_dev'])) { $composer_content['require_dev'] = array_merge($composer_content['require_dev'], $addon_composer_content['require_dev']); } $this->setComposerContent($composer_content); //admin-package文件扩展 $admin_package_array = $this->getNpmContent('admin'); $addon_admin_package_array = $this->getAddonNpmContent($addon, 'admin'); - if(isset($addon_admin_package_array['dependencies'])) - { + if (isset($addon_admin_package_array['dependencies'])) { $admin_package_array['dependencies'] = array_merge($admin_package_array['dependencies'], $addon_admin_package_array['dependencies']); } - if(isset($addon_admin_package_array['devDependencies'])) - { + if (isset($addon_admin_package_array['devDependencies'])) { $admin_package_array['devDependencies'] = array_merge($admin_package_array['devDependencies'], $addon_admin_package_array['devDependencies']); } $this->setNpmContent($admin_package_array, 'admin'); @@ -67,13 +63,11 @@ class CoreDependService extends CoreAddonBaseService //web-package文件扩展 $web_package_array = $this->getNpmContent('web'); $addon_web_package_array = $this->getAddonNpmContent($addon, 'web'); - if(isset($addon_web_package_array['dependencies'])) - { + if (isset($addon_web_package_array['dependencies'])) { $web_package_array['dependencies'] = array_merge($web_package_array['dependencies'], $addon_web_package_array['dependencies']); } - if(isset($addon_web_package_array['devDependencies'])) - { + if (isset($addon_web_package_array['devDependencies'])) { $web_package_array['devDependencies'] = array_merge($web_package_array['devDependencies'], $addon_web_package_array['devDependencies']); } $this->setNpmContent($web_package_array, 'web'); @@ -81,13 +75,11 @@ class CoreDependService extends CoreAddonBaseService //uni-app-package文件扩展 $wap_package_array = $this->getNpmContent('uni-app'); $addon_wap_package_array = $this->getAddonNpmContent($addon, 'wap'); - if(isset($addon_wap_package_array['dependencies'])) - { + if (isset($addon_wap_package_array['dependencies'])) { $wap_package_array['dependencies'] = array_merge($wap_package_array['dependencies'], $addon_wap_package_array['dependencies']); } - if(isset($addon_wap_package_array['devDependencies'])) - { + if (isset($addon_wap_package_array['devDependencies'])) { $wap_package_array['devDependencies'] = array_merge($wap_package_array['devDependencies'], $addon_wap_package_array['devDependencies']); } $this->setNpmContent($wap_package_array, 'wap'); @@ -105,12 +97,12 @@ class CoreDependService extends CoreAddonBaseService /** * 获取插件的composer内容 - * @param $addon + * @param string $addon * @return array|mixed */ public function getAddonComposerContent(string $addon) { - $composer_path = $this->geAddonPackagePath($addon). 'composer.json'; + $composer_path = $this->geAddonPackagePath($addon) . 'composer.json'; return $this->jsonFileToArray($composer_path); } @@ -130,13 +122,11 @@ class CoreDependService extends CoreAddonBaseService */ public function getNpmContent(string $type) { - if($type == 'admin') - { + if ($type == 'admin') { $file_path = $this->admin_npm_file; - }elseif($type == 'web') - { + } elseif ($type == 'web') { $file_path = $this->web_npm_file; - }else{ + } else { $file_path = $this->wap_npm_file; } return $this->jsonFileToArray($file_path); @@ -150,14 +140,12 @@ class CoreDependService extends CoreAddonBaseService */ public function getAddonNpmContent(string $addon, string $type) { - if($type == 'admin') - { - $file_path = $this->geAddonPackagePath($addon).'admin-package.json'; - }elseif($type == 'web') - { - $file_path = $this->geAddonPackagePath($addon).'web-package.json'; - }else{ - $file_path = $this->geAddonPackagePath($addon).'uni-app-package.json'; + if ($type == 'admin') { + $file_path = $this->geAddonPackagePath($addon) . 'admin-package.json'; + } elseif ($type == 'web') { + $file_path = $this->geAddonPackagePath($addon) . 'web-package.json'; + } else { + $file_path = $this->geAddonPackagePath($addon) . 'uni-app-package.json'; } return $this->jsonFileToArray($file_path); } @@ -165,17 +153,16 @@ class CoreDependService extends CoreAddonBaseService /** * 更新npm内容 * @param array $content + * @param string $type * @return bool */ public function setNpmContent(array $content, string $type) { - if($type == 'admin') - { + if ($type == 'admin') { $file_path = $this->admin_npm_file; - }elseif($type == 'web') - { + } elseif ($type == 'web') { $file_path = $this->web_npm_file; - }else{ + } else { $file_path = $this->wap_npm_file; } return $this->writeArrayToJsonFile($content, $file_path); diff --git a/niucloud/app/service/core/addon/WapTrait.php b/niucloud/app/service/core/addon/WapTrait.php index 03f9858d8..f55f5530d 100644 --- a/niucloud/app/service/core/addon/WapTrait.php +++ b/niucloud/app/service/core/addon/WapTrait.php @@ -25,8 +25,7 @@ trait WapTrait /** * 编译 diy-group 自定义组件代码文件 * @param $compile_path - * @param $addon_name - * @return string + * @return false|int */ public function compileDiyComponentsCode($compile_path) { @@ -35,14 +34,13 @@ trait WapTrait $content .= " \n"; - $content .= " \n"; $root_path = $compile_path . str_replace('/', DIRECTORY_SEPARATOR, 'components/diy'); // 扩展组件根目录 $file_arr = getFileMap($root_path); if (!empty($file_arr)) { foreach ($file_arr as $ck => $cv) { - if (strpos($cv, 'index.vue') !== false) { + if (str_contains($cv, 'index.vue')) { $path = str_replace($root_path . '/', '', $ck); $path = str_replace('/index.vue', '', $path); @@ -54,7 +52,7 @@ trait WapTrait $name_arr = explode('-', $path); foreach ($name_arr as $k => $v) { // 首字母大写 - $name_arr[ $k ] = strtoupper(substr($v, 0, 1)) . substr($v, 1); + $name_arr[$k] = strtoupper($v[0] ?? '') . substr($v, 1); } $name = implode('', $name_arr); $file_name = 'diy-' . $path; @@ -125,15 +123,13 @@ trait WapTrait $content .= " @import './index.scss';\n"; $content .= "\n"; - $res = file_put_contents($compile_path . str_replace('/', DIRECTORY_SEPARATOR, 'components/diy/group/index.vue'), $content); - return $res; + return file_put_contents($compile_path . str_replace('/', DIRECTORY_SEPARATOR, 'components/diy/group/index.vue'), $content); } /** * 编译 fixed-group 固定模板组件代码文件 * @param $compile_path - * @param $addon_name - * @return string + * @return false|int */ public function compileFixedComponentsCode($compile_path) { @@ -145,7 +141,7 @@ trait WapTrait if (!empty($file_arr)) { foreach ($file_arr as $ck => $cv) { - if (strpos($cv, 'index.vue') !== false) { + if (str_contains($cv, 'index.vue')) { $path = str_replace($root_path . '/', '', $ck); $path = str_replace('/index.vue', '', $path); @@ -153,17 +149,10 @@ trait WapTrait continue; } - // 获取自定义组件 key 关键词 - $name_arr = explode('-', $path); - foreach ($name_arr as $k => $v) { - // 首字母大写 - $name_arr[ $k ] = strtoupper(substr($v, 0, 1)) . substr($v, 1); - } - $name = implode('', $name_arr); $file_name = 'fixed-' . $path; - $content .= " \n"; $content .= "\n"; $content .= "\n"; - $res = file_put_contents($compile_path . str_replace('/', DIRECTORY_SEPARATOR, 'components/fixed/group/index.vue'), $content); - return $res; + return file_put_contents($compile_path . str_replace('/', DIRECTORY_SEPARATOR, 'components/fixed/group/index.vue'), $content); } /** @@ -196,7 +183,7 @@ trait WapTrait $uniapp_pages = require $this->geAddonPackagePath($this->addon) . 'uni-app-pages.php'; - if (empty($uniapp_pages[ 'pages' ])) { + if (empty($uniapp_pages['pages'])) { return; } @@ -212,11 +199,11 @@ trait WapTrait $pattern = "/\s+\/\/ {$page_begin}[\S\s]+\/\/ {$page_end}(\n,)?/"; $content = preg_replace($pattern, '', $content); - $uniapp_pages[ 'pages' ] = str_replace('PAGE_BEGIN', $page_begin, $uniapp_pages[ 'pages' ]); - $uniapp_pages[ 'pages' ] = str_replace('PAGE_END', $page_end, $uniapp_pages[ 'pages' ]); + $uniapp_pages['pages'] = str_replace('PAGE_BEGIN', $page_begin, $uniapp_pages['pages']); + $uniapp_pages['pages'] = str_replace('PAGE_END', $page_end, $uniapp_pages['pages']); $replacement = ",// {{PAGE}}\n"; - $replacement .= $uniapp_pages[ 'pages' ] . "\n,"; + $replacement .= $uniapp_pages['pages'] . "\n,"; $page_begin_matches_count = preg_match_all('/PAGE_BEGIN/', $content . $replacement, $page_begin_matches); @@ -231,8 +218,7 @@ trait WapTrait $content = preg_replace('/PAGE_END\n,\s+\],/', "PAGE_END\n],", $content); // 找到页面路由文件 pages.json,写入内容 - $res = file_put_contents($compile_path . "pages.json", $content); - return $res; + return file_put_contents($compile_path . "pages.json", $content); } /** @@ -246,7 +232,7 @@ trait WapTrait $uniapp_pages = require $this->geAddonPackagePath($this->addon) . 'uni-app-pages.php'; - if (empty($uniapp_pages[ 'pages' ])) { + if (empty($uniapp_pages['pages'])) { return; } @@ -257,8 +243,8 @@ trait WapTrait $page_begin = $addon . '_PAGE_BEGIN'; $page_end = $addon . '_PAGE_END'; - $uniapp_pages[ 'pages' ] = str_replace('PAGE_BEGIN', $page_begin, $uniapp_pages[ 'pages' ]); - $uniapp_pages[ 'pages' ] = str_replace('PAGE_END', $page_end, $uniapp_pages[ 'pages' ]); + $uniapp_pages['pages'] = str_replace('PAGE_BEGIN', $page_begin, $uniapp_pages['pages']); + $uniapp_pages['pages'] = str_replace('PAGE_END', $page_end, $uniapp_pages['pages']); // 清除插件页面路由代码块 $pattern = "/\s+\/\/ {$page_begin}[\S\s]+\/\/ {$page_end}(\n,)?/"; @@ -274,8 +260,7 @@ trait WapTrait // 清除最后一个逗号 $content = preg_replace('/PAGE_END\n,\s+\],/', "PAGE_END\n],", $content); - $res = file_put_contents($compile_path . "pages.json", $content); - return $res; + return file_put_contents($compile_path . "pages.json", $content); } diff --git a/niucloud/app/service/core/applet/CoreAppletDownloadService.php b/niucloud/app/service/core/applet/CoreAppletDownloadService.php index 8e292297d..dff6a7a5a 100644 --- a/niucloud/app/service/core/applet/CoreAppletDownloadService.php +++ b/niucloud/app/service/core/applet/CoreAppletDownloadService.php @@ -12,9 +12,11 @@ namespace app\service\core\applet; use app\dict\applet\AppletlDict; -use app\service\core\applet\CoreAppletVersionService; use core\base\BaseCoreService; use core\exception\CommonException; +use RuntimeException; +use think\response\File; +use ZipArchive; /** * 小程序包下载 @@ -32,7 +34,7 @@ class CoreAppletDownloadService extends BaseCoreService parent::__construct(); //查询这个版本的信息 $version_info = (new CoreAppletVersionService())->getInfo($version_id); - if(empty($version_info)) throw new CommonException();//不存在的版本 + if(empty($version_info)) throw new CommonException('APPLET_VERSION_NOT_EXISTS');//不存在的版本 $this->version_id = $version_id; $this->version = $version_info['version']; $this->type = $version_info['type']; @@ -42,38 +44,34 @@ class CoreAppletDownloadService extends BaseCoreService public function setReplace($replace) { $this->replace = $replace; -// [ -// [ -// 'path' => '', -// 'variable' => [ -// 'site_name' => '牛' -// ] -// ] -// ]; return $this; } /** * 下载小程序包 * @param int $site_id - * @return \think\response\File + * @return File */ public function download(int $site_id) { - $zip = new \ZipArchive; + $zip = new ZipArchive; + $this->replace = event('AppletReplace', ['site_id' => $site_id, 'type' => $this->type])[0] ?? []; $file_name = $site_id.'.zip'; $dir = $this->root_path .'/applet/'. $this->type.'/'.$this->version.'/'; //新生成一个当前站点这个版本的压缩包,如果已存在就直接下载 $file = $dir.$file_name; if(!file_exists($file)){ - if(!copy($this->path, $file)) throw new CommonException();//文件拷贝失败 + if (! is_dir($dir) && ! mkdir($dir, 0777, true) && ! is_dir($dir)) { + throw new RuntimeException(sprintf('Directory "%s" was not created', $dir)); + } + if(!copy($this->path, $file)) throw new CommonException('APPLET_VERSION_PACKAGE_NOT_EXIST');//文件拷贝失败 if ($zip->open($file) === true) { //编译 $this->compile($zip); //关闭 $zip->close(); } else { - throw new CommonException(); + throw new CommonException('APPLET_VERSION_PACKAGE_NOT_EXIST'); } } //新增下载记录 @@ -88,19 +86,20 @@ class CoreAppletDownloadService extends BaseCoreService */ public function compile($zip) { - foreach ($this->replace as $k => $v) { + foreach ($this->replace as $v) { $item_path = $v['path']; $item_variable = $v['variable']; //Read contents into memory $old_contents = $zip->getFromName($item_path); //Modify contents: + $temp_content = $old_contents; foreach($item_variable as $variable_k => $variable_v){ - $new_contents = str_replace($variable_k, $variable_v, $old_contents); + $temp_content = str_replace($variable_k, $variable_v, $temp_content); } //Delete the old... $zip->deleteName($item_path); //Write the new... - $zip->addFromString($item_path, $new_contents); + $zip->addFromString($item_path, $temp_content); } } } \ No newline at end of file diff --git a/niucloud/app/service/core/applet/CoreAppletSiteVersionService.php b/niucloud/app/service/core/applet/CoreAppletSiteVersionService.php index b1f77efa8..05b21159d 100644 --- a/niucloud/app/service/core/applet/CoreAppletSiteVersionService.php +++ b/niucloud/app/service/core/applet/CoreAppletSiteVersionService.php @@ -11,13 +11,13 @@ namespace app\service\core\applet; -use app\dict\applet\AppletlDict; -use app\dict\sys\FileDict; use app\model\applet\AppletSiteVersion; use app\model\applet\AppletVersion; -use app\service\core\upload\CoreUploadService; use core\base\BaseCoreService; use core\exception\CommonException; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; /** * 小程序包 站点 @@ -36,7 +36,7 @@ class CoreAppletSiteVersionService extends BaseCoreService * 版本升级列表 * @param int $site_id * @param array $where - * @return mixed + * @return array */ public function getPage(int $site_id, array $where = []) { @@ -50,7 +50,9 @@ class CoreAppletSiteVersionService extends BaseCoreService /** * 获取版本升级信息 + * @param int $site_id * @param int $id + * @return array */ public function getInfo(int $site_id, int $id) { @@ -61,14 +63,14 @@ class CoreAppletSiteVersionService extends BaseCoreService /** * 添加版本升级记录 * @param int $site_id + * @param int $version_id * @param string $action - * @param array $data * @return true */ public function add(int $site_id, int $version_id, string $action) { $version_info = (new CoreAppletVersionService())->getInfo($version_id); - if ($version_info) throw new CommonException('APPLET_VERSION_NOT_EXISTS'); + if (empty($version_info)) throw new CommonException('APPLET_VERSION_NOT_EXISTS'); $data['site_id'] = $site_id; $data['type'] = $version_info['type']; $data['create_time'] = time(); @@ -86,6 +88,9 @@ class CoreAppletSiteVersionService extends BaseCoreService * @param string $type * @param string $action * @return mixed|string + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function getLastVersion(int $site_id, string $type, string $action = '') { diff --git a/niucloud/app/service/core/applet/CoreAppletVersionService.php b/niucloud/app/service/core/applet/CoreAppletVersionService.php index ab246ae6b..9946a632a 100644 --- a/niucloud/app/service/core/applet/CoreAppletVersionService.php +++ b/niucloud/app/service/core/applet/CoreAppletVersionService.php @@ -11,12 +11,8 @@ namespace app\service\core\applet; -use app\dict\applet\AppletlDict; -use app\dict\sys\FileDict; use app\model\applet\AppletVersion; -use app\service\core\upload\CoreUploadService; use core\base\BaseCoreService; -use core\exception\CommonException; /** * 小程序包发布版本 @@ -33,7 +29,7 @@ class CoreAppletVersionService extends BaseCoreService /** * 获取版本列表 * @param array $where - * @param string $order + * @return array */ public function getPage(array $where = []) { @@ -45,6 +41,7 @@ class CoreAppletVersionService extends BaseCoreService /** * 获取版本信息 * @param int $id + * @return array */ public function getInfo(int $id) { @@ -56,6 +53,7 @@ class CoreAppletVersionService extends BaseCoreService /** * 通过版本号查询版本内容 * @param string $version + * @param string $type * @return array */ public function getInfoByVersion(string $version, string $type){ diff --git a/niucloud/app/service/core/captcha/CoreCaptchaImgService.php b/niucloud/app/service/core/captcha/CoreCaptchaImgService.php index 7130ef631..43da0068d 100644 --- a/niucloud/app/service/core/captcha/CoreCaptchaImgService.php +++ b/niucloud/app/service/core/captcha/CoreCaptchaImgService.php @@ -15,6 +15,7 @@ use app\Request; use core\base\BaseCoreService; use core\exception\AuthException; use core\exception\CaptchaException; +use Exception; use Fastknife\Exception\ParamException; use Fastknife\Service\BlockPuzzleCaptchaService; use Fastknife\Service\ClickWordCaptchaService; @@ -34,8 +35,6 @@ class CoreCaptchaImgService extends BaseCoreService /** * 创建验证码 - * @param int $site_id - * @param array|null $data * @return array */ public function create(){ @@ -46,7 +45,6 @@ class CoreCaptchaImgService extends BaseCoreService /** * 一次验证验证码 - * @param Request $request * @return true */ public function check(){ @@ -55,14 +53,13 @@ class CoreCaptchaImgService extends BaseCoreService $service = $this->getCaptchaService(); $service->check($captcha_key, $captcha_code); return true; - } catch (\Exception $e) { + } catch ( Exception $e) { throw new CaptchaException('CAPTCHA_ERROR'); } } /** * 一次验证验证码 - * @param Request $request * @return true */ public function verification(){ @@ -78,7 +75,7 @@ class CoreCaptchaImgService extends BaseCoreService /** * 验证验证码参数 - * @return true + * @return array */ protected function validate(){ $captcha_key = request()->param('captcha_key', ''); @@ -89,16 +86,10 @@ class CoreCaptchaImgService extends BaseCoreService protected function getCaptchaService($captcha_type = 'blockPuzzle') { $config = config('imgcaptcha'); - switch ($captcha_type) { - case 'clickWord': - $service = new ClickWordCaptchaService($config); - break; - case 'blockPuzzle': - $service = new BlockPuzzleCaptchaService($config); - break; - default: - throw new AuthException(''); - } - return $service; + return match ($captcha_type) { + 'clickWord' => new ClickWordCaptchaService($config), + 'blockPuzzle' => new BlockPuzzleCaptchaService($config), + default => throw new AuthException('CAPTCHA_INVALID'), + }; } } \ No newline at end of file diff --git a/niucloud/app/service/core/captcha/CoreCaptchaService.php b/niucloud/app/service/core/captcha/CoreCaptchaService.php index de41984f7..18756c679 100644 --- a/niucloud/app/service/core/captcha/CoreCaptchaService.php +++ b/niucloud/app/service/core/captcha/CoreCaptchaService.php @@ -50,7 +50,6 @@ class CoreCaptchaService extends BaseCoreService /** * 核验验证码 - * @param Request $request * @return true */ public function check(){ diff --git a/niucloud/app/service/core/member/CoreMemberAccountService.php b/niucloud/app/service/core/member/CoreMemberAccountService.php index 78aec8e02..c3ed60252 100644 --- a/niucloud/app/service/core/member/CoreMemberAccountService.php +++ b/niucloud/app/service/core/member/CoreMemberAccountService.php @@ -15,6 +15,7 @@ use app\model\member\Member; use app\model\member\MemberAccountLog; use core\base\BaseCoreService; use core\exception\CommonException; +use Exception; use think\facade\Db; /** @@ -80,7 +81,7 @@ class CoreMemberAccountService extends BaseCoreService event("memberAccount", $data); Db::commit(); return $res->id; - } catch ( \Exception $e) { + } catch ( Exception $e) { Db::rollback(); throw new CommonException($e->getMessage()); } diff --git a/niucloud/app/service/core/member/CoreMemberCashOutService.php b/niucloud/app/service/core/member/CoreMemberCashOutService.php index 3bb4215d8..3d4ed3658 100644 --- a/niucloud/app/service/core/member/CoreMemberCashOutService.php +++ b/niucloud/app/service/core/member/CoreMemberCashOutService.php @@ -20,8 +20,11 @@ use app\model\member\MemberCashOut; use app\service\core\pay\CoreTransferService; use core\base\BaseCoreService; use core\exception\CommonException; +use Exception; use think\facade\Cache; use think\facade\Db; +use think\Model; +use Throwable; /** * 会员提现 @@ -41,7 +44,7 @@ class CoreMemberCashOutService extends BaseCoreService * 获取对象 * @param int $site_id * @param int $id - * @return MemberCashOut|array|mixed|\think\Model + * @return MemberCashOut|array|mixed|Model */ public function find(int $site_id, int $id){ return $this->model->where([ @@ -51,9 +54,11 @@ class CoreMemberCashOutService extends BaseCoreService } /** + * @param int $site_id * @param int $id - * @param $data - * @return void + * @param string $action + * @param array $data + * @return true */ public function audit(int $site_id, int $id, string $action, $data = []){ @@ -73,8 +78,9 @@ class CoreMemberCashOutService extends BaseCoreService /** * 审核通过 + * @param int $site_id * @param MemberCashOut $cash_out - * @param $data + * @param array $data * @return true */ public function agree(int $site_id, MemberCashOut $cash_out, array $data = []){ @@ -86,7 +92,7 @@ class CoreMemberCashOutService extends BaseCoreService if($config['is_auto_transfer']){ try { $this->transfer($site_id, $cash_out['id']); - } catch (\Throwable $e) { + } catch ( Throwable $e) { } } @@ -95,8 +101,9 @@ class CoreMemberCashOutService extends BaseCoreService /** * 拒绝 + * @param int $site_id * @param MemberCashOut $cash_out - * @param $data + * @param array $data * @return true */ public function refuse(int $site_id, MemberCashOut $cash_out, array $data){ @@ -157,7 +164,7 @@ class CoreMemberCashOutService extends BaseCoreService * 提现转账完成 * @param $site_id * @param $transfer_no - * @return void + * @return true */ public function transferFinish($site_id, $transfer_no){ $cash_out = $this->model->where( @@ -169,16 +176,21 @@ class CoreMemberCashOutService extends BaseCoreService if($cash_out->isEmpty()) throw new CommonException('RECHARGE_LOG_NOT_EXIST'); if($cash_out['status'] != MemberCashOutDict::WAIT_TRANSFER) throw new CommonException('CASHOUT_STATUS_NOT_IN_WAIT_TRANSFER'); + //减去提现中金额 + $this->give($site_id, $cash_out); $cash_out->save([ 'status' => MemberCashOutDict::TRANSFERED, 'transfer_time' => time() ]); + return true; } /** * 申请提现 - * @param $data + * @param int $site_id + * @param int $member_id + * @param array $data * @return true */ public function apply(int $site_id, int $member_id, array $data){ @@ -239,7 +251,7 @@ class CoreMemberCashOutService extends BaseCoreService $core_member_cash_out_service->audit($site_id, $cash_out->id, 'agree'); } Db::commit(); - }catch ( \Exception $e) { + }catch ( Exception $e) { Db::rollback(); throw new CommonException($e->getMessage()); } @@ -278,6 +290,24 @@ class CoreMemberCashOutService extends BaseCoreService ); return true; } + + /** + * 累加提现金额,累减提现中金额 + * @param int $site_id + * @param MemberCashOut $cash_out + * @return true + */ + public function give(int $site_id, MemberCashOut $cash_out){ + $core_member_service = new CoreMemberService(); + $member = $core_member_service->find($site_id, $cash_out->member_id); + if($member->isEmpty()) throw new CommonException('MEMBER_NOT_EXIST'); + $member->save( + [ + $cash_out->account_type.'_cash_outing' => $member[$cash_out->account_type.'_cash_outing'] - $cash_out->apply_money + ] + ); + return true; + } /** * 创建订单编号 * @param int $site_id @@ -291,7 +321,7 @@ class CoreMemberCashOutService extends BaseCoreService if (!isset($max_no) || empty($max_no)) { $max_no = 1; } else { - $max_no = $max_no + 1; + ++$max_no; } $cash_out_no = $time_str . $site_id . sprintf('%03d', $max_no); Cache::set("cash_out_no_" . $site_id . "_" . $time_str, $max_no); diff --git a/niucloud/app/service/core/member/CoreMemberConfigService.php b/niucloud/app/service/core/member/CoreMemberConfigService.php index 0d0be8215..7327f96c3 100644 --- a/niucloud/app/service/core/member/CoreMemberConfigService.php +++ b/niucloud/app/service/core/member/CoreMemberConfigService.php @@ -28,7 +28,8 @@ class CoreMemberConfigService extends BaseCoreService { /** * 获取注册与登录设置 - * @param $site_id + * @param int $site_id + * @return array */ public function getLoginConfig(int $site_id){ $info = (new CoreConfigService())->getConfig($site_id, 'LOGIN')['value'] ?? []; @@ -43,9 +44,9 @@ class CoreMemberConfigService extends BaseCoreService /** * 注册与登录设置 - * @param $site_id - * @param $data - * @return SysConfig|bool|Model + * @param int $site_id + * @param array $data + * @return true */ public function setLoginConfig(int $site_id, array $data){ $config = [ @@ -61,7 +62,8 @@ class CoreMemberConfigService extends BaseCoreService /** * 获取会员设置 - * @param $site_id + * @param int $site_id + * @return array */ public function getMemberConfig(int $site_id){ $info = (new CoreConfigService())->getConfig($site_id, 'MEMBER')['value'] ?? []; @@ -73,9 +75,9 @@ class CoreMemberConfigService extends BaseCoreService /** * 会员设置 - * @param $site_id - * @param $data - * @return SysConfig|bool|Model + * @param int $site_id + * @param array $data + * @return true */ public function setMemberConfig(int $site_id, array $data){ $config = [ @@ -107,9 +109,9 @@ class CoreMemberConfigService extends BaseCoreService /** * 会员提现配置 - * @param $site_id - * @param $data - * @return SysConfig|bool|Model + * @param int $site_id + * @param array $data + * @return true */ public function setCashOutConfig(int $site_id, array $data){ //校验转账方式是否合法 diff --git a/niucloud/app/service/core/member/CoreMemberLabelService.php b/niucloud/app/service/core/member/CoreMemberLabelService.php index ff8674f2e..a73325aa1 100644 --- a/niucloud/app/service/core/member/CoreMemberLabelService.php +++ b/niucloud/app/service/core/member/CoreMemberLabelService.php @@ -13,6 +13,9 @@ namespace app\service\core\member; use app\model\member\MemberLabel; use core\base\BaseCoreService; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; use think\facade\Cache; /** @@ -34,9 +37,9 @@ class CoreMemberLabelService extends BaseCoreService * @param int $site_id * @param array $label_ids * @return mixed - * @throws \think\db\exception\DataNotFoundException - * @throws \think\db\exception\DbException - * @throws \think\db\exception\ModelNotFoundException + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function getMemberLabelListByLabelIds(int $site_id, array $label_ids){ sort($label_ids); @@ -52,11 +55,11 @@ class CoreMemberLabelService extends BaseCoreService /** * 获取全部会员标签 - * @param $site_id + * @param int $site_id * @return mixed - * @throws \think\db\exception\DataNotFoundException - * @throws \think\db\exception\DbException - * @throws \think\db\exception\ModelNotFoundException + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function getAll(int $site_id){ $cache_name = __METHOD__ . $site_id; diff --git a/niucloud/app/service/core/member/CoreMemberService.php b/niucloud/app/service/core/member/CoreMemberService.php index 2a81210ef..d3033817f 100644 --- a/niucloud/app/service/core/member/CoreMemberService.php +++ b/niucloud/app/service/core/member/CoreMemberService.php @@ -14,7 +14,10 @@ namespace app\service\core\member; use app\model\member\Member; use app\model\site\Site; use core\base\BaseCoreService; +use think\db\exception\DataNotFoundException; use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; +use think\Model; /** * 会员信息服务层 @@ -35,7 +38,7 @@ class CoreMemberService extends BaseCoreService * @param int $member_id * @param string $field * @param $data - * @return mixed + * @return Member */ public function modify(int $site_id, int $member_id, string $field, $data) { @@ -57,7 +60,7 @@ class CoreMemberService extends BaseCoreService * 通过会员查询openid * @param int $site_id * @param int $member_id - * @return void + * @return array */ public function getInfoByMemberId(int $site_id, int $member_id){ $where = array( @@ -71,7 +74,7 @@ class CoreMemberService extends BaseCoreService * 查询会员实例 * @param int $site_id * @param int $member_id - * @return Member|array|mixed|\think\Model + * @return Member|array|mixed|Model */ public function find(int $site_id, int $member_id){ $where = array( @@ -106,7 +109,10 @@ class CoreMemberService extends BaseCoreService /** * 生成会员编码 * @param int $site_id - * @return void + * @return string + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public static function createMemberNo(int $site_id) { $site = (new Site())->where([ ['site_id', '=', $site_id] ])->find(); @@ -129,7 +135,11 @@ class CoreMemberService extends BaseCoreService /** * 设置会员会员码 * @param int $site_id + * @param int $member_id * @return void + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public static function setMemberNo(int $site_id, int $member_id) { $site = (new Site())->where([ ['site_id', '=', $site_id] ])->find(); diff --git a/niucloud/app/service/core/menu/CoreMenuService.php b/niucloud/app/service/core/menu/CoreMenuService.php index 0ac284b1f..387b70d36 100644 --- a/niucloud/app/service/core/menu/CoreMenuService.php +++ b/niucloud/app/service/core/menu/CoreMenuService.php @@ -15,8 +15,9 @@ use app\dict\sys\AppTypeDict; use app\model\addon\Addon; use app\model\sys\SysMenu; use app\service\admin\sys\MenuService; -use core\dict\DictLoader; use core\base\BaseCoreService; +use core\dict\DictLoader; +use think\db\exception\DbException; use think\facade\Cache; use think\facade\Db; @@ -31,19 +32,102 @@ class CoreMenuService extends BaseCoreService parent::__construct(); $this->model = new SysMenu(); } + /** - * 安装菜单 - * @param array $menu_list - * @return true + * 插件卸载 + * @param $addon + * @return bool */ - public function install(array $menu_list) + public function uninstallAddonMenu($addon) { - $this->model->replace()->insertAll($menu_list); + $addon_loader = new DictLoader("Menu"); + + //获取插件删除替换的菜单key + $addon_admin_tree = $addon_loader->load(["addon" => $addon, "app_type" => "admin"]); + + if (isset($addon_admin_tree["delete"])) { + //软删除数据 + $this->model->where([["menu_key", "in", $addon_admin_tree["delete"]], ["app_type", "=", "admin"]])->update(["delete_time" => 0]); + } + + $addon_site_tree = $addon_loader->load(["addon" => $addon, "app_type" => "site"]); + + if (isset($addon_site_tree["delete"])) { + //软删除数据 + $this->model->where([["menu_key", "in", $addon_site_tree["delete"]], ["app_type", "=", "site"]])->update(["delete_time" => 0]); + } + $this->deleteByAddon($addon); // 清除缓存 Cache::tag(MenuService::$cache_tag_name)->clear(); return true; } + /** + * 删除插件菜单(强删除) + * @param string $addon + * @return true + * @throws DbException + */ + public function deleteByAddon(string $addon) + { + Db::name("sys_menu")->where([['addon', '=', $addon]])->delete(); + //$this->model->where([['addon', '=', $addon]])->delete(); + return true; + } + + /** + * 刷新所有插件菜单 + */ + public function refreshAllAddonMenu() + { + + $addons = (new Addon())->field("key")->select()->toArray(); + foreach ($addons as $k => $v) { + $this->refreshAddonMenu($v["key"]); + } + return true; + } + + /** + * 安装或者刷新插件菜单 + * @param $addon + * @return bool + */ + public function refreshAddonMenu($addon) + { + $addon_loader = new DictLoader("Menu"); + + //获取插件删除替换的菜单key + $addon_admin_tree = $addon_loader->load(["addon" => $addon, "app_type" => "admin"]); + + if (isset($addon_admin_tree["delete"])) { + //软删除数据 + $this->model->where([["menu_key", "in", $addon_admin_tree["delete"]], ["app_type", "=", "admin"]])->useSoftDelete('delete_time', time())->delete(); + unset($addon_admin_tree["delete"]); + } + $menu = []; + if (!empty($addon_admin_tree)) { + $menu = $this->loadMenu($addon_admin_tree, "admin", $addon); + } + + $addon_site_tree = $addon_loader->load(["addon" => $addon, "app_type" => "site"]); + + if (isset($addon_site_tree["delete"])) { + //软删除数据 + $this->model->where([["menu_key", "in", $addon_site_tree["delete"]], ["app_type", "=", "site"]])->useSoftDelete('delete_time', time())->delete(); + unset($addon_site_tree["delete"]); + } + + if (!empty($addon_site_tree)) { + $site_menu = $this->loadMenu($addon_site_tree, "site", $addon); + $menu = array_merge($menu, $site_menu); + } + $this->deleteByAddon($addon); + $this->install($menu); + return true; + + } + /** * 加载菜单 * @return array @@ -52,7 +136,7 @@ class CoreMenuService extends BaseCoreService { //加载系统 $menu_list = []; - $this->menuTreeToList($menu_tree, '',$app_type, $addon, $menu_list); + $this->menuTreeToList($menu_tree, '', $app_type, $addon, $menu_list); return $menu_list; } @@ -61,8 +145,10 @@ class CoreMenuService extends BaseCoreService * @param array $tree * @param string $parent_key * @param string $app_type + * @param string $addon + * @param array $menu_list */ - private function menuTreeToList(array $tree, string $parent_key = '', string $app_type = AppTypeDict::ADMIN, string $addon = '', array &$menu_list= []) + private function menuTreeToList(array $tree, string $parent_key = '', string $app_type = AppTypeDict::ADMIN, string $addon = '', array &$menu_list = []) { if (is_array($tree)) { foreach ($tree as $key => $value) { @@ -83,115 +169,28 @@ class CoreMenuService extends BaseCoreService 'is_show' => $value['is_show'] ?? 1 ]; $refer = $value; - if (isset($refer[ 'children' ])) { - unset($refer[ 'children' ]); - array_push($menu_list, $item); - $p_key = $refer[ 'menu_key' ]; - $this->menuTreeToList($value[ 'children' ],$p_key, $app_type,$addon, $menu_list); + if (isset($refer['children'])) { + unset($refer['children']); + $menu_list[] = $item; + $p_key = $refer['menu_key']; + $this->menuTreeToList($value['children'], $p_key, $app_type, $addon, $menu_list); } else { - array_push($menu_list, $item); + $menu_list[] = $item; } } } } /** - * 删除插件菜单(强删除) - * @param string $addon + * 安装菜单 + * @param array $menu_list * @return true */ - public function deleteByAddon(string $addon){ - Db::name("sys_menu")->where([['addon', '=', $addon]])->delete(); - //$this->model->where([['addon', '=', $addon]])->delete(); - return true; - } - - /** - * 安装或者刷新插件菜单 - * @param $addon - * @return bool - */ - public function refreshAddonMenu($addon) + public function install(array $menu_list) { - $addon_loader = new DictLoader("Menu"); - - //获取插件删除替换的菜单key - $addon_admin_tree = $addon_loader->load(["addon" => $addon, "app_type" => "admin"]); - - if(isset($addon_admin_tree["delete"])) - { - //软删除数据 - $this->model->where([["menu_key", "in", $addon_admin_tree["delete"]], ["app_type", "=", "admin"]])->useSoftDelete('delete_time',time())->delete(); - unset($addon_admin_tree["delete"]); - } - $menu = []; - if(!empty($addon_admin_tree)) - { - $menu = $this->loadMenu($addon_admin_tree, "admin", $addon); - } - - $addon_site_tree = $addon_loader->load(["addon" => $addon, "app_type" => "site"]); - - if(isset($addon_site_tree["delete"])) - { - //软删除数据 - $this->model->where([["menu_key", "in", $addon_site_tree["delete"]], ["app_type", "=", "site"]])->useSoftDelete('delete_time',time())->delete(); - unset($addon_site_tree["delete"]); - } - - if(!empty($addon_site_tree)) - { - $site_menu = $this->loadMenu($addon_site_tree, "site", $addon); - $menu = array_merge($menu, $site_menu); - } - $this->deleteByAddon($addon); - $this->install($menu); - return true; - - } - - /** - * 插件卸载 - * @param $addon - * @return bool - */ - public function uninstallAddonMenu($addon) - { - $addon_loader = new DictLoader("Menu"); - - //获取插件删除替换的菜单key - $addon_admin_tree = $addon_loader->load(["addon" => $addon, "app_type" => "admin"]); - - if(isset($addon_admin_tree["delete"])) - { - //软删除数据 - $this->model->where([["menu_key", "in", $addon_admin_tree["delete"]], ["app_type", "=", "admin"]])->update(["delete_time" => 0]); - } - - $addon_site_tree = $addon_loader->load(["addon" => $addon, "app_type" => "site"]); - - if(isset($addon_site_tree["delete"])) - { - //软删除数据 - $this->model->where([["menu_key", "in", $addon_site_tree["delete"]], ["app_type", "=", "site"]])->update(["delete_time" => 0]); - } - $this->deleteByAddon($addon); + $this->model->replace()->insertAll($menu_list); // 清除缓存 Cache::tag(MenuService::$cache_tag_name)->clear(); return true; } - - /** - * 刷新所有插件菜单 - */ - public function refreshAllAddonMenu() - { - - $addons = (new Addon())->field("key")->select()->toArray(); - foreach ($addons as $k => $v) - { - $this->refreshAddonMenu($v["key"]); - } - return true; - } } \ No newline at end of file diff --git a/niucloud/app/service/core/niucloud/CoreAuthService.php b/niucloud/app/service/core/niucloud/CoreAuthService.php new file mode 100644 index 000000000..ef24b6937 --- /dev/null +++ b/niucloud/app/service/core/niucloud/CoreAuthService.php @@ -0,0 +1,42 @@ +httpGet('authinfo', ['code' => $this->code, 'secret' => $this->secret]); + if(!empty($auth_info['data'])){ + $auth_info['data']['address_type'] = true; + if($auth_info['data']['site_address'] != $_SERVER['HTTP_HOST']) $auth_info['data']['address_type'] = false; + } + return $auth_info; + } + + +} \ No newline at end of file diff --git a/niucloud/app/service/core/niucloud/CoreModuleService.php b/niucloud/app/service/core/niucloud/CoreModuleService.php new file mode 100644 index 000000000..250bf680c --- /dev/null +++ b/niucloud/app/service/core/niucloud/CoreModuleService.php @@ -0,0 +1,68 @@ + '' + ]; + + return $this->httpGet('member_app_all', $params); + } + + /** + * 授权信息 + * @param $module_id + * @return array|Collection|Response|object|ResponseInterface|string + * @throws GuzzleException + */ + public function getAuthInfo() + { + return $this->httpGet('member_app'); + } + + /** + * 版本下载 + * @param $app_key + * @param $dir + * @return string|void + * @throws GuzzleException + */ + public function downloadModule($app_key, $dir) + { + if (!is_dir($dir) && !mkdir($dir, 0777, true) && !is_dir($dir)) { + throw new RuntimeException(sprintf('Directory "%s" was not created', $dir)); + } + + $path = $dir . $app_key . time() . '.zip'; + return $this->download('member_app_download/' . $app_key, [], $path); + } + + public function update($app_key, $version_id) + { + + } +} \ No newline at end of file diff --git a/niucloud/app/service/core/niucloud/CoreNiucloudConfigService.php b/niucloud/app/service/core/niucloud/CoreNiucloudConfigService.php new file mode 100644 index 000000000..7da5f87bf --- /dev/null +++ b/niucloud/app/service/core/niucloud/CoreNiucloudConfigService.php @@ -0,0 +1,41 @@ +getConfig(0, ConfigKeyDict::NIUCLOUD_CONFIG)['value'] ?? []; + if(empty($info)) + { + $info = [ + 'auth_code' => '', + 'auth_secret' => '' + ]; + } + return $info; + } + + +} \ No newline at end of file diff --git a/niucloud/app/service/core/niucloud/CoreNotifyService.php b/niucloud/app/service/core/niucloud/CoreNotifyService.php new file mode 100644 index 000000000..823707963 --- /dev/null +++ b/niucloud/app/service/core/niucloud/CoreNotifyService.php @@ -0,0 +1,45 @@ +validateSignature(); + $message = request()->param('Message'); + $message_type = request()->param('MsgType'); + switch($message_type){ + case 'auth': + $this->setAccessToken($message['AccessToken']['token']); + break; + } + return success(); + } + + + +} \ No newline at end of file diff --git a/niucloud/app/service/core/notice/CoreNoticeService.php b/niucloud/app/service/core/notice/CoreNoticeService.php index 3341580d3..2611499c6 100644 --- a/niucloud/app/service/core/notice/CoreNoticeService.php +++ b/niucloud/app/service/core/notice/CoreNoticeService.php @@ -16,6 +16,9 @@ use app\dict\notice\NoticeDict; use app\model\sys\SysNotice; use core\base\BaseCoreService; use core\exception\NoticeException; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; /** @@ -33,10 +36,14 @@ class CoreNoticeService extends BaseCoreService } - /** * 获取当前站点消息 + * @param int $site_id + * @param array $keys * @return array + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function getList(int $site_id, array $keys = []) { @@ -77,7 +84,9 @@ class CoreNoticeService extends BaseCoreService /** * 获取消息内容(可以做缓存) + * @param int $site_id * @param string $key + * @return array */ public function getInfo(int $site_id, string $key) { diff --git a/niucloud/app/service/core/notice/CoreNoticeSmsLogService.php b/niucloud/app/service/core/notice/CoreNoticeSmsLogService.php index f80802a3b..f4c190b48 100644 --- a/niucloud/app/service/core/notice/CoreNoticeSmsLogService.php +++ b/niucloud/app/service/core/notice/CoreNoticeSmsLogService.php @@ -31,7 +31,7 @@ class CoreNoticeSmsLogService extends BaseCoreService * 获取短信发送记录列表 * @param int $site_id * @param array $where - * @return mixed + * @return array */ public function getPage(int $site_id, array $where = []) { @@ -44,7 +44,9 @@ class CoreNoticeSmsLogService extends BaseCoreService /** * 获取短信发送记录信息 + * @param int $site_id * @param int $id + * @return array */ public function getInfo(int $site_id, int $id) { @@ -56,6 +58,7 @@ class CoreNoticeSmsLogService extends BaseCoreService * 添加短信发送记录 * @param int $site_id * @param array $data + * @return mixed|null */ public function add(int $site_id, array $data) { @@ -70,6 +73,7 @@ class CoreNoticeSmsLogService extends BaseCoreService * @param int $site_id * @param int $id * @param array $data + * @return true */ public function edit(int $site_id, int $id, array $data) { @@ -80,7 +84,9 @@ class CoreNoticeSmsLogService extends BaseCoreService /** * 删除短信发送记录 + * @param int $site_id * @param int $id + * @return bool */ public function del(int $site_id, int $id) { diff --git a/niucloud/app/service/core/order/recharge/CoreRechargeOrderService.php b/niucloud/app/service/core/order/recharge/CoreRechargeOrderService.php index a6663691c..dfe1ac36c 100644 --- a/niucloud/app/service/core/order/recharge/CoreRechargeOrderService.php +++ b/niucloud/app/service/core/order/recharge/CoreRechargeOrderService.php @@ -11,6 +11,7 @@ namespace app\service\core\order\recharge; +use app\dict\member\MemberAccountTypeDict; use app\dict\order\RechargeOrderDict; use app\dict\pay\PayDict; use app\model\order\RechargeOrder; @@ -19,7 +20,10 @@ use app\service\core\member\CoreMemberAccountService; use app\service\core\pay\CorePayService; use core\base\BaseCoreService; use core\exception\CommonException; -use think\facade\Cache; +use Exception; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; use think\facade\Db; /** @@ -64,12 +68,12 @@ class CoreRechargeOrderService extends BaseCoreService ]; Db::startTrans(); try{ - //添加订单支付表 - $order_data['out_trade_no'] = (new CorePayService())->create($data['site_id'], PayDict::MEMBER, $order_data['member_id'], $order_data['order_money'], $order_data['order_type'], get_lang("dict_order.trade_type_recharge")); //添加订单表 - $order_data['order_no'] = $this->createOrderNo($data['site_id']); + $order_data['order_no'] = create_no(); $create_order = (new RechargeOrder())->create($order_data); $order_id = $create_order->order_id; + //添加订单支付表 + (new CorePayService())->create($data['site_id'], PayDict::MEMBER, $order_data['member_id'], $order_data['order_money'], $order_data['order_type'], $order_id, get_lang("dict_order.trade_type_recharge")); //添加订单项目表 $order_item_model = new RechargeOrderItem(); foreach ($order_items as $k => $order_item) @@ -80,57 +84,40 @@ class CoreRechargeOrderService extends BaseCoreService Db::commit(); //返回订单信息 return [ - 'order_id' => $order_id, - 'out_trade_no' => $order_data['out_trade_no'] + 'trade_type' => $order_data['order_type'], + 'trade_id' => $order_id ]; - - }catch (\Exception $e) + }catch ( Exception $e) { Db::rollback(); throw new CommonException($e->getMessage()); } } - /** - * 创建订单编号 - * @param int $site_id - * @return string - */ - public function createOrderNo(int $site_id) - { - $time_str = date('YmdHi'); - $max_no = Cache::get("recharge_order_no_".$site_id."_".$time_str); - - if (!isset($max_no) || empty($max_no)) { - $max_no = 1; - } else { - $max_no = $max_no + 1; - } - $order_no = $time_str . $site_id .sprintf('%03d', $max_no); - Cache::set("recharge_order_no_".$site_id."_".$time_str, $max_no); - return $order_no; - } /** * 订单支付 * @param array $pay_info + * @return true */ public function pay(array $pay_info) { try { + $trade_id = $pay_info['trade_id'] ?? 0; $order_model = new RechargeOrder(); - $order_info = $order_model->where([['site_id', '=', $pay_info['site_id']], ['out_trade_no', '=', $pay_info['out_trade_no']]])->findOrEmpty()->toArray(); + $order_info = $order_model->where([['site_id', '=', $pay_info['site_id']], ['order_id', '=', $trade_id]])->findOrEmpty()->toArray(); if (empty($order_info)) throw new CommonException('ORDER_NOT_EXIST'); $order_data = [ 'pay_time' => time(), 'order_status' => RechargeOrderDict::FINISH, - 'is_enable_refund' => 1 // 是否允许退款 + 'is_enable_refund' => 1, // 是否允许退款 + 'out_trade_no' => $pay_info['out_trade_no']//支付后的交易流水号 ]; - $order_model->where([['site_id', '=', $pay_info['site_id']], ['out_trade_no', '=', $pay_info['out_trade_no']]])->update($order_data); + $order_model->where([['site_id', '=', $pay_info['site_id']], ['order_id', '=', $trade_id]])->update($order_data); //会员余额 - (new CoreMemberAccountService())->addLog($order_info['site_id'], $order_info['member_id'], 'balance', $order_info['order_item_money'], 'recharge', '会员充值', $order_info['order_id']); + (new CoreMemberAccountService())->addLog($order_info['site_id'], $order_info['member_id'], MemberAccountTypeDict::BALANCE, $order_info['order_item_money'], 'recharge', '会员充值', $order_info['order_id']); return true; - }catch (\Exception $e) + }catch ( Exception $e) { throw new CommonException($e->getMessage()); } @@ -138,15 +125,23 @@ class CoreRechargeOrderService extends BaseCoreService /** * 关闭订单 - * @param $order_id - * @return void + * @param int $site_id + * @param int $order_id + * @return true + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function close(int $site_id, int $order_id){ $order = (new RechargeOrder())->where([ ['site_id', '=', $site_id ],['order_id', '=', $order_id ], ])->find(); if ($order->isEmpty()) throw new CommonException('ORDER_NOT_EXIST'); - if ($order->order_status == RechargeOrderDict::CLOSE) throw new CommonException('ORDER_CLOSED'); - + //如果是支付中的话 + //if ($order->order_status == RechargeOrderDict::CLOSE) throw new CommonException('ORDER_CLOSED'); + //关闭支付单据 + if ($order->order_status == RechargeOrderDict::WAIT_PAY) + (new CorePayService())->closeByTrade($site_id,'recharge', $order_id); $order->save(['order_status' => RechargeOrderDict::CLOSE]); + return true; } diff --git a/niucloud/app/service/core/order/recharge/CoreRechargeRefundService.php b/niucloud/app/service/core/order/recharge/CoreRechargeRefundService.php index 6ab0cedc9..8a984e6cf 100644 --- a/niucloud/app/service/core/order/recharge/CoreRechargeRefundService.php +++ b/niucloud/app/service/core/order/recharge/CoreRechargeRefundService.php @@ -20,6 +20,10 @@ use app\service\core\member\CoreMemberAccountService; use app\service\core\pay\CoreRefundService; use core\base\BaseCoreService; use core\exception\CommonException; +use Exception; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; use think\facade\Db; /** @@ -35,7 +39,10 @@ class CoreRechargeRefundService extends BaseCoreService * 创建充值订单退款 * @param int $site_id * @param int $order_id - * @return void + * @return true + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function create(int $site_id, int $order_id) { $order_model = (new RechargeOrderItem())->where([ ['site_id', '=', $site_id], ['order_id', '=', $order_id], ['item_type', '=', $this->order_type ] ])->with('ordermain')->find(); @@ -43,7 +50,7 @@ class CoreRechargeRefundService extends BaseCoreService $order_info = (new RechargeOrder())->where([ ['site_id', '=', $site_id], ['order_id', '=', $order_id] ])->field("order_no")->find(); if (empty($order)) throw new CommonException('ORDER_NOT_EXIST'); if (!$order['ordermain']['is_enable_refund']) throw new CommonException('NOT_ALLOW_APPLY_REFUND'); - if (!in_array($order['ordermain']['order_status'], [RechargeOrderDict::FINISH])) throw new CommonException('ORDER_UNPAID_NOT_ALLOW_APPLY_REFUND'); + if ($order['ordermain']['order_status'] != RechargeOrderDict::FINISH) throw new CommonException('ORDER_UNPAID_NOT_ALLOW_APPLY_REFUND'); if ($order['refund_status'] != RechargeOrderDict::NOT_APPLAY) throw new CommonException('REFUND_HAD_APPLIED'); Db::startTrans(); @@ -87,7 +94,7 @@ class CoreRechargeRefundService extends BaseCoreService Db::commit(); return true; - } catch (\Exception $e) { + } catch ( Exception $e) { Db::rollback(); throw new CommonException($e->getMessage()); } @@ -107,7 +114,11 @@ class CoreRechargeRefundService extends BaseCoreService /** * 退款完成 - * @return void + * @param $refund_no + * @return true + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function refundComplete($refund_no){ $model = (new RechargeOrderItemRefund())->where([ ['refund_no', '=', $refund_no ] ])->find(); @@ -122,7 +133,7 @@ class CoreRechargeRefundService extends BaseCoreService (new CoreRechargeOrderService())->close($model->site_id, $model->order_id); Db::commit(); return true; - } catch (\Exception $e) { + } catch ( Exception $e) { Db::rollback(); throw new CommonException($e->getMessage()); } diff --git a/niucloud/app/service/core/pay/CorePayChannelService.php b/niucloud/app/service/core/pay/CorePayChannelService.php index 9e482b33f..701e84201 100644 --- a/niucloud/app/service/core/pay/CorePayChannelService.php +++ b/niucloud/app/service/core/pay/CorePayChannelService.php @@ -17,6 +17,9 @@ use app\model\pay\PayChannel; use app\service\core\weapp\CoreWeappConfigService; use app\service\core\wechat\CoreWechatConfigService; use core\base\BaseCoreService; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; use think\Model; @@ -34,6 +37,7 @@ class CorePayChannelService extends BaseCoreService /** * 查询实例 + * @param int $site_id * @param array $where * @return PayChannel|array|mixed|Model */ @@ -48,12 +52,12 @@ class CorePayChannelService extends BaseCoreService * @param string $channel * @param string $trade_type * @return array|array[] - * @throws \think\db\exception\DataNotFoundException - * @throws \think\db\exception\DbException - * @throws \think\db\exception\ModelNotFoundException + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function getAllowPayTypeByChannel(int $site_id, string $channel, string $trade_type = ''){ - $channel_pay_list = $this->model->where([['site_id', '=', $site_id], ['channel', '=', $channel], ['status', '=', 1]])->field('type')->order('sort asc')->select()->toArray(); + $channel_pay_list = $this->model->where([['site_id', '=', $site_id], ['channel', '=', $channel], ['status', '=', 1]])->field('type,config')->order('sort asc')->select()->toArray(); if(!empty($channel_pay_list)){ $temp_channel_pay_list = array_column($channel_pay_list, 'type'); @@ -63,6 +67,11 @@ class CorePayChannelService extends BaseCoreService if(!empty($pay_type_list) && $trade_type == 'recharge'){ unset($pay_type_list[PayDict::BALANCEPAY]); } + // 线下支付做处理 + if (!empty($pay_type_list) && isset($pay_type_list[PayDict::OFFLINEPAY])) { + $temp_channel_pay_list = array_column($channel_pay_list, null, 'type'); + $pay_type_list[PayDict::OFFLINEPAY]['config'] = $temp_channel_pay_list[PayDict::OFFLINEPAY]['config']; + } return $pay_type_list ?? []; } @@ -88,8 +97,8 @@ class CorePayChannelService extends BaseCoreService /** * 获取完整的微信支付配置(根据场景) - * @param $site_id - * @return void + * @param int $site_id + * @return array */ public function getWechatPayFullConfig(int $site_id){ //TODO 先判断是否是开放平台授权,然后再决定使用什么appid diff --git a/niucloud/app/service/core/pay/CorePayEventService.php b/niucloud/app/service/core/pay/CorePayEventService.php index 3020febc4..887dc5bf0 100644 --- a/niucloud/app/service/core/pay/CorePayEventService.php +++ b/niucloud/app/service/core/pay/CorePayEventService.php @@ -17,6 +17,12 @@ use app\dict\pay\TransferDict; use core\base\BaseCoreService; use core\exception\PayException; use core\pay\PayLoader; +use Exception; +use Psr\Http\Message\ResponseInterface; +use think\Response; +use Yansongda\Pay\Exception\ContainerException; +use Yansongda\Pay\Exception\InvalidParamsException; +use Yansongda\Pay\Exception\ServiceNotFoundException; use Yansongda\Supports\Collection; /** @@ -58,7 +64,7 @@ class CorePayEventService extends BaseCoreService * 获取实例化应用 * @param string $action * @return PayLoader - * @throws \Exception + * @throws Exception */ public function app(string $action = 'query') { @@ -71,15 +77,17 @@ class CorePayEventService extends BaseCoreService /** * 去支付 - * @param $out_trade_no - * @param $money - * @param $boby - * @param $refund_url - * @param $quit_url - * @param $buyer_id + * @param string $out_trade_no + * @param float $money + * @param string $boby + * @param string $refund_url + * @param string $quit_url + * @param string $buyer_id + * @param string $openid * @return mixed + * @throws Exception */ - public function pay(string $out_trade_no, float $money, string $boby, string $refund_url = '', string $quit_url = '', string $buyer_id = '', string $openid = '') + public function pay(string $out_trade_no, float $money, string $boby, string $refund_url = '', string $quit_url = '', string $buyer_id = '', string $openid = '', string $voucher = '') { $pay_fun = ''; @@ -92,11 +100,12 @@ class CorePayEventService extends BaseCoreService 'quit_url' => $quit_url, 'buyer_id' => $buyer_id, 'openid' => $openid, - 'site_id' => $this->site_id + 'site_id' => $this->site_id, + 'voucher' => $voucher ); switch ($this->type) { case PayDict::WECHATPAY: - $params['money'] = $params['money'] * 100; + $params['money'] *= 100; switch ($this->channel) { case ChannelDict::H5://h5 @@ -146,21 +155,24 @@ class CorePayEventService extends BaseCoreService /** * 转账 - * @param $site_id - * @param $from_no - * @param $product_code 支付宝用 - * @param $scene - * @param $to_no - * @param $to_type 支付宝用 - * @param $to_name - * @return mixed|Collection + * @param float $money + * @param string $transfer_no + * @param string $to_no + * @param string $to_name + * @param string $remark + * @param array $transfer_list + * @param string $to_type 支付宝用 + * @param string $product_code 支付宝用 + * @param string $scene + * @return array + * @throws Exception */ public function transfer(float $money, string $transfer_no, string $to_no, string $to_name, string $remark, array $transfer_list = [], string $to_type = '', string $product_code = '', string $scene = '') { $transfer_type = TransferDict::getPayTypeByTransfer($this->type); switch ($transfer_type) { case PayDict::WECHATPAY: - $money = $money * 100; + $money *= 100; break; case PayDict::ALIPAY: break; @@ -182,6 +194,7 @@ class CorePayEventService extends BaseCoreService * 关闭支付 * @param string $out_trade_no * @return null + * @throws Exception */ public function close(string $out_trade_no) { @@ -190,29 +203,38 @@ class CorePayEventService extends BaseCoreService /** * 退款 - * @param $site_id - * @param $out_trade_no - * @param $money - * @return void + * @param string $out_trade_no + * @param float $money + * @param float $total + * @param string $refund_no + * @param string $voucher + * @return array + * @throws ContainerException + * @throws InvalidParamsException + * @throws ServiceNotFoundException */ - public function refund(string $out_trade_no, float $money, float $total, string $refund_no) + public function refund(string $out_trade_no, float $money, float $total, string $refund_no, $voucher = '') { if ($this->type == PayDict::WECHATPAY) { - $money = $money * 100; - $total = $total * 100; + $money *= 100; + $total *= 100; } return $this->app('refund')->refund([ 'site_id' => $this->site_id, 'out_trade_no' => $out_trade_no, 'money' => $money, 'total' => $total, - 'refund_no' => $refund_no + 'refund_no' => $refund_no, + 'voucher' => $voucher ]); } /** * 支付异步通知 - * @return void + * @param string $action + * @param callable $callback + * @return ResponseInterface|Response + * @throws Exception */ public function notify(string $action, callable $callback) { @@ -221,8 +243,11 @@ class CorePayEventService extends BaseCoreService /** * 查询普通支付订单 - * @param $out_trade_no + * @param string $out_trade_no * @return null + * @throws ContainerException + * @throws InvalidParamsException + * @throws ServiceNotFoundException */ public function getOrder(string $out_trade_no) { @@ -231,9 +256,10 @@ class CorePayEventService extends BaseCoreService /** * 查询退款订单 - * @param $out_trade_no - * @param $refund_no + * @param string $out_trade_no + * @param string $refund_no * @return null + * @throws Exception */ public function getRefund(string $out_trade_no, string $refund_no) { @@ -242,8 +268,9 @@ class CorePayEventService extends BaseCoreService /** * 查询转账订单 - * @param $transfer_no + * @param string $transfer_no * @return null + * @throws Exception */ public function getTransfer(string $transfer_no) { diff --git a/niucloud/app/service/core/pay/CorePayService.php b/niucloud/app/service/core/pay/CorePayService.php index 1f4b72814..6740bbf50 100644 --- a/niucloud/app/service/core/pay/CorePayService.php +++ b/niucloud/app/service/core/pay/CorePayService.php @@ -17,8 +17,12 @@ use app\job\pay\PayReturnTo; use app\model\pay\Pay; use core\base\BaseCoreService; use core\exception\PayException; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; use think\facade\Db; -use think\facade\Log; +use think\Model; +use Throwable; /** * 支付服务层 @@ -28,6 +32,7 @@ use think\facade\Log; class CorePayService extends BaseCoreService { protected $pay_event; + public function __construct() { parent::__construct(); @@ -38,18 +43,22 @@ class CorePayService extends BaseCoreService /** * 创建支付单据 * @param $site_id - * @param string $main + * @param string $main_type + * @param int $main_id * @param float $money - * @param string $trade_type + * @param string $trade_type 业务类型 + * @param int $trade_id 业务id * @param string $body * @return string|null */ - public function create($site_id, string $main_type, int $main_id, float $money, string $trade_type, string $body){ + public function create($site_id, string $main_type, int $main_id, float $money, string $trade_type, int $trade_id, string $body) + { $out_trade_no = create_no(); $data = array( 'site_id' => $site_id, 'money' => $money, 'trade_type' => $trade_type, + 'trade_id' => $trade_id, 'body' => $body, 'out_trade_no' => $out_trade_no, 'main_id' => $main_id, @@ -59,63 +68,135 @@ class CorePayService extends BaseCoreService return $out_trade_no; } + + /** + * 通过业务类型和id查询有效的支付单据 + * @param int $site_id + * @param string $trade_type + * @param int $trade_id + * @return Pay|array|mixed|Model + */ + public function findPayInfoByTrade(int $site_id, string $trade_type, int $trade_id) + { + $where = array( + ['site_id', '=', $site_id], + ['trade_type', '=', $trade_type], + ['trade_id', '=', $trade_id], + ['status', '<>', PayDict::STATUS_CALCLE],///不查询已取消的单据 + ); + return $this->model->where($where)->append(['type_name', 'status_name'])->findOrEmpty(); + } + /** * 通过交易流水号查询支付 * @param int $site_id * @param string $out_trade_no - * @return Pay|array|mixed|\think\Model + * @return Pay|array|mixed|Model */ - public function findPayInfoByOutTradeNo(int $site_id, string $out_trade_no){ + public function findPayInfoByOutTradeNo(int $site_id, string $out_trade_no) + { $where = array( ['site_id', '=', $site_id], ['out_trade_no', '=', $out_trade_no] ); - return $this->model->where($where)->append([ 'type_name', 'status_name'])->findOrEmpty(); + return $this->model->where($where)->append(['type_name', 'status_name'])->findOrEmpty(); } /** * 通过交易流水号查询支付信息以及支付方式() * @param int $site_id * @param string $out_trade_no + * @param string $channel * @return array + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ - public function getInfoByOutTradeNo(int $site_id, string $out_trade_no, string $channel){ + public function getInfoByOutTradeNo(int $site_id, string $out_trade_no, string $channel) + { $where = array( ['site_id', '=', $site_id], ['out_trade_no', '=', $out_trade_no] ); $pay = $this->model->where($where)->append(['type_name', 'status_name'])->findOrEmpty()->toArray(); - if(!empty($pay)){ + if (!empty($pay)) { //todo 校验场景控制支付方式 - $pay['pay_type_list'] = array_values((new CorePayChannelService())->getAllowPayTypeByChannel($site_id, $channel, $pay->trade_type)); + $pay['pay_type_list'] = array_values((new CorePayChannelService())->getAllowPayTypeByChannel($site_id, $channel, $pay['trade_type'])); } - return $pay; + return $pay; } + + /** + * 通过交易信息获取支付单据 + * @param int $site_id + * @param string $trade_type + * @param string $trade_id + * @param string $channel + * @return array + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException + */ + public function getInfoByTrade(int $site_id, string $trade_type, string $trade_id, string $channel) + { + $where = array( + ['site_id', '=', $site_id], + ['trade_type', '=', $trade_type], + ['trade_id', '=', $trade_id], + ); + $pay = $this->model->where($where)->append(['type_name', 'status_name'])->findOrEmpty()->toArray(); + if (!empty($pay)) { + //todo 校验场景控制支付方式 + $pay['pay_type_list'] = array_values((new CorePayChannelService())->getAllowPayTypeByChannel($site_id, $channel, $pay['trade_type'])); + } + return $pay; + } + + /** + * 获取支付方法 + * @param int $site_id + * @param string $trade_type + * @param string $channel + * @return array|array[] + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException + */ + public function getPayTypeByTrade(int $site_id, string $trade_type, string $channel) + { + //todo 校验场景控制支付方式 + return array_values((new CorePayChannelService())->getAllowPayTypeByChannel($site_id, $channel, $trade_type)); + } + /** * 去支付 * @param $site_id - * @param $out_trade_no + * @param $trade_type + * @param $trade_id * @param $type * @param $channel + * @param string $openid + * @param string $return_url * @param string $quit_url * @param string $buyer_id * @return mixed + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ - public function pay($site_id, $out_trade_no, $type, $channel, string $openid, string $return_url = '', string $quit_url = '', string $buyer_id = ''){ - $pay = $this->findPayInfoByOutTradeNo($site_id, $out_trade_no); - if($pay->isEmpty()) throw new PayException('ALIPAY_TRANSACTION_NO_NOT_EXIST'); - if($pay['status'] == PayDict::STATUS_ING) throw new PayException('PAYMENT_LOCK'); - if($pay['status'] == PayDict::STATUS_ED) throw new PayException('PAY_SUCCESS'); - if($pay['status'] == PayDict::STATUS_CALCLE) throw new PayException('PAY_IS_REMOVE'); + public function pay($site_id, $trade_type, $trade_id, $type, $channel, string $openid, string $return_url = '', string $quit_url = '', string $buyer_id = '', string $voucher = '') + { + //检测并创建支付单据 + $pay = $this->checkOrCreate($site_id, $trade_type, $trade_id); + $out_trade_no = $pay['out_trade_no']; $money = $pay['money']; $body = $pay['body']; $trade_type = $pay['trade_type']; - - if(!in_array($type, array_column((new CorePayChannelService())->getAllowPayTypeByChannel($site_id, $channel, $trade_type), 'key'))) throw new PayException('PAYMENT_METHOD_NOT_SCENE');//场景不支持 - - $pay_result = $this->pay_event->init($site_id, $channel, $type)->pay($out_trade_no, $money, $body, $return_url, $quit_url, $buyer_id, $openid ?? ''); + if (!in_array($type, array_column((new CorePayChannelService())->getAllowPayTypeByChannel($site_id, $channel, $trade_type), 'key'))) throw new PayException('PAYMENT_METHOD_NOT_SCENE');//场景不支持 + $pay_result = $this->pay_event->init($site_id, $channel, $type)->pay($out_trade_no, $money, $body, $return_url, $quit_url, $buyer_id, $openid ?? '', $voucher); //todo 特殊支付方式会直接返回支付状态,状态如果为已支付会直接支付 - if(!empty($pay_result['status']) && $pay_result['status'] == PayDict::STATUS_ED){ + if (!empty($pay_result['status']) && $pay_result['status'] == PayDict::STATUS_ED) { + $pay->save([ 'channel' => $channel ]); $this->paySuccess($site_id, [ 'status' => PayDict::STATUS_ED, 'type' => $type, @@ -123,51 +204,100 @@ class CorePayService extends BaseCoreService ]); return true; } - //将支付设置为支付中 - $pay->save( - [ - 'type' => $type, - 'status' => PayDict::STATUS_ING, - 'channel' => $channel - ] - ); - PayReturnTo::invoke(['site_id' => $site_id, 'out_trade_no' => $out_trade_no], secs:15); + + // 如果是线下支付 + if ($type == PayDict::OFFLINEPAY) { + //将支付设置为支付中 + $pay->save( + [ + 'type' => $type, + 'status' => PayDict::STATUS_AUDIT, + 'channel' => $channel + ] + ); + event('OfflinePayAfter', [ + 'trade_type' => $trade_type, + 'trade_id' => $trade_id, + 'out_trade_no' => $out_trade_no, + 'site_id' => $site_id + ]); + } else { + //将支付设置为支付中 + $pay->save( + [ + 'type' => $type, + 'status' => PayDict::STATUS_ING, + 'channel' => $channel + ] + ); + PayReturnTo::invoke(['site_id' => $site_id, 'out_trade_no' => $out_trade_no], secs: 15); + } return $pay_result; } + /** + * 检测支付单据 (如果不存在就创建,如果存在但支付中就尝试关闭) + * @param $site_id + * @param $trade_type + * @param $trade_id + * @return Pay|array|mixed|string|Model|null + */ + public function checkOrCreate($site_id, $trade_type, $trade_id) + { + $pay = $this->findPayInfoByTrade($site_id, $trade_type, $trade_id); + if ($pay->isEmpty()) { + //创建新的支付单据 + $pay = $this->createByTrade($site_id, $trade_type, $trade_id); + } + if ($pay['status'] == PayDict::STATUS_ED) throw new PayException('PAY_SUCCESS'); + if ($pay['status'] == PayDict::STATUS_CALCLE) throw new PayException('PAY_IS_REMOVE'); + if ($pay['status'] == PayDict::STATUS_ING) { + //尝试关闭原有的支付单据 + $this->close($site_id, $pay->out_trade_no); + //创建新的支付单据 + $pay = $this->createByTrade($site_id, $trade_type, $trade_id); + } + return $pay; + } + + /** + * 通过业务信息创建支付单据 + * @param $site_id + * @param $trade_type + * @param $trade_id + * @return Pay|array|mixed|Model + */ + public function createByTrade($site_id, $trade_type, $trade_id){ + //创建新的支付单据 + $data = event('PayCreate', ['site_id' => $site_id, 'trade_type' => $trade_type, 'trade_id' => $trade_id])[0] ?? []; + $out_trade_no = $this->create($site_id, $data['main_type'], $data['main_id'], $data['money'], $data['trade_type'], $data['trade_id'], $data['body']); + return $this->findPayInfoByOutTradeNo($site_id, $out_trade_no); + } + /** * 支付单据恢复到待支付 * @param int $site_id - * @param string $out_trade_no - * @return void + * @param $pay_item + * @return bool */ - public function returnTo(int $site_id, $pay_item){ - if(is_object($pay_item)){ + public function returnTo(int $site_id, $pay_item) + { + if (is_object($pay_item)) { $pay = $pay_item; - }else{ + $out_trade_no = $pay->out_trade_no; + } else { $out_trade_no = $pay_item; $pay = $this->findPayInfoByOutTradeNo($site_id, $out_trade_no); } - if($pay->isEmpty()) return true; - if($pay['status'] != PayDict::STATUS_ING) return true; - if(empty($pay->type)) return true; + if ($pay->isEmpty()) return true; + if ($pay['status'] != PayDict::STATUS_ING) return true; + if (empty($pay->type)) return true; //尝试取消或关闭第三方支付 - try{ + try { $close = $this->close($site_id, $out_trade_no); - }catch(\Throwable $e){ + } catch ( Throwable $e ) { $close = false; } - - //todo 交易流水号在同渠道已经不能用了 -// if($close){ -// $data = array( -// 'status' => PayDict::STATUS_WAIT, -// 'type' => '', -// 'channel' => '' -// ); -// $pay->save($data); -// } - return $close; } @@ -177,69 +307,96 @@ class CorePayService extends BaseCoreService * @param string $out_trade_no * @return true */ - public function close(int $site_id, string $out_trade_no){ + public function close(int $site_id, string $out_trade_no) + { $pay = $this->findPayInfoByOutTradeNo($site_id, $out_trade_no); - if($pay->isEmpty()) throw new PayException('ALIPAY_TRANSACTION_NO_NOT_EXIST'); - if($pay['status'] != PayDict::STATUS_ING) throw new PayException('TREAT_PAYMENT_IS_OPEN'); - if(empty($pay->type)) throw new PayException('TREAT_PAYMENT_IS_OPEN'); - //尝试取消或关闭第三方支付 - $close = $this->pay_event->init($site_id, $pay->channel, $pay->type)->close($out_trade_no); - if(!$close){//有问题查询第三方订单详情 - $order = $this->pay_event->init($site_id, $pay->channel, $pay->type)->getOrder($out_trade_no); - if(!empty($order)){ - if($order['status'] == OnlinePayDict::SUCCESS){//如果已支付,就将支付调整为已支付 - $this->paySuccess($site_id, [ - 'out_trade_no' => $out_trade_no, - 'type' => $pay->type - ]); - return false; + if ($pay->isEmpty()) throw new PayException('ALIPAY_TRANSACTION_NO_NOT_EXIST'); + if (empty($pay->type)) throw new PayException('TREAT_PAYMENT_IS_OPEN'); + if (!in_array($pay['status'], [ + PayDict::STATUS_WAIT, + PayDict::STATUS_ING + ])) throw new PayException('TREAT_PAYMENT_IS_OPEN'); + if ($pay['status'] == PayDict::STATUS_ING) { + //尝试取消或关闭第三方支付 + $close = $this->pay_event->init($site_id, $pay->channel, $pay->type)->close($out_trade_no); + if (!$close) {//有问题查询第三方订单详情 + $order = $this->pay_event->init($site_id, $pay->channel, $pay->type)->getOrder($out_trade_no); + if (!empty($order)) { + if ($order['status'] == OnlinePayDict::SUCCESS) {//如果已支付,就将支付调整为已支付 + $this->paySuccess($site_id, [ + 'out_trade_no' => $out_trade_no, + 'type' => $pay->type + ]); + return false; + } } } } //支付关闭 - $this->payClose($site_id,[ + $this->payClose($site_id, [ 'out_trade_no' => $out_trade_no ]); return true; } - + /** + * 通过业务信息关闭订单 + * @param int $site_id + * @param string $trade_type + * @param int $trade_id + * @return true + */ + public function closeByTrade(int $site_id, string $trade_type, int $trade_id) + { + $pay = $this->findPayInfoByTrade($site_id, $trade_type, $trade_id); + if ($pay->isEmpty()) throw new PayException('ALIPAY_TRANSACTION_NO_NOT_EXIST'); + if ($pay['status'] == PayDict::STATUS_ED) throw new PayException('DOCUMENT_IS_PAID');//当前单据已支付 + if (!in_array($pay['status'], [ + PayDict::STATUS_WAIT, + PayDict::STATUS_ING + ])) throw new PayException('IS_PAY_REMOVE_NOT_RESETTING');//只有待支付可以关闭支付 + if (!$this->close($site_id, $pay)) { + throw new PayException('DOCUMENT_IS_PAY_REMOVE'); + } + return true; + } /** * 支付完成 - * @param $out_trade_no - * @param $type - * @param $trade_no - * @return void + * @param int $site_id + * @param string $out_trade_no + * @param string $type + * @param array $params + * @return true */ - public function payNotify(int $site_id, string $out_trade_no, string $type, array $params = []){ + public function payNotify(int $site_id, string $out_trade_no, string $type, array $params = []) + { $pay = $this->findPayInfoByOutTradeNo($site_id, $out_trade_no); - if($pay->isEmpty()) throw new PayException('ALIPAY_TRANSACTION_NO_NOT_EXIST'); - if($pay['status'] == PayDict::STATUS_ED) throw new PayException('PAY_SUCCESS'); - if($pay['status'] == PayDict::STATUS_CALCLE) throw new PayException('PAY_IS_REMOVE'); + if ($pay->isEmpty()) throw new PayException('ALIPAY_TRANSACTION_NO_NOT_EXIST'); + if ($pay['status'] == PayDict::STATUS_ED) throw new PayException('DOCUMENT_IS_PAID'); + if ($pay['status'] == PayDict::STATUS_CALCLE) throw new PayException('PAY_IS_REMOVE'); $status = $params['status']; - switch($status){ + switch ($status) { case OnlinePayDict::SUCCESS://支付成功 - $this->paySuccess($site_id,[ + $this->paySuccess($site_id, [ 'out_trade_no' => $out_trade_no, 'type' => $type ]); break; case OnlinePayDict::CLOSED://支付关闭 - $this->payClose($site_id,[ + $this->payClose($site_id, [ 'out_trade_no' => $out_trade_no, 'type' => $type ]); break; case OnlinePayDict::NOTPAY://未支付 //todo 主动去校验支付状态 - $this->check($site_id,[ + $this->check($site_id, [ 'out_trade_no' => $out_trade_no, 'type' => $type ]); break; - } return true; } @@ -248,13 +405,16 @@ class CorePayService extends BaseCoreService /** * 异步通知 * @param int $site_id + * @param string $channel * @param string $type + * @param string $action * @return null */ - public function notify(int $site_id, string $channel, string $type, string $action){ - $callback = function($out_trade_no, $params) use($site_id,$type, $action){ + public function notify(int $site_id, string $channel, string $type, string $action) + { + $callback = function ($out_trade_no, $params) use ($site_id, $type, $action) { try { - switch($action){ + switch ($action) { case 'pay'://支付结果通知 return $this->payNotify($site_id, $out_trade_no, $type, $params); break; @@ -264,73 +424,48 @@ class CorePayService extends BaseCoreService } //找不到对应的业务 return true; - } catch (PayException $e) { + } catch ( PayException $e ) { return false; } }; return $this->pay_event->init($site_id, $channel, $type)->notify($action, $callback); } - /** - * 重置支付,更换新的交易流水号 - * @param int $site_id - * @param string $out_trade_no - * @param float $money - * @return string|null - */ - public function reset(int $site_id, string $out_trade_no, float $money = null){ - $pay = $this->findPayInfoByOutTradeNo($site_id, $out_trade_no); - if($pay->isEmpty()) throw new PayException('ALIPAY_TRANSACTION_NO_NOT_EXIST'); - if(!in_array($pay['status'], [ - PayDict::STATUS_WAIT, - PayDict::STATUS_ING - ])) throw new PayException('IS_PAY_REMOVE_NOT_RESETTING');//只有待支付可以重置支付 - if($pay['status'] == PayDict::STATUS_ING){ - if(!$this->close($site_id, $pay)){ - throw new PayException('DOCUMENT_IS_PAY_REMOVE'); - } - } - if(!$money){ - $money = $pay->money; - } - //todo 需要考虑是业务调用重置支付,还是支付重置反馈业务 - return $this->create($site_id, $pay->main_type, $pay->main_id, $money, $pay->trade_type, $pay->body); - } - /** * 校验支付订单的状态 * @param int $site_id * @param array $data - * @return void + * @return bool */ - public function check(int $site_id, array $data){ + public function check(int $site_id, array $data) + { $out_trade_no = $data['out_trade_no']; $pay = $this->findPayInfoByOutTradeNo($site_id, $out_trade_no); - if($pay->isEmpty()) throw new PayException('ALIPAY_TRANSACTION_NO_NOT_EXIST'); - if($pay['status'] == PayDict::STATUS_ED) throw new PayException('PAY_SUCCESS');//单据已支付 - if($pay['status'] == PayDict::STATUS_CALCLE) throw new PayException('PAY_IS_REMOVE');//单据已取消 + if ($pay->isEmpty()) throw new PayException('ALIPAY_TRANSACTION_NO_NOT_EXIST'); + if ($pay['status'] == PayDict::STATUS_ED) throw new PayException('PAY_SUCCESS');//单据已支付 + if ($pay['status'] == PayDict::STATUS_CALCLE) throw new PayException('PAY_IS_REMOVE');//单据已取消 //查询第三方支付单据 $pay_info = $this->pay_event->init($site_id, $pay->channel, $pay->type)->getOrder($out_trade_no); $type = $pay['type']; - if(empty($pay_info)) + if (empty($pay_info)) return false; $status = $pay_info['status']; - switch($status){ + switch ($status) { case OnlinePayDict::SUCCESS://支付成功 - $this->paySuccess($site_id,[ + $this->paySuccess($site_id, [ 'out_trade_no' => $out_trade_no, 'type' => $type ]); break; case OnlinePayDict::CLOSED://支付关闭 - $this->payClose($site_id,[ + $this->payClose($site_id, [ 'out_trade_no' => $out_trade_no, 'type' => $type ]); break; case OnlinePayDict::NOTPAY://未支付 //todo 主动去校验支付状态 - $this->check($site_id,[ + $this->check($site_id, [ 'out_trade_no' => $out_trade_no, 'type' => $type ]); @@ -345,11 +480,13 @@ class CorePayService extends BaseCoreService * @param $params * @return bool */ - public function paySuccess($site_id, $params){ + public function paySuccess($site_id, $params) + { $out_trade_no = $params['out_trade_no']; $pay = $this->findPayInfoByOutTradeNo($site_id, $out_trade_no); $type = $params['type']; $trade_type = $pay->trade_type; + $trade_id = $pay->trade_id; $data = array( 'pay_time' => time(), 'status' => PayDict::STATUS_ED, @@ -364,17 +501,17 @@ class CorePayService extends BaseCoreService Db::startTrans(); try { $pay->allowField($allow_field)->save($data); - $result = event('PaySuccess', ['out_trade_no' => $out_trade_no, 'trade_type' => $trade_type, 'site_id' => $site_id]); - if(!check_event_result($result)){ + $result = event('PaySuccess', ['out_trade_no' => $out_trade_no, 'trade_type' => $trade_type, 'site_id' => $site_id, 'trade_id' => $trade_id]); + if (!check_event_result($result)) { return false; } // 提交事务 Db::commit(); return true; - } catch (\Throwable $e) { + } catch ( Throwable $e ) { // 回滚事务 Db::rollback(); - throw new PayException($e->getMessage()); + throw new PayException($e->getMessage().$e->getFile().$e->getLine()); } return true; } @@ -385,16 +522,31 @@ class CorePayService extends BaseCoreService * @param $data * @return true */ - public function payClose($site_id, $data){ + public function payClose($site_id, $data) + { $out_trade_no = $data['out_trade_no']; - $this->model->where([ - ['site_id', '=', $site_id], - ['out_trade_no', '=', $out_trade_no] - ])->update([ - 'status' => PayDict::STATUS_CALCLE - ]); - //todo 可能操作相关的订单关闭 -// event(); - return true; + + Db::startTrans(); + try { + $pay = $this->findPayInfoByOutTradeNo($site_id, $out_trade_no); + $pay->save([ + 'status' => PayDict::STATUS_CALCLE, + 'fail_reason' => $data['reason'] ?? '' + ]); + + $result = event('PayClose', ['out_trade_no' => $out_trade_no, 'site_id' => $site_id, 'trade_type' => $pay->trade_type, 'trade_id' => $pay->trade_id ]); + if (!check_event_result($result)) { + Db::rollback(); + return false; + } + // 提交事务 + Db::commit(); + return true; + } catch ( Throwable $e ) { + // 回滚事务 + Db::rollback(); + throw new PayException($e->getMessage().$e->getFile().$e->getLine()); + } + } } \ No newline at end of file diff --git a/niucloud/app/service/core/pay/CoreRefundService.php b/niucloud/app/service/core/pay/CoreRefundService.php index 2329de32a..2cda18280 100644 --- a/niucloud/app/service/core/pay/CoreRefundService.php +++ b/niucloud/app/service/core/pay/CoreRefundService.php @@ -16,6 +16,7 @@ use app\model\pay\Refund; use core\base\BaseCoreService; use core\exception\PayException; use think\facade\Db; +use Throwable; /** * 退款服务层 @@ -34,15 +35,16 @@ class CoreRefundService extends BaseCoreService /** * 创建支付单据 - * @param $site_id + * @param int $site_id * @param string $out_trade_no * @param float $money + * @param string $reason * @return string|null */ public function create(int $site_id, string $out_trade_no, float $money, string $reason = ''){ //通过交易流水号获取支付单据 $pay = (new CorePayService())->findPayInfoByOutTradeNo($site_id, $out_trade_no); - if($pay->isEmpty()) throw new PayException();//单据不存在 + if($pay->isEmpty()) throw new PayException('ALIPAY_TRANSACTION_NO_NOT_EXIST');//单据不存在 //校验当前数据是否存在 //存在就修改,不存在就创建 $refund_no = create_no(); @@ -63,20 +65,20 @@ class CoreRefundService extends BaseCoreService /** * 退款 * @param int $site_id - * @param string $out_trade_no - * @param float $money - * @return void + * @param string $refund_no + * @param string $voucher + * @return true */ - public function refund(int $site_id, string $refund_no){ + public function refund(int $site_id, string $refund_no, $voucher = ''){ $refund = $this->findByRefundNo($site_id, $refund_no); - if($refund->isEmpty()) throw new PayException(); + if($refund->isEmpty()) throw new PayException('REFUND_NOT_EXIST'); $out_trade_no = $refund->out_trade_no; $money = $refund->money; try{ //判断成功的话,可以直接调用退款成功 - $pay_result = $this->pay_event->init($site_id, $refund->channel, $refund->type)->refund($out_trade_no, $money, $money, $refund_no); + $pay_result = $this->pay_event->init($site_id, $refund->channel, $refund->type)->refund($out_trade_no, $money, $money, $refund_no, $voucher); $this->refundNotify($site_id, $out_trade_no, $refund->type, $pay_result); - }catch (\Throwable $e) { + }catch ( Throwable $e) { throw new PayException($e->getMessage()); } return true; @@ -103,7 +105,7 @@ class CoreRefundService extends BaseCoreService $refund = $this->findByRefundNo($site_id, $refund_no); if($refund->isEmpty()) throw new PayException('REFUND_NOT_EXIST'); - if(!in_array($refund['status'], [RefundDict::WAIT, RefundDict::DEALING])) throw new PayException();//只有待退款和退款中的退款单据可以 + if(!in_array($refund['status'], [RefundDict::WAIT, RefundDict::DEALING])) throw new PayException('REFUND_IS_CHANGE');//只有待退款和退款中的退款单据可以 $status = $params['status'];//第三方支付的状态,根据状态进行下一步业务 // 启动事务 @@ -134,7 +136,7 @@ class CoreRefundService extends BaseCoreService // 提交事务 Db::commit(); return true; - } catch (\Throwable $e) { + } catch ( Throwable $e) { // 回滚事务 Db::rollback(); throw new PayException($e->getMessage()); @@ -152,7 +154,7 @@ class CoreRefundService extends BaseCoreService $refund_no = $data['refund_no']; $refund = $this->findByRefundNo($site_id, $refund_no); if($refund->isEmpty()) throw new PayException('REFUND_NOT_EXIST'); - if(!in_array($refund['status'], [RefundDict::WAIT, RefundDict::DEALING])) throw new PayException();//只有待退款和退款中的退款单据可以 + if(!in_array($refund['status'], [RefundDict::WAIT, RefundDict::DEALING])) throw new PayException('REFUND_IS_CHANGE');//只有待退款和退款中的退款单据可以 //查询第三方退款单据 $refund_info = $this->pay_event->init($site_id, $refund->channel, $refund->type)->getRefund($out_trade_no, $refund_no); //这儿的refund_info 已经统一整理成公共的数据格式 @@ -185,7 +187,7 @@ class CoreRefundService extends BaseCoreService * 退款完成 * @param int $site_id * @param array $data - * @return void + * @return bool */ public function refundSuccess(int $site_id, array $data){ @@ -209,7 +211,7 @@ class CoreRefundService extends BaseCoreService * 退款失败 * @param int $site_id * @param array $data - * @return void + * @return true */ public function refundFail(int $site_id, array $data){ $refund_no = $data['refund_no']; @@ -227,7 +229,7 @@ class CoreRefundService extends BaseCoreService * 退款处理中 * @param int $site_id * @param array $data - * @return void + * @return true */ public function refundDealing(int $site_id, array $data){ $out_trade_no = $data['out_trade_no']; diff --git a/niucloud/app/service/core/pay/CoreTransferService.php b/niucloud/app/service/core/pay/CoreTransferService.php index e52bc8a62..fb9e2269c 100644 --- a/niucloud/app/service/core/pay/CoreTransferService.php +++ b/niucloud/app/service/core/pay/CoreTransferService.php @@ -16,7 +16,10 @@ use app\model\pay\Pay; use app\model\pay\Transfer; use core\base\BaseCoreService; use core\exception\PayException; +use Exception; use think\facade\Db; +use think\Model; +use Throwable; /** * 支付转账服务层 @@ -35,13 +38,14 @@ class CoreTransferService extends BaseCoreService /** * 创建转账单据 - * @param $site_id + * @param int $site_id * @param string $main_type * @param int $main_id * @param float $money * @param string $trade_type - * @param array $data + * @param string $remark * @return string|null + * @throws Exception */ public function create(int $site_id, string $main_type, int $main_id, float $money, string $trade_type, string $remark){ $transfer_no = create_no(); @@ -64,6 +68,7 @@ class CoreTransferService extends BaseCoreService * 转账 * @param int $site_id * @param string $transfer_no + * @param string $transfer_type * @param array $data * @return true */ @@ -100,7 +105,7 @@ class CoreTransferService extends BaseCoreService //将返回的数据交给转账通知 $this->transferNotify($site_id, $transfer_no, $result); return true; - }catch(\Throwable $e){ + }catch( Throwable $e){ $this->fail($site_id, $transfer_no, $transfer_type, ['reason' => get_lang($e->getMessage())]); throw new PayException($e->getMessage()); } @@ -112,7 +117,7 @@ class CoreTransferService extends BaseCoreService * 通过转账单号查询转账 * @param int $site_id * @param string $transfer_no - * @return Pay|array|mixed|\think\Model + * @return Pay|array|mixed|Model */ public function findTransferByTransferNo(int $site_id, string $transfer_no){ $where = array( @@ -174,7 +179,7 @@ class CoreTransferService extends BaseCoreService // 提交事务 Db::commit(); return true; - } catch (\Throwable $e) { + } catch ( Throwable $e) { // 回滚事务 Db::rollback(); throw new PayException($e->getMessage()); @@ -211,12 +216,12 @@ class CoreTransferService extends BaseCoreService public function check(int $site_id, array $data){ $transfer_no = $data['transfer_no']; $transfer = $this->findTransferByTransferNo($site_id, $transfer_no); - if($transfer->isEmpty()) throw new PayException(''); - if(!in_array($transfer['status'], [TransferDict::DEALING, TransferDict::WAIT]) ) throw new PayException('');//只有待转账和转账中的订单可以校验 + if($transfer->isEmpty()) throw new PayException('TRANSFER_ORDER_INVALID'); + if(!in_array($transfer['status'], [TransferDict::DEALING, TransferDict::WAIT]) ) throw new PayException('TRANFER_IS_CHANGE');//只有待转账和转账中的订单可以校验 //查询第三方支付单据 $transfer_info = $this->pay_event->init($site_id, $transfer->channel, $transfer->type)->getTransfer($transfer_no); - if(empty($transfer_info)) throw new PayException();//查询不到转账信息 + if(empty($transfer_info)) throw new PayException('TRANSFER_ORDER_INVALID');//查询不到转账信息 $status = $transfer_info['status']; switch($status){ case TransferDict::SUCCESS: diff --git a/niucloud/app/service/core/paytype/CoreBalanceService.php b/niucloud/app/service/core/paytype/CoreBalanceService.php index 91f60776b..ad915c8a9 100644 --- a/niucloud/app/service/core/paytype/CoreBalanceService.php +++ b/niucloud/app/service/core/paytype/CoreBalanceService.php @@ -19,6 +19,7 @@ use app\model\pay\Refund; use app\service\core\member\CoreMemberAccountService; use app\service\core\pay\CorePayService; use core\base\BaseCoreService; +use think\Model; /** * 支付服务层 @@ -83,7 +84,7 @@ class CoreBalanceService extends BaseCoreService /** * 订单退款 * @param array $params - * @return true + * @return array */ public function refund(array $params){ $out_trade_no = $params['out_trade_no']; @@ -120,7 +121,7 @@ class CoreBalanceService extends BaseCoreService * 获取退款信息 * @param string|null $out_trade_no * @param string|null $refund_no - * @return Refund|array|mixed|\think\Model + * @return Refund|array|mixed|Model */ public function getRefund(?string $out_trade_no, ?string $refund_no = '') { return (new Refund())->where([ diff --git a/niucloud/app/service/core/paytype/CoreOfflineService.php b/niucloud/app/service/core/paytype/CoreOfflineService.php new file mode 100644 index 000000000..1ff7e8635 --- /dev/null +++ b/niucloud/app/service/core/paytype/CoreOfflineService.php @@ -0,0 +1,133 @@ +findPayInfoByOutTradeNo($site_id, $out_trade_no); + if ($pay->isEmpty()) throw new CommonException('ALIPAY_TRANSACTION_NO_NOT_EXIST'); + + $pay->voucher = $voucher; + $pay->save(); + + return [ + 'status' => PayDict::STATUS_ING, + 'out_trade_no' => $out_trade_no, + ]; + } + + /** + * 退款 + * @param array $params + * @return void + */ + public function refund(array $params){ + $refund_no = $params['refund_no'];//交易流水号 + $site_id = $params['site_id']; + $voucher = $params['voucher'] ?? ''; + + if (empty($voucher)) throw new CommonException('VOUCHER_NOT_EMPTY'); + + $pay = (new CoreRefundService())->findByRefundNo($site_id, $refund_no); + if ($pay->isEmpty()) throw new CommonException('ALIPAY_TRANSACTION_NO_NOT_EXIST'); + + $pay->voucher = $voucher; + $pay->save(); + + return [ + 'status' => RefundDict::SUCCESS, + 'refund_no' => $refund_no + ]; + } + + public function close(string $out_trade_no) { + return true; + } + + /** + * 获取退款信息 + * @param string|null $out_trade_no + * @param string|null $refund_no + * @return Refund|array|mixed|Model + */ + public function getRefund(?string $out_trade_no, ?string $refund_no = '') { + return (new Refund())->where([ + ['refund_no', '=', $refund_no], + ])->findOrEmpty(); + } + + /** + * 通过审核 + * @param int $site_id + * @param string $out_trade_no + * @return void + */ + public function pass(int $site_id, string $out_trade_no) { + $pay = (new CorePayService())->findPayInfoByOutTradeNo($site_id, $out_trade_no); + if ($pay->isEmpty()) throw new CommonException('ALIPAY_TRANSACTION_NO_NOT_EXIST'); + if ($pay->status != PayDict::STATUS_AUDIT) throw new CommonException('ONLY_PAYING_CAN_AUDIT'); + if ($pay->type != PayDict::OFFLINEPAY) throw new CommonException('ONLY_OFFLINEPAY_CAN_AUDIT'); + + return (new CorePayService())->paySuccess($site_id, [ + 'status' => PayDict::STATUS_ED, + 'type' => $pay->type, + 'out_trade_no' => $out_trade_no, + 'voucher' => $pay->voucher + ]); + } + + /** + * 未通过审核 + * @param int $site_id + * @param string $out_trade_no + * @param string $reason + * @return void + */ + public function refuse(int $site_id, string $out_trade_no, string $reason = '') { + $pay = (new CorePayService())->findPayInfoByOutTradeNo($site_id, $out_trade_no); + if ($pay->isEmpty()) throw new CommonException('ALIPAY_TRANSACTION_NO_NOT_EXIST'); + if ($pay->status != PayDict::STATUS_AUDIT) throw new CommonException('ONLY_PAYING_CAN_AUDIT'); + if ($pay->type != PayDict::OFFLINEPAY) throw new CommonException('ONLY_OFFLINEPAY_CAN_AUDIT'); + + return (new CorePayService())->payClose($site_id, [ + 'out_trade_no' => $out_trade_no, + 'reason' => $reason + ]); + } +} \ No newline at end of file diff --git a/niucloud/app/service/core/scan/CoreScanService.php b/niucloud/app/service/core/scan/CoreScanService.php index 01752d4d1..a52990c4d 100644 --- a/niucloud/app/service/core/scan/CoreScanService.php +++ b/niucloud/app/service/core/scan/CoreScanService.php @@ -34,6 +34,7 @@ class CoreScanService extends BaseCoreService /** * 扫码生成 * @param int $site_id + * @param string $action * @param array $data * @param int|null $expire * @return array|string|string[] diff --git a/niucloud/app/service/core/schedule/CoreScheduleService.php b/niucloud/app/service/core/schedule/CoreScheduleService.php index cb41bd837..549db8b89 100644 --- a/niucloud/app/service/core/schedule/CoreScheduleService.php +++ b/niucloud/app/service/core/schedule/CoreScheduleService.php @@ -17,8 +17,13 @@ use core\base\BaseCoreService; use core\dict\DictLoader; use core\exception\CommonException; use think\Container; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; use think\facade\Log; use think\helper\Str; +use think\Model; +use Throwable; /** * 计划任务服务层 @@ -37,6 +42,9 @@ class CoreScheduleService extends BaseCoreService * 获取自动任务列表 * @param array $where * @return mixed + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function getList(array $where = []) { @@ -52,7 +60,7 @@ class CoreScheduleService extends BaseCoreService /** * 任务分页列表 * @param array $where - * @return mixed + * @return array */ public function getPage(array $where = []) { @@ -72,6 +80,7 @@ class CoreScheduleService extends BaseCoreService /** * 获取信息 * @param int $id + * @return array */ public function getInfo(int $id) { @@ -127,7 +136,7 @@ class CoreScheduleService extends BaseCoreService /** * 查询对象实例 * @param int $id - * @return SysSchedule|array|mixed|\think\Model + * @return SysSchedule|array|mixed|Model */ public function find(int $id){ return $this->model->findOrEmpty($id); @@ -141,7 +150,7 @@ class CoreScheduleService extends BaseCoreService */ public function modifyStatus(int $id, $status){ $schedule = $this->find($id); - if($schedule->isEmpty()) throw new CommonException(); + if($schedule->isEmpty()) throw new CommonException('SCHEDULE_NOT_EXISTS'); $schedule->save([ 'status' => $status ]); @@ -152,6 +161,7 @@ class CoreScheduleService extends BaseCoreService /** * 添加任务 * @param array $data + * @return true */ public function add(array $data) { @@ -165,6 +175,7 @@ class CoreScheduleService extends BaseCoreService * 任务编辑 * @param int $id * @param array $data + * @return true */ public function edit(int $id, array $data) { @@ -176,6 +187,7 @@ class CoreScheduleService extends BaseCoreService /** * 删除任务 * @param int $id + * @return bool */ public function del(int $id) { @@ -192,7 +204,7 @@ class CoreScheduleService extends BaseCoreService $function = $schedule['function'] ?: 'doJob'; try { $result = Container::getInstance()->invoke([$class, $function ?? 'doJob']); - }catch(\Throwable $e){ + }catch( Throwable $e){ Log::write('计划任务:'.$schedule['name'].'发生错误, 错误原因:'.$e->getMessage()); } $schedule = $this->find($schedule['id']); diff --git a/niucloud/app/service/core/site/CoreSiteAccountService.php b/niucloud/app/service/core/site/CoreSiteAccountService.php index aa1b2bb78..9c1249216 100644 --- a/niucloud/app/service/core/site/CoreSiteAccountService.php +++ b/niucloud/app/service/core/site/CoreSiteAccountService.php @@ -11,15 +11,11 @@ namespace app\service\core\site; -use app\model\member\Member; -use app\model\member\MemberAccountLog; use app\model\pay\Pay; use app\model\pay\Refund; use app\model\pay\Transfer; use app\model\site\SiteAccountLog; use core\base\BaseCoreService; -use core\exception\CommonException; -use think\facade\Db; /** * 站点账单记录服务层 @@ -49,6 +45,7 @@ class CoreSiteAccountService extends BaseCoreService /** * 添加退款账单记录 + * @param int $site_id * @param string $refund_no * @return mixed */ @@ -67,7 +64,8 @@ class CoreSiteAccountService extends BaseCoreService /** * 添加转账账单记录 - * @param string $refund_no + * @param int $site_id + * @param string $transfer_no * @return mixed */ public function addTransferLog(int $site_id, string $transfer_no) diff --git a/niucloud/app/service/core/site/CoreSiteService.php b/niucloud/app/service/core/site/CoreSiteService.php index 70abc5590..8b4d13e7e 100644 --- a/niucloud/app/service/core/site/CoreSiteService.php +++ b/niucloud/app/service/core/site/CoreSiteService.php @@ -15,6 +15,10 @@ use app\dict\site\SiteDict; use app\model\site\Site; use core\base\BaseCoreService; use core\exception\CommonException; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; +use think\Model; /** * 站点服务层 @@ -55,7 +59,7 @@ class CoreSiteService extends BaseCoreService /** * 模型实例 * @param $site_id - * @return Site|array|mixed|\think\Model + * @return Site|array|mixed|Model */ public function find($site_id) { @@ -64,7 +68,10 @@ class CoreSiteService extends BaseCoreService /** * 获取过期的站点 - * @return void + * @return array + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function getExpireSiteList() { @@ -76,7 +83,7 @@ class CoreSiteService extends BaseCoreService /** * 站点到期(计划任务专用,切勿调用) - * @param $site_id + * @param int $site_id * @return bool */ public function expire(int $site_id) diff --git a/niucloud/app/service/core/sys/CoreAreaService.php b/niucloud/app/service/core/sys/CoreAreaService.php index b08b73833..c6156bb57 100644 --- a/niucloud/app/service/core/sys/CoreAreaService.php +++ b/niucloud/app/service/core/sys/CoreAreaService.php @@ -46,7 +46,7 @@ class CoreAreaService extends BaseCoreService /** * 获取地址列表 - * @param $pid + * @param int $pid * @return array * @throws DataNotFoundException * @throws DbException @@ -68,15 +68,17 @@ class CoreAreaService extends BaseCoreService public function getTree(int $level = 3) { $list = $this->model->where('level', '<=', $level)->field('id, pid, name, shortname, longitude, latitude, level, sort, status')->select()->toArray(); - return list_to_tree($list, 'id', 'pid', 'child', 0); + return list_to_tree($list); } + /** * 通过对应省市区县,地址,返回完整地址 * @param $province_id * @param $city_id * @param $district_id * @param $address - * @param string $tag 分隔符 + * @param string $tag 分隔符 + * @return string */ public function getFullAddress($province_id, $city_id, $district_id, $address, $tag = ' ') { diff --git a/niucloud/app/service/core/sys/CoreAttachmentService.php b/niucloud/app/service/core/sys/CoreAttachmentService.php index f7fc2e69b..6b11d58fa 100644 --- a/niucloud/app/service/core/sys/CoreAttachmentService.php +++ b/niucloud/app/service/core/sys/CoreAttachmentService.php @@ -35,7 +35,9 @@ class CoreAttachmentService extends BaseCoreService /** * 新增素材 - * @param $params + * @param int $site_id + * @param array $data + * @return mixed */ public function add(int $site_id, array $data){ $data['site_id'] = $site_id; @@ -47,7 +49,8 @@ class CoreAttachmentService extends BaseCoreService /** * 素材库模型对象 - * @param int $uid + * @param int $site_id + * @param int $att_id * @return mixed */ public function find(int $site_id, int $att_id){ @@ -80,10 +83,13 @@ class CoreAttachmentService extends BaseCoreService } return $this->model->where($where)->select()->toArray(); } + /** * 编辑素材 + * @param int $site_id + * @param int $att_id * @param array $data - * @param $where + * @return SysAttachment */ public function edit(int $site_id, int $att_id, array $data){ $where = array( @@ -95,7 +101,8 @@ class CoreAttachmentService extends BaseCoreService /** * 删除素材 - * @param int $uid + * @param int $site_id + * @param int $att_id * @return mixed */ public function del(int $site_id, int $att_id){ @@ -108,12 +115,14 @@ class CoreAttachmentService extends BaseCoreService /** * 删除附件库中的文件 - * @param $site_id - * @param $ids - * @return void + * @param int $site_id + * @param array $att_ids + * @return true + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function delAll(int $site_id, array $att_ids){ - $file_driver = (new CoreFileService())->driver($site_id); $core_attachment_service = new CoreAttachmentService(); $list = $core_attachment_service->getList($site_id, compact('att_ids')); if(empty($list)) @@ -121,6 +130,7 @@ class CoreAttachmentService extends BaseCoreService $ids = array_column($list, 'att_id'); foreach($list as $v){ + $file_driver = (new CoreFileService())->driver($site_id, $v['storage_type']); //读取上传附件的信息用于后续得校验和数据写入,删除失败直接通过 $file_driver->delete($v['path']); } diff --git a/niucloud/app/service/core/sys/CoreConfigService.php b/niucloud/app/service/core/sys/CoreConfigService.php index c831b37bb..8d091c37a 100644 --- a/niucloud/app/service/core/sys/CoreConfigService.php +++ b/niucloud/app/service/core/sys/CoreConfigService.php @@ -13,6 +13,7 @@ namespace app\service\core\sys; use app\model\sys\SysConfig; use core\base\BaseCoreService; +use think\Model; /** * 配置服务层 @@ -30,7 +31,7 @@ class CoreConfigService extends BaseCoreService * 获取配置信息 * @param int $site_id * @param string $key - * @return mixed + * @return array */ public function getConfig(int $site_id, string $key) { @@ -45,7 +46,8 @@ class CoreConfigService extends BaseCoreService * 设置配置 * @param int $site_id * @param string $key - * @param string $value + * @param array $value + * @return SysConfig|bool|Model */ public function setConfig(int $site_id, string $key, array $value) { @@ -75,6 +77,7 @@ class CoreConfigService extends BaseCoreService * @param int $site_id * @param int $status * @param string $key + * @return bool */ public function modifyStatus(int $site_id, int $status, string $key) { diff --git a/niucloud/app/service/core/sys/CoreSysConfigService.php b/niucloud/app/service/core/sys/CoreSysConfigService.php index 6824d97ef..60f5af595 100644 --- a/niucloud/app/service/core/sys/CoreSysConfigService.php +++ b/niucloud/app/service/core/sys/CoreSysConfigService.php @@ -11,7 +11,6 @@ namespace app\service\core\sys; -use app\model\site\Site; use core\base\BaseCoreService; /** diff --git a/niucloud/app/service/core/upload/CoreBase64Service.php b/niucloud/app/service/core/upload/CoreBase64Service.php index ef6001ebf..311aab75a 100644 --- a/niucloud/app/service/core/upload/CoreBase64Service.php +++ b/niucloud/app/service/core/upload/CoreBase64Service.php @@ -12,6 +12,7 @@ namespace app\service\core\upload; use core\exception\UploadFileException; +use Exception; /** * 上传服务层 @@ -32,7 +33,7 @@ class CoreBase64Service extends CoreFileService * @param int $site_id * @param string $file_dir * @return array - * @throws \Exception + * @throws Exception */ public function image(string $content, int $site_id, string $file_dir) { diff --git a/niucloud/app/service/core/upload/CoreFetchService.php b/niucloud/app/service/core/upload/CoreFetchService.php index f70982624..da80637b1 100644 --- a/niucloud/app/service/core/upload/CoreFetchService.php +++ b/niucloud/app/service/core/upload/CoreFetchService.php @@ -12,6 +12,7 @@ namespace app\service\core\upload; use core\exception\UploadFileException; +use Exception; /** * 上传服务层 @@ -32,6 +33,7 @@ class CoreFetchService extends CoreFileService * @param int $site_id * @param string $file_dir * @return array + * @throws Exception */ public function image(string $url, int $site_id, string $file_dir) { diff --git a/niucloud/app/service/core/upload/CoreFileService.php b/niucloud/app/service/core/upload/CoreFileService.php index 7811432bb..c712ba8fb 100644 --- a/niucloud/app/service/core/upload/CoreFileService.php +++ b/niucloud/app/service/core/upload/CoreFileService.php @@ -11,10 +11,11 @@ namespace app\service\core\upload; -use app\dict\sys\FileDict; use core\base\BaseCoreService; +use core\exception\UploadFileException; use core\upload\FileDriver; use core\upload\UploadLoader; +use Exception; /** * 上传服务层 @@ -26,11 +27,33 @@ class CoreFileService extends BaseCoreService protected $root_path = 'upload'; + protected $validate = []; + public function __construct(protected $is_attachment = false) { parent::__construct(); } + /** + * 设置上传根目录 + * @param $root_path + * @return void + */ + public function setRootPath($root_path){ + $this->root_path = $root_path; + return $this; + } + + /** + * 设置上传规则 + * @param array $validate ['ext' => [], 'mime' => [], 'size' => 0] + * @return void + */ + public function setValidate(array $validate){ + $this->validate = $validate; + return $this; + } + /** * @var FileDriver */ @@ -42,16 +65,17 @@ class CoreFileService extends BaseCoreService * @param int $site_id * @param string $storage_type * @return UploadLoader - * @throws \Exception + * @throws Exception */ public function driver(int $site_id, string $storage_type = ''){ if(!empty($storage_type)){ self::$storage_type = $storage_type; $core_storage_service = new CoreStorageService(); - $storage_config = $core_storage_service->getStorageByType($site_id, $storage_type); + $storage_config = $core_storage_service->getStorageByType($this->request->defaultSiteId(), $storage_type); }else{ $core_storage_service = new CoreStorageService(); $storage_config = $core_storage_service->getDefaultStorage($this->request->defaultSiteId()); + if(empty($storage_config)) throw new UploadFileException('UPLOAD_STORAGE_TYPE_ALL_CLOSE'); self::$storage_type = $storage_config['storage_type']; } $storage_config = $storage_config ?? []; diff --git a/niucloud/app/service/core/upload/CoreImageService.php b/niucloud/app/service/core/upload/CoreImageService.php index 8a5238d25..099b31ead 100644 --- a/niucloud/app/service/core/upload/CoreImageService.php +++ b/niucloud/app/service/core/upload/CoreImageService.php @@ -11,10 +11,10 @@ namespace app\service\core\upload; -use app\dict\sys\FileDict; use app\dict\sys\StorageDict; -use app\service\core\sys\CoreAttachmentService; use core\exception\UploadFileException; +use Exception; +use Throwable; /** * 图片处理层 @@ -29,10 +29,12 @@ class CoreImageService extends CoreFileService * @param $thumb_type 裁剪的图片规格 * @param bool $is_throw_exception 是否要抛出错误 * @return mixed - * @throws \Exception + * @throws Exception */ public function thumb(int $site_id, string $file_path, $thumb_type = 'all', bool $is_throw_exception = false) { + //文件转url + $file_path = path_to_url($file_path); $file_parse = parse_url($file_path); $scheme = $file_parse['scheme'] ?? ''; $host = $file_parse['host'] ?? ''; @@ -43,7 +45,7 @@ class CoreImageService extends CoreFileService $item_params = $v['params'] ?? []; $item_domain = $item_params['domain'] ?? ''; $item_storage_type = $v['storage_type']; - if(str_contains($file_path, $item_storage_type.'_')){ + if(str_contains($file_path, '_'.$item_storage_type)){ $this->upload_driver = $this->driver($site_id, $item_storage_type); }else{ if($item_domain == $file_domain){ @@ -60,7 +62,7 @@ class CoreImageService extends CoreFileService try { $thumb_list = $this->upload_driver->thumb($file_path, $thumb_type); return count($thumb_list) > 1 ? $thumb_list : $thumb_list[$thumb_type] ?? ''; - } catch (\Throwable $e) { + } catch ( Throwable $e) { if($is_throw_exception){ throw new UploadFileException($e->getMessage()); }else{ diff --git a/niucloud/app/service/core/upload/CoreUploadService.php b/niucloud/app/service/core/upload/CoreUploadService.php index 1e9b51a43..c4f3f584c 100644 --- a/niucloud/app/service/core/upload/CoreUploadService.php +++ b/niucloud/app/service/core/upload/CoreUploadService.php @@ -12,8 +12,8 @@ namespace app\service\core\upload; use app\dict\sys\FileDict; -use app\dict\sys\StorageDict; use app\service\core\sys\CoreAttachmentService; +use Exception; /** * 上传服务层 @@ -33,6 +33,7 @@ class CoreUploadService extends CoreFileService * @param string $file_dir * @param int $cate_id * @return array + * @throws Exception */ public function image(string $file, int $site_id, string $file_dir, int $cate_id = 0) { @@ -44,6 +45,48 @@ class CoreUploadService extends CoreFileService return $this->after($site_id, $file_dir, FileDict::IMAGE, $cate_id); } + /** + * 上传 + * @param int $site_id + * @param string $file_dir + * @param string $type + * @param int $cate_id + * @return array + */ + public function after(int $site_id, string $file_dir, string $type, int $cate_id = 0) + { + $file_info = $this->upload_driver->getFileInfo(); + $dir = $this->root_path . '/' . $file_dir; + //执行上传 + $this->upload_driver->setType($type)->setValidate($this->validate)->upload($dir); + $file_name = $this->upload_driver->getFileName(); + $full_path = $this->upload_driver->getFullPath($dir); + $core_attachment_service = new CoreAttachmentService(); + $url = $this->upload_driver->getUrl($full_path); + if ($this->is_attachment) { + //将数据写入附件表中 + $data = array( + 'name' => $file_name, + 'dir' => $dir, + 'att_type' => $type, + 'real_name' => $file_info['name'],//附件原名可能过长 + 'att_size' => $file_info['size'], + 'storage_type' => self::$storage_type, + 'path' => $full_path, + 'url' => $url, + 'cate_id' => $cate_id, + ); + $att_id = $core_attachment_service->add($site_id, $data); + } + $return_array = [ + 'url' => $url + ]; + if (!empty($att_id)) { + $return_array['att_id'] = $att_id; + } + return $return_array; + } + /** * 视频上传 * @param string $file @@ -51,19 +94,17 @@ class CoreUploadService extends CoreFileService * @param string $file_dir * @param int $cate_id * @return array + * @throws Exception */ public function video(string $file, int $site_id, string $file_dir, int $cate_id) { - //实例化上传引擎 $this->upload_driver = $this->driver($site_id); //读取上传附件的信息用于后续得校验和数据写入 $this->upload_driver->read($file); return $this->after($site_id, $file_dir, FileDict::VIDEO, $cate_id); - } - /** * 上传文件 * @param string $file @@ -72,7 +113,7 @@ class CoreUploadService extends CoreFileService * @param string $file_dir * @param string $storage_type * @return array - * @throws \Exception + * @throws Exception */ public function document(string $file, int $site_id, string $type, string $file_dir, string $storage_type) { @@ -83,50 +124,4 @@ class CoreUploadService extends CoreFileService return $this->after($site_id, $file_dir, $type); } - - - /** - * 上传 - * @param int $site_id - * @param string $file_dir - * @param string $type - * @param int $cate_id - * @return array - */ - public function after(int $site_id, string $file_dir, string $type, int $cate_id = 0){ - - $file_info = $this->upload_driver->getFileInfo(); - - $dir = $this->root_path .'/'. $file_dir; - //执行上传 - $this->upload_driver->setType($type)->setValidate(config('upload.rules')[$type])->upload($dir); - - $file_name = $this->upload_driver->getFileName(); - $full_path = $this->upload_driver->getFullPath($dir); - $core_attachment_service = new CoreAttachmentService(); - $url = $this->upload_driver->getUrl($full_path); - if($this->is_attachment){ - //将数据写入附件表中 - $data = array( - 'name' => $file_name, - 'dir' => $dir, - 'att_type' => $type, - 'real_name' => $file_info['name'],//附件原名可能过长 - 'att_size' => $file_info['size'], - 'upload_type' => self::$storage_type, - 'path' => $full_path, - 'url' => $url, - 'cate_id' => $cate_id, - ); - $att_id = $core_attachment_service->add($site_id, $data); - } - $return_array = [ - 'url' => $url - ]; - if(!empty($att_id)){ - $return_array['att_id'] = $att_id; - } - return $return_array; - } - } \ No newline at end of file diff --git a/niucloud/app/service/core/weapp/CoreWeappAuthService.php b/niucloud/app/service/core/weapp/CoreWeappAuthService.php index 1c8549803..61609b042 100644 --- a/niucloud/app/service/core/weapp/CoreWeappAuthService.php +++ b/niucloud/app/service/core/weapp/CoreWeappAuthService.php @@ -12,7 +12,11 @@ namespace app\service\core\weapp; use core\base\BaseCoreService; +use EasyWeChat\Kernel\Exceptions\DecryptException; use EasyWeChat\Kernel\Exceptions\InvalidArgumentException; +use EasyWeChat\Kernel\Exceptions\InvalidConfigException; +use EasyWeChat\Kernel\Support\Collection; +use GuzzleHttp\Exception\GuzzleException; use Psr\Http\Message\ResponseInterface; /** @@ -27,10 +31,9 @@ class CoreWeappAuthService extends BaseCoreService /** * 网页授权 * @param int $site_id - * @param string $url - * @param string $scopes + * @param string|null $code * @return string - * @throws InvalidArgumentException + * @throws InvalidConfigException */ public function session(int $site_id, ?string $code) { @@ -39,10 +42,12 @@ class CoreWeappAuthService extends BaseCoreService /** * 开发者后台校验与解密开放数据 + * @param int $site_id * @param string $session * @param string $iv - * @param string $encryptedData - * @return void + * @param string $encrypted_data + * @return array + * @throws DecryptException */ public function decryptData(int $site_id, string $session, string $iv, string $encrypted_data){ return CoreWeappService::app($site_id)->encryptor->decryptData($session, $iv, $encrypted_data); @@ -52,9 +57,9 @@ class CoreWeappAuthService extends BaseCoreService * 获取小程序手机号 * @param int $site_id * @param string $code - * @return array|\EasyWeChat\Kernel\Support\Collection|object|ResponseInterface|string - * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException - * @throws \GuzzleHttp\Exception\GuzzleException + * @return array|Collection|object|ResponseInterface|string + * @throws InvalidConfigException + * @throws GuzzleException */ public function getUserPhoneNumber(int $site_id,string $code){ return CoreWeappService::app($site_id)->phone_number->getUserPhoneNumber($code); diff --git a/niucloud/app/service/core/weapp/CoreWeappConfigService.php b/niucloud/app/service/core/weapp/CoreWeappConfigService.php index 4c4c63d6f..9d62d0484 100644 --- a/niucloud/app/service/core/weapp/CoreWeappConfigService.php +++ b/niucloud/app/service/core/weapp/CoreWeappConfigService.php @@ -45,8 +45,8 @@ class CoreWeappConfigService extends BaseCoreService /** * 微信小程序配置 - * @param $site_id - * @param $data + * @param int $site_id + * @param array $data * @return SysConfig|bool|Model */ public function setWeappConfig(int $site_id, array $data){ diff --git a/niucloud/app/service/core/weapp/CoreWeappService.php b/niucloud/app/service/core/weapp/CoreWeappService.php index cfc890135..da2e782e5 100644 --- a/niucloud/app/service/core/weapp/CoreWeappService.php +++ b/niucloud/app/service/core/weapp/CoreWeappService.php @@ -14,6 +14,7 @@ namespace app\service\core\weapp; use core\base\BaseCoreService; use core\exception\WechatException; use EasyWeChat\Factory; +use EasyWeChat\MiniProgram\Application; /** @@ -26,7 +27,7 @@ class CoreWeappService extends BaseCoreService /** * 获取小程序的handle * @param int $site_id - * @return \EasyWeChat\MiniProgram\Application + * @return Application */ public static function app(int $site_id) { @@ -37,9 +38,6 @@ class CoreWeappService extends BaseCoreService $config = array( 'app_id' => $weapp_config['app_id'], 'secret' => $weapp_config['app_secret'], - 'http' => [ - 'throw' => true,//默认不抛出,还是有系统业务决定是否抛出 - ], // 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名 'response_type' => 'array', /** @@ -73,6 +71,7 @@ class CoreWeappService extends BaseCoreService * - log_template: 指定 HTTP 日志模板,请参考:https://github.com/guzzle/guzzle/blob/master/src/MessageFormatter.php */ 'http' => [ + 'throw' => true,//默认不抛出,还是有系统业务决定是否抛出 'max_retries' => 1, 'retry_delay' => 500, 'timeout' => 5.0, diff --git a/niucloud/app/service/core/weapp/CoreWeappTemplateService.php b/niucloud/app/service/core/weapp/CoreWeappTemplateService.php index 72dd6db95..c1e8d92f0 100644 --- a/niucloud/app/service/core/weapp/CoreWeappTemplateService.php +++ b/niucloud/app/service/core/weapp/CoreWeappTemplateService.php @@ -13,6 +13,9 @@ namespace app\service\core\weapp; use core\base\BaseCoreService; use EasyWeChat\Kernel\Exceptions\InvalidArgumentException; +use EasyWeChat\Kernel\Exceptions\InvalidConfigException; +use EasyWeChat\Kernel\Support\Collection; +use GuzzleHttp\Exception\GuzzleException; use Psr\Http\Message\ResponseInterface; /** @@ -30,12 +33,15 @@ class CoreWeappTemplateService extends BaseCoreService /** * 订阅消息发送 - * @param $site_id - * @param $data - * @return array|\EasyWeChat\Kernel\Support\Collection|object|ResponseInterface|string + * @param int $site_id + * @param string $template_id + * @param string $touser + * @param array $data + * @param string $page + * @return array|Collection|object|ResponseInterface|string + * @throws GuzzleException * @throws InvalidArgumentException - * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException - * @throws \GuzzleHttp\Exception\GuzzleException + * @throws InvalidConfigException */ public function send(int $site_id, string $template_id, string $touser, array $data, string $page = ''){ @@ -53,10 +59,9 @@ class CoreWeappTemplateService extends BaseCoreService * @param $tid * @param $kidList * @param $sceneDesc - * @return array|\EasyWeChat\Kernel\Support\Collection|object|ResponseInterface|string - * @throws InvalidArgumentException - * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException - * @throws \GuzzleHttp\Exception\GuzzleException + * @return array|Collection|object|ResponseInterface|string + * @throws GuzzleException + * @throws InvalidConfigException */ public function addTemplate(int $site_id, $tid, $kidList, $sceneDesc){ // $tid = 563; // 模板标题 id,可通过接口获取,也可登录小程序后台查看获取 @@ -70,10 +75,9 @@ class CoreWeappTemplateService extends BaseCoreService * 删除帐号下的个人模板 * @param int $site_id * @param $template_id - * @return array|\EasyWeChat\Kernel\Support\Collection|object|ResponseInterface|string - * @throws InvalidArgumentException - * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException - * @throws \GuzzleHttp\Exception\GuzzleException + * @return array|Collection|object|ResponseInterface|string + * @throws InvalidConfigException + * @throws GuzzleException */ public function deleteTemplate(int $site_id, $template_id){ return $this->template($site_id)->deleteTemplate($template_id); diff --git a/niucloud/app/service/core/wechat/CoreWechatApiService.php b/niucloud/app/service/core/wechat/CoreWechatApiService.php index e0dd808ab..529139ee4 100644 --- a/niucloud/app/service/core/wechat/CoreWechatApiService.php +++ b/niucloud/app/service/core/wechat/CoreWechatApiService.php @@ -13,6 +13,8 @@ namespace app\service\core\wechat; use core\base\BaseCoreService; use EasyWeChat\Kernel\Exceptions\InvalidArgumentException; +use EasyWeChat\Kernel\Exceptions\InvalidConfigException; +use GuzzleHttp\Exception\GuzzleException; /** * 微信服务api提供 @@ -31,9 +33,12 @@ class CoreWechatApiService extends BaseCoreService /** * 批量获取用户基本信息 + * @param int $site_id * @param array $openids * @param string $lang * @return mixed + * @throws GuzzleException + * @throws InvalidConfigException */ public function userInfoBatchget(int $site_id, array $openids, string $lang = 'zh_CN') { @@ -51,9 +56,12 @@ class CoreWechatApiService extends BaseCoreService /** * 创建菜单按钮接口 - * @param $site_id - * @param $buttons - * @throws InvalidArgumentException + * @param int $site_id + * @param array $buttons + * @param array $match_rule + * @return mixed + * @throws GuzzleException + * @throws InvalidConfigException */ public function menuCreate(int $site_id, array $buttons, array $match_rule = []) { diff --git a/niucloud/app/service/core/wechat/CoreWechatConfigService.php b/niucloud/app/service/core/wechat/CoreWechatConfigService.php index fa2f7b6b9..9ebd645ef 100644 --- a/niucloud/app/service/core/wechat/CoreWechatConfigService.php +++ b/niucloud/app/service/core/wechat/CoreWechatConfigService.php @@ -28,7 +28,8 @@ class CoreWechatConfigService extends BaseCoreService { /** * 获取微信公众号配置 - * @param $site_id + * @param int $site_id + * @return array */ public function getWechatConfig(int $site_id){ $info = (new CoreConfigService())->getConfig($site_id, ConfigKeyDict::WECHAT)['value'] ?? []; @@ -46,8 +47,8 @@ class CoreWechatConfigService extends BaseCoreService /** * 设置微信公众号配置 - * @param $site_id - * @param $data + * @param int $site_id + * @param array $data * @return SysConfig|bool|Model */ public function setWechatConfig(int $site_id, array $data){ diff --git a/niucloud/app/service/core/wechat/CoreWechatFansService.php b/niucloud/app/service/core/wechat/CoreWechatFansService.php index 669d02c5b..59cd7567c 100644 --- a/niucloud/app/service/core/wechat/CoreWechatFansService.php +++ b/niucloud/app/service/core/wechat/CoreWechatFansService.php @@ -33,8 +33,8 @@ class CoreWechatFansService extends BaseCoreService /** * 新增微信粉丝 - * @param $site_id - * @param $data + * @param int $site_id + * @param array $data * @return void */ public function add(int $site_id, array $data) @@ -47,16 +47,15 @@ class CoreWechatFansService extends BaseCoreService public function find(array|string $where) { - $fans = $this->model->where($where)->findOrEmpty(); - return $fans; + return $this->model->where($where)->findOrEmpty(); } /** * 修改微信粉丝 - * @param $site_id - * @param $open_id //可以是UnionID 也可以是openid - * @param $data - * @return void + * @param int $site_id + * @param string $open_id //可以是UnionID 也可以是openid + * @param array $data + * @return true */ public function edit(int $site_id, string $open_id, array $data) { @@ -113,9 +112,10 @@ class CoreWechatFansService extends BaseCoreService /** * 粉丝关注事件 - * @param $site_id - * @param $from_user_uame - * @return void + * @param int $site_id + * @param string $app_id + * @param string $from_user_name + * @return true */ public function subscribe(int $site_id, string $app_id, string $from_user_name) { @@ -137,9 +137,9 @@ class CoreWechatFansService extends BaseCoreService /** * 粉丝取消关注事件 - * @param $site_id - * @param $from_user_uame - * @return void + * @param int $site_id + * @param string $from_user_name + * @return true */ public function unsubscribe(int $site_id, string $from_user_name) { diff --git a/niucloud/app/service/core/wechat/CoreWechatMessageService.php b/niucloud/app/service/core/wechat/CoreWechatMessageService.php index 7be285d51..313586223 100644 --- a/niucloud/app/service/core/wechat/CoreWechatMessageService.php +++ b/niucloud/app/service/core/wechat/CoreWechatMessageService.php @@ -16,6 +16,10 @@ use app\service\core\scan\CoreScanService; use Closure; use core\base\BaseCoreService; use EasyWeChat\Kernel\Messages\Text; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; +use think\facade\Lang; /** * 微信事件中间件类(用于中间件注册) @@ -27,9 +31,12 @@ class CoreWechatMessageService extends BaseCoreService /** * 通过注入来分配消息事件类型 + * @param int $site_id * @param $message - * @param Closure $next * @return mixed + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function message(int $site_id, $message) { @@ -88,7 +95,7 @@ class CoreWechatMessageService extends BaseCoreService * 扫码事件 * @param int $site_id * @param $message - * @return News|Text|false + * @return Lang */ public function scan(int $site_id, $message){ $key = str_replace('qrscene_', '', $message['EventKey']); @@ -120,8 +127,9 @@ class CoreWechatMessageService extends BaseCoreService /** * 取消关注事件 + * @param $site_id * @param $message - * @return void + * @return true */ public function unsubscribe($site_id, $message){ $core_wechat_fans_service = new CoreWechatFansService(); @@ -131,9 +139,12 @@ class CoreWechatMessageService extends BaseCoreService /** * 文本回复事件 - * @param $site_id + * @param int $site_id * @param $message * @return News|Text|false + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ function text(int $site_id, $message) { diff --git a/niucloud/app/service/core/wechat/CoreWechatReplyService.php b/niucloud/app/service/core/wechat/CoreWechatReplyService.php index 6c462f8dc..789b4aac8 100644 --- a/niucloud/app/service/core/wechat/CoreWechatReplyService.php +++ b/niucloud/app/service/core/wechat/CoreWechatReplyService.php @@ -17,6 +17,9 @@ use app\model\wechat\WechatReply; use core\base\BaseCoreService; use core\exception\AdminException; use EasyWeChat\Kernel\Messages\Text; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; use think\Model; @@ -36,7 +39,7 @@ class CoreWechatReplyService extends BaseCoreService /** *关键字回复列表 - * @return void + * @return array */ public function getKeywordPage(int $site_id, array $data = []) { @@ -50,13 +53,13 @@ class CoreWechatReplyService extends BaseCoreService if (!empty($data['name'])) { $where[] = ['name', 'like', '%' . $data['name'] . '%']; } - return $this->getPageList($this->model, $where, 'name,keyword,matching_type,content_type,status,sort,create_time', 'uid desc', []); + return $this->getPageList($this->model, $where, 'name,keyword,matching_type,content_type,status,sort,create_time', 'uid desc'); } /** * 获取关键词回复信息 - * @param $site_id - * @param $id + * @param int $site_id + * @param int $id * @return array */ public function getKeywordInfo(int $site_id, int $id) @@ -70,9 +73,12 @@ class CoreWechatReplyService extends BaseCoreService /** * 通过关键词查询回复 - * @param $site_id - * @param $keyword + * @param int $site_id + * @param string $keyword * @return void + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function getKeywordInfoByKeyword(int $site_id, string $keyword) { @@ -105,9 +111,9 @@ class CoreWechatReplyService extends BaseCoreService /** * 新增关键词回复 - * @param $site_id - * @param $data - * @return WechatReply + * @param int $site_id + * @param string $data + * @return true */ public function addKeyword(int $site_id,string $data) { @@ -119,9 +125,10 @@ class CoreWechatReplyService extends BaseCoreService /** * 更新关键词回复 - * @param $site_id - * @param $data - * @return void + * @param int $site_id + * @param int $id + * @param array $data + * @return WechatReply */ public function editKeyword(int $site_id, int $id, array $data) { @@ -152,21 +159,19 @@ class CoreWechatReplyService extends BaseCoreService /** * - * @param $where + * @param array|string $where * @return WechatReply|array|mixed|Model */ public function find(array|string $where) { - $reply = $this->model->where($where)->findOrEmpty(); - - return $reply; + return $this->model->where($where)->findOrEmpty(); } /** * 获取默认回复 - * @param $site_id - * @return void + * @param int $site_id + * @return array */ public function getDefault(int $site_id) { @@ -179,8 +184,8 @@ class CoreWechatReplyService extends BaseCoreService /** * 更新默认回复 - * @param $site_id - * @param $data + * @param int $site_id + * @param array $data * @return void */ public function editDefault(int $site_id, array $data) @@ -203,8 +208,8 @@ class CoreWechatReplyService extends BaseCoreService /** * 获取关注回复 - * @param $site_id - * @return void + * @param int $site_id + * @return array */ public function getSubscribe(int $site_id) { @@ -217,8 +222,8 @@ class CoreWechatReplyService extends BaseCoreService /** * 更新关注回复 - * @param $site_id - * @param $data + * @param int $site_id + * @param array $data * @return void */ public function editSubscribe(int $site_id, array $data) @@ -242,10 +247,13 @@ class CoreWechatReplyService extends BaseCoreService /** * 回复 - * @param $site_id - * @param $event - * @param $content + * @param int $site_id + * @param string $event + * @param string $content * @return void + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function reply(int $site_id, string $event = '', string $content = '') { @@ -266,8 +274,7 @@ class CoreWechatReplyService extends BaseCoreService if ($info['status'] == ReplyDict::STATUS_ON) { switch($info['content_type']) { case ReplyDict::CONTENT_TYPE_TEXT://文本 - $text = new Text($info['content']); - return $text; + return new Text($info['content']); case ReplyDict::CONTENT_TYPE_NEW://图文 //todo 转化为临时素材或永久素材 $items = [ diff --git a/niucloud/app/service/core/wechat/CoreWechatServeService.php b/niucloud/app/service/core/wechat/CoreWechatServeService.php index 19ffe8dea..fe686f91f 100644 --- a/niucloud/app/service/core/wechat/CoreWechatServeService.php +++ b/niucloud/app/service/core/wechat/CoreWechatServeService.php @@ -14,10 +14,12 @@ namespace app\service\core\wechat; use core\base\BaseCoreService; use EasyWeChat\Kernel\Exceptions\BadRequestException; use EasyWeChat\Kernel\Exceptions\InvalidArgumentException; +use EasyWeChat\Kernel\Exceptions\InvalidConfigException; use EasyWeChat\Kernel\Exceptions\RuntimeException; use Overtrue\Socialite\Contracts\UserInterface; use Psr\Http\Message\ResponseInterface; use ReflectionException; +use Symfony\Component\HttpFoundation\Response; use Throwable; /** @@ -35,13 +37,11 @@ class CoreWechatServeService extends BaseCoreService * @param string $url * @param string $scopes * @return string - * @throws InvalidArgumentException */ public function authorization(int $site_id, string $url = '', string $scopes = 'snsapi_base') { $oauth = CoreWechatService::app($site_id)->oauth; - $redirect_url = $oauth->scopes([$scopes])->redirect($url); - return $redirect_url; + return $oauth->scopes([$scopes])->redirect($url); } /** @@ -49,13 +49,11 @@ class CoreWechatServeService extends BaseCoreService * @param int $site_id * @param string $code * @return UserInterface - * @throws InvalidArgumentException */ public function userFromCode(int $site_id, string $code) { $oauth = CoreWechatService::app($site_id)->oauth; - $user = $oauth->userFromCode($code); - return $user; + return $oauth->userFromCode($code); } public function getUser($user) @@ -75,13 +73,12 @@ class CoreWechatServeService extends BaseCoreService /** * 事件推送 - * @param $site_id - * @return ResponseInterface + * @param int $site_id + * @return Response * @throws BadRequestException * @throws InvalidArgumentException - * @throws RuntimeException * @throws ReflectionException - * @throws Throwable + * @throws InvalidConfigException */ public function serve(int $site_id) { @@ -98,8 +95,7 @@ class CoreWechatServeService extends BaseCoreService public function jssdkConfig(int $site_id, string $url = '') { $jssdk = CoreWechatService::app($site_id)->jssdk; - $config = $jssdk->setUrl($url)->buildConfig([], false, false, false); - return $config; + return $jssdk->setUrl($url)->buildConfig([], false, false, false); } public function scan(int $site_id, string $key, int $expire_seconds = 6 * 24 * 3600){ diff --git a/niucloud/app/service/core/wechat/CoreWechatService.php b/niucloud/app/service/core/wechat/CoreWechatService.php index 981332c4b..750703135 100644 --- a/niucloud/app/service/core/wechat/CoreWechatService.php +++ b/niucloud/app/service/core/wechat/CoreWechatService.php @@ -15,6 +15,7 @@ use core\base\BaseCoreService; use core\exception\WechatException; use EasyWeChat\Factory; use EasyWeChat\Kernel\Exceptions\InvalidArgumentException; +use EasyWeChat\OfficialAccount\Application; /** * easywechat主体提供 @@ -25,9 +26,8 @@ class CoreWechatService extends BaseCoreService { /** * 获取公众号的handle - * @param $site_id - * @return - * @throws InvalidArgumentException + * @param int $site_id + * @return Application */ public static function app(int $site_id) { @@ -41,9 +41,6 @@ class CoreWechatService extends BaseCoreService 'token' => $wechat_config['token'], 'aes_key' => $wechat_config['encoding_aes_key'],// 明文模式请勿填写 EncodingAESKey 'encryption_type' => $wechat_config['encryption_type'],//消息加解密方式 - 'http' => [ - 'throw' => true,//默认不抛出,还是有系统业务决定是否抛出 - ], // 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名 'response_type' => 'array', /** @@ -80,11 +77,11 @@ class CoreWechatService extends BaseCoreService 'max_retries' => 1, 'retry_delay' => 500, 'timeout' => 5.0, + 'throw' => true,//默认不抛出,还是有系统业务决定是否抛出 // 'base_uri' => 'https://api.weixin.qq.com/', // 如果你在国外想要覆盖默认的 url 的时候才使用,根据不同的模块配置不同的 uri ], ); - $app = Factory::officialAccount($config); - return $app; + return Factory::officialAccount($config); } } \ No newline at end of file diff --git a/niucloud/app/service/core/wechat/CoreWechatTemplateService.php b/niucloud/app/service/core/wechat/CoreWechatTemplateService.php index 1b85ad222..e82c89980 100644 --- a/niucloud/app/service/core/wechat/CoreWechatTemplateService.php +++ b/niucloud/app/service/core/wechat/CoreWechatTemplateService.php @@ -13,6 +13,11 @@ namespace app\service\core\wechat; use core\base\BaseCoreService; use EasyWeChat\Kernel\Exceptions\InvalidArgumentException; +use EasyWeChat\Kernel\Exceptions\InvalidConfigException; +use EasyWeChat\Kernel\Support\Collection; +use EasyWeChat\OfficialAccount\TemplateMessage\Client; +use GuzzleHttp\Exception\GuzzleException; +use Psr\Http\Message\ResponseInterface; /** * easywechat主体提供 @@ -24,8 +29,7 @@ class CoreWechatTemplateService extends BaseCoreService /** * 获取模板消息业务对象 * @param $site_id - * @return \EasyWeChat\OfficialAccount\TemplateMessage\Client - * @throws InvalidArgumentException + * @return Client */ public function template($site_id){ return CoreWechatService::app($site_id)->template_message; @@ -33,18 +37,18 @@ class CoreWechatTemplateService extends BaseCoreService /** * 发送模板消息 - * @param $site_id - * @param $open_id - * @param $wechat_template_id - * @param $data - * @param $first - * @param $remark - * @param $url - * @param $miniprogram - * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string + * @param int $site_id + * @param string $open_id + * @param string $wechat_template_id + * @param array $data + * @param string $first + * @param string $remark + * @param string $url + * @param string $miniprogram + * @return array|Collection|object|ResponseInterface|string * @throws InvalidArgumentException - * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException - * @throws \GuzzleHttp\Exception\GuzzleException + * @throws InvalidConfigException + * @throws GuzzleException */ public function send(int $site_id, string $open_id, string $wechat_template_id, array $data, string $first, string $remark, string $url = '', $miniprogram = ''){ if(!empty($first)) $data['first'] = $first; @@ -64,10 +68,9 @@ class CoreWechatTemplateService extends BaseCoreService * 删除 * @param int $site_id * @param string $templateId - * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string - * @throws InvalidArgumentException - * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException - * @throws \GuzzleHttp\Exception\GuzzleException + * @return array|Collection|object|ResponseInterface|string + * @throws GuzzleException + * @throws InvalidConfigException */ public function deletePrivateTemplate(int $site_id, string $templateId){ return $this->template($site_id)->deletePrivateTemplate($templateId); @@ -77,10 +80,9 @@ class CoreWechatTemplateService extends BaseCoreService * 添加 * @param int $site_id * @param string $shortId - * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string - * @throws InvalidArgumentException - * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException - * @throws \GuzzleHttp\Exception\GuzzleException + * @return array|Collection|object|ResponseInterface|string + * @throws GuzzleException + * @throws InvalidConfigException */ public function addTemplate(int $site_id, string $shortId){ return $this->template($site_id)->addTemplate($shortId); diff --git a/niucloud/app/validate/article/Article.php b/niucloud/app/validate/article/Article.php index 8a176f9ef..a404e5f5e 100644 --- a/niucloud/app/validate/article/Article.php +++ b/niucloud/app/validate/article/Article.php @@ -51,7 +51,7 @@ class Article extends Validate ]; protected $scene = [ - 'add' => ['title','intro', 'summary', 'image', 'author', 'is_show', 'sort', 'content', 'category_id'], - 'edit' => ['title','intro', 'summary', 'image', 'author', 'is_show', 'sort', 'content', 'category_id'], + 'add' => ['title', 'intro', 'summary', 'image', 'author', 'is_show', 'sort', 'content', 'category_id'], + 'edit' => ['title', 'intro', 'summary', 'image', 'author', 'is_show', 'sort', 'content', 'category_id'], ]; } \ No newline at end of file diff --git a/niucloud/app/validate/diy/Diy.php b/niucloud/app/validate/diy/Diy.php index 2f5411f27..554bc78e5 100644 --- a/niucloud/app/validate/diy/Diy.php +++ b/niucloud/app/validate/diy/Diy.php @@ -11,14 +11,14 @@ namespace app\validate\diy; -use app\dict\diy\TemplateDict; +use think\Validate; /** * 自定义页面验证器 * Class Diy * @package app\validate\diy */ -class Diy extends \think\Validate +class Diy extends Validate { protected $rule = [ @@ -32,8 +32,8 @@ class Diy extends \think\Validate protected $message = []; protected $scene = [ - "add" => [ 'title', 'name', 'type', 'value', 'is_default' ], - "edit" => [ 'title', 'name', 'value', 'is_default' ], + "add" => ['title', 'name', 'type', 'value', 'is_default'], + "edit" => ['title', 'name', 'value', 'is_default'], ]; } \ No newline at end of file diff --git a/niucloud/app/validate/diy/DiyRoute.php b/niucloud/app/validate/diy/DiyRoute.php index 138946229..cdda13ab2 100644 --- a/niucloud/app/validate/diy/DiyRoute.php +++ b/niucloud/app/validate/diy/DiyRoute.php @@ -11,12 +11,14 @@ namespace app\validate\diy; +use think\Validate; + /** * 自定义路由表验证器 * Class DiyRoute * @package app\validate\diy */ -class DiyRoute extends \think\Validate +class DiyRoute extends Validate { protected $rule = [ @@ -29,8 +31,8 @@ class DiyRoute extends \think\Validate protected $message = []; protected $scene = [ - "add" => [ 'title', 'name', 'page' ], - "edit" => [ 'title', 'name', 'page' ] + "add" => ['title', 'name', 'page'], + "edit" => ['title', 'name', 'page'] ]; } \ No newline at end of file diff --git a/niucloud/app/validate/generator/Generator.php b/niucloud/app/validate/generator/Generator.php index 167627b98..6cf83469e 100644 --- a/niucloud/app/validate/generator/Generator.php +++ b/niucloud/app/validate/generator/Generator.php @@ -36,7 +36,7 @@ class Generator extends Validate protected $scene = [ 'add' => ['table_name'], - "edit" => ['table_name','table_content','class_name', 'module_name', 'table_column'], + "edit" => ['table_name', 'table_content', 'class_name', 'module_name', 'table_column'], "create" => ['id'], ]; } \ No newline at end of file diff --git a/niucloud/app/validate/member/CashOut.php b/niucloud/app/validate/member/CashOut.php index bf6c17a41..954b027f8 100644 --- a/niucloud/app/validate/member/CashOut.php +++ b/niucloud/app/validate/member/CashOut.php @@ -20,22 +20,23 @@ use think\Validate; */ class CashOut extends Validate { - protected $rule = [ + protected $rule = [ 'apply_money' => 'min:0.01', // 提现金额 'account_type' => "checkAccountType", 'transfer_type' => 'checkTransferType', 'account_id' => 'checkAccountId' ]; - protected $message = [ + protected $message = [ 'apply_money.min' => 'validate_member_cash_out.apply_money_min', ]; protected $scene = [ - 'apply' => ['apply_money', 'account_type', 'transfer_type', 'account_id'], + 'apply' => ['apply_money', 'account_type', 'transfer_type', 'account_id'], ]; - protected function checkAccountId($value, $rule, $data = []) { + protected function checkAccountId($value, $rule, $data = []) + { if ($data['transfer_type'] == TransferDict::WECHAT) { return true; } else { @@ -43,13 +44,14 @@ class CashOut extends Validate } } - protected function checkTransferType($value){ - $transfer_type = array_keys(TransferDict::getTransferType()); - return in_array($value, $transfer_type) ? true : 'validate_member_cash_out.not_support_transfer_type'; + protected function checkTransferType($value) + { + return array_key_exists($value, TransferDict::getTransferType()) ? true : 'validate_member_cash_out.not_support_transfer_type'; } - protected function checkAccountType($value) { - $account_type = [ MemberAccountTypeDict::MONEY, MemberAccountTypeDict::COMMISSION ]; + protected function checkAccountType($value) + { + $account_type = [MemberAccountTypeDict::MONEY, MemberAccountTypeDict::COMMISSION]; return in_array($value, $account_type) ? true : 'validate_member_cash_out.not_support_account_type'; } } \ No newline at end of file diff --git a/niucloud/app/validate/member/CashOutAccount.php b/niucloud/app/validate/member/CashOutAccount.php index 3af033670..193569ffc 100644 --- a/niucloud/app/validate/member/CashOutAccount.php +++ b/niucloud/app/validate/member/CashOutAccount.php @@ -20,20 +20,20 @@ use think\Validate; class CashOutAccount extends Validate { protected $rule = [ - 'account_type' => 'checkAccountType', + 'account_type' => 'checkAccountType', 'bank_name' => 'checkBankName', 'account_no' => 'require', 'realname' => 'require' ]; - protected $message = [ + protected $message = [ 'account_type.require' => 'validate_member_cash_out_account.account_type_require', 'account_no.require' => 'validate_member_cash_out_account.account_no_require', 'realname.require' => 'validate_member_cash_out_account.realname_require', ]; protected $scene = [ - 'addOrEdit' => ['account_type', 'bank_name', 'account_no', 'realname'], + 'addOrEdit' => ['account_type', 'bank_name', 'account_no', 'realname'], ]; protected function checkBankName($value, $rule, $data = []) @@ -41,8 +41,8 @@ class CashOutAccount extends Validate return $data['account_type'] != 'bank' || !empty($value) ? true : 'validate_member_cash_out_account.bank_name_require'; } - protected function checkAccountType($value){ - $transfer_type = array_keys(TransferDict::getTransferType()); - return in_array($value, $transfer_type) ? true : 'validate_member_cash_out_account.not_support_transfer_type'; + protected function checkAccountType($value) + { + return array_key_exists($value, TransferDict::getTransferType()) ? true : 'validate_member_cash_out_account.not_support_transfer_type'; } } \ No newline at end of file diff --git a/niucloud/app/validate/member/CashOutConfig.php b/niucloud/app/validate/member/CashOutConfig.php index 695242fb3..db288fb24 100644 --- a/niucloud/app/validate/member/CashOutConfig.php +++ b/niucloud/app/validate/member/CashOutConfig.php @@ -20,16 +20,16 @@ class CashOutConfig extends Validate { - protected $rule = [ + protected $rule = [ 'is_open' => 'in:0,1', //是否开启 'min' => 'min:0', //最低提现金额 'rate' => 'between:0,100', //提现手续费比率 'is_auto_verify' => 'in:0,1', //是否自动审核 'is_auto_transfer' => 'in:0,1', //是否自动转账 - 'transfer_type' => 'require', + 'transfer_type' => 'require', ]; - protected $message = [ + protected $message = [ 'is_open.in' => 'validate_member.cash_out_is_open_in', 'min.min' => 'validate_member.cash_out_min_min', 'rate.between' => 'validate_member.cash_out_rate_between', @@ -39,6 +39,6 @@ class CashOutConfig extends Validate ]; protected $scene = [ - 'set' => ['is_open', 'min', 'rate', 'is_auto_verify', 'is_auto_transfer', 'transfer_type'], + 'set' => ['is_open', 'min', 'rate', 'is_auto_verify', 'is_auto_transfer', 'transfer_type'], ]; } \ No newline at end of file diff --git a/niucloud/app/validate/member/LoginConfig.php b/niucloud/app/validate/member/LoginConfig.php index 30bcd744b..9fe6e3f2b 100644 --- a/niucloud/app/validate/member/LoginConfig.php +++ b/niucloud/app/validate/member/LoginConfig.php @@ -22,15 +22,15 @@ class LoginConfig extends Validate { - protected $rule = [ - 'is_username' => 'number|between:0,1', - 'is_mobile' => 'number|between:0,1', - 'is_auth_register' => 'number|between:0,1', - 'is_bind_mobile' => 'number|between:0,1', + protected $rule = [ + 'is_username' => 'number|between:0,1', + 'is_mobile' => 'number|between:0,1', + 'is_auth_register' => 'number|between:0,1', + 'is_bind_mobile' => 'number|between:0,1', ]; - protected $message = [ + protected $message = [ 'is_username.number' => 'validate_member.is_username_number', 'is_username.between' => 'validate_member.is_username_between', 'is_mobile.number' => 'validate_member.is_mobile_number', @@ -42,6 +42,6 @@ class LoginConfig extends Validate ]; protected $scene = [ - 'set' => ['is_username', 'is_mobile', 'is_auth_register', 'is_bind_mobile'], + 'set' => ['is_username', 'is_mobile', 'is_auth_register', 'is_bind_mobile'], ]; } \ No newline at end of file diff --git a/niucloud/app/validate/member/Member.php b/niucloud/app/validate/member/Member.php index c115a0a34..ca53d79e6 100644 --- a/niucloud/app/validate/member/Member.php +++ b/niucloud/app/validate/member/Member.php @@ -13,6 +13,7 @@ namespace app\validate\member; use app\dict\common\CommonDict; use app\dict\member\MemberDict; +use think\facade\Lang; use think\Validate; /** @@ -24,22 +25,22 @@ class Member extends Validate { - protected $rule = [ - 'nickname' => 'requireWithout:field|max:30|requireIf:field,nickname', - 'mobile' => 'mobile', + protected $rule = [ + 'nickname' => 'requireWithout:field|max:30|requireIf:field,nickname', + 'mobile' => 'mobile', 'sex' => 'checkSex', 'birthday' => 'date', - 'username' => 'require', + 'username' => 'require|checkUsername', 'password' => 'require', - 'status' => 'require|checkStatus', + 'status' => 'require|checkStatus', ]; - protected $message = [ + protected $message = [ 'nickname.requireWithout' => 'validate_member.nickname_require', 'nickname.requireIf' => 'validate_member.nickname_require', - 'nickname.max' => 'validate_member.nickname_max', - 'mobile.require' => 'validate_member.mobile_require', - 'mobile.mobile' => 'validate_member.mobile_mobile', + 'nickname.max' => 'validate_member.nickname_max', + 'mobile.require' => 'validate_member.mobile_require', + 'mobile.mobile' => 'validate_member.mobile_mobile', 'birthday' => 'validate_member.birthday_format', 'username.require' => 'validate_member.username_require', 'username.unique' => 'validate_member.username_is_exist', @@ -50,20 +51,31 @@ class Member extends Validate ]; protected $scene = [ - 'add' => ['birthday', 'mobile', 'password'], - 'edit' => ['sex', 'birthday'], - 'modify' => ['sex', 'birthday'], - 'account_register' => ['username', 'password', 'mobile'], + 'add' => ['birthday', 'mobile', 'password'], + 'edit' => ['sex', 'birthday'], + 'modify' => ['sex', 'birthday'], + 'account_register' => ['username', 'password', 'mobile'], 'reset_password' => ['password', 'mobile'], 'set_status' => ['status'] ]; + /** + * 账号不能是纯数字 + * @param $value + * @param $rule + * @param $data + * @return Lang|true + */ + public function checkUsername($value, $rule, $data = []){ + return preg_match('/^\d+$/', $value) ? get_lang("validate_member.username_cannot_pure_number") : true; + } + /** * 自定义验证 性别 * @param $value * @param $rule * @param array $data - * @return bool|string + * @return Lang|true */ protected function checkSex($value, $rule, $data = []) { diff --git a/niucloud/app/validate/member/MemberConfig.php b/niucloud/app/validate/member/MemberConfig.php index 76246512e..e6b31347e 100644 --- a/niucloud/app/validate/member/MemberConfig.php +++ b/niucloud/app/validate/member/MemberConfig.php @@ -11,6 +11,7 @@ namespace app\validate\member; +use think\facade\Lang; use think\Validate; /** @@ -20,17 +21,32 @@ use think\Validate; */ class MemberConfig extends Validate { - protected $rule = [ - 'length' => 'number|min:10,max:20' + protected $rule = [ + 'length' => 'number|checkLength' ]; - protected $message = [ + protected $message = [ 'length.number' => 'validate_member_config.length_number', - 'length.min' => 'validate_member_config.length_min', - 'max.20' => 'validate_member_config.length_max' ]; protected $scene = [ - 'set' => ['length'], + 'set' => ['length'], ]; + + /** + * 自定义验证 长度 + * @param $value + * @param $rule + * @param array $data + * @return Lang|true + */ + protected function checkLength($value, $rule, $data = []) + { + $length = (int)$value; + $prefix_len = strlen($data['prefix'] ?? ''); + if (empty($length)) return get_lang("validate_member_config.length_number"); + if (($length - $prefix_len < 4) || $length > 30) return get_lang("validate_member_config.length_between"); + return true; + } + } \ No newline at end of file diff --git a/niucloud/app/validate/member/MemberLabel.php b/niucloud/app/validate/member/MemberLabel.php index 4670742a0..297971f7b 100644 --- a/niucloud/app/validate/member/MemberLabel.php +++ b/niucloud/app/validate/member/MemberLabel.php @@ -22,22 +22,22 @@ class MemberLabel extends Validate { - protected $rule = [ - 'label_name' => 'require|max:30', - 'memo' => 'max:200', - 'sort' => 'number', + protected $rule = [ + 'label_name' => 'require|max:30', + 'memo' => 'max:200', + 'sort' => 'number', ]; - protected $message = [ + protected $message = [ 'label_name.require' => 'validate_member.label_name_require', - 'label_name.max' => 'validate_member.label_name_max', - 'memo.max' => 'validate_member.memo_max', - 'sort.number' => 'validate_member.sort_number', + 'label_name.max' => 'validate_member.label_name_max', + 'memo.max' => 'validate_member.memo_max', + 'sort.number' => 'validate_member.sort_number', ]; protected $scene = [ - 'add' => ['label_name', 'memo', 'sort'], - 'edit' => ['label_name', 'memo', 'sort'], + 'add' => ['label_name', 'memo', 'sort'], + 'edit' => ['label_name', 'memo', 'sort'], ]; } \ No newline at end of file diff --git a/niucloud/app/validate/pay/Pay.php b/niucloud/app/validate/pay/Pay.php index 8d0cd214d..8f213ed9f 100644 --- a/niucloud/app/validate/pay/Pay.php +++ b/niucloud/app/validate/pay/Pay.php @@ -12,6 +12,7 @@ namespace app\validate\pay; use app\dict\pay\PayDict; +use think\facade\Lang; use think\Validate; /** @@ -24,17 +25,17 @@ class Pay extends Validate //用户名或密码的规范可能是从数据库中获取的 protected $rule = [ //支付宝 - 'app_id' => 'requireIf:type,'.PayDict::ALIPAY, - 'app_secret_cert' => 'requireIf:type,'.PayDict::ALIPAY, - 'app_public_cert_path' => 'requireIf:type,'.PayDict::ALIPAY, - 'alipay_public_cert_path' => 'requireIf:type,'.PayDict::ALIPAY, - 'alipay_root_cert_path' => 'requireIf:type,'.PayDict::ALIPAY, + 'app_id' => 'requireIf:type,' . PayDict::ALIPAY, + 'app_secret_cert' => 'requireIf:type,' . PayDict::ALIPAY, + 'app_public_cert_path' => 'requireIf:type,' . PayDict::ALIPAY, + 'alipay_public_cert_path' => 'requireIf:type,' . PayDict::ALIPAY, + 'alipay_root_cert_path' => 'requireIf:type,' . PayDict::ALIPAY, //微信 - 'mch_id' => 'requireIf:type,'.PayDict::WECHATPAY, - 'mch_secret_key' => 'requireIf:type,'.PayDict::WECHATPAY, - 'mch_secret_cert' => 'requireIf:type,'.PayDict::WECHATPAY, - 'mch_public_cert_path' => 'requireIf:type,'.PayDict::WECHATPAY, + 'mch_id' => 'requireIf:type,' . PayDict::WECHATPAY, + 'mch_secret_key' => 'requireIf:type,' . PayDict::WECHATPAY, + 'mch_secret_cert' => 'requireIf:type,' . PayDict::WECHATPAY, + 'mch_public_cert_path' => 'requireIf:type,' . PayDict::WECHATPAY, //支付方式 'type' => 'require|checkPayType', @@ -46,18 +47,18 @@ class Pay extends Validate 'app_public_cert_path.requireIf' => 'validate_pay.app_public_cert_path_requireif', 'alipay_public_cert_path.requireIf' => 'validate_pay.alipay_public_cert_path_requireif', 'alipay_root_cert_path.requireIf' => 'validate_pay.alipay_root_cert_path_requireif', - + 'mch_id.requireIf' => 'validate_pay.mch_id_requireif', 'mch_secret_key.requireIf' => 'validate_pay.mch_secret_key_requireif', 'mch_secret_cert.requireIf' => 'validate_pay.mch_secret_cert_requireif', 'mch_public_cert_path.requireIf' => 'validate_pay.mch_public_cert_path_requireif', - + ]; protected $scene = [ 'set' => [ 'app_id', 'app_secret_cert', 'app_public_cert_path', 'alipay_public_cert_path', 'alipay_root_cert_path', - 'mch_id','mch_secret_key','mch_secret_cert','mch_public_cert_path', + 'mch_id', 'mch_secret_key', 'mch_secret_cert', 'mch_public_cert_path', 'type', ], ]; @@ -67,11 +68,11 @@ class Pay extends Validate * @param $value * @param $rule * @param array $data - * @return bool|string + * @return Lang|true */ protected function checkPayType($value, $rule, $data = []) { - return isset( PayDict::getPayType()[$value]) ? true : get_lang("validate_pay.not_exit_pay_type"); + return isset(PayDict::getPayType()[$value]) ? true : get_lang("validate_pay.not_exit_pay_type"); } } \ No newline at end of file diff --git a/niucloud/app/validate/pay/PayTemplate.php b/niucloud/app/validate/pay/PayTemplate.php index aa3f01611..4288d832a 100644 --- a/niucloud/app/validate/pay/PayTemplate.php +++ b/niucloud/app/validate/pay/PayTemplate.php @@ -12,6 +12,7 @@ namespace app\validate\pay; use app\dict\pay\PayDict; +use think\facade\Lang; use think\Validate; /** @@ -25,17 +26,17 @@ class PayTemplate extends Validate protected $rule = [ 'name' => 'require', //支付宝 - 'app_id' => 'requireIf:type,'.PayDict::ALIPAY, - 'app_secret_cert' => 'requireIf:type,'.PayDict::ALIPAY, - 'app_public_cert_path' => 'requireIf:type,'.PayDict::ALIPAY, - 'alipay_public_cert_path' => 'requireIf:type,'.PayDict::ALIPAY, - 'alipay_root_cert_path' => 'requireIf:type,'.PayDict::ALIPAY, + 'app_id' => 'requireIf:type,' . PayDict::ALIPAY, + 'app_secret_cert' => 'requireIf:type,' . PayDict::ALIPAY, + 'app_public_cert_path' => 'requireIf:type,' . PayDict::ALIPAY, + 'alipay_public_cert_path' => 'requireIf:type,' . PayDict::ALIPAY, + 'alipay_root_cert_path' => 'requireIf:type,' . PayDict::ALIPAY, //微信 - 'mch_id' => 'requireIf:type,'.PayDict::WECHATPAY, - 'mch_secret_key' => 'requireIf:type,'.PayDict::WECHATPAY, - 'mch_secret_cert' => 'requireIf:type,'.PayDict::WECHATPAY, - 'mch_public_cert_path' => 'requireIf:type,'.PayDict::WECHATPAY, + 'mch_id' => 'requireIf:type,' . PayDict::WECHATPAY, + 'mch_secret_key' => 'requireIf:type,' . PayDict::WECHATPAY, + 'mch_secret_cert' => 'requireIf:type,' . PayDict::WECHATPAY, + 'mch_public_cert_path' => 'requireIf:type,' . PayDict::WECHATPAY, //支付方式 'type' => 'require|checkPayType', @@ -47,7 +48,7 @@ class PayTemplate extends Validate 'app_public_cert_path.requireIf' => 'validate_pay.app_public_cert_path_requireif', 'alipay_public_cert_path.requireIf' => 'validate_pay.alipay_public_cert_path_requireif', 'alipay_root_cert_path.requireIf' => 'validate_pay.alipay_root_cert_path_requireif', - + 'mch_id.requireIf' => 'validate_pay.mch_id_requireif', 'mch_secret_key.requireIf' => 'validate_pay.mch_secret_key_requireif', 'mch_secret_cert.requireIf' => 'validate_pay.mch_secret_cert_requireif', @@ -59,12 +60,12 @@ class PayTemplate extends Validate protected $scene = [ 'add' => [ 'app_id', 'app_secret_cert', 'app_public_cert_path', 'alipay_public_cert_path', 'alipay_root_cert_path', - 'mch_id','mch_secret_key','mch_secret_cert','mch_public_cert_path', + 'mch_id', 'mch_secret_key', 'mch_secret_cert', 'mch_public_cert_path', 'type', 'name' ], 'edit' => [ 'app_id', 'app_secret_cert', 'app_public_cert_path', 'alipay_public_cert_path', 'alipay_root_cert_path', - 'mch_id','mch_secret_key','mch_secret_cert','mch_public_cert_path', + 'mch_id', 'mch_secret_key', 'mch_secret_cert', 'mch_public_cert_path', 'name' ], ]; @@ -74,11 +75,11 @@ class PayTemplate extends Validate * @param $value * @param $rule * @param array $data - * @return bool|string + * @return Lang|true */ protected function checkPayType($value, $rule, $data = []) { - return isset( PayDict::getPayType()[$value]) ? true : get_lang('validate_pay.not_exit_pay_type'); + return isset(PayDict::getPayType()[$value]) ? true : get_lang('validate_pay.not_exit_pay_type'); } } \ No newline at end of file diff --git a/niucloud/app/validate/site/Site.php b/niucloud/app/validate/site/Site.php index 79dae362c..06ce8a315 100644 --- a/niucloud/app/validate/site/Site.php +++ b/niucloud/app/validate/site/Site.php @@ -22,22 +22,22 @@ class Site extends Validate { - protected $rule = [ - 'site_name' => 'require|max:20', - 'group_id' => 'require|number', - 'expire_time' => 'date', + protected $rule = [ + 'site_name' => 'require|max:20', + 'group_id' => 'require|number', + 'expire_time' => 'date', ]; - protected $message = [ + protected $message = [ 'site_name.require' => 'validate_site.site_name_require', - 'site_name.max' => 'validate_site.site_name_max', + 'site_name.max' => 'validate_site.site_name_max', 'group_id.require' => 'validate_site.group_id_require', - 'group_id.number' => 'validate_site.group_id_number', - 'expire_time.number' => 'validate_site.expire_time_number', + 'group_id.number' => 'validate_site.group_id_number', + 'expire_time.number' => 'validate_site.expire_time_number', ]; protected $scene = [ - 'add' => ['site_name', 'group_id', 'expire_time'], + 'add' => ['site_name', 'group_id', 'expire_time'], "edit" => ['site_name'] ]; } \ No newline at end of file diff --git a/niucloud/app/validate/site/SiteGroup.php b/niucloud/app/validate/site/SiteGroup.php index 66508c6a4..d7eb3e786 100644 --- a/niucloud/app/validate/site/SiteGroup.php +++ b/niucloud/app/validate/site/SiteGroup.php @@ -22,20 +22,20 @@ class SiteGroup extends Validate { - protected $rule = [ - 'group_name' => 'require|max:20', - 'group_roles' => 'require', + protected $rule = [ + 'group_name' => 'require|max:20', + 'group_roles' => 'require', ]; - protected $message = [ + protected $message = [ 'group_name.require' => 'validate_site.group_name_require', - 'group_name.max' => 'validate_site.group_name_max', + 'group_name.max' => 'validate_site.group_name_max', 'group_roles.require' => 'validate_site.group_roles_require', ]; protected $scene = [ - 'add' => ['group_name', 'group_roles'], - 'edit' => ['group_name', 'group_roles'], + 'add' => ['group_name', 'group_roles'], + 'edit' => ['group_name', 'group_roles'], ]; } \ No newline at end of file diff --git a/niucloud/app/validate/sys/AttachmentCategory.php b/niucloud/app/validate/sys/AttachmentCategory.php index ff0e90cd1..57f228bf3 100644 --- a/niucloud/app/validate/sys/AttachmentCategory.php +++ b/niucloud/app/validate/sys/AttachmentCategory.php @@ -12,6 +12,7 @@ namespace app\validate\sys; use app\dict\sys\FileDict; +use think\facade\Lang; use think\Validate; /** @@ -42,7 +43,7 @@ class AttachmentCategory extends Validate * @param $value * @param $rule * @param array $data - * @return bool|string + * @return Lang|true */ protected function checkMenuType($value, $rule, $data = []) { diff --git a/niucloud/app/validate/sys/Menu.php b/niucloud/app/validate/sys/Menu.php index b832f9ba7..484501a9a 100644 --- a/niucloud/app/validate/sys/Menu.php +++ b/niucloud/app/validate/sys/Menu.php @@ -13,6 +13,7 @@ namespace app\validate\sys; use app\dict\sys\MenuTypeDict; use app\dict\sys\MethodDict; +use think\facade\Lang; use think\Validate; /** @@ -51,7 +52,7 @@ class Menu extends Validate * @param $value * @param $rule * @param array $data - * @return bool|string + * @return Lang|true */ protected function checkMenuType($value, $rule, $data = []) { @@ -63,7 +64,7 @@ class Menu extends Validate * @param $value * @param $rule * @param array $data - * @return bool|string + * @return Lang|true */ protected function checkMethodType($value, $rule, $data = []) { diff --git a/niucloud/app/validate/sys/Page.php b/niucloud/app/validate/sys/Page.php index 03960bf3f..bb4ea6d68 100644 --- a/niucloud/app/validate/sys/Page.php +++ b/niucloud/app/validate/sys/Page.php @@ -10,6 +10,7 @@ // +---------------------------------------------------------------------- namespace app\validate\sys; + use think\Validate; /** @@ -17,16 +18,15 @@ use think\Validate; * Class Page * @package app\validate\sys */ - class Page extends Validate { - protected $rule = [ - 'page' => 'number|min:1', - 'limit' => 'number|between:1,120', + protected $rule = [ + 'page' => 'number|min:1', + 'limit' => 'number|between:1,120', ]; - protected $message = [ + protected $message = [ 'page.number' => 'validate_page.page_error', 'page.min' => 'validate_page.page_error', 'limit.number' => 'validate_page.limit_number', diff --git a/niucloud/app/validate/sys/Role.php b/niucloud/app/validate/sys/Role.php index 5abd04db3..883890bef 100644 --- a/niucloud/app/validate/sys/Role.php +++ b/niucloud/app/validate/sys/Role.php @@ -10,6 +10,7 @@ // +---------------------------------------------------------------------- namespace app\validate\sys; + use think\Validate; /** @@ -20,16 +21,16 @@ class Role extends Validate { //用户名或密码的规范可能是从数据库中获取的 - protected $rule = [ - 'role_name' => 'require', + protected $rule = [ + 'role_name' => 'require', ]; - protected $message = [ + protected $message = [ 'role_name.require' => 'validate_role.role_name_require', ]; protected $scene = [ - 'add' => ['role_name'], + 'add' => ['role_name'], 'edit' => ['role_name'] ]; } \ No newline at end of file diff --git a/niucloud/app/validate/sys/Schedule.php b/niucloud/app/validate/sys/Schedule.php index 2702e7f49..5387b121a 100644 --- a/niucloud/app/validate/sys/Schedule.php +++ b/niucloud/app/validate/sys/Schedule.php @@ -10,7 +10,9 @@ // +---------------------------------------------------------------------- namespace app\validate\sys; + use app\service\core\schedule\CoreScheduleService; +use think\facade\Lang; use think\Validate; /** @@ -20,17 +22,17 @@ class Schedule extends Validate { //用户名或密码的规范可能是从数据库中获取的 - protected $rule = [ - 'key' => 'require|unique:sys_schedule|checkKeyType', + protected $rule = [ + 'key' => 'require|unique:sys_schedule|checkKeyType', ]; - protected $message = [ + protected $message = [ 'key.require' => 'validate_schedule.schedule_require', 'key.unique' => 'validate_schedule.schedule_unique', ]; protected $scene = [ - 'add' => ['key'], + 'add' => ['key'], 'edit' => [], ]; @@ -39,7 +41,7 @@ class Schedule extends Validate * @param $value * @param $rule * @param array $data - * @return bool|string + * @return Lang|true */ protected function checkKeyType($value, $rule, $data = []) { diff --git a/niucloud/app/validate/sys/User.php b/niucloud/app/validate/sys/User.php index 7fe58ce38..e945fbc3d 100644 --- a/niucloud/app/validate/sys/User.php +++ b/niucloud/app/validate/sys/User.php @@ -10,6 +10,7 @@ // +---------------------------------------------------------------------- namespace app\validate\sys; + use think\Validate; /** @@ -20,23 +21,23 @@ class User extends Validate { //用户名或密码的规范可能是从数据库中获取的 - protected $rule = [ - 'username' => 'require|unique:sys_user', - 'real_name' => 'requireWithout:field|requireIf:field,real_name', + protected $rule = [ + 'username' => 'require|unique:sys_user', + 'real_name' => 'requireWithout:field|requireIf:field,real_name', 'password' => 'require', ]; - protected $message = [ + protected $message = [ 'username.require' => 'validate_user.username_require', 'username.unique' => 'validate_user.username_unique', - 'username.max' => 'validate_user.username_max', - 'real_name.requireWithout' => 'validate_user.real_name_require', - 'real_name.requireIf' => 'validate_user.real_name_require', - 'password.require' => 'validate_user.password_require', + 'username.max' => 'validate_user.username_max', + 'real_name.requireWithout' => 'validate_user.real_name_require', + 'real_name.requireIf' => 'validate_user.real_name_require', + 'password.require' => 'validate_user.password_require', ]; protected $scene = [ - 'add' => ['username','password'], + 'add' => ['username', 'password'], 'edit' => [], 'modify' => [] ]; diff --git a/niucloud/config/cron.php b/niucloud/config/cron.php new file mode 100644 index 000000000..e5a24290a --- /dev/null +++ b/niucloud/config/cron.php @@ -0,0 +1,5 @@ + [] +]; \ No newline at end of file diff --git a/niucloud/config/imgcaptcha.php b/niucloud/config/imgcaptcha.php index 727ca3eb3..4374d0cda 100644 --- a/niucloud/config/imgcaptcha.php +++ b/niucloud/config/imgcaptcha.php @@ -3,6 +3,9 @@ declare(strict_types=1); /** * 请将该文件放置于config目录 */ + +use think\facade\Cache; + return [ 'font_file' => '', //自定义字体包路径, 不填使用默认值 //文字验证码 @@ -22,6 +25,6 @@ return [ 'text' => '' ], 'cache' => [ - 'constructor' => [\think\facade\Cache::class, 'instance'] + 'constructor' => [Cache::class, 'instance'] ] ]; diff --git a/niucloud/config/niucloud.php b/niucloud/config/niucloud.php new file mode 100644 index 000000000..b811532a0 --- /dev/null +++ b/niucloud/config/niucloud.php @@ -0,0 +1,16 @@ + [ + 'code' => env('niucloud.code', ''),//授权码 + 'secret' => env('niucloud.secret', ''),//授权秘钥 + ], + 'http' => [ + 'max_retries' => 1,// 重试次数,默认 1,指定当 http 请求失败时重试的次数。 + 'retry_delay' => 500,//重试延迟间隔(单位:ms),默认 500 + 'timeout' => 5.0,//最大运行时间(超时) + 'verify' => false,//请求时验证SSL证书行为。设置成 true 启用SSL证书验证,默认使用操作系统提供的CA包。设置成 false 禁用证书验证(这是不安全的!)。设置成字符串启用验证,并使用该字符串作为自定义证书CA包的路径。 + ], + 'response_type' => 'array', + +]; diff --git a/niucloud/config/pay.php b/niucloud/config/pay.php index 8b76e26e1..0a26463d7 100644 --- a/niucloud/config/pay.php +++ b/niucloud/config/pay.php @@ -22,5 +22,8 @@ return [ 'balancepay' => [ 'driver' => 'app\service\core\paytype\CoreBalanceService', //反射类的名字 ], + 'offlinepay' => [ + 'driver' => 'app\service\core\paytype\CoreOfflineService' + ] ] ]; diff --git a/niucloud/config/upload.php b/niucloud/config/upload.php index 90c07bdce..17deb2065 100644 --- a/niucloud/config/upload.php +++ b/niucloud/config/upload.php @@ -58,7 +58,8 @@ return [ 'ext' => ['zip', 'rar'], 'mime' => [ 'application/zip', - 'application/vnd.rar' + 'application/vnd.rar', + 'application/x-zip-compressed' ], 'size' => 2097152 ] diff --git a/niucloud/core/base/BaseAdminService.php b/niucloud/core/base/BaseAdminService.php index 394b2c46c..763312438 100644 --- a/niucloud/core/base/BaseAdminService.php +++ b/niucloud/core/base/BaseAdminService.php @@ -24,6 +24,7 @@ class BaseAdminService extends BaseService protected $uid; protected $app_type; + public function __construct() { parent::__construct(); diff --git a/niucloud/core/base/BaseController.php b/niucloud/core/base/BaseController.php index 9adcda687..793b992b4 100644 --- a/niucloud/core/base/BaseController.php +++ b/niucloud/core/base/BaseController.php @@ -1,5 +1,5 @@ app = $app; + $this->app = $app; $this->request = $this->app->request; // 控制器初始化 $this->initialize(); @@ -52,15 +52,16 @@ abstract class BaseController // 初始化 protected function initialize() - {} + { + } /** * 验证数据 * @access protected - * @param array $data 数据 - * @param string|array $validate 验证器名或者验证规则数组 - * @param array $message 提示信息 - * @param bool $batch 是否批量验证 + * @param array $data 数据 + * @param string|array $validate 验证器名或者验证规则数组 + * @param array $message 提示信息 + * @param bool $batch 是否批量验证 * @return array|string|true * @throws ValidateException */ @@ -75,7 +76,7 @@ abstract class BaseController [$validate, $scene] = explode('.', $validate); } $class = str_contains($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate); - $v = new $class(); + $v = new $class(); if (!empty($scene)) { $v->scene($scene); } @@ -85,13 +86,11 @@ abstract class BaseController // 是否批量验证 if ($batch || $this->batchValidate) { - $v->batch(true); + $v->batch(); } - return $v->failException(true)->check($data); + return $v->failException()->check($data); } - - } diff --git a/niucloud/core/base/BaseJob.php b/niucloud/core/base/BaseJob.php index ea623bf41..f1122a0b1 100644 --- a/niucloud/core/base/BaseJob.php +++ b/niucloud/core/base/BaseJob.php @@ -13,6 +13,7 @@ namespace core\base; use core\job\Dispatch; use think\queue\Job; +use Throwable; /** * 队列 @@ -43,7 +44,7 @@ abstract class BaseJob extends Dispatch $data = $params['data'] ?? [];//数据 $error_count = $params['error_count'] ?? 0;//执行任务错误的最大重试次数 $this->runJob($action, $job, $data, $error_count); - } catch ( \Throwable $e ) { + } catch ( Throwable $e ) { $job->delete(); } } diff --git a/niucloud/core/base/BaseService.php b/niucloud/core/base/BaseService.php index 0034cd0b7..3b9e8dd59 100644 --- a/niucloud/core/base/BaseService.php +++ b/niucloud/core/base/BaseService.php @@ -13,6 +13,7 @@ namespace core\base; use app\validate\sys\Page; +use think\db\exception\DbException; use think\Model; /** @@ -33,11 +34,13 @@ abstract class BaseService { $this->request = request(); } + /** * 分页列表参数(页码和每页多少条) * @return mixed */ - public function getPageParam(){ + public function getPageParam() + { $page = request()->params([ ['page', 1], @@ -50,29 +53,31 @@ abstract class BaseService /** * 分页列表 + * @param Model $model * @param array $where * @param string $field * @param string $order - * @param int $page - * @param int $limit + * @param array $append * @param null $with //数组可以是数组 function($query) use ($with){$query->with($with);} * @param null $each //闭包匿名函数 function($item, $key){$item['nickname'] = 'think';return $item;} - * @return mixed + * @return array + * @throws DbException */ - public function getPageList(Model $model, array $where, string $field = '*', string $order = '', array $append = [], $with = null, $each = null){ + public function getPageList(Model $model, array $where, string $field = '*', string $order = '', array $append = [], $with = null, $each = null) + { $page_params = $this->getPageParam(); $page = $page_params['page']; $limit = $page_params['limit']; - $list = $model->where($where)->when($append, function($query) use ($append){ + $list = $model->where($where)->when($append, function ($query) use ($append) { $query->append($append); - })->when($with, function ($query) use($with){ + })->when($with, function ($query) use ($with) { $query->with($with); })->field($field)->order($order)->paginate([ 'list_rows' => $limit, 'page' => $page, ]); - if(!empty($each)){ + if (!empty($each)) { $list = $list->each($each); } return $list->toArray(); @@ -81,8 +86,9 @@ abstract class BaseService /** * 分页数据查询,传入model(查询后结果) * @param $model BaseModel - * @param $each - * @return mixed + * @param null $each + * @return array + * @throws DbException */ public function pageQuery($model, $each = null) { @@ -93,7 +99,7 @@ abstract class BaseService 'list_rows' => $limit, 'page' => $page, ]); - if(!empty($each)){ + if (!empty($each)) { $list = $list->each($each); } return $list->toArray(); @@ -109,22 +115,23 @@ abstract class BaseService * @param null $with * @param null $each * @return array - * @throws \think\db\exception\DbException + * @throws DbException */ - public function getPageViewList(Model $model, array $where, string $field = '*', string $order = '', array $append = [], $with = null, $each = null){ + public function getPageViewList(Model $model, array $where, string $field = '*', string $order = '', array $append = [], $with = null, $each = null) + { $page_params = $this->getPageParam(); $page = $page_params['page']; $limit = $page_params['limit']; - $list = $model->where($where)->when($append, function($query) use ($append){ + $list = $model->where($where)->when($append, function ($query) use ($append) { $query->append($append); - })->when($with, function ($query) use($with){ + })->when($with, function ($query) use ($with) { $query->withJoin($with); })->field($field)->order($order)->paginate([ 'list_rows' => $limit, 'page' => $page, ]); - if(!empty($each)){ + if (!empty($each)) { $list = $list->each($each); } return $list->toArray(); diff --git a/niucloud/core/dict/BaseDict.php b/niucloud/core/dict/BaseDict.php index b2f320321..31adf7659 100644 --- a/niucloud/core/dict/BaseDict.php +++ b/niucloud/core/dict/BaseDict.php @@ -17,16 +17,17 @@ use think\facade\Db; /** * Class BaseAddon - * @package + * @package */ abstract class BaseDict extends Storage { //插件整体缓存标识 public static $cache_tag_name = 'addon_cash'; + /** * 初始化 * @param array $config - * @return mixed|void + * @return void */ protected function initialize(array $config = []) { @@ -37,23 +38,19 @@ abstract class BaseDict extends Storage */ protected function getLocalAddons() { - if(!file_exists(root_path()."install.lock")) - { + if (!file_exists(root_path() . "install.lock")) { //尚未安装不加载插件 return []; } $addons = Cache::get("local_install_addons"); - if(empty($addons)) - { + if (empty($addons)) { $addons = Db::name("addon")->column("key"); - if(empty($addons)) - { + if (empty($addons)) { Cache::set("local_install_addons", -1); - }else + } else Cache::set("local_install_addons", $addons); } - if($addons == -1) - { + if ($addons == -1) { $addons = []; } return $addons; @@ -66,7 +63,7 @@ abstract class BaseDict extends Storage */ protected function getAddonPath(string $addon) { - return root_path() . 'addon' . DIRECTORY_SEPARATOR. $addon. DIRECTORY_SEPARATOR; + return root_path() . 'addon' . DIRECTORY_SEPARATOR . $addon . DIRECTORY_SEPARATOR; } @@ -76,8 +73,9 @@ abstract class BaseDict extends Storage */ protected function getAppPath() { - return root_path(). "app". DIRECTORY_SEPARATOR; + return root_path() . "app" . DIRECTORY_SEPARATOR; } + /** * 获取插件对应app目录 * @param string $addon @@ -85,7 +83,7 @@ abstract class BaseDict extends Storage */ protected function getAddonAppPath(string $addon) { - return $this->getAddonPath($addon). "app". DIRECTORY_SEPARATOR; + return $this->getAddonPath($addon) . "app" . DIRECTORY_SEPARATOR; } /** @@ -93,25 +91,27 @@ abstract class BaseDict extends Storage */ protected function getDictPath() { - return root_path(). 'app'. DIRECTORY_SEPARATOR. 'dict'. DIRECTORY_SEPARATOR; + return root_path() . 'app' . DIRECTORY_SEPARATOR . 'dict' . DIRECTORY_SEPARATOR; } /** *获取插件对应的dict目录 * @param string $addon + * @return string */ protected function getAddonDictPath(string $addon) { - return $this->getAddonPath($addon). 'app'. DIRECTORY_SEPARATOR. 'dict'. DIRECTORY_SEPARATOR; + return $this->getAddonPath($addon) . 'app' . DIRECTORY_SEPARATOR . 'dict' . DIRECTORY_SEPARATOR; } /** *获取插件对应的config目录 * @param string $addon + * @return string */ protected function getAddonConfigPath(string $addon) { - return $this->getAddonPath($addon). 'config'. DIRECTORY_SEPARATOR; + return $this->getAddonPath($addon) . 'config' . DIRECTORY_SEPARATOR; } /** @@ -127,16 +127,16 @@ abstract class BaseDict extends Storage foreach ($files as $file) { $config = include $file; if (!empty($config)) { - if (isset($config[ 'file_sort' ])) { - $sort = $config[ 'file_sort' ]; - unset($config[ 'file_sort' ]); + if (isset($config['file_sort'])) { + $sort = $config['file_sort']; + unset($config['file_sort']); $sort = $sort * 10; while (array_key_exists($sort, $files_data)) { $sort++; } - $files_data[ $sort ] = $config; + $files_data[$sort] = $config; } else { - $files_data[ $default_sort ] = $config; + $files_data[$default_sort] = $config; $default_sort++; } } diff --git a/niucloud/core/dict/DictLoader.php b/niucloud/core/dict/DictLoader.php index b383701d0..229bd1117 100644 --- a/niucloud/core/dict/DictLoader.php +++ b/niucloud/core/dict/DictLoader.php @@ -14,8 +14,8 @@ namespace core\dict; use core\loader\Loader; /** - * @see \core\dict\DictLoader - * @mixin \core\dict\BaseDict + * @see DictLoader + * @mixin BaseDict * @method array|null load(array $data = []) */ class DictLoader extends Loader @@ -28,9 +28,10 @@ class DictLoader extends Loader protected $namespace = '\\core\\dict\\'; protected $config_name = 'dict'; + /** * 默认驱动 - * @return mixed + * @return string */ protected function getDefault() { diff --git a/niucloud/core/dict/Event.php b/niucloud/core/dict/Event.php index d30846965..3b4ecc397 100644 --- a/niucloud/core/dict/Event.php +++ b/niucloud/core/dict/Event.php @@ -15,19 +15,17 @@ class Event extends BaseDict { /** * 加载事件 - * @param array $system_event 系统事件 + * @param array $data * @return array|mixed */ public function load(array $data) { - $addons = $this->getLocalAddons(); + $addons = $this->getLocalAddons(); $event_files = []; - foreach ($addons as $k => $v) - { - $event_path = $this->getAddonAppPath($v)."event.php"; - if(is_file($event_path)) - { + foreach ($addons as $v) { + $event_path = $this->getAddonAppPath($v) . "event.php"; + if (is_file($event_path)) { $event_files[] = $event_path; } } diff --git a/niucloud/core/dict/Icon.php b/niucloud/core/dict/Icon.php index e874797cd..704facb5f 100644 --- a/niucloud/core/dict/Icon.php +++ b/niucloud/core/dict/Icon.php @@ -22,16 +22,16 @@ class Icon extends BaseDict * @param array $data * @return array */ - public function load(array $data) : array + public function load(array $data): array { $sys_path = dirname(app()->getRootPath()) . str_replace('/', DIRECTORY_SEPARATOR, '/admin/src/styles/icon'); $file_arr = getFileMap($sys_path); $icon_arr = []; if (!empty($file_arr)) { foreach ($file_arr as $ck => $cv) { - if (strpos($cv, '.json') !== false) { + if (str_contains($cv, '.json')) { $json_string = file_get_contents($ck); - $icon = json_decode($json_string, true); + $icon = json_decode($json_string, true, 512, JSON_THROW_ON_ERROR); $icon_arr[] = $icon; } } diff --git a/niucloud/core/dict/Lang.php b/niucloud/core/dict/Lang.php index c5580f534..ba91d4ba5 100644 --- a/niucloud/core/dict/Lang.php +++ b/niucloud/core/dict/Lang.php @@ -21,7 +21,7 @@ class Lang extends BaseDict public function load(array $data) { $addons = $this->getLocalAddons(); - $system_lang_path = $this->getAppPath() . "lang" . DIRECTORY_SEPARATOR . $data[ 'lang_type' ] . DIRECTORY_SEPARATOR; + $system_lang_path = $this->getAppPath() . "lang" . DIRECTORY_SEPARATOR . $data['lang_type'] . DIRECTORY_SEPARATOR; $lang_files = [ $system_lang_path . "api.php", $system_lang_path . "dict.php", @@ -29,8 +29,8 @@ class Lang extends BaseDict ]; - foreach ($addons as $k => $v) { - $lang_path = $this->getAddonAppPath($v) . "lang" . DIRECTORY_SEPARATOR . $data[ 'lang_type' ] . DIRECTORY_SEPARATOR; + foreach ($addons as $v) { + $lang_path = $this->getAddonAppPath($v) . "lang" . DIRECTORY_SEPARATOR . $data['lang_type'] . DIRECTORY_SEPARATOR; $api_path = $lang_path . "api.php"; $dict_path = $lang_path . "dict.php"; diff --git a/niucloud/core/dict/MemberAccountChangeType.php b/niucloud/core/dict/MemberAccountChangeType.php index 18f64a2ad..b95d1e8fc 100644 --- a/niucloud/core/dict/MemberAccountChangeType.php +++ b/niucloud/core/dict/MemberAccountChangeType.php @@ -20,20 +20,17 @@ class MemberAccountChangeType extends BaseDict */ public function load(array $data = []) { - $addons = $this->getLocalAddons(); + $addons = $this->getLocalAddons(); $account_change_type_files = []; - $system_change_type_file = $this->getDictPath()."member". DIRECTORY_SEPARATOR. "account_change_type.php"; + $system_change_type_file = $this->getDictPath() . "member" . DIRECTORY_SEPARATOR . "account_change_type.php"; - if(is_file($system_change_type_file)) - { + if (is_file($system_change_type_file)) { $account_change_type_files[] = $system_change_type_file; } - foreach ($addons as $k => $v) - { - $addon_change_type_file = $this->getAddonDictPath($v)."member". DIRECTORY_SEPARATOR. "account_change_type.php"; - if(is_file($addon_change_type_file)) - { + foreach ($addons as $v) { + $addon_change_type_file = $this->getAddonDictPath($v) . "member" . DIRECTORY_SEPARATOR . "account_change_type.php"; + if (is_file($addon_change_type_file)) { $account_change_type_files[] = $addon_change_type_file; } } @@ -41,8 +38,7 @@ class MemberAccountChangeType extends BaseDict $account_change_type_datas = $this->loadFiles($account_change_type_files); $account_change_type_array = []; - foreach ($account_change_type_datas as $account_change_type_data) - { + foreach ($account_change_type_datas as $account_change_type_data) { $account_change_type_array = empty($account_change_type_array) ? $account_change_type_data : array_merge2($account_change_type_array, $account_change_type_data); } return $account_change_type_array; diff --git a/niucloud/core/dict/Menu.php b/niucloud/core/dict/Menu.php index 60cf8d7d7..ef44d5183 100644 --- a/niucloud/core/dict/Menu.php +++ b/niucloud/core/dict/Menu.php @@ -15,14 +15,13 @@ class Menu extends BaseDict { /** * 加载菜单 - * @param array $data //传入插件,应用类型 - * @return array|mixed + * @param array $data //传入插件,应用类型 + * @return array */ - public function load(array $data):array + public function load(array $data): array { - $menu_path = $this->getAddonDictPath($data['addon'])."menu".DIRECTORY_SEPARATOR. $data['app_type']. ".php"; - if(is_file($menu_path)) - { + $menu_path = $this->getAddonDictPath($data['addon']) . "menu" . DIRECTORY_SEPARATOR . $data['app_type'] . ".php"; + if (is_file($menu_path)) { return include $menu_path; } return []; diff --git a/niucloud/core/dict/Notice.php b/niucloud/core/dict/Notice.php index 44506d851..f32fbcfbe 100644 --- a/niucloud/core/dict/Notice.php +++ b/niucloud/core/dict/Notice.php @@ -21,25 +21,21 @@ class Notice extends BaseDict public function load(array $data) { $template_files = []; - $system_path = $this->getDictPath(). "notice". DIRECTORY_SEPARATOR. $data['type']. ".php"; - if(is_file($system_path)) - { + $system_path = $this->getDictPath() . "notice" . DIRECTORY_SEPARATOR . $data['type'] . ".php"; + if (is_file($system_path)) { $template_files[] = $system_path; } - $addons = $this->getLocalAddons(); - foreach ($addons as $k => $v) - { - $template_path = $this->getAddonDictPath($v). "notice". DIRECTORY_SEPARATOR. $data['type']. ".php"; - if(is_file($template_path)) - { + $addons = $this->getLocalAddons(); + foreach ($addons as $v) { + $template_path = $this->getAddonDictPath($v) . "notice" . DIRECTORY_SEPARATOR . $data['type'] . ".php"; + if (is_file($template_path)) { $template_files[] = $template_path; } } $template_files_data = $this->loadFiles($template_files); $template_data_array = []; - foreach ($template_files_data as $file_data) - { + foreach ($template_files_data as $file_data) { $template_data_array = empty($template_data_array) ? $file_data : array_merge($template_data_array, $file_data); } return $template_data_array; diff --git a/niucloud/core/dict/Route.php b/niucloud/core/dict/Route.php index 95af50f5f..d120dea34 100644 --- a/niucloud/core/dict/Route.php +++ b/niucloud/core/dict/Route.php @@ -16,17 +16,15 @@ class Route extends BaseDict /** * 加载路由 * @param array $data 传入路由端口 - * @return array|mixed + * @return true */ public function load(array $data) { - $addons = $this->getLocalAddons(); + $addons = $this->getLocalAddons(); - foreach ($addons as $k => $v) - { - $route_path = $this->getAddonAppPath($v). DIRECTORY_SEPARATOR. $data['app_type']. DIRECTORY_SEPARATOR. "route". DIRECTORY_SEPARATOR. "route.php"; - if(is_file($route_path)) - { + foreach ($addons as $k => $v) { + $route_path = $this->getAddonAppPath($v) . DIRECTORY_SEPARATOR . $data['app_type'] . DIRECTORY_SEPARATOR . "route" . DIRECTORY_SEPARATOR . "route.php"; + if (is_file($route_path)) { include $route_path; } } diff --git a/niucloud/core/dict/Schedule.php b/niucloud/core/dict/Schedule.php index 0d03849fb..23bae1494 100644 --- a/niucloud/core/dict/Schedule.php +++ b/niucloud/core/dict/Schedule.php @@ -22,35 +22,28 @@ class Schedule extends BaseDict { $addon = $data['addon'] ?? ''; $schedule_files = []; - if(empty($addon)) - { - $system_path = $this->getDictPath(). 'schedule'. DIRECTORY_SEPARATOR. 'schedule.php'; - if(is_file($system_path)) - { + if (empty($addon)) { + $system_path = $this->getDictPath() . 'schedule' . DIRECTORY_SEPARATOR . 'schedule.php'; + if (is_file($system_path)) { $schedule_files[] = $system_path; } - $addons = $this->getLocalAddons(); - foreach ($addons as $k => $v) - { - $addon_path = $this->getAddonDictPath($v). 'schedule'. DIRECTORY_SEPARATOR. 'schedule.php'; - if(is_file($addon_path)) - { + $addons = $this->getLocalAddons(); + foreach ($addons as $v) { + $addon_path = $this->getAddonDictPath($v) . 'schedule' . DIRECTORY_SEPARATOR . 'schedule.php'; + if (is_file($addon_path)) { $schedule_files[] = $addon_path; } } - }else{ + } else { $schedule_files = []; - if($addon == 'system'){ - $schedule_files = []; - $system_path = $this->getDictPath(). 'schedule'. DIRECTORY_SEPARATOR. 'schedule.php'; - if(is_file($system_path)) - { + if ($addon == 'system') { + $system_path = $this->getDictPath() . 'schedule' . DIRECTORY_SEPARATOR . 'schedule.php'; + if (is_file($system_path)) { $schedule_files[] = $system_path; } - }else{ - $addon_path = $this->getAddonDictPath($addon). 'schedule'. DIRECTORY_SEPARATOR. 'schedule.php'; - if(is_file($addon_path)) - { + } else { + $addon_path = $this->getAddonDictPath($addon) . 'schedule' . DIRECTORY_SEPARATOR . 'schedule.php'; + if (is_file($addon_path)) { $schedule_files[] = $addon_path; } } @@ -58,8 +51,7 @@ class Schedule extends BaseDict } $schedule_files_data = $this->loadFiles($schedule_files); $schedule_data_array = []; - foreach ($schedule_files_data as $file_data) - { + foreach ($schedule_files_data as $file_data) { $schedule_data_array = empty($schedule_data_array) ? $file_data : array_merge($schedule_data_array, $file_data); } return $schedule_data_array; diff --git a/niucloud/core/dict/UniappComponent.php b/niucloud/core/dict/UniappComponent.php index 8f31aef92..ba2a7ab5e 100644 --- a/niucloud/core/dict/UniappComponent.php +++ b/niucloud/core/dict/UniappComponent.php @@ -20,20 +20,17 @@ class UniappComponent extends BaseDict */ public function load(array $data) { - $addons = $this->getLocalAddons(); + $addons = $this->getLocalAddons(); $components_files = []; - foreach ($addons as $k => $v) - { - $components_path = $this->getAddonDictPath($v). "diy". DIRECTORY_SEPARATOR. "components.php"; - if(is_file($components_path)) - { + foreach ($addons as $v) { + $components_path = $this->getAddonDictPath($v) . "diy" . DIRECTORY_SEPARATOR . "components.php"; + if (is_file($components_path)) { $components_files[] = $components_path; } } $components_files_data = $this->loadFiles($components_files); $components = $data; - foreach ($components_files_data as $file_data) - { + foreach ($components_files_data as $file_data) { $components = empty($components) ? $file_data : array_merge2($components, $file_data); } return $components; diff --git a/niucloud/core/dict/UniappLink.php b/niucloud/core/dict/UniappLink.php index 2d861ee6a..0958d0b4a 100644 --- a/niucloud/core/dict/UniappLink.php +++ b/niucloud/core/dict/UniappLink.php @@ -22,7 +22,7 @@ class UniappLink extends BaseDict { $addons = $this->getLocalAddons(); $link_files = []; - foreach ($addons as $k => $v) { + foreach ($addons as $v) { $link_path = $this->getAddonDictPath($v) . "diy" . DIRECTORY_SEPARATOR . "links.php"; if (is_file($link_path)) { $link_files[] = $link_path; diff --git a/niucloud/core/dict/UniappPages.php b/niucloud/core/dict/UniappPages.php index 536eb7455..33bb24536 100644 --- a/niucloud/core/dict/UniappPages.php +++ b/niucloud/core/dict/UniappPages.php @@ -22,7 +22,7 @@ class UniappPages extends BaseDict { $addons = $this->getLocalAddons(); $page_files = []; - foreach ($addons as $k => $v) { + foreach ($addons as $v) { $page_path = $this->getAddonDictPath($v) . "diy" . DIRECTORY_SEPARATOR . "pages.php"; if (is_file($page_path)) { $page_files[] = $page_path; diff --git a/niucloud/core/dict/UniappTemplate.php b/niucloud/core/dict/UniappTemplate.php index 9dd628f7d..1e4611fcd 100644 --- a/niucloud/core/dict/UniappTemplate.php +++ b/niucloud/core/dict/UniappTemplate.php @@ -22,7 +22,7 @@ class UniappTemplate extends BaseDict { $addons = $this->getLocalAddons(); $page_files = []; - foreach ($addons as $k => $v) { + foreach ($addons as $v) { $page_path = $this->getAddonDictPath($v) . "diy" . DIRECTORY_SEPARATOR . "template.php"; if (is_file($page_path)) { $page_files[] = $page_path; diff --git a/niucloud/core/exception/AddonException.php b/niucloud/core/exception/AddonException.php index 59634410e..f10b15459 100644 --- a/niucloud/core/exception/AddonException.php +++ b/niucloud/core/exception/AddonException.php @@ -1,4 +1,5 @@ job($class)->secs($secs); if (is_array($action)) { diff --git a/niucloud/core/loader/Loader.php b/niucloud/core/loader/Loader.php index 248e7dc07..e3403f6b8 100644 --- a/niucloud/core/loader/Loader.php +++ b/niucloud/core/loader/Loader.php @@ -2,6 +2,8 @@ namespace core\loader; +use Exception; +use think\DbManager; use think\Facade; use think\helper\Str; @@ -15,17 +17,18 @@ abstract class Loader extends Facade protected $class = null; protected $config = null; protected $config_file = null; + /** - * @param string $type - * @return object|\think\DbManager - * @throws \Exception + * @param string $name + * @param array $config */ - public function __construct($name = '', array $config = []){ - if(is_array($name)){ + public function __construct($name = '', array $config = []) + { + if (is_array($name)) { $config = $name; $name = null; } - if($name){ + if ($name) { $this->name = $name; } $this->config = $config; @@ -40,10 +43,11 @@ abstract class Loader extends Facade /** * 创建实例对象 * @param string $type - * @return object|\think\DbManager - * @throws \Exception + * @return object|DbManager + * @throws Exception */ - public function create(string $type){ + public function create(string $type) + { $class = $this->getClass($type); return self::createFacade($class, [ $this->name, @@ -56,18 +60,19 @@ abstract class Loader extends Facade * 获取类 * @param string $type * @return mixed|string - * @throws \Exception + * @throws Exception */ - public function getClass(string $type){ - $class = config($this->config_name.'.drivers.'.$type.'.driver'); + public function getClass(string $type) + { + $class = config($this->config_name . '.drivers.' . $type . '.driver'); if (!empty($class) && class_exists($class)) { return $class; - }else{ + } else { if ($this->namespace || str_contains($type, '\\')) { $class = str_contains($type, '\\') ? $type : $this->namespace . $type; - if(class_exists($class)){ + if (class_exists($class)) { return $class; - }else{ + } else { $class = str_contains($type, '\\') ? $type : $this->namespace . Str::studly($type); if (class_exists($class)) { return $class; @@ -75,20 +80,21 @@ abstract class Loader extends Facade } } } - throw new \Exception("Driver [$type] not supported."); + throw new Exception("Driver [$type] not supported."); } /** * 通过装载器获取实例 - * @return object|\think\DbManager - * @throws \Exception + * @return object|DbManager + * @throws Exception */ - public function getLoader(){ + public function getLoader() + { - if(empty($this->class)){ + if (empty($this->class)) { $this->name = $this->name ?: $this->getDefault(); if (!$this->name) { - throw new \Exception(sprintf( + throw new Exception(sprintf( 'could not find driver [%s].', static::class )); } @@ -96,11 +102,13 @@ abstract class Loader extends Facade } return $this->class; } + /** * 动态调用 * @param $method * @param $arguments * @return mixed + * @throws Exception */ public function __call($method, $arguments) { diff --git a/niucloud/core/loader/Storage.php b/niucloud/core/loader/Storage.php index fb4df3273..50aea02b8 100644 --- a/niucloud/core/loader/Storage.php +++ b/niucloud/core/loader/Storage.php @@ -1,4 +1,5 @@ config_file = $config_file; $this->initialize($config); } + /** * 设置错误信息 * @param string|null $error diff --git a/niucloud/core/oauth/BaseOauth.php b/niucloud/core/oauth/BaseOauth.php index 8907f49f7..cea4bc657 100644 --- a/niucloud/core/oauth/BaseOauth.php +++ b/niucloud/core/oauth/BaseOauth.php @@ -13,10 +13,11 @@ abstract class BaseOauth extends Storage { protected $config;//配置 protected $site_id; + /** * 初始化 * @param array $config - * @return mixed|void + * @return void */ protected function initialize(array $config = []) { @@ -25,7 +26,7 @@ abstract class BaseOauth extends Storage /** * 获取粉丝信息 - * @param string $openid + * @param string|null $openid * @return mixed */ abstract public function getFansInfo(string $openid = null); @@ -39,6 +40,4 @@ abstract class BaseOauth extends Storage abstract public function oauth(string $code = null, array $options = []); - - } \ No newline at end of file diff --git a/niucloud/core/oauth/OauthLoader.php b/niucloud/core/oauth/OauthLoader.php index 3cd651402..e93276f3c 100644 --- a/niucloud/core/oauth/OauthLoader.php +++ b/niucloud/core/oauth/OauthLoader.php @@ -14,7 +14,7 @@ namespace core\oauth; use core\loader\Loader; /** - * @see \core\oauth\OauthLoader + * @see OauthLoader * @package think\facade */ class OauthLoader extends Loader @@ -26,6 +26,7 @@ class OauthLoader extends Loader protected $namespace = '\\core\\oauth\\'; protected $config_name = 'oauth'; + /** * 默认驱动 * @return mixed diff --git a/niucloud/core/oauth/Weapp.php b/niucloud/core/oauth/Weapp.php index 7ef269751..bb60fe0c5 100644 --- a/niucloud/core/oauth/Weapp.php +++ b/niucloud/core/oauth/Weapp.php @@ -13,7 +13,7 @@ class Weapp extends BaseOauth /** * @param array $config - * @return mixed|void + * @return void */ protected function initialize(array $config = []) { diff --git a/niucloud/core/oauth/Wechat.php b/niucloud/core/oauth/Wechat.php index a1daa8785..803b9ff58 100644 --- a/niucloud/core/oauth/Wechat.php +++ b/niucloud/core/oauth/Wechat.php @@ -15,7 +15,7 @@ class Wechat extends BaseOauth /** * @param array $config - * @return mixed|void + * @return void */ protected function initialize(array $config = []) { @@ -27,9 +27,11 @@ class Wechat extends BaseOauth // TODO: Implement getFansInfo() method. } - public function instance(){ + public function instance() + { return CoreWechatService::app($this->site_id)->oauth; } + public function oauth(string $code = null, array $options = []) { // $this->instance()-> diff --git a/niucloud/core/pay/Alipay.php b/niucloud/core/pay/Alipay.php index 2ff62a2a4..b0bb1083a 100644 --- a/niucloud/core/pay/Alipay.php +++ b/niucloud/core/pay/Alipay.php @@ -6,8 +6,8 @@ use app\dict\pay\OnlinePayDict; use app\dict\pay\RefundDict; use app\dict\pay\TransferDict; use core\exception\PayException; -use Psr\Http\Message\MessageInterface; use Psr\Http\Message\ResponseInterface; +use Throwable; use Yansongda\Pay\Exception\ContainerException; use Yansongda\Pay\Exception\InvalidParamsException; use Yansongda\Pay\Exception\ServiceNotFoundException; @@ -25,7 +25,8 @@ class Alipay extends BasePay /** * @param array $config - * @return mixed|void + * @return void + * @throws ContainerException */ protected function initialize(array $config = []) { @@ -37,13 +38,15 @@ class Alipay extends BasePay Pay::config($this->config); } - public function mp(array $params){ + public function mp(array $params) + { } + /** * 网页支付 * @param array $params - * @return ResponseInterface + * @return array */ public function web(array $params) { @@ -57,7 +60,7 @@ class Alipay extends BasePay /** * 手机网页支付 * @param array $params - * @return ResponseInterface + * @return array */ public function wap(array $params) { @@ -72,8 +75,8 @@ class Alipay extends BasePay /** * app支付 - * @param $params - * @return mixed|ResponseInterface + * @param array $params + * @return array */ public function app(array $params) { @@ -86,8 +89,8 @@ class Alipay extends BasePay /** * 小程序支付 - * @param $params - * @return mixed|ResponseInterface + * @param array $params + * @return Collection */ public function mini(array $params) { @@ -101,8 +104,8 @@ class Alipay extends BasePay /** * 付款码支付 - * @param $params - * @return mixed|Collection + * @param array $params + * @return Collection */ public function pos(array $params) { @@ -116,8 +119,8 @@ class Alipay extends BasePay /** * 扫码支付 - * @param $params - * @return mixed|Collection + * @param array $params + * @return Collection */ public function scan(array $params) { @@ -130,13 +133,13 @@ class Alipay extends BasePay /** * 转账 - * @param $params - * @return mixed|Collection + * @param array $params + * @return array */ public function transfer(array $params) { - $result = $this->returnFormat(Pay::alipay()->transfer([ + $result = $this->returnFormat(Pay::alipay()->transfer([ 'out_biz_no' => $params['transfer_no'], 'trans_amount' => $params['money'], 'product_code' => $params['product_code'] ?: 'TRANS_ACCOUNT_NO_PWD',//业务产品码,单笔无密转账到支付宝账户固定为 : TRANS_ACCOUNT_NO_PWD; 收发现金红包固定为 : STD_RED_PACKET; @@ -147,9 +150,9 @@ class Alipay extends BasePay 'name' => $params['to_name'],//参与方真实姓名,如果非空,将校验收款支付宝账号姓名一致性。当identity_type=ALIPAY_LOGON_ID时,本字段必填。 ], ])); - if(!empty($result['msg']) && $result['msg'] != 'Success'){ + if (!empty($result['msg']) && $result['msg'] != 'Success') { throw new PayException($result['sub_msg']); - }else{ + } else { $status = $result['status']; $status_array = array( 'SUCCESS' => TransferDict::SUCCESS, @@ -160,7 +163,7 @@ class Alipay extends BasePay $res = array( 'status' => $status_array[$status], ); - if($status == 'FAIL'){ + if ($status == 'FAIL') { $res['fail_reason'] = $result['fail_reason']; } } @@ -169,31 +172,35 @@ class Alipay extends BasePay /** * 支付关闭 - * @param $out_trade_no - * @return void + * @param string $out_trade_no + * @return bool + * @throws ContainerException + * @throws InvalidParamsException + * @throws ServiceNotFoundException */ - public function close(string $out_trade_no){ + public function close(string $out_trade_no) + { $result = $this->returnFormat(Pay::alipay()->close([ 'out_trade_no' => $out_trade_no, ])); //todo 支付宝关闭异步回调 - if(!empty($result['msg']) && $result['msg'] == 'Success'){ + if (!empty($result['msg']) && $result['msg'] == 'Success') { return true; - }else{ + } else { return false; } } /** * 退款 - * @param $out_trade_no - * @param $money - * @return array|MessageInterface|Collection|null + * @param array $params + * @return array|false * @throws ContainerException * @throws InvalidParamsException * @throws ServiceNotFoundException */ - public function refund(array $params){ + public function refund(array $params) + { $out_trade_no = $params['out_trade_no']; $money = $params['money']; // $total = $params['total']; @@ -203,11 +210,11 @@ class Alipay extends BasePay 'refund_amount' => $money, 'out_request_no' => $refund_no ])); - if(!empty($result['msg']) && $result['msg'] == 'Success'){ + if (!empty($result['msg']) && $result['msg'] == 'Success') { $fund_change = $result['fund_change'];//退款是否成功可以根据同步响应的 fund_change 参数来判断,fund_change 表示本次退款是否发生了资金变化,返回 Y 表示退款成功,返回 N 则表示本次退款未发生资金变动 。 - if($fund_change == 'Y'){ + if ($fund_change == 'Y') { $status = RefundDict::SUCCESS; - }else{ + } else { $status = RefundDict::DEALING; } return [ @@ -215,26 +222,26 @@ class Alipay extends BasePay 'refund_no' => $refund_no, 'out_trade_no' => $out_trade_no ]; - }else{ + } else { //todo 这儿可以抛出错误 return false; } - - return $result; } /** * 支部异步回调 - * @param $out_trade_no - * @return void + * @param string $action + * @param callable $callback + * @return ResponseInterface|string */ - public function notify(string $action, Callable $callback){ - try{ + public function notify(string $action, callable $callback) + { + try { $result = Pay::alipay()->callback(); //通过返回的值 - if(!empty($result)){//成功 - if($action == 'pay'){ + if (!empty($result)) {//成功 + if ($action == 'pay') { //todo 这儿需要具体设计 $temp_data = array( 'mchid' => $result['seller_id'], @@ -242,14 +249,14 @@ class Alipay extends BasePay 'result' => $result ); $callback_result = $callback($result['out_trade_no'], $temp_data); - if(is_bool($callback_result) && $callback_result){ + if (is_bool($callback_result) && $callback_result) { return Pay::alipay()->success(); } } } return $this->fail(); - } catch (\Throwable $e) { + } catch ( Throwable $e ) { return $this->fail(); } @@ -258,23 +265,27 @@ class Alipay extends BasePay /** * 查询普通支付订单 - * @param $out_trade_no - * @return void + * @param array $params + * @return array + * @throws ContainerException + * @throws InvalidParamsException + * @throws ServiceNotFoundException */ - public function getOrder(array $params = []){ + public function getOrder(array $params = []) + { $out_trade_no = $params['out_trade_no']; $order = [ 'out_trade_no' => $out_trade_no, ]; $result = $this->returnFormat(Pay::alipay()->find($order)); - if(!empty($result['msg']) && $result['msg'] == 'Success'){ + if (!empty($result['msg']) && $result['msg'] == 'Success') { return [ 'status' => OnlinePayDict::getAliPayStatus($result['trade_status']) ]; - }else{ - if(!empty($result['sub_code']) && $result['sub_code'] == 'ACQ.ACQ.SYSTEM_ERROR'){ + } else { + if (!empty($result['sub_code']) && $result['sub_code'] == 'ACQ.ACQ.SYSTEM_ERROR') { throw new PayException($result['msg']); - }else{ + } else { return []; } } @@ -282,11 +293,15 @@ class Alipay extends BasePay /** * 查询退款单据 - * @param $out_trade_no - * @param $refund_no - * @return void + * @param string $out_trade_no + * @param string|null $refund_no + * @return array + * @throws ContainerException + * @throws InvalidParamsException + * @throws ServiceNotFoundException */ - public function getRefund(string $out_trade_no, ?string $refund_no){ + public function getRefund(string $out_trade_no, ?string $refund_no) + { $order = [ 'out_trade_no' => $out_trade_no, 'out_request_no' => $refund_no, @@ -294,11 +309,11 @@ class Alipay extends BasePay ]; $result = $this->returnFormat(Pay::alipay()->find($order)); - if(!empty($result['msg']) && $result['msg'] == 'Success'){ + if (!empty($result['msg']) && $result['msg'] == 'Success') { $refund_status = $result['refund_status'] ?? ''; - if($refund_status == 'REFUND_SUCCESS'){ + if ($refund_status == 'REFUND_SUCCESS') { $status = RefundDict::SUCCESS; - }else{ + } else { $status = RefundDict::DEALING; } return [ @@ -306,10 +321,10 @@ class Alipay extends BasePay 'refund_no' => $refund_no, 'out_trade_no' => $out_trade_no ]; - }else{ - if(!empty($result['sub_code']) && $result['sub_code'] == 'ACQ.ACQ.SYSTEM_ERROR'){ + } else { + if (!empty($result['sub_code']) && $result['sub_code'] == 'ACQ.ACQ.SYSTEM_ERROR') { throw new PayException($result['msg']); - }else{ + } else { return []; } } @@ -317,16 +332,20 @@ class Alipay extends BasePay /** * 获取转账订单 - * @param $transfer_no - * @return void + * @param string $transfer_no + * @return array + * @throws ContainerException + * @throws InvalidParamsException + * @throws ServiceNotFoundException */ - public function getTransfer(string $transfer_no){ + public function getTransfer(string $transfer_no) + { $order = [ 'out_biz_no' => $transfer_no, '_type' => 'transfer' ]; $result = $this->returnFormat(Pay::alipay()->find($order)); - if(!empty($result['msg']) && $result['msg'] == 'Success'){ + if (!empty($result['msg']) && $result['msg'] == 'Success') { $status = $result['SUCCESS'] ?? ''; $status_array = array( 'SUCCESS' => TransferDict::SUCCESS, @@ -338,20 +357,22 @@ class Alipay extends BasePay 'status' => $status_array[$status], 'transfer_no' => $transfer_no ]; - }else{ - if(!empty($result['sub_code']) && $result['sub_code'] == 'ACQ.ACQ.SYSTEM_ERROR'){ + } else { + if (!empty($result['sub_code']) && $result['sub_code'] == 'ACQ.ACQ.SYSTEM_ERROR') { throw new PayException($result['msg']); - }else{ + } else { return []; } } } - public function fail(){ + public function fail() + { return 'fail'; } - public function returnUrl($params){ + public function returnUrl($params) + { return ['url' => $params->getHeader('Location')[0]]; } } \ No newline at end of file diff --git a/niucloud/core/pay/BasePay.php b/niucloud/core/pay/BasePay.php index 7b94b57e2..af49dfc06 100644 --- a/niucloud/core/pay/BasePay.php +++ b/niucloud/core/pay/BasePay.php @@ -3,6 +3,8 @@ namespace core\pay; use core\loader\Storage; +use Psr\Http\Message\MessageInterface; +use Yansongda\Supports\Collection; /** * 文件管理驱动类 @@ -15,7 +17,7 @@ abstract class BasePay extends Storage /** * 初始化 * @param array $config - * @return mixed|void + * @return void */ protected function initialize(array $config = []) { @@ -24,52 +26,56 @@ abstract class BasePay extends Storage /** * 网页支付 - * @param $save_dir + * @param array $params * @return mixed */ abstract protected function web(array $params); /** * 手机网站支付 - * @param $dir + * @param array $params * @return mixed */ abstract protected function wap(array $params); /** * app支付 - * @param $dir + * @param array $params * @return mixed */ abstract protected function app(array $params); /** * 小程序支付 - * @param $dir + * @param array $params * @return mixed */ abstract protected function mini(array $params); + /** * 付款码支付 - * @param $dir + * @param array $params * @return mixed */ abstract protected function pos(array $params); + /** * 扫码支付 - * @param $dir + * @param array $params * @return mixed */ abstract protected function scan(array $params); + /** * 转账 - * @param $dir + * @param array $params * @return mixed */ abstract protected function transfer(array $params); + /** * 公众号支付 - * @param $dir + * @param array $params * @return mixed */ abstract protected function mp(array $params); @@ -90,10 +96,11 @@ abstract class BasePay extends Storage /** * 支付通知 + * @param string $action * @param callable $callback * @return mixed */ - abstract protected function notify(string $action, Callable $callback); + abstract protected function notify(string $action, callable $callback); /** * 查询支付订单 @@ -104,7 +111,7 @@ abstract class BasePay extends Storage /** * 查询退款订单 - * @param string|null $out_trade_no + * @param string $out_trade_no * @param string|null $refund_no * @return mixed */ @@ -123,18 +130,19 @@ abstract class BasePay extends Storage * @param string $type * @return mixed */ - protected function payConfig(array $config, string $type){ + protected function payConfig(array $config, string $type) + { return array_merge( [ 'logger' => [ 'enable' => true, - 'file' => root_path('runtime') . 'paylog'.DIRECTORY_SEPARATOR.date('Ym').DIRECTORY_SEPARATOR.date('d').'.log', + 'file' => root_path('runtime') . 'paylog' . DIRECTORY_SEPARATOR . date('Ym') . DIRECTORY_SEPARATOR . date('d') . '.log', 'level' => env('app_debug') ? 'debug' : 'info', // 建议生产环境等级调整为 info,开发环境为 debug 'type' => 'single', // optional, 可选 daily. 'max_file' => 30, // optional, 当 type 为 daily 时有效,默认 30 天 ], 'http' => [ // optional - 'timeout' => 5.0, + 'timeout' => 5.0, ] ], [ @@ -147,12 +155,13 @@ abstract class BasePay extends Storage ); } - public function returnFormat($param){ - if($param instanceof \Psr\Http\Message\MessageInterface){ + public function returnFormat($param) + { + if ($param instanceof MessageInterface) { return $param->getBody()->getContents(); - }else if($param instanceof \Yansongda\Supports\Collection){ + } else if ($param instanceof Collection) { return $param->all(); - }else{ + } else { return $param; } } @@ -162,14 +171,17 @@ abstract class BasePay extends Storage * @param $our_trade_no * @param $refund_no * @param $status + * @param int $success_time + * @param string $reason * @return array */ - public function getRefundData($our_trade_no, $refund_no, $status, $success_time = 0, $reason = ''){ + public function getRefundData($our_trade_no, $refund_no, $status, $success_time = 0, $reason = '') + { return [ 'our_trade_no' => $our_trade_no, 'refund_no' => $refund_no, 'status' => $status, - 'success_time' =>$success_time, + 'success_time' => $success_time, 'reason' => $reason ]; } @@ -181,10 +193,10 @@ abstract class BasePay extends Storage * @param $reason * @return void */ - public function getTransferData($transfer_no, $status, $reason){ + public function getTransferData($transfer_no, $status, $reason) + { } - } \ No newline at end of file diff --git a/niucloud/core/pay/PayLoader.php b/niucloud/core/pay/PayLoader.php index 8d6da06e4..b0a771c51 100644 --- a/niucloud/core/pay/PayLoader.php +++ b/niucloud/core/pay/PayLoader.php @@ -14,9 +14,9 @@ namespace core\pay; use core\loader\Loader; /** - * @see \core\pay\PayLoader + * @see PayLoader * @package think\facade - * @mixin \core\pay\Wechatpay + * @mixin Wechatpay * @method string|null upload(string $dir) 附件上传 * @method array fetch(string $url, ?string $key) 抓取远程附件 * @method mixed delete(string $file_name) 附件删除 @@ -30,6 +30,7 @@ class PayLoader extends Loader protected $namespace = '\\core\\pay\\'; protected $config_name = 'pay'; + /** * 默认驱动 * @return mixed diff --git a/niucloud/core/pay/Wechatpay.php b/niucloud/core/pay/Wechatpay.php index f2adc24bf..1db1f5d4b 100644 --- a/niucloud/core/pay/Wechatpay.php +++ b/niucloud/core/pay/Wechatpay.php @@ -9,6 +9,8 @@ use core\exception\PayException; use EasyWeChat\Factory; use Psr\Http\Message\MessageInterface; use Psr\Http\Message\ResponseInterface; +use think\Response; +use Throwable; use Yansongda\Pay\Exception\ContainerException; use Yansongda\Pay\Exception\InvalidParamsException; use Yansongda\Pay\Exception\ServiceNotFoundException; @@ -27,7 +29,8 @@ class Wechatpay extends BasePay /** * @param array $config - * @return mixed|void + * @return void + * @throws ContainerException */ protected function initialize(array $config = []) { @@ -43,7 +46,8 @@ class Wechatpay extends BasePay * @param array $params * @return mixed|Collection */ - public function mp(array $params){ + public function mp(array $params) + { $result = $this->returnFormat(Pay::wechat()->mp([ 'out_trade_no' => $params['out_trade_no'], 'description' => $params['boby'], @@ -55,7 +59,7 @@ class Wechatpay extends BasePay ], ])); $code = $result['code'] ?? 0; - if($code == 0) return $result; + if ($code == 0) return $result; //支付错误抛出 throw new PayException($result['message']); } @@ -63,7 +67,7 @@ class Wechatpay extends BasePay /** * 手机网页支付 - * @param $params + * @param array $params * @return mixed */ public function wap(array $params) @@ -82,18 +86,20 @@ class Wechatpay extends BasePay ], ]; //这儿有些特殊, 默认情况下,H5 支付所使用的 appid 是微信公众号的 appid,即配置文件中的 mp_app_id 参数,如果想使用关联的小程序的 appid,则只需要在调用参数中增加 ['_type' => 'mini'] 即可 - if(!empty($order['type'])){ + if (!empty($order['type'])) { $order['_type'] = 'mini'; // 注意这一行 } return $this->returnFormat(Pay::wechat()->wap($order)); } - public function web(array $params){ + public function web(array $params) + { } + /** * app支付 - * @param $params + * @param array $params * @return mixed|ResponseInterface */ public function app(array $params) @@ -109,7 +115,7 @@ class Wechatpay extends BasePay /** * 小程序支付 - * @param $params + * @param array $params * @return mixed|ResponseInterface */ public function mini(array $params) @@ -129,12 +135,12 @@ class Wechatpay extends BasePay /** * 付款码支付 - * @param $params + * @param array $params * @return mixed|Collection */ public function pos(array $params) { - //todo 需要自定义通过plugin来侧载开发 + //todo 需要自定义通过plugin来侧载开发 $app = Factory::payment([ 'app_id' => $this->config['appid'], //应用id 'mch_id' => $this->config["mch_id"] ?? '', //商户号 @@ -159,7 +165,7 @@ class Wechatpay extends BasePay /** * 扫码支付 - * @param $params + * @param array $params * @return mixed|Collection */ public function scan(array $params) @@ -175,23 +181,23 @@ class Wechatpay extends BasePay /** * 转账(微信的转账是很多笔的) - * @param $params - * @return mixed|Collection + * @param array $params + * @return array */ public function transfer(array $params) { //这儿的批次信息可能是这儿生成的,但依然需要记录 $order = [ - 'out_batch_no' => time().'',// + 'out_batch_no' => time() . '',// 'batch_name' => $params['remark'], 'batch_remark' => $params['remark'], ]; $transfer_list = $params['transfer_list']; //单笔转账 - if(empty($transfer_list)){ + if (empty($transfer_list)) { $transfer_list = array( [ - 'transfer_no' => $params['transfer_no'].'1', + 'transfer_no' => $params['transfer_no'] . '1', 'money' => (int)$params['money'], 'remark' => $params['remark'], 'openid' => $params['to_no'] @@ -201,31 +207,31 @@ class Wechatpay extends BasePay $total_amount = 0; $total_num = 0; - foreach($transfer_list as $v){ + foreach ($transfer_list as $v) { $item_transfer = [ - 'out_detail_no' => time().'1', + 'out_detail_no' => time() . '1', 'transfer_amount' => (int)$v['money'], 'transfer_remark' => $v['remark'], 'openid' => $v['openid'], ]; $total_amount += (int)$v['money']; $total_num++; - if(!empty($v['user_name'])){ + if (!empty($v['user_name'])) { $item_transfer['user_name'] = $v['user_name'];// 明文传参即可,sdk 会自动加密 } $order['transfer_detail_list'][] = $item_transfer; } - $order['total_amount'] = (int)$total_amount; - $order['total_num'] = (int)$total_num; + $order['total_amount'] = $total_amount; + $order['total_num'] = $total_num; $result = $this->returnFormat(Pay::wechat()->transfer($order)); - if(!empty($result['code'])){ + if (!empty($result['code'])) { // if($result['code'] == 'PARAM_ERROR'){ // throw new PayException(); // }else if($result['code'] == 'INVALID_REQUEST'){ // throw new PayException(); // } - if($result['code'] == 'INVALID_REQUEST'){ + if ($result['code'] == 'INVALID_REQUEST') { throw new PayException(700010); } throw new PayException($result['message']); @@ -235,10 +241,14 @@ class Wechatpay extends BasePay /** * 支付关闭 - * @param $out_trade_no + * @param string $out_trade_no * @return void + * @throws ContainerException + * @throws InvalidParamsException + * @throws ServiceNotFoundException */ - public function close(string $out_trade_no){ + public function close(string $out_trade_no) + { $result = Pay::wechat()->close([ 'out_trade_no' => $out_trade_no, ]); @@ -247,14 +257,14 @@ class Wechatpay extends BasePay /** * 退款 - * @param $out_trade_no - * @param $money - * @return array|MessageInterface|Collection|null + * @param array $params + * @return array * @throws ContainerException * @throws InvalidParamsException * @throws ServiceNotFoundException */ - public function refund(array $params){ + public function refund(array $params) + { $out_trade_no = $params['out_trade_no']; $money = $params['money']; $total = $params['total']; @@ -286,13 +296,15 @@ class Wechatpay extends BasePay /** * 异步回调 - * @param $out_trade_no - * @return void + * @param string $action + * @param callable $callback + * @return ResponseInterface|Response */ - public function notify(string $action, Callable $callback){ - try{ + public function notify(string $action, callable $callback) + { + try { $result = $this->returnFormat(Pay::wechat()->callback()); - if($action == 'pay') {//支付 + if ($action == 'pay') {//支付 if ($result['event_type'] == 'TRANSACTION.SUCCESS') { $pay_trade_data = $result['resource']['ciphertext']; @@ -307,7 +319,7 @@ class Wechatpay extends BasePay return Pay::wechat()->success(); } } - }else if($action == 'refund'){//退款 + } else if ($action == 'refund') {//退款 if ($result['event_type'] == 'REFUND.SUCCESS') { $refund_trade_data = $result['resource']['ciphertext']; $temp_params = [ @@ -325,7 +337,7 @@ class Wechatpay extends BasePay } return $this->fail(); - } catch (\Throwable $e) { + } catch ( Throwable $e ) { // throw new PayException($e->getMessage()); return $this->fail($e->getMessage()); } @@ -333,28 +345,28 @@ class Wechatpay extends BasePay /** * 查询普通支付订单 - * @param string $out_trade_no - * @param string $transaction_id + * @param array $params * @return array|MessageInterface|Collection|null * @throws ContainerException * @throws InvalidParamsException * @throws ServiceNotFoundException */ - public function getOrder(array $params = []){ + public function getOrder(array $params = []) + { $out_trade_no = $params['out_trade_no']; - $transaction_id = $params['transaction_id']; + $transaction_id = $params['transaction_id'] ?? ''; $order = [ ]; - if(!empty($out_trade_no)){ + if (!empty($out_trade_no)) { $order['out_trade_no'] = $out_trade_no; } - if(!empty($transaction_id)){ + if (!empty($transaction_id)) { $order['transaction_id'] = $transaction_id; } $result = Pay::wechat()->find($order); - if(empty($result)) + if (empty($result)) return $result; $result = $this->returnFormat($result); return [ @@ -364,17 +376,21 @@ class Wechatpay extends BasePay /** * 查询退款单据 - * @param $out_trade_no - * @param $refund_no - * @return void + * @param string|null $out_trade_no + * @param string|null $refund_no + * @return array|Collection|MessageInterface|null + * @throws ContainerException + * @throws InvalidParamsException + * @throws ServiceNotFoundException */ - public function getRefund(?string $out_trade_no, ?string $refund_no = ''){ + public function getRefund(?string $out_trade_no, ?string $refund_no = '') + { $order = [ '_type' => 'refund', 'out_refund_no' => $refund_no ]; $result = Pay::wechat()->find($order); - if(empty($result)) + if (empty($result)) return $result; $result = $this->returnFormat($result); $refund_status_array = [ @@ -392,10 +408,13 @@ class Wechatpay extends BasePay /** * 获取转账订单(todo 切勿调用) - * @param $transfer_no - * @return void + * @param string $transfer_no + * @return array + * @throws ContainerException + * @throws InvalidParamsException */ - public function getTransfer(string $transfer_no){ + public function getTransfer(string $transfer_no) + { $params = [ 'out_batch_no' => $transfer_no, ]; @@ -417,7 +436,8 @@ class Wechatpay extends BasePay } - public function fail($message = ''){ + public function fail($message = '') + { $response = [ 'code' => 'FAIL', 'message' => $message ?: '失败', diff --git a/niucloud/core/sms/Aliyun.php b/niucloud/core/sms/Aliyun.php index 88b22803a..7993c4444 100644 --- a/niucloud/core/sms/Aliyun.php +++ b/niucloud/core/sms/Aliyun.php @@ -21,9 +21,10 @@ class Aliyun extends BaseSms protected $app_key = ''; protected $secret_key = ''; protected $sign = ''; + /** * @param array $config - * @return mixed|void + * @return void */ protected function initialize(array $config = []) { @@ -39,7 +40,7 @@ class Aliyun extends BaseSms * @param string $mobile * @param string $template_id * @param array $data - * @return array|false + * @return array */ public function send(string $mobile, string $template_id, array $data = []) { @@ -56,10 +57,10 @@ class Aliyun extends BaseSms ->debug(false) ->options([ 'query' => [ - 'PhoneNumbers' => $mobile, - 'SignName' => $this->sign, - 'TemplateCode' => $template_id, - 'TemplateParam' => json_encode($data, JSON_UNESCAPED_UNICODE), + 'PhoneNumbers' => $mobile, + 'SignName' => $this->sign, + 'TemplateCode' => $template_id, + 'TemplateParam' => json_encode($data, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE), ], ]) ->request(); @@ -70,7 +71,7 @@ class Aliyun extends BaseSms } $message = $res['Message'] ?? $res; throw new NoticeException($message); - } catch( Exception $e) { + } catch ( Exception $e ) { throw new NoticeException($e->getMessage()); } } diff --git a/niucloud/core/sms/BaseSms.php b/niucloud/core/sms/BaseSms.php index 2678c277b..6a4c44fcb 100644 --- a/niucloud/core/sms/BaseSms.php +++ b/niucloud/core/sms/BaseSms.php @@ -15,14 +15,14 @@ use core\loader\Storage; /** * Class BaseSms - * @package + * @package */ abstract class BaseSms extends Storage { /** * 初始化 * @param array $config - * @return mixed|void + * @return void */ protected function initialize(array $config = []) { @@ -43,6 +43,7 @@ abstract class BaseSms extends Storage * @return mixed */ abstract public function modify(string $sign = null, string $mobile, string $code); + /** * 短信模板 * @param int $page diff --git a/niucloud/core/sms/SmsLoader.php b/niucloud/core/sms/SmsLoader.php index 3d4fd8483..7adbf3e67 100644 --- a/niucloud/core/sms/SmsLoader.php +++ b/niucloud/core/sms/SmsLoader.php @@ -14,9 +14,9 @@ namespace core\sms; use core\loader\Loader; /** - * @see \core\sms\SmsLoader + * @see SmsLoader * @package think\facade - * @mixin \core\sms\BaseSms + * @mixin BaseSms * @method string|null send(string $mobile, string $template_id, array $data) 发送短信 */ class SmsLoader extends Loader @@ -30,6 +30,7 @@ class SmsLoader extends Loader protected $namespace = '\\core\\sms\\'; protected $config_name = 'sms'; + /** * 默认驱动 * @return mixed diff --git a/niucloud/core/sms/Tencent.php b/niucloud/core/sms/Tencent.php index 739f9d843..1a594f959 100644 --- a/niucloud/core/sms/Tencent.php +++ b/niucloud/core/sms/Tencent.php @@ -32,9 +32,10 @@ class Tencent extends BaseSms protected $secret_key = ''; protected $sign = ''; protected $app_id = ''; + /** * @param array $config - * @return mixed|void + * @return void */ protected function initialize(array $config = []) { @@ -46,8 +47,6 @@ class Tencent extends BaseSms } - - /** * 发送短信 * @return bool|mixed @@ -64,28 +63,27 @@ class Tencent extends BaseSms $client = new SmsClient($cred, 'ap-guangzhou', $clientProfile); $params = [ - 'PhoneNumberSet' => ['+86' . $mobile], - 'TemplateID' => $template_id, - 'Sign' => $this->sign, - 'TemplateParamSet' => $data, - 'SmsSdkAppid' => $this->app_id, + 'PhoneNumberSet' => ['+86' . $mobile], + 'TemplateID' => $template_id, + 'Sign' => $this->sign, + 'TemplateParamSet' => $data, + 'SmsSdkAppid' => $this->app_id, ]; $req = new SendSmsRequest(); - $req->fromJsonString(json_encode($params)); - $resp = json_decode($client->SendSms($req)->toJsonString(), true); + $req->fromJsonString(json_encode($params, JSON_THROW_ON_ERROR)); + $resp = json_decode($client->SendSms($req)->toJsonString(), true, 512, JSON_THROW_ON_ERROR); if (isset($resp['SendStatusSet']) && $resp['SendStatusSet'][0]['Code'] == 'Ok') { return $resp; } else { - $message = $res['SendStatusSet'][0]['Message'] ?? json_encode($resp); - throw new CommonException( $message); + $message = $res['SendStatusSet'][0]['Message'] ?? json_encode($resp, JSON_THROW_ON_ERROR); + throw new CommonException($message); } - } catch( Exception $e) { + } catch ( Exception $e ) { throw new NoticeException($e->getMessage()); } } - public function modify(string $sign = null, string $mobile, string $code) { } diff --git a/niucloud/core/template/BaseTemplate.php b/niucloud/core/template/BaseTemplate.php index ca2e497b1..ac3162c28 100644 --- a/niucloud/core/template/BaseTemplate.php +++ b/niucloud/core/template/BaseTemplate.php @@ -15,14 +15,14 @@ use core\loader\Storage; /** * Class BaseTemplate - * @package + * @package */ abstract class BaseTemplate extends Storage { /** * 初始化 * @param array $config - * @return mixed|void + * @return void */ protected function initialize(array $config = []) { @@ -30,7 +30,6 @@ abstract class BaseTemplate extends Storage } - /** * 发送模板消息 * @return mixed @@ -39,14 +38,14 @@ abstract class BaseTemplate extends Storage /** * 增加模板消息 - * @param string $shortId + * @param array $data * @return mixed */ abstract protected function addTemplate(array $data); /** * 删除消息模板 - * @param string $templateId + * @param array $data * @return mixed */ abstract protected function delete(array $data); diff --git a/niucloud/core/template/TemplateLoader.php b/niucloud/core/template/TemplateLoader.php index a22c9f08c..428a2b221 100644 --- a/niucloud/core/template/TemplateLoader.php +++ b/niucloud/core/template/TemplateLoader.php @@ -14,9 +14,9 @@ namespace core\template; use core\loader\Loader; /** - * @see \core\template\TemplateLoader + * @see TemplateLoader * @package think\facade - * @mixin \core\template\Wechat + * @mixin Wechat * @method string|null send(array $data) 发送 * @method mixed addTemplate(array $data) 增加 * @method mixed delete(array $data) 删除 @@ -33,6 +33,7 @@ class TemplateLoader extends Loader protected $namespace = '\\core\\template\\'; protected $config_name = 'template'; + /** * 默认驱动 * @return mixed diff --git a/niucloud/core/template/Weapp.php b/niucloud/core/template/Weapp.php index 00bbb20f2..bc053a904 100644 --- a/niucloud/core/template/Weapp.php +++ b/niucloud/core/template/Weapp.php @@ -12,15 +12,22 @@ namespace core\template; use app\service\core\weapp\CoreWeappService; +use EasyWeChat\Kernel\Exceptions\InvalidArgumentException; +use EasyWeChat\Kernel\Exceptions\InvalidConfigException; +use EasyWeChat\Kernel\Support\Collection; +use EasyWeChat\MiniProgram\SubscribeMessage\Client; +use GuzzleHttp\Exception\GuzzleException; +use Psr\Http\Message\ResponseInterface; class Weapp extends BaseTemplate { protected $site_id; + /** * @param array $config - * @return mixed|void + * @return void */ protected function initialize(array $config = []) { @@ -31,18 +38,23 @@ class Weapp extends BaseTemplate /** * 实例化订阅消息业务 - * @return \EasyWeChat\MiniProgram\SubscribeMessage\Client + * @return Client */ - public function template(){ + public function template() + { return CoreWeappService::app($this->site_id)->subscribe_message; } + /** * 消息发送 - * @param string $templateId * @param array $data - * @return mixed|void + * @return array|Collection|object|ResponseInterface|string + * @throws GuzzleException + * @throws InvalidArgumentException + * @throws InvalidConfigException */ - public function send(array $data){ + public function send(array $data) + { return $this->template()->send([ 'template_id' => $data['template_id'], 'touser' => $data['openid'], @@ -54,26 +66,33 @@ class Weapp extends BaseTemplate /** * 添加模板消息 * @param array $data - * @return mixed|void + * @return array|Collection|object|ResponseInterface|string + * @throws GuzzleException + * @throws InvalidConfigException */ - public function addTemplate(array $data){ + public function addTemplate(array $data) + { return $this->template()->addTemplate($data['tid'], $data['kid_list'], $data['scene_desc']); } /** * 删除 * @param array $data - * @return mixed|void + * @return array|Collection|object|ResponseInterface|string + * @throws GuzzleException + * @throws InvalidConfigException */ - public function delete(array $data){ + public function delete(array $data) + { return $this->template()->deleteTemplate($data['template_id']); } /** * 获取 - * @return mixed|void + * @return void */ - public function get(){ + public function get() + { } } \ No newline at end of file diff --git a/niucloud/core/template/Wechat.php b/niucloud/core/template/Wechat.php index 2ca9bc05a..c259089a5 100644 --- a/niucloud/core/template/Wechat.php +++ b/niucloud/core/template/Wechat.php @@ -12,15 +12,22 @@ namespace core\template; use app\service\core\wechat\CoreWechatService; +use EasyWeChat\Kernel\Exceptions\InvalidArgumentException; +use EasyWeChat\Kernel\Exceptions\InvalidConfigException; +use EasyWeChat\Kernel\Support\Collection; +use EasyWeChat\OfficialAccount\TemplateMessage\Client; +use GuzzleHttp\Exception\GuzzleException; +use Psr\Http\Message\ResponseInterface; class Wechat extends BaseTemplate { protected $site_id; + /** * @param array $config - * @return mixed|void + * @return void */ protected function initialize(array $config = []) { @@ -31,19 +38,23 @@ class Wechat extends BaseTemplate /** * 实例化模板消息业务 - * @return \EasyWeChat\OfficialAccount\TemplateMessage\Client - * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException + * @return Client */ - public function template(){ + public function template() + { return CoreWechatService::app($this->site_id)->template_message; } + /** * 消息发送 - * @param string $templateId * @param array $data - * @return mixed|void + * @return array|Collection|object|ResponseInterface|string + * @throws GuzzleException + * @throws InvalidArgumentException + * @throws InvalidConfigException */ - public function send(array $data){ + public function send(array $data) + { $openid = $data['openid']; $template_id = $data['template_id']; $template_data = $data['data']; @@ -52,8 +63,8 @@ class Wechat extends BaseTemplate $url = $data['url']; $miniprogram = $data['miniprogram']; - if(!empty($first)) $template_data['first'] = $first; - if(!empty($remark)) $template_data['remark'] = $remark; + if (!empty($first)) $template_data['first'] = $first; + if (!empty($remark)) $template_data['remark'] = $remark; return $this->template()->send([ 'touser' => $openid, 'template_id' => $template_id, @@ -65,27 +76,34 @@ class Wechat extends BaseTemplate /** * 添加模板消息 - * @param string $shortId - * @return mixed|void + * @param array $data + * @return array|Collection|object|ResponseInterface|string + * @throws GuzzleException + * @throws InvalidConfigException */ - public function addTemplate(array $data){ + public function addTemplate(array $data) + { return $this->template()->addTemplate($data['shortId']); } /** * 删除 - * @param string $templateId - * @return mixed|void + * @param array $data + * @return array|Collection|object|ResponseInterface|string + * @throws GuzzleException + * @throws InvalidConfigException */ - public function delete(array $data){ + public function delete(array $data) + { return $this->template()->deletePrivateTemplate($data['templateId']); } /** * 获取 - * @return mixed|void + * @return void */ - public function get(){ + public function get() + { } } \ No newline at end of file diff --git a/niucloud/core/upload/Aliyun.php b/niucloud/core/upload/Aliyun.php index 9f1fa398b..b4f61a10f 100644 --- a/niucloud/core/upload/Aliyun.php +++ b/niucloud/core/upload/Aliyun.php @@ -1,4 +1,5 @@ config['access_key']; @@ -29,8 +31,8 @@ class Aliyun extends BaseUpload /** * 执行上传 - * @param $save_dir (保存路径) - * @return bool|mixed + * @param string $dir + * @return true */ public function upload(string $dir) { @@ -43,17 +45,39 @@ class Aliyun extends BaseUpload $this->getRealPath() ); return true; - } catch (OssException $e) { + } catch ( OssException $e ) { throw new UploadFileException($e->getMessage()); } } + /** + * base64上云 + * @param string $base64_data + * @param string|null $key + * @return true + */ + public function base64(string $base64_data, ?string $key = null) + { + $bucket = $this->config['bucket']; + try { + $base64_file = base64_decode($base64_data); + if (!$base64_file) throw new UploadFileException('FILE_ERROE'); + $this->client()->putObject( + $bucket, + $key, + $base64_file + ); + return true; + } catch ( OssException $e ) { + throw new UploadFileException($e->getMessage()); + } + } /** * Notes: 抓取远程资源 - * @param $url - * @param null $key - * @return mixed|void + * @param string $url + * @param string|null $key + * @return true */ public function fetch(string $url, ?string $key = null) { @@ -66,7 +90,7 @@ class Aliyun extends BaseUpload $content ); return true; - } catch (OssException $e) { + } catch ( OssException $e ) { throw new UploadFileException($e->getMessage()); } @@ -74,8 +98,8 @@ class Aliyun extends BaseUpload /** * 删除文件 - * @param $file_name - * @return bool|mixed + * @param string $file_name + * @return true */ public function delete(string $file_name) { @@ -83,21 +107,22 @@ class Aliyun extends BaseUpload try { $this->client()->deleteObject($bucket, $file_name); return true; - } catch (OssException $e) { + } catch ( OssException $e ) { throw new UploadFileException($e->getMessage()); } } - public function thumb($file_path, $thumb_type){ + public function thumb($file_path, $thumb_type) + { $thumb_config = config('upload.thumb.thumb_type'); $thumb_data = []; - foreach($thumb_config as $k => $v){ - if($thumb_type == 'all' || $thumb_type == $k){ + foreach ($thumb_config as $k => $v) { + if ($thumb_type == 'all' || $thumb_type == $k || (is_array($thumb_type) && in_array($k, $thumb_type))) { $width = $v['width']; $height = $v['height']; //拼装缩略路径 - $item_thumb = $file_path. '?x-oss-process=image/resize,h_' . $height . ',w_' . $width; + $item_thumb = $file_path . '?x-oss-process=image/resize,h_' . $height . ',w_' . $width; $thumb_data[$k] = $item_thumb; } } diff --git a/niucloud/core/upload/BaseUpload.php b/niucloud/core/upload/BaseUpload.php index 8eeab76af..9c57b49f3 100644 --- a/niucloud/core/upload/BaseUpload.php +++ b/niucloud/core/upload/BaseUpload.php @@ -12,6 +12,7 @@ namespace core\upload; use core\exception\UploadFileException; use core\loader\Storage; + /** * Class BaseUpload */ @@ -27,13 +28,14 @@ abstract class BaseUpload extends Storage protected $validate; protected $type; - protected $config = null; + protected $config; //可能还需要一个完整路径 protected $storage_type; + /** * 初始化 * @param array $config - * @return mixed|void + * @return void */ protected function initialize(array $config = []) { @@ -43,22 +45,29 @@ abstract class BaseUpload extends Storage /** * 附件上传 - * @param $save_dir + * @param string $dir * @return mixed */ abstract protected function upload(string $dir); /** * 抓取远程附件 - * @param $url - * @param $key + * @param string $url + * @param string|null $key * @return mixed */ abstract protected function fetch(string $url, ?string $key); + /** + * base64文件上云 + * @param string $base64_data + * @param string|null $key + * @return mixed + */ + abstract protected function base64(string $base64_data, ?string $key = null); /** * 附件删除 - * @param $file_name + * @param string $file_name * @return mixed */ abstract protected function delete(string $file_name); @@ -66,29 +75,32 @@ abstract class BaseUpload extends Storage /** * 缩略图 * @param string $file_path - * @param $type + * @param $thumb_type * @return mixed */ abstract protected function thumb(string $file_path, $thumb_type); + /** * 读取文件 - * @param $name + * @param string $name + * @param bool $is_rename */ - public function read(string $name, bool $is_rename = true){ + public function read(string $name, bool $is_rename = true) + { $this->name = $name; $this->file = request()->file($name); - if(empty($this->file)) + if (empty($this->file)) throw new UploadFileException(100012); $this->file_info = [ - 'name' => $this->file->getOriginalName(),//文件原始名称 - 'mime' => $this->file->getOriginalMime(),//上传文件类型信息 + 'name' => $this->file->getOriginalName(),//文件原始名称 + 'mime' => $this->file->getOriginalMime(),//上传文件类型信息 'real_path' => $this->file->getRealPath(),//上传文件真实路径 - 'ext' => $this->file->getOriginalExtension(),//上传文件后缀 - 'size' => $this->file->getSize(),//上传文件大小 + 'ext' => $this->file->getOriginalExtension(),//上传文件后缀 + 'size' => $this->file->getSize(),//上传文件大小 ]; - if($is_rename){ + if ($is_rename) { $this->file_name = $this->createFileName(); - }else{ + } else { $this->file_name = $this->file_info['name']; } @@ -99,7 +111,8 @@ abstract class BaseUpload extends Storage * @param string $type * @return $this */ - public function setType(string $type){ + public function setType(string $type) + { $this->type = $type; return $this; } @@ -107,7 +120,8 @@ abstract class BaseUpload extends Storage /** * 校验文件是否合法 */ - public function check(){ + public function check() + { } @@ -115,13 +129,14 @@ abstract class BaseUpload extends Storage * 生成新的文件名 * @return string */ - public function createFileName(string $key = '', string $ext = ''){ + public function createFileName(string $key = '', string $ext = '') + { //DIRECTORY_SEPARATOR 常量 - $storage_tag = '_'.$this->storage_type; - if(empty($key)){ - return time().md5($this->file_info['real_path']).$storage_tag.'.'.$this->file_info['ext']; - }else{ - return time().md5($key).$storage_tag.'.'.$ext; + $storage_tag = '_' . $this->storage_type; + if (empty($key)) { + return time() . md5($this->file_info['real_path']) . $storage_tag . '.' . $this->file_info['ext']; + } else { + return time() . md5($key) . $storage_tag . '.' . $ext; } } @@ -130,7 +145,8 @@ abstract class BaseUpload extends Storage * 获取原始附件信息 * @return mixed */ - public function getFileInfo(){ + public function getFileInfo() + { return $this->file_info; } @@ -138,14 +154,17 @@ abstract class BaseUpload extends Storage * 获取上传文件的真实完整路径 * @return mixed */ - public function getRealPath(){ + public function getRealPath() + { return $this->file_info['real_path']; } + /** * 获取生成的文件完整地址 - * @return mixed + * @return string */ - public function getFullPath(string $dir = ''){ + public function getFullPath(string $dir = '') + { return $this->full_path ?: $this->concatFullPath($dir); } @@ -154,7 +173,8 @@ abstract class BaseUpload extends Storage * @param string $dir * @return string */ - public function concatFullPath(string $dir = ''){ + public function concatFullPath(string $dir = '') + { $this->full_path = implode('/', array_filter([$dir, $this->getFileName()])); return $this->full_path; } @@ -167,11 +187,13 @@ abstract class BaseUpload extends Storage { return $this->file_name; } - public function getUrl(string $path = ''){ + + public function getUrl(string $path = '') + { $path = !empty($path) ? $path : $this->getFullPath(); $domain = $this->config['domain'] ?? ''; - $domain = empty($domain) ? '' : $domain.'/'; - return $domain.$path; + $domain = empty($domain) ? '' : $domain . '/'; + return $domain . $path; } /** @@ -179,16 +201,14 @@ abstract class BaseUpload extends Storage * @param array $validate * @return $this */ - public function setValidate(array $validate = []){ + public function setValidate(array $validate = []) + { $this->validate = $validate ?: config('upload.rules')[$this->type] ?? []; return $this; } /** * 根据上传文件的类型来校验文件是否符合配置 - * @param int $site_id - * @param string $file - * @param string $att_type * @return void */ public function validate() diff --git a/niucloud/core/upload/Local.php b/niucloud/core/upload/Local.php index 844033d20..4fd2cc1a5 100644 --- a/niucloud/core/upload/Local.php +++ b/niucloud/core/upload/Local.php @@ -1,11 +1,12 @@ 'top-left', - 1 => 'op-center', - 2 => 'top-right', - 3 => 'center-left', - 4 => 'center', - 5 => 'center-right', - 6 => 'bottom-left', - 7 => 'bottom-center', - 8 => 'bottom-right', - 9 => 'smart' + 'top-left' => 'top-left', + 'top-center' => 'top-center', + 'top-right' => 'top-right', + 'center-left' => 'center-left', + 'center' => 'center', + 'center-right' => 'center-right', + 'bottom-left' => 'bottom-left', + 'bottom-center' => 'bottom-center', + 'bottom-right' => 'bottom-right', ); + protected function initialize(array $config = []) { parent::initialize($config); @@ -34,7 +35,8 @@ class Local extends BaseUpload public function upload(string $dir) { $this->validate(); - mkdirs($dir); + + mkdirs_or_notexist($dir, 0777); $this->file->move($dir, $this->file_name); //错误一般是已经被抛出了 return true; @@ -43,21 +45,21 @@ class Local extends BaseUpload /** * 远程获取图片 - * @param $url - * @param $key + * @param string $url + * @param string|null $key * @return true */ public function fetch(string $url, ?string $key) { try { - mkdirs($key); + mkdirs_or_notexist($key, 0777); $content = @file_get_contents($url); if (!empty($content)) { file_put_contents($key, $content); // $fp = fopen($key, "w"); // fwrite($fp, $content); // fclose($fp); - }else{ + } else { throw new UploadFileException(203006); } return true; @@ -70,56 +72,73 @@ class Local extends BaseUpload * base64转图片 * @param string $content * @param string|null $key - * @return void + * @return true */ - public function base64(string $content, ?string $key){ + public function base64(string $content, ?string $key = null) + { - mkdirs($key); + mkdirs_or_notexist($key); file_put_contents(url_to_path($key), base64_decode($content)); return true; } /** * 删除本地附件 - * @param $file_name - * @return bool|mixed + * @param string $file_name + * @return bool */ public function delete(string $file_name) { $file_path = url_to_path($file_name); - if (!file_exists($file_path)) { - return true; + if (file_exists($file_path)) { + $result = unlink($file_path); // throw new UploadFileException(100013); + }else{ + $result = true; } - return unlink($file_path); + //顺便删除相关的缩略图 + $dirname = dirname($file_name); + $file_list = []; + search_dir($dirname, $file_list); + if(!empty($file_list)){ + $file_arr = explode('/', $file_name); + $only_file_name = end($file_arr); + foreach($file_list as $v){ + if(str_contains($v, $only_file_name) && file_exists($v)){ + unlink($v); + } + } + } + return $result; } /** * 缩略图 * @param $file_path - * @param array $type + * @param $thumb_type * @return array * @throws Exception */ - public function thumb($file_path, $thumb_type){ + public function thumb($file_path, $thumb_type) + { //todo 判断缩略图是否存在 $thumb_config = config('upload.thumb.thumb_type'); // …… //获取文件原名 获取 $file_arr = explode('/', $file_path); - $file_name = end($file_arr); $thumb_list = []; //获取文件后缀 - foreach($thumb_config as $k => $v){ - if($thumb_type == 'all' || $thumb_type == $k || (is_array($thumb_type) && in_array($k, $thumb_type))){ + foreach ($thumb_config as $k => $v) { + if ($thumb_type == 'all' || $thumb_type == $k || (is_array($thumb_type) && in_array($k, $thumb_type))) { $new_width = $v['width']; $new_height = $v['height']; - $new_thumb_path = str_replace($file_name, $new_width.'x'.$new_height.'_'.$file_name, $file_path); - if(!file_exists($new_thumb_path)){ + $new_thumb_path = str_replace($file_name, $new_width . 'x' . $new_height . '_' . $file_name, $file_path); + + if (!file_exists($new_thumb_path)) { $editor = Grafika::createEditor(); - $editor->open( $image, $file_path); - $editor->resizeFit( $image, $new_width,$new_height ); + $editor->open($image, $file_path); + $editor->resizeFit($image, $new_width, $new_height); //新缩略图文件名称 $editor->save($image, $new_thumb_path, null, null, false, 0777); } @@ -130,7 +149,69 @@ class Local extends BaseUpload return $thumb_list; } - public function water(){ + /** + * 图片水印 + * @param $file_path + * @return mixed + * @throws Exception + */ + public function water($file_path) + { + $water_config = []; + if (!empty($water_config)) { + $status = $water_config['status'];//是否启用 + if ($status) { + $editor = Grafika::createEditor(); + $editor->open($image, $file_path); + if ($water_config['type'] == 'image') { + $water_image = $water_config['image']; + if (!empty($water_image)) { + //判断水印图片是否是本地图片 + if (check_file_is_remote($water_image)) { + $file_arr = explode('.', $water_image); + $ext_name = end($file_arr); + $name = $this->createFileName($water_image, $ext_name); + $watermark_image = 'upload/water/' . $name; + $this->fetch($water_image, $watermark_image); + } + if (file_exists($water_image)) { + } + $editor->open($image1, $water_config['image']); + $editor->blend($image, $image1, 'normal', $water_config['opacity'], $this->position[$water_config['position']], $water_config['offset_x'], $water_config['offset_y']); + } + } else { + if ($water_config['text']) { + $position = $this->position[$water_config['position']]; + $offset_x = $water_config['offset_x'];//水平偏移值 + $offset_y = $water_config['offset_y'];//垂直偏移值 + $width = $image->getWidth(); + $height = $image->getHeight(); + + //获取文字信息 + $info = imagettfbbox($water_config['size'], $water_config['angle'], $water_config['font'], $water_config['text']); + $minx = min($info[0], $info[2], $info[4], $info[6]); + $maxx = max($info[0], $info[2], $info[4], $info[6]); + $miny = min($info[1], $info[3], $info[5], $info[7]); + $maxy = max($info[1], $info[3], $info[5], $info[7]); + /* 计算文字初始坐标和尺寸 */ + $x = $minx; + $y = abs($miny); + $w = $maxx - $minx; + $h = $maxy - $miny; + //转化坐标 + $position = new Position($position, $offset_x, $offset_y); + // Position is for $image2. $image1 is canvas. + list($offset_x, $offset_y) = $position->getXY($width, $height, $w, $h); + + $editor->text($image, $water_config['text'], $water_config['size'], $offset_x, $offset_y, new Color($water_config['color']), $water_config['font'], $water_config['angle']); + } + $editor->save($image, $file_path); + + + } + } + return $file_path; + } } } \ No newline at end of file diff --git a/niucloud/core/upload/Qiniu.php b/niucloud/core/upload/Qiniu.php index 683abac6c..2bc4208b7 100644 --- a/niucloud/core/upload/Qiniu.php +++ b/niucloud/core/upload/Qiniu.php @@ -1,4 +1,5 @@ 'NorthWest', + 'top-center' => 'North', + 'top-right' => 'NorthEast', + 'center-left' => 'West', + 'center' => 'Center', + 'center-right' => 'East', + 'bottom-left' => 'SouthWest', + 'bottom-center' => 'South', + 'bottom-right' => 'SouthEast', + ); + protected function initialize(array $config = []) { parent::initialize($config); } + /** * 获取一个鉴权对象 * @return Auth */ - public function auth(){ + public function auth() + { $access_key = $this->config['access_key']; $secret_key = $this->config['secret_key']; return new Auth($access_key, $secret_key); } + + /** + * @throws Exception + */ public function upload(string $dir) { $this->validate(); @@ -36,7 +54,7 @@ class Qiniu extends BaseUpload $up_token = $this->auth()->uploadToken($bucket); // 初始化 UploadManager 对象并进行文件的上传。 $upload_mgr = new UploadManager(); - list($ret, $err) = $upload_mgr->putFile($up_token, $this->getFullPath(), $this->getRealPath()); + [$ret, $err] = $upload_mgr->putFile($up_token, $this->getFullPath(), $this->getRealPath()); if ($err !== null) throw new UploadFileException($err->message()); return true; @@ -44,8 +62,8 @@ class Qiniu extends BaseUpload /** * 抓取网络资源到空间 - * @param $url - * @param $key + * @param string $url + * @param string|null $key * @return true * @throws Exception */ @@ -53,14 +71,14 @@ class Qiniu extends BaseUpload { $bucket = $this->config['bucket']; $auth = $this->auth(); - if(!str_contains($url, 'http://') && !str_contains($url, 'https://')){ + if (!str_contains($url, 'http://') && !str_contains($url, 'https://')) { $token = $auth->uploadToken($bucket); $upload_mgr = new UploadManager(); - list($ret, $err) = $upload_mgr->putFile($token, $key, $url); - }else{ + [$ret, $err] = $upload_mgr->putFile($token, $key, $url); + } else { //抓取网络资源到空间 $bucket_manager = new BucketManager($auth); - list($ret, $err) = $bucket_manager->fetch($url, $bucket, $key);//不指定key时,以文件内容的hash作为文件名 + [$ret, $err] = $bucket_manager->fetch($url, $bucket, $key);//不指定key时,以文件内容的hash作为文件名 } if ($err !== null) @@ -68,10 +86,32 @@ class Qiniu extends BaseUpload return true; } + /** + * base64资源上传 + * @param string $base64_data + * @param string|null $key + * @return true + */ + public function base64(string $base64_data, ?string $key = null) + { + $bucket = $this->config['bucket']; + $auth = $this->auth(); + $up_token = $this->auth()->uploadToken($bucket); + // 初始化 UploadManager 对象并进行文件的上传。 + $upload_mgr = new UploadManager(); + //将 base64 编码的图片数据解码 + $base64_file = base64_decode($base64_data); + if (!$base64_file) throw new UploadFileException('FILE_ERROE'); + // 初始化 UpLoadManager 对象并进行文件的上传 + list($ret, $err) = $upload_mgr->put($up_token, $key, $base64_file); + if ($err !== null) throw new UploadFileException($err->message); + return true; + } + /** * 删除空间中的文件 - * @param $file_name - * @return bool|mixed + * @param string $file_name + * @return true */ public function delete(string $file_name) { @@ -79,27 +119,62 @@ class Qiniu extends BaseUpload $auth = $this->auth(); $config = new Config(); $bucket_manager = new BucketManager($auth, $config); - $err = $bucket_manager->delete($bucket, $file_name); + [$ret, $err] = $bucket_manager->delete($bucket, $file_name); if ($err !== null) throw new UploadFileException($err->message()); return true; } - public function thumb($file_path, $thumb_type){ -// http://examples-1251000004.cos.ap-shanghai.myqcloud.com/sample.jpeg?imageView2/1/w/400/h/600/q/85 + public function thumb($file_path, $thumb_type) + { +// mageView2/1/w/400/h/600/q/85 $thumb_config = config('upload.thumb.thumb_type'); $thumb_data = []; - foreach($thumb_config as $k => $v){ - if($thumb_type == 'all' || $thumb_type == $k){ + foreach ($thumb_config as $k => $v) { + if ($thumb_type == 'all' || $thumb_type == $k || (is_array($thumb_type) && in_array($k, $thumb_type))) { // ?x-oss-process=image/resize,m_fill,w_200,h_600,quality,q_60 $width = $v['width']; $height = $v['height']; //拼装缩略路径 - $item_thumb = $file_path.'?imageView2/2/w/' . $width . '/h/' . $height; + $item_thumb = $file_path . '?imageView2/2/w/' . $width . '/h/' . $height; $thumb_data[$k] = $item_thumb; } } return $thumb_data; } + + + /** + * 图片水印 + * @param $file_path + * @return mixed + * @throws Exception + */ + public function water($file_path) + { + $water_config = []; + $water_path = $file_path; + if (!empty($water_config)) { + $status = $water_config['status'];//是否启用 + if ($status) { + //判断当前的云图片是否存在?,存在符号的话需要用|连接 + if (str_contains($file_path, '?')) { + $water_path .= '|watermark'; + } else { + $water_path .= '?watermark'; + } + if ($water_config['type'] == 'image') { + $water_image = $water_config['image']; + if (!empty($water_image)) { + $water_path .= '/1/image/' . base64_encode($water_image) . '/gravity/' . $this->position[$water_config['position']] . '/dissolve/' . $water_config['opacity'] . '/dx/' . $water_config['offset_x'] . '/dy/' . $water_config['offset_y']; + } + } else { + $water_path .= '/2/text/' . base64_encode($water_config['text']) . '/font/' . base64_encode($water_config['font']) . '/fill/' . base64_encode($water_config['color']) . '/fontsize/' . $water_config['size'] . '/gravity/' . $this->position[$water_config['position']] . '/dx/' . $water_config['offset_x'] . '/dy/' . $water_config['offset_y']; + } + } + } + return $water_path; + } + } \ No newline at end of file diff --git a/niucloud/core/upload/Tencent.php b/niucloud/core/upload/Tencent.php index 011007d3a..7475b7875 100644 --- a/niucloud/core/upload/Tencent.php +++ b/niucloud/core/upload/Tencent.php @@ -11,6 +11,19 @@ use Qcloud\Cos\Client; */ class Tencent extends BaseUpload { + + private $position = array( + 'top-left' => 'northwest', + 'top-center' => 'north', + 'top-right' => 'northeast', + 'center-left' => 'west', + 'center' => 'center', + 'center-right' => 'east', + 'bottom-left' => 'southwest', + 'bottom-center' => 'south', + 'bottom-right' => 'southeast', + ); + protected function initialize(array $config = []) { parent::initialize($config); @@ -40,8 +53,8 @@ class Tencent extends BaseUpload /** * 执行上传 - * @param $save_dir (保存路径) - * @return bool|mixed + * @param string $dir + * @return true */ public function upload(string $dir) { @@ -60,11 +73,34 @@ class Tencent extends BaseUpload } } + /** + * base文件上云 + * @param string $base64_data + * @param string|null $key + * @return true + */ + public function base64(string $base64_data, ?string $key = null) + { + $bucket = $this->config['bucket']; + try { + $base64_file = base64_decode($base64_data); + if (!$base64_file) throw new UploadFileException('FILE_ERROE'); + $result = $this->client()->putObject(array( + 'Bucket' => $bucket, //存储桶名称,由BucketName-Appid 组成,可以在COS控制台查看 https://console.tencentcloud.com/cos5/bucket + 'Key' => $key, + 'Body' => $base64_file, + )); + // 请求成功 + return true; + } catch ( Exception $e ) { + throw new UploadFileException($e->getMessage()); + } + } /** * notes: 抓取远程资源(最大支持上传5G文件) - * @param $url - * @param null $key - * @return mixed|void + * @param string $url + * @param string|null $key + * @return true */ public function fetch(string $url, ?string $key = null) { @@ -85,8 +121,8 @@ class Tencent extends BaseUpload /** * 删除一个简单对象 - * @param $file_name - * @return bool|mixed + * @param string $file_name + * @return true */ public function delete(string $file_name) { @@ -108,17 +144,52 @@ class Tencent extends BaseUpload $thumb_config = config('upload.thumb.thumb_type'); $thumb_data = []; - foreach($thumb_config as $k => $v){ - if($thumb_type == 'all' || $thumb_type == $k){ + foreach ($thumb_config as $k => $v) { + if ($thumb_type == 'all' || $thumb_type == $k || (is_array($thumb_type) && in_array($k, $thumb_type))) { // ?x-oss-process=image/resize,m_fill,w_200,h_600,quality,q_60 $width = $v['width']; $height = $v['height']; //拼装缩略路径 - $item_thumb = $file_path.'?imageMogr2/thumbnail/' . $width . 'x' . $height; + $item_thumb = $file_path . '?imageMogr2/thumbnail/' . $width . 'x' . $height; $thumb_data[$k] = $item_thumb; } } return $thumb_data; } + + + /** + * 图片水印 + * @param $file_path + * @return mixed + * @throws Exception + */ + public function water($file_path) + { + $water_config = []; + $water_path = $file_path; + if (!empty($water_config)) { + $status = $water_config['status'];//是否启用 + if($status){ + //判断当前的云图片是否存在?,存在符号的话需要用|连接 + if(str_contains($file_path, '?')){ + $water_path .= '&watermark'; + }else{ + $water_path .= '?watermark'; + } + if ($water_config['type'] == 'image') { + $water_image = $water_config['image']; + if(!empty($water_image)){ + //http://examples-1251000004.cos.ap-shanghai.myqcloud.com/sample.jpeg?watermark/1/image/aHR0cDovL2V4YW1wbGVzLTEyNTEwMDAwMDQucGljc2gubXlxY2xvdWQuY29tL3NodWl5aW4uanBn/gravity/southeast + $water_path .= '/1/image/' . base64_encode($water_image) . '/gravity/' . $this->position[$water_config['position']] . '/blogo/1/dx/' . $water_config['offset_x'] . '/dy/' . $water_config['offset_y'].'/dissolve/'.$water_config['opacity']; + } + } else { + //http://examples-1251000004.cos.ap-shanghai.myqcloud.com/sample.jpeg?q-sign-algorithm=&watermark/2/text/6IW-6K6v5LqRwrfkuIfosaHkvJjlm74/fill/IzNEM0QzRA/fontsize/20/dissolve/50/gravity/northeast/dx/20/dy/20/batch/1/degree/45 + $water_path .= '/2/text/' . base64_encode($water_config['text']) . '/font/' . base64_encode($water_config['font']) . '/fill/' . base64_encode($water_config['color']) . '/fontsize/' . $water_config['size'] . '/gravity/' . $this->position[$water_config['position']] . '/dx/' . $water_config['offset_x'] . '/dy/' . $water_config['offset_y']; + } + } + } + return $water_path; + } } diff --git a/niucloud/core/upload/UploadLoader.php b/niucloud/core/upload/UploadLoader.php index baa6f3949..ff6afacf5 100644 --- a/niucloud/core/upload/UploadLoader.php +++ b/niucloud/core/upload/UploadLoader.php @@ -14,13 +14,14 @@ namespace core\upload; use core\loader\Loader; /** - * @see \core\upload\UploadLoader + * @see UploadLoader * @package think\facade - * @mixin \core\upload\BaseUpload + * @mixin BaseUpload * @method string|null upload(string $dir) 附件上传 * @method array fetch(string $url, ?string $key) 抓取远程附件 * @method mixed delete(string $file_name) 附件删除 * @method mixed thumb(string $file_path, $thumb_type) 附件删除 + * @method mixed base64(string $base64_data, ?string $key = null) base文件上传 */ class UploadLoader extends Loader { @@ -31,6 +32,7 @@ class UploadLoader extends Loader protected $namespace = '\\core\\upload\\'; protected $config_name = 'upload'; + /** * 默认驱动 * @return mixed diff --git a/niucloud/core/util/Barcode.php b/niucloud/core/util/Barcode.php new file mode 100644 index 000000000..b49915c19 --- /dev/null +++ b/niucloud/core/util/Barcode.php @@ -0,0 +1,68 @@ +color_black = new \BCGColor(0, 0, 0); + $this->color_white = new \BCGColor(255, 255, 255); + $this->size = $size; + $this->fontPath = str_replace("\\", "/", root_path() . "core/util/barcode/font/Arial.ttf"); + $this->font = new \BCGFontFile($this->fontPath, $this->size); + $this->content = $content; + } + + //生成条形码 + public function generateBarcode($path='', $scale = 2){ + try { + $code = new \BCGcode128(); + $code->setScale($scale); + $code->setThickness(30); // 条形码的厚度 + $code->setForegroundColor($this->color_black); // 条形码颜色 + $code->setBackgroundColor($this->color_white); // 空白间隙颜色 + $code->setFont($this->font); // + $code->parse($this->content); // 条形码需要的数据内容 + } catch(Exception $exception) { + $this->drawException = $exception; + } + + if($path == ''){ + $path = 'upload/barcode';//条形码存放路径 + } + + if (! is_dir($path)) { + $mode = intval('0777', 8); + mkdir($path, $mode, true); + chmod($path, $mode); + } + $path = $path . '/' . $this->content . '.png'; + if (file_exists($path)) { + unlink($path); + } + + //根据以上条件绘制条形码 + $drawing = new \BCGDrawing('', $this->color_white); + if($this->drawException) { + $drawing->drawException($this->drawException); + } else { + $drawing->setBarcode($code); + $drawing->setFilename($path); + $drawing->draw(); + } + // 生成PNG格式的图片 + $drawing->finish(\BCGDrawing::IMG_FORMAT_PNG); + return $path; + } +} +?> \ No newline at end of file diff --git a/niucloud/core/util/QRcode.php b/niucloud/core/util/QRcode.php new file mode 100644 index 000000000..52c92ce7e --- /dev/null +++ b/niucloud/core/util/QRcode.php @@ -0,0 +1,3312 @@ + + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + + +/* + * Version: 1.1.4 + * Build: 2010100721 + */ + + + +//---- qrconst.php ----------------------------- + + + + + +/* + * PHP QR Code encoder + * + * Common constants + * + * Based on libqrencode C library distributed under LGPL 2.1 + * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi + * + * PHP QR Code is distributed under LGPL 3 + * Copyright (C) 2010 Dominik Dzienia + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + // Encoding modes + + define('QR_MODE_NUL', -1); + define('QR_MODE_NUM', 0); + define('QR_MODE_AN', 1); + define('QR_MODE_8', 2); + define('QR_MODE_KANJI', 3); + define('QR_MODE_STRUCTURE', 4); + + // Levels of error correction. + + define('QR_ECLEVEL_L', 0); + define('QR_ECLEVEL_M', 1); + define('QR_ECLEVEL_Q', 2); + define('QR_ECLEVEL_H', 3); + + // Supported output formats + + define('QR_FORMAT_TEXT', 0); + define('QR_FORMAT_PNG', 1); + + class qrstr { + public static function set(&$srctab, $x, $y, $repl, $replLen = false) { + $srctab[$y] = substr_replace($srctab[$y], ($replLen !== false)?substr($repl,0,$replLen):$repl, $x, ($replLen !== false)?$replLen:strlen($repl)); + } + } + + + +//---- merged_config.php ----------------------------- + + + + +/* + * PHP QR Code encoder + * + * Config file, tuned-up for merged verion + */ + + define('QR_CACHEABLE', false); // use cache - more disk reads but less CPU power, masks and format templates are stored there + define('QR_CACHE_DIR', false); // used when QR_CACHEABLE === true + define('QR_LOG_DIR', false); // default error logs dir + + define('QR_FIND_BEST_MASK', true); // if true, estimates best mask (spec. default, but extremally slow; set to false to significant performance boost but (propably) worst quality code + define('QR_FIND_FROM_RANDOM', 2); // if false, checks all masks available, otherwise value tells count of masks need to be checked, mask id are got randomly + define('QR_DEFAULT_MASK', 2); // when QR_FIND_BEST_MASK === false + + define('QR_PNG_MAXIMUM_SIZE', 1024); // maximum allowed png image width (in pixels), tune to make sure GD and PHP can handle such big images + + + + +//---- qrtools.php ----------------------------- + + + + +/* + * PHP QR Code encoder + * + * Toolset, handy and debug utilites. + * + * PHP QR Code is distributed under LGPL 3 + * Copyright (C) 2010 Dominik Dzienia + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + class QRtools { + + //---------------------------------------------------------------------- + public static function binarize($frame) + { + $len = count($frame); + foreach ($frame as &$frameLine) { + + for($i=0; $i<$len; $i++) { + $frameLine[$i] = (ord($frameLine[$i])&1)?'1':'0'; + } + } + + return $frame; + } + + //---------------------------------------------------------------------- + public static function tcpdfBarcodeArray($code, $mode = 'QR,L', $tcPdfVersion = '4.5.037') + { + $barcode_array = array(); + + if (!is_array($mode)) + $mode = explode(',', $mode); + + $eccLevel = 'L'; + + if (count($mode) > 1) { + $eccLevel = $mode[1]; + } + + $qrTab = QRcode::text($code, false, $eccLevel); + $size = count($qrTab); + + $barcode_array['num_rows'] = $size; + $barcode_array['num_cols'] = $size; + $barcode_array['bcode'] = array(); + + foreach ($qrTab as $line) { + $arrAdd = array(); + foreach(str_split($line) as $char) + $arrAdd[] = ($char=='1')?1:0; + $barcode_array['bcode'][] = $arrAdd; + } + + return $barcode_array; + } + + //---------------------------------------------------------------------- + public static function clearCache() + { + self::$frames = array(); + } + + //---------------------------------------------------------------------- + public static function buildCache() + { + QRtools::markTime('before_build_cache'); + + $mask = new QRmask(); + for ($a=1; $a <= QRSPEC_VERSION_MAX; $a++) { + $frame = QRspec::newFrame($a); + if (QR_IMAGE) { + $fileName = QR_CACHE_DIR.'frame_'.$a.'.png'; + QRimage::png(self::binarize($frame), $fileName, 1, 0); + } + + $width = count($frame); + $bitMask = array_fill(0, $width, array_fill(0, $width, 0)); + for ($maskNo=0; $maskNo<8; $maskNo++) + $mask->makeMaskNo($maskNo, $width, $frame, $bitMask, true); + } + + QRtools::markTime('after_build_cache'); + } + + //---------------------------------------------------------------------- + public static function log($outfile, $err) + { + if (QR_LOG_DIR !== false) { + if ($err != '') { + if ($outfile !== false) { + file_put_contents(QR_LOG_DIR.basename($outfile).'-errors.txt', date('Y-m-d H:i:s').': '.$err, FILE_APPEND); + } else { + file_put_contents(QR_LOG_DIR.'errors.txt', date('Y-m-d H:i:s').': '.$err, FILE_APPEND); + } + } + } + } + + //---------------------------------------------------------------------- + public static function dumpMask($frame) + { + $width = count($frame); + for($y=0;$y<$width;$y++) { + for($x=0;$x<$width;$x++) { + echo ord($frame[$y][$x]).','; + } + } + } + + //---------------------------------------------------------------------- + public static function markTime($markerId) + { + list($usec, $sec) = explode(" ", microtime()); + $time = ((float)$usec + (float)$sec); + + if (!isset($GLOBALS['qr_time_bench'])) + $GLOBALS['qr_time_bench'] = array(); + + $GLOBALS['qr_time_bench'][$markerId] = $time; + } + + //---------------------------------------------------------------------- + public static function timeBenchmark() + { + self::markTime('finish'); + + $lastTime = 0; + $startTime = 0; + $p = 0; + + echo ' + + '; + + foreach($GLOBALS['qr_time_bench'] as $markerId=>$thisTime) { + if ($p > 0) { + echo ''; + } else { + $startTime = $thisTime; + } + + $p++; + $lastTime = $thisTime; + } + + echo ' + + +
BENCHMARK
till '.$markerId.': '.number_format($thisTime-$lastTime, 6).'s
TOTAL: '.number_format($lastTime-$startTime, 6).'s
'; + } + + } + + //########################################################################## + + QRtools::markTime('start'); + + + + +//---- qrspec.php ----------------------------- + + + + +/* + * PHP QR Code encoder + * + * QR Code specifications + * + * Based on libqrencode C library distributed under LGPL 2.1 + * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi + * + * PHP QR Code is distributed under LGPL 3 + * Copyright (C) 2010 Dominik Dzienia + * + * The following data / specifications are taken from + * "Two dimensional symbol -- QR-code -- Basic Specification" (JIS X0510:2004) + * or + * "Automatic identification and data capture techniques -- + * QR Code 2005 bar code symbology specification" (ISO/IEC 18004:2006) + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + define('QRSPEC_VERSION_MAX', 40); + define('QRSPEC_WIDTH_MAX', 177); + + define('QRCAP_WIDTH', 0); + define('QRCAP_WORDS', 1); + define('QRCAP_REMINDER', 2); + define('QRCAP_EC', 3); + + class QRspec { + + public static $capacity = array( + array( 0, 0, 0, array( 0, 0, 0, 0)), + array( 21, 26, 0, array( 7, 10, 13, 17)), // 1 + array( 25, 44, 7, array( 10, 16, 22, 28)), + array( 29, 70, 7, array( 15, 26, 36, 44)), + array( 33, 100, 7, array( 20, 36, 52, 64)), + array( 37, 134, 7, array( 26, 48, 72, 88)), // 5 + array( 41, 172, 7, array( 36, 64, 96, 112)), + array( 45, 196, 0, array( 40, 72, 108, 130)), + array( 49, 242, 0, array( 48, 88, 132, 156)), + array( 53, 292, 0, array( 60, 110, 160, 192)), + array( 57, 346, 0, array( 72, 130, 192, 224)), //10 + array( 61, 404, 0, array( 80, 150, 224, 264)), + array( 65, 466, 0, array( 96, 176, 260, 308)), + array( 69, 532, 0, array( 104, 198, 288, 352)), + array( 73, 581, 3, array( 120, 216, 320, 384)), + array( 77, 655, 3, array( 132, 240, 360, 432)), //15 + array( 81, 733, 3, array( 144, 280, 408, 480)), + array( 85, 815, 3, array( 168, 308, 448, 532)), + array( 89, 901, 3, array( 180, 338, 504, 588)), + array( 93, 991, 3, array( 196, 364, 546, 650)), + array( 97, 1085, 3, array( 224, 416, 600, 700)), //20 + array(101, 1156, 4, array( 224, 442, 644, 750)), + array(105, 1258, 4, array( 252, 476, 690, 816)), + array(109, 1364, 4, array( 270, 504, 750, 900)), + array(113, 1474, 4, array( 300, 560, 810, 960)), + array(117, 1588, 4, array( 312, 588, 870, 1050)), //25 + array(121, 1706, 4, array( 336, 644, 952, 1110)), + array(125, 1828, 4, array( 360, 700, 1020, 1200)), + array(129, 1921, 3, array( 390, 728, 1050, 1260)), + array(133, 2051, 3, array( 420, 784, 1140, 1350)), + array(137, 2185, 3, array( 450, 812, 1200, 1440)), //30 + array(141, 2323, 3, array( 480, 868, 1290, 1530)), + array(145, 2465, 3, array( 510, 924, 1350, 1620)), + array(149, 2611, 3, array( 540, 980, 1440, 1710)), + array(153, 2761, 3, array( 570, 1036, 1530, 1800)), + array(157, 2876, 0, array( 570, 1064, 1590, 1890)), //35 + array(161, 3034, 0, array( 600, 1120, 1680, 1980)), + array(165, 3196, 0, array( 630, 1204, 1770, 2100)), + array(169, 3362, 0, array( 660, 1260, 1860, 2220)), + array(173, 3532, 0, array( 720, 1316, 1950, 2310)), + array(177, 3706, 0, array( 750, 1372, 2040, 2430)) //40 + ); + + //---------------------------------------------------------------------- + public static function getDataLength($version, $level) + { + return self::$capacity[$version][QRCAP_WORDS] - self::$capacity[$version][QRCAP_EC][$level]; + } + + //---------------------------------------------------------------------- + public static function getECCLength($version, $level) + { + return self::$capacity[$version][QRCAP_EC][$level]; + } + + //---------------------------------------------------------------------- + public static function getWidth($version) + { + return self::$capacity[$version][QRCAP_WIDTH]; + } + + //---------------------------------------------------------------------- + public static function getRemainder($version) + { + return self::$capacity[$version][QRCAP_REMINDER]; + } + + //---------------------------------------------------------------------- + public static function getMinimumVersion($size, $level) + { + + for($i=1; $i<= QRSPEC_VERSION_MAX; $i++) { + $words = self::$capacity[$i][QRCAP_WORDS] - self::$capacity[$i][QRCAP_EC][$level]; + if($words >= $size) + return $i; + } + + return -1; + } + + //###################################################################### + + public static $lengthTableBits = array( + array(10, 12, 14), + array( 9, 11, 13), + array( 8, 16, 16), + array( 8, 10, 12) + ); + + //---------------------------------------------------------------------- + public static function lengthIndicator($mode, $version) + { + if ($mode == QR_MODE_STRUCTURE) + return 0; + + if ($version <= 9) { + $l = 0; + } else if ($version <= 26) { + $l = 1; + } else { + $l = 2; + } + + return self::$lengthTableBits[$mode][$l]; + } + + //---------------------------------------------------------------------- + public static function maximumWords($mode, $version) + { + if($mode == QR_MODE_STRUCTURE) + return 3; + + if($version <= 9) { + $l = 0; + } else if($version <= 26) { + $l = 1; + } else { + $l = 2; + } + + $bits = self::$lengthTableBits[$mode][$l]; + $words = (1 << $bits) - 1; + + if($mode == QR_MODE_KANJI) { + $words *= 2; // the number of bytes is required + } + + return $words; + } + + // Error correction code ----------------------------------------------- + // Table of the error correction code (Reed-Solomon block) + // See Table 12-16 (pp.30-36), JIS X0510:2004. + + public static $eccTable = array( + array(array( 0, 0), array( 0, 0), array( 0, 0), array( 0, 0)), + array(array( 1, 0), array( 1, 0), array( 1, 0), array( 1, 0)), // 1 + array(array( 1, 0), array( 1, 0), array( 1, 0), array( 1, 0)), + array(array( 1, 0), array( 1, 0), array( 2, 0), array( 2, 0)), + array(array( 1, 0), array( 2, 0), array( 2, 0), array( 4, 0)), + array(array( 1, 0), array( 2, 0), array( 2, 2), array( 2, 2)), // 5 + array(array( 2, 0), array( 4, 0), array( 4, 0), array( 4, 0)), + array(array( 2, 0), array( 4, 0), array( 2, 4), array( 4, 1)), + array(array( 2, 0), array( 2, 2), array( 4, 2), array( 4, 2)), + array(array( 2, 0), array( 3, 2), array( 4, 4), array( 4, 4)), + array(array( 2, 2), array( 4, 1), array( 6, 2), array( 6, 2)), //10 + array(array( 4, 0), array( 1, 4), array( 4, 4), array( 3, 8)), + array(array( 2, 2), array( 6, 2), array( 4, 6), array( 7, 4)), + array(array( 4, 0), array( 8, 1), array( 8, 4), array(12, 4)), + array(array( 3, 1), array( 4, 5), array(11, 5), array(11, 5)), + array(array( 5, 1), array( 5, 5), array( 5, 7), array(11, 7)), //15 + array(array( 5, 1), array( 7, 3), array(15, 2), array( 3, 13)), + array(array( 1, 5), array(10, 1), array( 1, 15), array( 2, 17)), + array(array( 5, 1), array( 9, 4), array(17, 1), array( 2, 19)), + array(array( 3, 4), array( 3, 11), array(17, 4), array( 9, 16)), + array(array( 3, 5), array( 3, 13), array(15, 5), array(15, 10)), //20 + array(array( 4, 4), array(17, 0), array(17, 6), array(19, 6)), + array(array( 2, 7), array(17, 0), array( 7, 16), array(34, 0)), + array(array( 4, 5), array( 4, 14), array(11, 14), array(16, 14)), + array(array( 6, 4), array( 6, 14), array(11, 16), array(30, 2)), + array(array( 8, 4), array( 8, 13), array( 7, 22), array(22, 13)), //25 + array(array(10, 2), array(19, 4), array(28, 6), array(33, 4)), + array(array( 8, 4), array(22, 3), array( 8, 26), array(12, 28)), + array(array( 3, 10), array( 3, 23), array( 4, 31), array(11, 31)), + array(array( 7, 7), array(21, 7), array( 1, 37), array(19, 26)), + array(array( 5, 10), array(19, 10), array(15, 25), array(23, 25)), //30 + array(array(13, 3), array( 2, 29), array(42, 1), array(23, 28)), + array(array(17, 0), array(10, 23), array(10, 35), array(19, 35)), + array(array(17, 1), array(14, 21), array(29, 19), array(11, 46)), + array(array(13, 6), array(14, 23), array(44, 7), array(59, 1)), + array(array(12, 7), array(12, 26), array(39, 14), array(22, 41)), //35 + array(array( 6, 14), array( 6, 34), array(46, 10), array( 2, 64)), + array(array(17, 4), array(29, 14), array(49, 10), array(24, 46)), + array(array( 4, 18), array(13, 32), array(48, 14), array(42, 32)), + array(array(20, 4), array(40, 7), array(43, 22), array(10, 67)), + array(array(19, 6), array(18, 31), array(34, 34), array(20, 61)),//40 + ); + + //---------------------------------------------------------------------- + // CACHEABLE!!! + + public static function getEccSpec($version, $level, array &$spec) + { + if (count($spec) < 5) { + $spec = array(0,0,0,0,0); + } + + $b1 = self::$eccTable[$version][$level][0]; + $b2 = self::$eccTable[$version][$level][1]; + $data = self::getDataLength($version, $level); + $ecc = self::getECCLength($version, $level); + + if($b2 == 0) { + $spec[0] = $b1; + $spec[1] = (int)($data / $b1); + $spec[2] = (int)($ecc / $b1); + $spec[3] = 0; + $spec[4] = 0; + } else { + $spec[0] = $b1; + $spec[1] = (int)($data / ($b1 + $b2)); + $spec[2] = (int)($ecc / ($b1 + $b2)); + $spec[3] = $b2; + $spec[4] = $spec[1] + 1; + } + } + + // Alignment pattern --------------------------------------------------- + + // Positions of alignment patterns. + // This array includes only the second and the third position of the + // alignment patterns. Rest of them can be calculated from the distance + // between them. + + // See Table 1 in Appendix E (pp.71) of JIS X0510:2004. + + public static $alignmentPattern = array( + array( 0, 0), + array( 0, 0), array(18, 0), array(22, 0), array(26, 0), array(30, 0), // 1- 5 + array(34, 0), array(22, 38), array(24, 42), array(26, 46), array(28, 50), // 6-10 + array(30, 54), array(32, 58), array(34, 62), array(26, 46), array(26, 48), //11-15 + array(26, 50), array(30, 54), array(30, 56), array(30, 58), array(34, 62), //16-20 + array(28, 50), array(26, 50), array(30, 54), array(28, 54), array(32, 58), //21-25 + array(30, 58), array(34, 62), array(26, 50), array(30, 54), array(26, 52), //26-30 + array(30, 56), array(34, 60), array(30, 58), array(34, 62), array(30, 54), //31-35 + array(24, 50), array(28, 54), array(32, 58), array(26, 54), array(30, 58), //35-40 + ); + + + /** -------------------------------------------------------------------- + * Put an alignment marker. + * @param frame + * @param width + * @param ox,oy center coordinate of the pattern + */ + public static function putAlignmentMarker(array &$frame, $ox, $oy) + { + $finder = array( + "\xa1\xa1\xa1\xa1\xa1", + "\xa1\xa0\xa0\xa0\xa1", + "\xa1\xa0\xa1\xa0\xa1", + "\xa1\xa0\xa0\xa0\xa1", + "\xa1\xa1\xa1\xa1\xa1" + ); + + $yStart = $oy-2; + $xStart = $ox-2; + + for($y=0; $y<5; $y++) { + QRstr::set($frame, $xStart, $yStart+$y, $finder[$y]); + } + } + + //---------------------------------------------------------------------- + public static function putAlignmentPattern($version, &$frame, $width) + { + if($version < 2) + return; + + $d = self::$alignmentPattern[$version][1] - self::$alignmentPattern[$version][0]; + if($d < 0) { + $w = 2; + } else { + $w = (int)(($width - self::$alignmentPattern[$version][0]) / $d + 2); + } + + if($w * $w - 3 == 1) { + $x = self::$alignmentPattern[$version][0]; + $y = self::$alignmentPattern[$version][0]; + self::putAlignmentMarker($frame, $x, $y); + return; + } + + $cx = self::$alignmentPattern[$version][0]; + for($x=1; $x<$w - 1; $x++) { + self::putAlignmentMarker($frame, 6, $cx); + self::putAlignmentMarker($frame, $cx, 6); + $cx += $d; + } + + $cy = self::$alignmentPattern[$version][0]; + for($y=0; $y<$w-1; $y++) { + $cx = self::$alignmentPattern[$version][0]; + for($x=0; $x<$w-1; $x++) { + self::putAlignmentMarker($frame, $cx, $cy); + $cx += $d; + } + $cy += $d; + } + } + + // Version information pattern ----------------------------------------- + + // Version information pattern (BCH coded). + // See Table 1 in Appendix D (pp.68) of JIS X0510:2004. + + // size: [QRSPEC_VERSION_MAX - 6] + + public static $versionPattern = array( + 0x07c94, 0x085bc, 0x09a99, 0x0a4d3, 0x0bbf6, 0x0c762, 0x0d847, 0x0e60d, + 0x0f928, 0x10b78, 0x1145d, 0x12a17, 0x13532, 0x149a6, 0x15683, 0x168c9, + 0x177ec, 0x18ec4, 0x191e1, 0x1afab, 0x1b08e, 0x1cc1a, 0x1d33f, 0x1ed75, + 0x1f250, 0x209d5, 0x216f0, 0x228ba, 0x2379f, 0x24b0b, 0x2542e, 0x26a64, + 0x27541, 0x28c69 + ); + + //---------------------------------------------------------------------- + public static function getVersionPattern($version) + { + if($version < 7 || $version > QRSPEC_VERSION_MAX) + return 0; + + return self::$versionPattern[$version -7]; + } + + // Format information -------------------------------------------------- + // See calcFormatInfo in tests/test_qrspec.c (orginal qrencode c lib) + + public static $formatInfo = array( + array(0x77c4, 0x72f3, 0x7daa, 0x789d, 0x662f, 0x6318, 0x6c41, 0x6976), + array(0x5412, 0x5125, 0x5e7c, 0x5b4b, 0x45f9, 0x40ce, 0x4f97, 0x4aa0), + array(0x355f, 0x3068, 0x3f31, 0x3a06, 0x24b4, 0x2183, 0x2eda, 0x2bed), + array(0x1689, 0x13be, 0x1ce7, 0x19d0, 0x0762, 0x0255, 0x0d0c, 0x083b) + ); + + public static function getFormatInfo($mask, $level) + { + if($mask < 0 || $mask > 7) + return 0; + + if($level < 0 || $level > 3) + return 0; + + return self::$formatInfo[$level][$mask]; + } + + // Frame --------------------------------------------------------------- + // Cache of initial frames. + + public static $frames = array(); + + /** -------------------------------------------------------------------- + * Put a finder pattern. + * @param frame + * @param width + * @param ox,oy upper-left coordinate of the pattern + */ + public static function putFinderPattern(&$frame, $ox, $oy) + { + $finder = array( + "\xc1\xc1\xc1\xc1\xc1\xc1\xc1", + "\xc1\xc0\xc0\xc0\xc0\xc0\xc1", + "\xc1\xc0\xc1\xc1\xc1\xc0\xc1", + "\xc1\xc0\xc1\xc1\xc1\xc0\xc1", + "\xc1\xc0\xc1\xc1\xc1\xc0\xc1", + "\xc1\xc0\xc0\xc0\xc0\xc0\xc1", + "\xc1\xc1\xc1\xc1\xc1\xc1\xc1" + ); + + for($y=0; $y<7; $y++) { + QRstr::set($frame, $ox, $oy+$y, $finder[$y]); + } + } + + //---------------------------------------------------------------------- + public static function createFrame($version) + { + $width = self::$capacity[$version][QRCAP_WIDTH]; + $frameLine = str_repeat ("\0", $width); + $frame = array_fill(0, $width, $frameLine); + + // Finder pattern + self::putFinderPattern($frame, 0, 0); + self::putFinderPattern($frame, $width - 7, 0); + self::putFinderPattern($frame, 0, $width - 7); + + // Separator + $yOffset = $width - 7; + + for($y=0; $y<7; $y++) { + $frame[$y][7] = "\xc0"; + $frame[$y][$width - 8] = "\xc0"; + $frame[$yOffset][7] = "\xc0"; + $yOffset++; + } + + $setPattern = str_repeat("\xc0", 8); + + QRstr::set($frame, 0, 7, $setPattern); + QRstr::set($frame, $width-8, 7, $setPattern); + QRstr::set($frame, 0, $width - 8, $setPattern); + + // Format info + $setPattern = str_repeat("\x84", 9); + QRstr::set($frame, 0, 8, $setPattern); + QRstr::set($frame, $width - 8, 8, $setPattern, 8); + + $yOffset = $width - 8; + + for($y=0; $y<8; $y++,$yOffset++) { + $frame[$y][8] = "\x84"; + $frame[$yOffset][8] = "\x84"; + } + + // Timing pattern + + for($i=1; $i<$width-15; $i++) { + $frame[6][7+$i] = chr(0x90 | ($i & 1)); + $frame[7+$i][6] = chr(0x90 | ($i & 1)); + } + + // Alignment pattern + self::putAlignmentPattern($version, $frame, $width); + + // Version information + if($version >= 7) { + $vinf = self::getVersionPattern($version); + + $v = $vinf; + + for($x=0; $x<6; $x++) { + for($y=0; $y<3; $y++) { + $frame[($width - 11)+$y][$x] = chr(0x88 | ($v & 1)); + $v = $v >> 1; + } + } + + $v = $vinf; + for($y=0; $y<6; $y++) { + for($x=0; $x<3; $x++) { + $frame[$y][$x+($width - 11)] = chr(0x88 | ($v & 1)); + $v = $v >> 1; + } + } + } + + // and a little bit... + $frame[$width - 8][8] = "\x81"; + + return $frame; + } + + //---------------------------------------------------------------------- + public static function debug($frame, $binary_mode = false) + { + if ($binary_mode) { + + foreach ($frame as &$frameLine) { + $frameLine = join('  ', explode('0', $frameLine)); + $frameLine = join('██', explode('1', $frameLine)); + } + + ?> + +


        '; + echo join("
        ", $frame); + echo '






'; + + } else { + + foreach ($frame as &$frameLine) { + $frameLine = join(' ', explode("\xc0", $frameLine)); + $frameLine = join('', explode("\xc1", $frameLine)); + $frameLine = join(' ', explode("\xa0", $frameLine)); + $frameLine = join('', explode("\xa1", $frameLine)); + $frameLine = join('', explode("\x84", $frameLine)); //format 0 + $frameLine = join('', explode("\x85", $frameLine)); //format 1 + $frameLine = join('', explode("\x81", $frameLine)); //special bit + $frameLine = join(' ', explode("\x90", $frameLine)); //clock 0 + $frameLine = join('', explode("\x91", $frameLine)); //clock 1 + $frameLine = join(' ', explode("\x88", $frameLine)); //version + $frameLine = join('', explode("\x89", $frameLine)); //version + $frameLine = join('♦', explode("\x01", $frameLine)); + $frameLine = join('⋅', explode("\0", $frameLine)); + } + + ?> + + "; + echo join("
", $frame); + echo "
"; + + } + } + + //---------------------------------------------------------------------- + public static function serial($frame) + { + return gzcompress(join("\n", $frame), 9); + } + + //---------------------------------------------------------------------- + public static function unserial($code) + { + return explode("\n", gzuncompress($code)); + } + + //---------------------------------------------------------------------- + public static function newFrame($version) + { + if($version < 1 || $version > QRSPEC_VERSION_MAX) + return null; + + if(!isset(self::$frames[$version])) { + + $fileName = QR_CACHE_DIR.'frame_'.$version.'.dat'; + + if (QR_CACHEABLE) { + if (file_exists($fileName)) { + self::$frames[$version] = self::unserial(file_get_contents($fileName)); + } else { + self::$frames[$version] = self::createFrame($version); + file_put_contents($fileName, self::serial(self::$frames[$version])); + } + } else { + self::$frames[$version] = self::createFrame($version); + } + } + + if(is_null(self::$frames[$version])) + return null; + + return self::$frames[$version]; + } + + //---------------------------------------------------------------------- + public static function rsBlockNum($spec) { return $spec[0] + $spec[3]; } + public static function rsBlockNum1($spec) { return $spec[0]; } + public static function rsDataCodes1($spec) { return $spec[1]; } + public static function rsEccCodes1($spec) { return $spec[2]; } + public static function rsBlockNum2($spec) { return $spec[3]; } + public static function rsDataCodes2($spec) { return $spec[4]; } + public static function rsEccCodes2($spec) { return $spec[2]; } + public static function rsDataLength($spec) { return ($spec[0] * $spec[1]) + ($spec[3] * $spec[4]); } + public static function rsEccLength($spec) { return ($spec[0] + $spec[3]) * $spec[2]; } + + } + + + +//---- qrimage.php ----------------------------- + + + + +/* + * PHP QR Code encoder + * + * Image output of code using GD2 + * + * PHP QR Code is distributed under LGPL 3 + * Copyright (C) 2010 Dominik Dzienia + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + define('QR_IMAGE', true); + + class QRimage { + + //---------------------------------------------------------------------- + public static function png($frame, $filename = false, $pixelPerPoint = 4, $outerFrame = 4,$saveandprint=FALSE) + { + $image = self::image($frame, $pixelPerPoint, $outerFrame); + + if ($filename === false) { + Header("Content-type: image/png"); + ImagePng($image); + } else { + if($saveandprint===TRUE){ + ImagePng($image, $filename); + header("Content-type: image/png"); + ImagePng($image); + }else{ + ImagePng($image, $filename); + } + } + + ImageDestroy($image); + } + + //---------------------------------------------------------------------- + public static function jpg($frame, $filename = false, $pixelPerPoint = 8, $outerFrame = 4, $q = 85) + { + $image = self::image($frame, $pixelPerPoint, $outerFrame); + + if ($filename === false) { + Header("Content-type: image/jpeg"); + ImageJpeg($image, null, $q); + } else { + ImageJpeg($image, $filename, $q); + } + + ImageDestroy($image); + } + + //---------------------------------------------------------------------- + private static function image($frame, $pixelPerPoint = 4, $outerFrame = 4) + { + $h = count($frame); + $w = strlen($frame[0]); + + $imgW = $w + 2*$outerFrame; + $imgH = $h + 2*$outerFrame; + + $base_image =ImageCreate($imgW, $imgH); + + $col[0] = ImageColorAllocate($base_image,255,255,255); + $col[1] = ImageColorAllocate($base_image,0,0,0); + + imagefill($base_image, 0, 0, $col[0]); + + for($y=0; $y<$h; $y++) { + for($x=0; $x<$w; $x++) { + if ($frame[$y][$x] == '1') { + ImageSetPixel($base_image,$x+$outerFrame,$y+$outerFrame,$col[1]); + } + } + } + + $target_image =ImageCreate($imgW * $pixelPerPoint, $imgH * $pixelPerPoint); + ImageCopyResized($target_image, $base_image, 0, 0, 0, 0, $imgW * $pixelPerPoint, $imgH * $pixelPerPoint, $imgW, $imgH); + ImageDestroy($base_image); + + return $target_image; + } + } + + + +//---- qrinput.php ----------------------------- + + + + +/* + * PHP QR Code encoder + * + * Input encoding class + * + * Based on libqrencode C library distributed under LGPL 2.1 + * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi + * + * PHP QR Code is distributed under LGPL 3 + * Copyright (C) 2010 Dominik Dzienia + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + define('STRUCTURE_HEADER_BITS', 20); + define('MAX_STRUCTURED_SYMBOLS', 16); + + class QRinputItem { + + public $mode; + public $size; + public $data; + public $bstream; + + public function __construct($mode, $size, $data, $bstream = null) + { + $setData = array_slice($data, 0, $size); + + if (count($setData) < $size) { + $setData = array_merge($setData, array_fill(0,$size-count($setData),0)); + } + + if(!QRinput::check($mode, $size, $setData)) { + throw new \Exception('Error m:'.$mode.',s:'.$size.',d:'.join(',',$setData)); + return null; + } + + $this->mode = $mode; + $this->size = $size; + $this->data = $setData; + $this->bstream = $bstream; + } + + //---------------------------------------------------------------------- + public function encodeModeNum($version) + { + try { + + $words = (int)($this->size / 3); + $bs = new QRbitstream(); + + $val = 0x1; + $bs->appendNum(4, $val); + $bs->appendNum(QRspec::lengthIndicator(QR_MODE_NUM, $version), $this->size); + + for($i=0; $i<$words; $i++) { + $val = (ord($this->data[$i*3 ]) - ord('0')) * 100; + $val += (ord($this->data[$i*3+1]) - ord('0')) * 10; + $val += (ord($this->data[$i*3+2]) - ord('0')); + $bs->appendNum(10, $val); + } + + if($this->size - $words * 3 == 1) { + $val = ord($this->data[$words*3]) - ord('0'); + $bs->appendNum(4, $val); + } else if($this->size - $words * 3 == 2) { + $val = (ord($this->data[$words*3 ]) - ord('0')) * 10; + $val += (ord($this->data[$words*3+1]) - ord('0')); + $bs->appendNum(7, $val); + } + + $this->bstream = $bs; + return 0; + + } catch (Exception $e) { + return -1; + } + } + + //---------------------------------------------------------------------- + public function encodeModeAn($version) + { + try { + $words = (int)($this->size / 2); + $bs = new QRbitstream(); + + $bs->appendNum(4, 0x02); + $bs->appendNum(QRspec::lengthIndicator(QR_MODE_AN, $version), $this->size); + + for($i=0; $i<$words; $i++) { + $val = (int)QRinput::lookAnTable(ord($this->data[$i*2 ])) * 45; + $val += (int)QRinput::lookAnTable(ord($this->data[$i*2+1])); + + $bs->appendNum(11, $val); + } + + if($this->size & 1) { + $val = QRinput::lookAnTable(ord($this->data[$words * 2])); + $bs->appendNum(6, $val); + } + + $this->bstream = $bs; + return 0; + + } catch (Exception $e) { + return -1; + } + } + + //---------------------------------------------------------------------- + public function encodeMode8($version) + { + try { + $bs = new QRbitstream(); + + $bs->appendNum(4, 0x4); + $bs->appendNum(QRspec::lengthIndicator(QR_MODE_8, $version), $this->size); + + for($i=0; $i<$this->size; $i++) { + $bs->appendNum(8, ord($this->data[$i])); + } + + $this->bstream = $bs; + return 0; + + } catch (Exception $e) { + return -1; + } + } + + //---------------------------------------------------------------------- + public function encodeModeKanji($version) + { + try { + + $bs = new QRbitrtream(); + + $bs->appendNum(4, 0x8); + $bs->appendNum(QRspec::lengthIndicator(QR_MODE_KANJI, $version), (int)($this->size / 2)); + + for($i=0; $i<$this->size; $i+=2) { + $val = (ord($this->data[$i]) << 8) | ord($this->data[$i+1]); + if($val <= 0x9ffc) { + $val -= 0x8140; + } else { + $val -= 0xc140; + } + + $h = ($val >> 8) * 0xc0; + $val = ($val & 0xff) + $h; + + $bs->appendNum(13, $val); + } + + $this->bstream = $bs; + return 0; + + } catch (Exception $e) { + return -1; + } + } + + //---------------------------------------------------------------------- + public function encodeModeStructure() + { + try { + $bs = new QRbitstream(); + + $bs->appendNum(4, 0x03); + $bs->appendNum(4, ord($this->data[1]) - 1); + $bs->appendNum(4, ord($this->data[0]) - 1); + $bs->appendNum(8, ord($this->data[2])); + + $this->bstream = $bs; + return 0; + + } catch (Exception $e) { + return -1; + } + } + + //---------------------------------------------------------------------- + public function estimateBitStreamSizeOfEntry($version) + { + $bits = 0; + + if($version == 0) + $version = 1; + + switch($this->mode) { + case QR_MODE_NUM: $bits = QRinput::estimateBitsModeNum($this->size); break; + case QR_MODE_AN: $bits = QRinput::estimateBitsModeAn($this->size); break; + case QR_MODE_8: $bits = QRinput::estimateBitsMode8($this->size); break; + case QR_MODE_KANJI: $bits = QRinput::estimateBitsModeKanji($this->size);break; + case QR_MODE_STRUCTURE: return STRUCTURE_HEADER_BITS; + default: + return 0; + } + + $l = QRspec::lengthIndicator($this->mode, $version); + $m = 1 << $l; + $num = (int)(($this->size + $m - 1) / $m); + + $bits += $num * (4 + $l); + + return $bits; + } + + //---------------------------------------------------------------------- + public function encodeBitStream($version) + { + try { + + unset($this->bstream); + $words = QRspec::maximumWords($this->mode, $version); + + if($this->size > $words) { + + $st1 = new QRinputItem($this->mode, $words, $this->data); + $st2 = new QRinputItem($this->mode, $this->size - $words, array_slice($this->data, $words)); + + $st1->encodeBitStream($version); + $st2->encodeBitStream($version); + + $this->bstream = new QRbitstream(); + $this->bstream->append($st1->bstream); + $this->bstream->append($st2->bstream); + + unset($st1); + unset($st2); + + } else { + + $ret = 0; + + switch($this->mode) { + case QR_MODE_NUM: $ret = $this->encodeModeNum($version); break; + case QR_MODE_AN: $ret = $this->encodeModeAn($version); break; + case QR_MODE_8: $ret = $this->encodeMode8($version); break; + case QR_MODE_KANJI: $ret = $this->encodeModeKanji($version);break; + case QR_MODE_STRUCTURE: $ret = $this->encodeModeStructure(); break; + + default: + break; + } + + if($ret < 0) + return -1; + } + + return $this->bstream->size(); + + } catch (Exception $e) { + return -1; + } + } + }; + + //########################################################################## + + class QRinput { + + public $items; + + private $version; + private $level; + + //---------------------------------------------------------------------- + public function __construct($version = 0, $level = QR_ECLEVEL_L) + { + if ($version < 0 || $version > QRSPEC_VERSION_MAX || $level > QR_ECLEVEL_H) { + throw new \Exception('Invalid version no'); + return NULL; + } + + $this->version = $version; + $this->level = $level; + } + + //---------------------------------------------------------------------- + public function getVersion() + { + return $this->version; + } + + //---------------------------------------------------------------------- + public function setVersion($version) + { + if($version < 0 || $version > QRSPEC_VERSION_MAX) { + throw new \Exception('Invalid version no'); + return -1; + } + + $this->version = $version; + + return 0; + } + + //---------------------------------------------------------------------- + public function getErrorCorrectionLevel() + { + return $this->level; + } + + //---------------------------------------------------------------------- + public function setErrorCorrectionLevel($level) + { + if($level > QR_ECLEVEL_H) { + throw new \Exception('Invalid ECLEVEL'); + return -1; + } + + $this->level = $level; + + return 0; + } + + //---------------------------------------------------------------------- + public function appendEntry(QRinputItem $entry) + { + $this->items[] = $entry; + } + + //---------------------------------------------------------------------- + public function append($mode, $size, $data) + { + try { + $entry = new QRinputItem($mode, $size, $data); + $this->items[] = $entry; + return 0; + } catch (Exception $e) { + return -1; + } + } + + //---------------------------------------------------------------------- + + public function insertStructuredAppendHeader($size, $index, $parity) + { + if( $size > MAX_STRUCTURED_SYMBOLS ) { + throw new \Exception('insertStructuredAppendHeader wrong size'); + } + + if( $index <= 0 || $index > MAX_STRUCTURED_SYMBOLS ) { + throw new \Exception('insertStructuredAppendHeader wrong index'); + } + + $buf = array($size, $index, $parity); + + try { + $entry = new QRinputItem(QR_MODE_STRUCTURE, 3, buf); + array_unshift($this->items, $entry); + return 0; + } catch (Exception $e) { + return -1; + } + } + + //---------------------------------------------------------------------- + public function calcParity() + { + $parity = 0; + + foreach($this->items as $item) { + if($item->mode != QR_MODE_STRUCTURE) { + for($i=$item->size-1; $i>=0; $i--) { + $parity ^= $item->data[$i]; + } + } + } + + return $parity; + } + + //---------------------------------------------------------------------- + public static function checkModeNum($size, $data) + { + for($i=0; $i<$size; $i++) { + if((ord($data[$i]) < ord('0')) || (ord($data[$i]) > ord('9'))){ + return false; + } + } + + return true; + } + + //---------------------------------------------------------------------- + public static function estimateBitsModeNum($size) + { + $w = (int)$size / 3; + $bits = $w * 10; + + switch($size - $w * 3) { + case 1: + $bits += 4; + break; + case 2: + $bits += 7; + break; + default: + break; + } + + return $bits; + } + + //---------------------------------------------------------------------- + public static $anTable = array( + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + 36, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 44, -1, -1, -1, -1, -1, + -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 + ); + + //---------------------------------------------------------------------- + public static function lookAnTable($c) + { + return (($c > 127)?-1:self::$anTable[$c]); + } + + //---------------------------------------------------------------------- + public static function checkModeAn($size, $data) + { + for($i=0; $i<$size; $i++) { + if (self::lookAnTable(ord($data[$i])) == -1) { + return false; + } + } + + return true; + } + + //---------------------------------------------------------------------- + public static function estimateBitsModeAn($size) + { + $w = (int)($size / 2); + $bits = $w * 11; + + if($size & 1) { + $bits += 6; + } + + return $bits; + } + + //---------------------------------------------------------------------- + public static function estimateBitsMode8($size) + { + return $size * 8; + } + + //---------------------------------------------------------------------- + public function estimateBitsModeKanji($size) + { + return (int)(($size / 2) * 13); + } + + //---------------------------------------------------------------------- + public static function checkModeKanji($size, $data) + { + if($size & 1) + return false; + + for($i=0; $i<$size; $i+=2) { + $val = (ord($data[$i]) << 8) | ord($data[$i+1]); + if( $val < 0x8140 + || ($val > 0x9ffc && $val < 0xe040) + || $val > 0xebbf) { + return false; + } + } + + return true; + } + + /*********************************************************************** + * Validation + **********************************************************************/ + + public static function check($mode, $size, $data) + { + if($size <= 0) + return false; + + switch($mode) { + case QR_MODE_NUM: return self::checkModeNum($size, $data); break; + case QR_MODE_AN: return self::checkModeAn($size, $data); break; + case QR_MODE_KANJI: return self::checkModeKanji($size, $data); break; + case QR_MODE_8: return true; break; + case QR_MODE_STRUCTURE: return true; break; + + default: + break; + } + + return false; + } + + + //---------------------------------------------------------------------- + public function estimateBitStreamSize($version) + { + $bits = 0; + + foreach($this->items as $item) { + $bits += $item->estimateBitStreamSizeOfEntry($version); + } + + return $bits; + } + + //---------------------------------------------------------------------- + public function estimateVersion() + { + $version = 0; + $prev = 0; + do { + $prev = $version; + $bits = $this->estimateBitStreamSize($prev); + $version = QRspec::getMinimumVersion((int)(($bits + 7) / 8), $this->level); + if ($version < 0) { + return -1; + } + } while ($version > $prev); + + return $version; + } + + //---------------------------------------------------------------------- + public static function lengthOfCode($mode, $version, $bits) + { + $payload = $bits - 4 - QRspec::lengthIndicator($mode, $version); + switch($mode) { + case QR_MODE_NUM: + $chunks = (int)($payload / 10); + $remain = $payload - $chunks * 10; + $size = $chunks * 3; + if($remain >= 7) { + $size += 2; + } else if($remain >= 4) { + $size += 1; + } + break; + case QR_MODE_AN: + $chunks = (int)($payload / 11); + $remain = $payload - $chunks * 11; + $size = $chunks * 2; + if($remain >= 6) + $size++; + break; + case QR_MODE_8: + $size = (int)($payload / 8); + break; + case QR_MODE_KANJI: + $size = (int)(($payload / 13) * 2); + break; + case QR_MODE_STRUCTURE: + $size = (int)($payload / 8); + break; + default: + $size = 0; + break; + } + + $maxsize = QRspec::maximumWords($mode, $version); + if($size < 0) $size = 0; + if($size > $maxsize) $size = $maxsize; + + return $size; + } + + //---------------------------------------------------------------------- + public function createBitStream() + { + $total = 0; + + foreach($this->items as $item) { + $bits = $item->encodeBitStream($this->version); + + if($bits < 0) + return -1; + + $total += $bits; + } + + return $total; + } + + //---------------------------------------------------------------------- + public function convertData() + { + $ver = $this->estimateVersion(); + if($ver > $this->getVersion()) { + $this->setVersion($ver); + } + + for(;;) { + $bits = $this->createBitStream(); + + if($bits < 0) + return -1; + + $ver = QRspec::getMinimumVersion((int)(($bits + 7) / 8), $this->level); + if($ver < 0) { + throw new \Exception('WRONG VERSION'); + return -1; + } else if($ver > $this->getVersion()) { + $this->setVersion($ver); + } else { + break; + } + } + + return 0; + } + + //---------------------------------------------------------------------- + public function appendPaddingBit(&$bstream) + { + $bits = $bstream->size(); + $maxwords = QRspec::getDataLength($this->version, $this->level); + $maxbits = $maxwords * 8; + + if ($maxbits == $bits) { + return 0; + } + + if ($maxbits - $bits < 5) { + return $bstream->appendNum($maxbits - $bits, 0); + } + + $bits += 4; + $words = (int)(($bits + 7) / 8); + + $padding = new QRbitstream(); + $ret = $padding->appendNum($words * 8 - $bits + 4, 0); + + if($ret < 0) + return $ret; + + $padlen = $maxwords - $words; + + if($padlen > 0) { + + $padbuf = array(); + for($i=0; $i<$padlen; $i++) { + $padbuf[$i] = ($i&1)?0x11:0xec; + } + + $ret = $padding->appendBytes($padlen, $padbuf); + + if($ret < 0) + return $ret; + + } + + $ret = $bstream->append($padding); + + return $ret; + } + + //---------------------------------------------------------------------- + public function mergeBitStream() + { + if($this->convertData() < 0) { + return null; + } + + $bstream = new QRbitstream(); + + foreach($this->items as $item) { + $ret = $bstream->append($item->bstream); + if($ret < 0) { + return null; + } + } + + return $bstream; + } + + //---------------------------------------------------------------------- + public function getBitStream() + { + + $bstream = $this->mergeBitStream(); + + if($bstream == null) { + return null; + } + + $ret = $this->appendPaddingBit($bstream); + if($ret < 0) { + return null; + } + + return $bstream; + } + + //---------------------------------------------------------------------- + public function getByteStream() + { + $bstream = $this->getBitStream(); + if($bstream == null) { + return null; + } + + return $bstream->toByte(); + } + } + + + + + + +//---- qrbitstream.php ----------------------------- + + + + +/* + * PHP QR Code encoder + * + * Bitstream class + * + * Based on libqrencode C library distributed under LGPL 2.1 + * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi + * + * PHP QR Code is distributed under LGPL 3 + * Copyright (C) 2010 Dominik Dzienia + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + class QRbitstream { + + public $data = array(); + + //---------------------------------------------------------------------- + public function size() + { + return count($this->data); + } + + //---------------------------------------------------------------------- + public function allocate($setLength) + { + $this->data = array_fill(0, $setLength, 0); + return 0; + } + + //---------------------------------------------------------------------- + public static function newFromNum($bits, $num) + { + $bstream = new QRbitstream(); + $bstream->allocate($bits); + + $mask = 1 << ($bits - 1); + for($i=0; $i<$bits; $i++) { + if($num & $mask) { + $bstream->data[$i] = 1; + } else { + $bstream->data[$i] = 0; + } + $mask = $mask >> 1; + } + + return $bstream; + } + + //---------------------------------------------------------------------- + public static function newFromBytes($size, $data) + { + $bstream = new QRbitstream(); + $bstream->allocate($size * 8); + $p=0; + + for($i=0; $i<$size; $i++) { + $mask = 0x80; + for($j=0; $j<8; $j++) { + if($data[$i] & $mask) { + $bstream->data[$p] = 1; + } else { + $bstream->data[$p] = 0; + } + $p++; + $mask = $mask >> 1; + } + } + + return $bstream; + } + + //---------------------------------------------------------------------- + public function append(QRbitstream $arg) + { + if (is_null($arg)) { + return -1; + } + + if($arg->size() == 0) { + return 0; + } + + if($this->size() == 0) { + $this->data = $arg->data; + return 0; + } + + $this->data = array_values(array_merge($this->data, $arg->data)); + + return 0; + } + + //---------------------------------------------------------------------- + public function appendNum($bits, $num) + { + if ($bits == 0) + return 0; + + $b = QRbitstream::newFromNum($bits, $num); + + if(is_null($b)) + return -1; + + $ret = $this->append($b); + unset($b); + + return $ret; + } + + //---------------------------------------------------------------------- + public function appendBytes($size, $data) + { + if ($size == 0) + return 0; + + $b = QRbitstream::newFromBytes($size, $data); + + if(is_null($b)) + return -1; + + $ret = $this->append($b); + unset($b); + + return $ret; + } + + //---------------------------------------------------------------------- + public function toByte() + { + + $size = $this->size(); + + if($size == 0) { + return array(); + } + + $data = array_fill(0, (int)(($size + 7) / 8), 0); + $bytes = (int)($size / 8); + + $p = 0; + + for($i=0; $i<$bytes; $i++) { + $v = 0; + for($j=0; $j<8; $j++) { + $v = $v << 1; + $v |= $this->data[$p]; + $p++; + } + $data[$i] = $v; + } + + if($size & 7) { + $v = 0; + for($j=0; $j<($size & 7); $j++) { + $v = $v << 1; + $v |= $this->data[$p]; + $p++; + } + $data[$bytes] = $v; + } + + return $data; + } + + } + + + + +//---- qrsplit.php ----------------------------- + + + + +/* + * PHP QR Code encoder + * + * Input splitting classes + * + * Based on libqrencode C library distributed under LGPL 2.1 + * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi + * + * PHP QR Code is distributed under LGPL 3 + * Copyright (C) 2010 Dominik Dzienia + * + * The following data / specifications are taken from + * "Two dimensional symbol -- QR-code -- Basic Specification" (JIS X0510:2004) + * or + * "Automatic identification and data capture techniques -- + * QR Code 2005 bar code symbology specification" (ISO/IEC 18004:2006) + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + class QRsplit { + + public $dataStr = ''; + public $input; + public $modeHint; + + //---------------------------------------------------------------------- + public function __construct($dataStr, $input, $modeHint) + { + $this->dataStr = $dataStr; + $this->input = $input; + $this->modeHint = $modeHint; + } + + //---------------------------------------------------------------------- + public static function isdigitat($str, $pos) + { + if ($pos >= strlen($str)) + return false; + + return ((ord($str[$pos]) >= ord('0'))&&(ord($str[$pos]) <= ord('9'))); + } + + //---------------------------------------------------------------------- + public static function isalnumat($str, $pos) + { + if ($pos >= strlen($str)) + return false; + + return (QRinput::lookAnTable(ord($str[$pos])) >= 0); + } + + //---------------------------------------------------------------------- + public function identifyMode($pos) + { + if ($pos >= strlen($this->dataStr)) + return QR_MODE_NUL; + + $c = $this->dataStr[$pos]; + + if(self::isdigitat($this->dataStr, $pos)) { + return QR_MODE_NUM; + } else if(self::isalnumat($this->dataStr, $pos)) { + return QR_MODE_AN; + } else if($this->modeHint == QR_MODE_KANJI) { + + if ($pos+1 < strlen($this->dataStr)) + { + $d = $this->dataStr[$pos+1]; + $word = (ord($c) << 8) | ord($d); + if(($word >= 0x8140 && $word <= 0x9ffc) || ($word >= 0xe040 && $word <= 0xebbf)) { + return QR_MODE_KANJI; + } + } + } + + return QR_MODE_8; + } + + //---------------------------------------------------------------------- + public function eatNum() + { + $ln = QRspec::lengthIndicator(QR_MODE_NUM, $this->input->getVersion()); + + $p = 0; + while(self::isdigitat($this->dataStr, $p)) { + $p++; + } + + $run = $p; + $mode = $this->identifyMode($p); + + if($mode == QR_MODE_8) { + $dif = QRinput::estimateBitsModeNum($run) + 4 + $ln + + QRinput::estimateBitsMode8(1) // + 4 + l8 + - QRinput::estimateBitsMode8($run + 1); // - 4 - l8 + if($dif > 0) { + return $this->eat8(); + } + } + if($mode == QR_MODE_AN) { + $dif = QRinput::estimateBitsModeNum($run) + 4 + $ln + + QRinput::estimateBitsModeAn(1) // + 4 + la + - QRinput::estimateBitsModeAn($run + 1);// - 4 - la + if($dif > 0) { + return $this->eatAn(); + } + } + + $ret = $this->input->append(QR_MODE_NUM, $run, str_split($this->dataStr)); + if($ret < 0) + return -1; + + return $run; + } + + //---------------------------------------------------------------------- + public function eatAn() + { + $la = QRspec::lengthIndicator(QR_MODE_AN, $this->input->getVersion()); + $ln = QRspec::lengthIndicator(QR_MODE_NUM, $this->input->getVersion()); + + $p = 0; + + while(self::isalnumat($this->dataStr, $p)) { + if(self::isdigitat($this->dataStr, $p)) { + $q = $p; + while(self::isdigitat($this->dataStr, $q)) { + $q++; + } + + $dif = QRinput::estimateBitsModeAn($p) // + 4 + la + + QRinput::estimateBitsModeNum($q - $p) + 4 + $ln + - QRinput::estimateBitsModeAn($q); // - 4 - la + + if($dif < 0) { + break; + } else { + $p = $q; + } + } else { + $p++; + } + } + + $run = $p; + + if(!self::isalnumat($this->dataStr, $p)) { + $dif = QRinput::estimateBitsModeAn($run) + 4 + $la + + QRinput::estimateBitsMode8(1) // + 4 + l8 + - QRinput::estimateBitsMode8($run + 1); // - 4 - l8 + if($dif > 0) { + return $this->eat8(); + } + } + + $ret = $this->input->append(QR_MODE_AN, $run, str_split($this->dataStr)); + if($ret < 0) + return -1; + + return $run; + } + + //---------------------------------------------------------------------- + public function eatKanji() + { + $p = 0; + + while($this->identifyMode($p) == QR_MODE_KANJI) { + $p += 2; + } + + $ret = $this->input->append(QR_MODE_KANJI, $p, str_split($this->dataStr)); + if($ret < 0) + return -1; + + return $run; + } + + //---------------------------------------------------------------------- + public function eat8() + { + $la = QRspec::lengthIndicator(QR_MODE_AN, $this->input->getVersion()); + $ln = QRspec::lengthIndicator(QR_MODE_NUM, $this->input->getVersion()); + + $p = 1; + $dataStrLen = strlen($this->dataStr); + + while($p < $dataStrLen) { + + $mode = $this->identifyMode($p); + if($mode == QR_MODE_KANJI) { + break; + } + if($mode == QR_MODE_NUM) { + $q = $p; + while(self::isdigitat($this->dataStr, $q)) { + $q++; + } + $dif = QRinput::estimateBitsMode8($p) // + 4 + l8 + + QRinput::estimateBitsModeNum($q - $p) + 4 + $ln + - QRinput::estimateBitsMode8($q); // - 4 - l8 + if($dif < 0) { + break; + } else { + $p = $q; + } + } else if($mode == QR_MODE_AN) { + $q = $p; + while(self::isalnumat($this->dataStr, $q)) { + $q++; + } + $dif = QRinput::estimateBitsMode8($p) // + 4 + l8 + + QRinput::estimateBitsModeAn($q - $p) + 4 + $la + - QRinput::estimateBitsMode8($q); // - 4 - l8 + if($dif < 0) { + break; + } else { + $p = $q; + } + } else { + $p++; + } + } + + $run = $p; + $ret = $this->input->append(QR_MODE_8, $run, str_split($this->dataStr)); + + if($ret < 0) + return -1; + + return $run; + } + + //---------------------------------------------------------------------- + public function splitString() + { + while (strlen($this->dataStr) > 0) + { + if($this->dataStr == '') + return 0; + + $mode = $this->identifyMode(0); + + switch ($mode) { + case QR_MODE_NUM: $length = $this->eatNum(); break; + case QR_MODE_AN: $length = $this->eatAn(); break; + case QR_MODE_KANJI: + if ($hint == QR_MODE_KANJI) + $length = $this->eatKanji(); + else $length = $this->eat8(); + break; + default: $length = $this->eat8(); break; + + } + + if($length == 0) return 0; + if($length < 0) return -1; + + $this->dataStr = substr($this->dataStr, $length); + } + } + + //---------------------------------------------------------------------- + public function toUpper() + { + $stringLen = strlen($this->dataStr); + $p = 0; + + while ($p<$stringLen) { + $mode = self::identifyMode(substr($this->dataStr, $p), $this->modeHint); + if($mode == QR_MODE_KANJI) { + $p += 2; + } else { + if (ord($this->dataStr[$p]) >= ord('a') && ord($this->dataStr[$p]) <= ord('z')) { + $this->dataStr[$p] = chr(ord($this->dataStr[$p]) - 32); + } + $p++; + } + } + + return $this->dataStr; + } + + //---------------------------------------------------------------------- + public static function splitStringToQRinput($string, QRinput $input, $modeHint, $casesensitive = true) + { + if(is_null($string) || $string == '\0' || $string == '') { + throw new \Exception('empty string!!!'); + } + + $split = new QRsplit($string, $input, $modeHint); + + if(!$casesensitive) + $split->toUpper(); + + return $split->splitString(); + } + } + + + +//---- qrrscode.php ----------------------------- + + + + +/* + * PHP QR Code encoder + * + * Reed-Solomon error correction support + * + * Copyright (C) 2002, 2003, 2004, 2006 Phil Karn, KA9Q + * (libfec is released under the GNU Lesser General Public License.) + * + * Based on libqrencode C library distributed under LGPL 2.1 + * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi + * + * PHP QR Code is distributed under LGPL 3 + * Copyright (C) 2010 Dominik Dzienia + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + class QRrsItem { + + public $mm; // Bits per symbol + public $nn; // Symbols per block (= (1<= $this->nn) { + $x -= $this->nn; + $x = ($x >> $this->mm) + ($x & $this->nn); + } + + return $x; + } + + //---------------------------------------------------------------------- + public static function init_rs_char($symsize, $gfpoly, $fcr, $prim, $nroots, $pad) + { + // Common code for intializing a Reed-Solomon control block (char or int symbols) + // Copyright 2004 Phil Karn, KA9Q + // May be used under the terms of the GNU Lesser General Public License (LGPL) + + $rs = null; + + // Check parameter ranges + if($symsize < 0 || $symsize > 8) return $rs; + if($fcr < 0 || $fcr >= (1<<$symsize)) return $rs; + if($prim <= 0 || $prim >= (1<<$symsize)) return $rs; + if($nroots < 0 || $nroots >= (1<<$symsize)) return $rs; // Can't have more roots than symbol values! + if($pad < 0 || $pad >= ((1<<$symsize) -1 - $nroots)) return $rs; // Too much padding + + $rs = new QRrsItem(); + $rs->mm = $symsize; + $rs->nn = (1<<$symsize)-1; + $rs->pad = $pad; + + $rs->alpha_to = array_fill(0, $rs->nn+1, 0); + $rs->index_of = array_fill(0, $rs->nn+1, 0); + + // PHP style macro replacement ;) + $NN =& $rs->nn; + $A0 =& $NN; + + // Generate Galois field lookup tables + $rs->index_of[0] = $A0; // log(zero) = -inf + $rs->alpha_to[$A0] = 0; // alpha**-inf = 0 + $sr = 1; + + for($i=0; $i<$rs->nn; $i++) { + $rs->index_of[$sr] = $i; + $rs->alpha_to[$i] = $sr; + $sr <<= 1; + if($sr & (1<<$symsize)) { + $sr ^= $gfpoly; + } + $sr &= $rs->nn; + } + + if($sr != 1){ + // field generator polynomial is not primitive! + $rs = NULL; + return $rs; + } + + /* Form RS code generator polynomial from its roots */ + $rs->genpoly = array_fill(0, $nroots+1, 0); + + $rs->fcr = $fcr; + $rs->prim = $prim; + $rs->nroots = $nroots; + $rs->gfpoly = $gfpoly; + + /* Find prim-th root of 1, used in decoding */ + for($iprim=1;($iprim % $prim) != 0;$iprim += $rs->nn) + ; // intentional empty-body loop! + + $rs->iprim = (int)($iprim / $prim); + $rs->genpoly[0] = 1; + + for ($i = 0,$root=$fcr*$prim; $i < $nroots; $i++, $root += $prim) { + $rs->genpoly[$i+1] = 1; + + // Multiply rs->genpoly[] by @**(root + x) + for ($j = $i; $j > 0; $j--) { + if ($rs->genpoly[$j] != 0) { + $rs->genpoly[$j] = $rs->genpoly[$j-1] ^ $rs->alpha_to[$rs->modnn($rs->index_of[$rs->genpoly[$j]] + $root)]; + } else { + $rs->genpoly[$j] = $rs->genpoly[$j-1]; + } + } + // rs->genpoly[0] can never be zero + $rs->genpoly[0] = $rs->alpha_to[$rs->modnn($rs->index_of[$rs->genpoly[0]] + $root)]; + } + + // convert rs->genpoly[] to index form for quicker encoding + for ($i = 0; $i <= $nroots; $i++) + $rs->genpoly[$i] = $rs->index_of[$rs->genpoly[$i]]; + + return $rs; + } + + //---------------------------------------------------------------------- + public function encode_rs_char($data, &$parity) + { + $MM =& $this->mm; + $NN =& $this->nn; + $ALPHA_TO =& $this->alpha_to; + $INDEX_OF =& $this->index_of; + $GENPOLY =& $this->genpoly; + $NROOTS =& $this->nroots; + $FCR =& $this->fcr; + $PRIM =& $this->prim; + $IPRIM =& $this->iprim; + $PAD =& $this->pad; + $A0 =& $NN; + + $parity = array_fill(0, $NROOTS, 0); + + for($i=0; $i< ($NN-$NROOTS-$PAD); $i++) { + + $feedback = $INDEX_OF[$data[$i] ^ $parity[0]]; + if($feedback != $A0) { + // feedback term is non-zero + + // This line is unnecessary when GENPOLY[NROOTS] is unity, as it must + // always be for the polynomials constructed by init_rs() + $feedback = $this->modnn($NN - $GENPOLY[$NROOTS] + $feedback); + + for($j=1;$j<$NROOTS;$j++) { + $parity[$j] ^= $ALPHA_TO[$this->modnn($feedback + $GENPOLY[$NROOTS-$j])]; + } + } + + // Shift + array_shift($parity); + if($feedback != $A0) { + array_push($parity, $ALPHA_TO[$this->modnn($feedback + $GENPOLY[0])]); + } else { + array_push($parity, 0); + } + } + } + } + + //########################################################################## + + class QRrs { + + public static $items = array(); + + //---------------------------------------------------------------------- + public static function init_rs($symsize, $gfpoly, $fcr, $prim, $nroots, $pad) + { + foreach(self::$items as $rs) { + if($rs->pad != $pad) continue; + if($rs->nroots != $nroots) continue; + if($rs->mm != $symsize) continue; + if($rs->gfpoly != $gfpoly) continue; + if($rs->fcr != $fcr) continue; + if($rs->prim != $prim) continue; + + return $rs; + } + + $rs = QRrsItem::init_rs_char($symsize, $gfpoly, $fcr, $prim, $nroots, $pad); + array_unshift(self::$items, $rs); + + return $rs; + } + } + + + +//---- qrmask.php ----------------------------- + + + + +/* + * PHP QR Code encoder + * + * Masking + * + * Based on libqrencode C library distributed under LGPL 2.1 + * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi + * + * PHP QR Code is distributed under LGPL 3 + * Copyright (C) 2010 Dominik Dzienia + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + define('N1', 3); + define('N2', 3); + define('N3', 40); + define('N4', 10); + + class QRmask { + + public $runLength = array(); + + //---------------------------------------------------------------------- + public function __construct() + { + $this->runLength = array_fill(0, QRSPEC_WIDTH_MAX + 1, 0); + } + + //---------------------------------------------------------------------- + public function writeFormatInformation($width, &$frame, $mask, $level) + { + $blacks = 0; + $format = QRspec::getFormatInfo($mask, $level); + + for($i=0; $i<8; $i++) { + if($format & 1) { + $blacks += 2; + $v = 0x85; + } else { + $v = 0x84; + } + + $frame[8][$width - 1 - $i] = chr($v); + if($i < 6) { + $frame[$i][8] = chr($v); + } else { + $frame[$i + 1][8] = chr($v); + } + $format = $format >> 1; + } + + for($i=0; $i<7; $i++) { + if($format & 1) { + $blacks += 2; + $v = 0x85; + } else { + $v = 0x84; + } + + $frame[$width - 7 + $i][8] = chr($v); + if($i == 0) { + $frame[8][7] = chr($v); + } else { + $frame[8][6 - $i] = chr($v); + } + + $format = $format >> 1; + } + + return $blacks; + } + + //---------------------------------------------------------------------- + public function mask0($x, $y) { return ($x+$y)&1; } + public function mask1($x, $y) { return ($y&1); } + public function mask2($x, $y) { return ($x%3); } + public function mask3($x, $y) { return ($x+$y)%3; } + public function mask4($x, $y) { return (((int)($y/2))+((int)($x/3)))&1; } + public function mask5($x, $y) { return (($x*$y)&1)+($x*$y)%3; } + public function mask6($x, $y) { return ((($x*$y)&1)+($x*$y)%3)&1; } + public function mask7($x, $y) { return ((($x*$y)%3)+(($x+$y)&1))&1; } + + //---------------------------------------------------------------------- + private function generateMaskNo($maskNo, $width, $frame) + { + $bitMask = array_fill(0, $width, array_fill(0, $width, 0)); + + for($y=0; $y<$width; $y++) { + for($x=0; $x<$width; $x++) { + if(ord($frame[$y][$x]) & 0x80) { + $bitMask[$y][$x] = 0; + } else { + $maskFunc = call_user_func(array($this, 'mask'.$maskNo), $x, $y); + $bitMask[$y][$x] = ($maskFunc == 0)?1:0; + } + + } + } + + return $bitMask; + } + + //---------------------------------------------------------------------- + public static function serial($bitFrame) + { + $codeArr = array(); + + foreach ($bitFrame as $line) + $codeArr[] = join('', $line); + + return gzcompress(join("\n", $codeArr), 9); + } + + //---------------------------------------------------------------------- + public static function unserial($code) + { + $codeArr = array(); + + $codeLines = explode("\n", gzuncompress($code)); + foreach ($codeLines as $line) + $codeArr[] = str_split($line); + + return $codeArr; + } + + //---------------------------------------------------------------------- + public function makeMaskNo($maskNo, $width, $s, &$d, $maskGenOnly = false) + { + $b = 0; + $bitMask = array(); + + $fileName = QR_CACHE_DIR.'mask_'.$maskNo.DIRECTORY_SEPARATOR.'mask_'.$width.'_'.$maskNo.'.dat'; + + if (QR_CACHEABLE) { + if (file_exists($fileName)) { + $bitMask = self::unserial(file_get_contents($fileName)); + } else { + $bitMask = $this->generateMaskNo($maskNo, $width, $s, $d); + if (!file_exists(QR_CACHE_DIR.'mask_'.$maskNo)) + mkdir(QR_CACHE_DIR.'mask_'.$maskNo); + file_put_contents($fileName, self::serial($bitMask)); + } + } else { + $bitMask = $this->generateMaskNo($maskNo, $width, $s, $d); + } + + if ($maskGenOnly) + return; + + $d = $s; + + for($y=0; $y<$width; $y++) { + for($x=0; $x<$width; $x++) { + if($bitMask[$y][$x] == 1) { + $d[$y][$x] = chr(ord($s[$y][$x]) ^ (int)$bitMask[$y][$x]); + } + $b += (int)(ord($d[$y][$x]) & 1); + } + } + + return $b; + } + + //---------------------------------------------------------------------- + public function makeMask($width, $frame, $maskNo, $level) + { + $masked = array_fill(0, $width, str_repeat("\0", $width)); + $this->makeMaskNo($maskNo, $width, $frame, $masked); + $this->writeFormatInformation($width, $masked, $maskNo, $level); + + return $masked; + } + + //---------------------------------------------------------------------- + public function calcN1N3($length) + { + $demerit = 0; + + for($i=0; $i<$length; $i++) { + + if($this->runLength[$i] >= 5) { + $demerit += (N1 + ($this->runLength[$i] - 5)); + } + if($i & 1) { + if(($i >= 3) && ($i < ($length-2)) && ($this->runLength[$i] % 3 == 0)) { + $fact = (int)($this->runLength[$i] / 3); + if(($this->runLength[$i-2] == $fact) && + ($this->runLength[$i-1] == $fact) && + ($this->runLength[$i+1] == $fact) && + ($this->runLength[$i+2] == $fact)) { + if(($this->runLength[$i-3] < 0) || ($this->runLength[$i-3] >= (4 * $fact))) { + $demerit += N3; + } else if((($i+3) >= $length) || ($this->runLength[$i+3] >= (4 * $fact))) { + $demerit += N3; + } + } + } + } + } + return $demerit; + } + + //---------------------------------------------------------------------- + public function evaluateSymbol($width, $frame) + { + $head = 0; + $demerit = 0; + + for($y=0; $y<$width; $y++) { + $head = 0; + $this->runLength[0] = 1; + + $frameY = $frame[$y]; + + if ($y>0) + $frameYM = $frame[$y-1]; + + for($x=0; $x<$width; $x++) { + if(($x > 0) && ($y > 0)) { + $b22 = ord($frameY[$x]) & ord($frameY[$x-1]) & ord($frameYM[$x]) & ord($frameYM[$x-1]); + $w22 = ord($frameY[$x]) | ord($frameY[$x-1]) | ord($frameYM[$x]) | ord($frameYM[$x-1]); + + if(($b22 | ($w22 ^ 1))&1) { + $demerit += N2; + } + } + if(($x == 0) && (ord($frameY[$x]) & 1)) { + $this->runLength[0] = -1; + $head = 1; + $this->runLength[$head] = 1; + } else if($x > 0) { + if((ord($frameY[$x]) ^ ord($frameY[$x-1])) & 1) { + $head++; + $this->runLength[$head] = 1; + } else { + $this->runLength[$head]++; + } + } + } + + $demerit += $this->calcN1N3($head+1); + } + + for($x=0; $x<$width; $x++) { + $head = 0; + $this->runLength[0] = 1; + + for($y=0; $y<$width; $y++) { + if($y == 0 && (ord($frame[$y][$x]) & 1)) { + $this->runLength[0] = -1; + $head = 1; + $this->runLength[$head] = 1; + } else if($y > 0) { + if((ord($frame[$y][$x]) ^ ord($frame[$y-1][$x])) & 1) { + $head++; + $this->runLength[$head] = 1; + } else { + $this->runLength[$head]++; + } + } + } + + $demerit += $this->calcN1N3($head+1); + } + + return $demerit; + } + + + //---------------------------------------------------------------------- + public function mask($width, $frame, $level) + { + $minDemerit = PHP_INT_MAX; + $bestMaskNum = 0; + $bestMask = array(); + + $checked_masks = array(0,1,2,3,4,5,6,7); + + if (QR_FIND_FROM_RANDOM !== false) { + + $howManuOut = 8-(QR_FIND_FROM_RANDOM % 9); + for ($i = 0; $i < $howManuOut; $i++) { + $remPos = rand (0, count($checked_masks)-1); + unset($checked_masks[$remPos]); + $checked_masks = array_values($checked_masks); + } + + } + + $bestMask = $frame; + + foreach($checked_masks as $i) { + $mask = array_fill(0, $width, str_repeat("\0", $width)); + + $demerit = 0; + $blacks = 0; + $blacks = $this->makeMaskNo($i, $width, $frame, $mask); + $blacks += $this->writeFormatInformation($width, $mask, $i, $level); + $blacks = (int)(100 * $blacks / ($width * $width)); + $demerit = (int)((int)(abs($blacks - 50) / 5) * N4); + $demerit += $this->evaluateSymbol($width, $mask); + + if($demerit < $minDemerit) { + $minDemerit = $demerit; + $bestMask = $mask; + $bestMaskNum = $i; + } + } + + return $bestMask; + } + + //---------------------------------------------------------------------- + } + + + + +//---- qrencode.php ----------------------------- + + + + +/* + * PHP QR Code encoder + * + * Main encoder classes. + * + * Based on libqrencode C library distributed under LGPL 2.1 + * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi + * + * PHP QR Code is distributed under LGPL 3 + * Copyright (C) 2010 Dominik Dzienia + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + class QRrsblock { + public $dataLength; + public $data = array(); + public $eccLength; + public $ecc = array(); + + public function __construct($dl, $data, $el, &$ecc, QRrsItem $rs) + { + $rs->encode_rs_char($data, $ecc); + + $this->dataLength = $dl; + $this->data = $data; + $this->eccLength = $el; + $this->ecc = $ecc; + } + }; + + //########################################################################## + + class QRrawcode { + public $version; + public $datacode = array(); + public $ecccode = array(); + public $blocks; + public $rsblocks = array(); //of RSblock + public $count; + public $dataLength; + public $eccLength; + public $b1; + + //---------------------------------------------------------------------- + public function __construct(QRinput $input) + { + $spec = array(0,0,0,0,0); + + $this->datacode = $input->getByteStream(); + if(is_null($this->datacode)) { + throw new \Exception('null imput string'); + } + + QRspec::getEccSpec($input->getVersion(), $input->getErrorCorrectionLevel(), $spec); + + $this->version = $input->getVersion(); + $this->b1 = QRspec::rsBlockNum1($spec); + $this->dataLength = QRspec::rsDataLength($spec); + $this->eccLength = QRspec::rsEccLength($spec); + $this->ecccode = array_fill(0, $this->eccLength, 0); + $this->blocks = QRspec::rsBlockNum($spec); + + $ret = $this->init($spec); + if($ret < 0) { + throw new \Exception('block alloc error'); + return null; + } + + $this->count = 0; + } + + //---------------------------------------------------------------------- + public function init(array $spec) + { + $dl = QRspec::rsDataCodes1($spec); + $el = QRspec::rsEccCodes1($spec); + $rs = QRrs::init_rs(8, 0x11d, 0, 1, $el, 255 - $dl - $el); + + + $blockNo = 0; + $dataPos = 0; + $eccPos = 0; + for($i=0; $iecccode,$eccPos); + $this->rsblocks[$blockNo] = new QRrsblock($dl, array_slice($this->datacode, $dataPos), $el, $ecc, $rs); + $this->ecccode = array_merge(array_slice($this->ecccode,0, $eccPos), $ecc); + + $dataPos += $dl; + $eccPos += $el; + $blockNo++; + } + + if(QRspec::rsBlockNum2($spec) == 0) + return 0; + + $dl = QRspec::rsDataCodes2($spec); + $el = QRspec::rsEccCodes2($spec); + $rs = QRrs::init_rs(8, 0x11d, 0, 1, $el, 255 - $dl - $el); + + if($rs == NULL) return -1; + + for($i=0; $iecccode,$eccPos); + $this->rsblocks[$blockNo] = new QRrsblock($dl, array_slice($this->datacode, $dataPos), $el, $ecc, $rs); + $this->ecccode = array_merge(array_slice($this->ecccode,0, $eccPos), $ecc); + + $dataPos += $dl; + $eccPos += $el; + $blockNo++; + } + + return 0; + } + + //---------------------------------------------------------------------- + public function getCode() + { + $ret; + + if($this->count < $this->dataLength) { + $row = $this->count % $this->blocks; + $col = $this->count / $this->blocks; + if($col >= $this->rsblocks[0]->dataLength) { + $row += $this->b1; + } + $ret = $this->rsblocks[$row]->data[$col]; + } else if($this->count < $this->dataLength + $this->eccLength) { + $row = ($this->count - $this->dataLength) % $this->blocks; + $col = ($this->count - $this->dataLength) / $this->blocks; + $ret = $this->rsblocks[$row]->ecc[$col]; + } else { + return 0; + } + $this->count++; + + return $ret; + } + } + + //########################################################################## + + class QRcode { + + public $version; + public $width; + public $data; + + //---------------------------------------------------------------------- + public function encodeMask(QRinput $input, $mask) + { + if($input->getVersion() < 0 || $input->getVersion() > QRSPEC_VERSION_MAX) { + throw new \Exception('wrong version'); + } + if($input->getErrorCorrectionLevel() > QR_ECLEVEL_H) { + throw new \Exception('wrong level'); + } + + $raw = new QRrawcode($input); + + QRtools::markTime('after_raw'); + + $version = $raw->version; + $width = QRspec::getWidth($version); + $frame = QRspec::newFrame($version); + + $filler = new FrameFiller($width, $frame); + if(is_null($filler)) { + return NULL; + } + + // inteleaved data and ecc codes + for($i=0; $i<$raw->dataLength + $raw->eccLength; $i++) { + $code = $raw->getCode(); + $bit = 0x80; + for($j=0; $j<8; $j++) { + $addr = $filler->next(); + $filler->setFrameAt($addr, 0x02 | (($bit & $code) != 0)); + $bit = $bit >> 1; + } + } + + QRtools::markTime('after_filler'); + + unset($raw); + + // remainder bits + $j = QRspec::getRemainder($version); + for($i=0; $i<$j; $i++) { + $addr = $filler->next(); + $filler->setFrameAt($addr, 0x02); + } + + $frame = $filler->frame; + unset($filler); + + + // masking + $maskObj = new QRmask(); + if($mask < 0) { + + if (QR_FIND_BEST_MASK) { + $masked = $maskObj->mask($width, $frame, $input->getErrorCorrectionLevel()); + } else { + $masked = $maskObj->makeMask($width, $frame, (intval(QR_DEFAULT_MASK) % 8), $input->getErrorCorrectionLevel()); + } + } else { + $masked = $maskObj->makeMask($width, $frame, $mask, $input->getErrorCorrectionLevel()); + } + + if($masked == NULL) { + return NULL; + } + + QRtools::markTime('after_mask'); + + $this->version = $version; + $this->width = $width; + $this->data = $masked; + + return $this; + } + + //---------------------------------------------------------------------- + public function encodeInput(QRinput $input) + { + return $this->encodeMask($input, -1); + } + + //---------------------------------------------------------------------- + public function encodeString8bit($string, $version, $level) + { + if(string == NULL) { + throw new \Exception('empty string!'); + return NULL; + } + + $input = new QRinput($version, $level); + if($input == NULL) return NULL; + + $ret = $input->append($input, QR_MODE_8, strlen($string), str_split($string)); + if($ret < 0) { + unset($input); + return NULL; + } + return $this->encodeInput($input); + } + + //---------------------------------------------------------------------- + public function encodeString($string, $version, $level, $hint, $casesensitive) + { + + if($hint != QR_MODE_8 && $hint != QR_MODE_KANJI) { + throw new \Exception('bad hint'); + return NULL; + } + + $input = new QRinput($version, $level); + if($input == NULL) return NULL; + + $ret = QRsplit::splitStringToQRinput($string, $input, $hint, $casesensitive); + if($ret < 0) { + return NULL; + } + + return $this->encodeInput($input); + } + + //---------------------------------------------------------------------- + public static function png($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4, $saveandprint=false) + { + $enc = QRencode::factory($level, $size, $margin); + return $enc->encodePNG($text, $outfile, $saveandprint=false); + } + + //---------------------------------------------------------------------- + public static function text($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4) + { + $enc = QRencode::factory($level, $size, $margin); + return $enc->encode($text, $outfile); + } + + //---------------------------------------------------------------------- + public static function raw($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4) + { + $enc = QRencode::factory($level, $size, $margin); + return $enc->encodeRAW($text, $outfile); + } + } + + //########################################################################## + + class FrameFiller { + + public $width; + public $frame; + public $x; + public $y; + public $dir; + public $bit; + + //---------------------------------------------------------------------- + public function __construct($width, &$frame) + { + $this->width = $width; + $this->frame = $frame; + $this->x = $width - 1; + $this->y = $width - 1; + $this->dir = -1; + $this->bit = -1; + } + + //---------------------------------------------------------------------- + public function setFrameAt($at, $val) + { + $this->frame[$at['y']][$at['x']] = chr($val); + } + + //---------------------------------------------------------------------- + public function getFrameAt($at) + { + return ord($this->frame[$at['y']][$at['x']]); + } + + //---------------------------------------------------------------------- + public function next() + { + do { + + if($this->bit == -1) { + $this->bit = 0; + return array('x'=>$this->x, 'y'=>$this->y); + } + + $x = $this->x; + $y = $this->y; + $w = $this->width; + + if($this->bit == 0) { + $x--; + $this->bit++; + } else { + $x++; + $y += $this->dir; + $this->bit--; + } + + if($this->dir < 0) { + if($y < 0) { + $y = 0; + $x -= 2; + $this->dir = 1; + if($x == 6) { + $x--; + $y = 9; + } + } + } else { + if($y == $w) { + $y = $w - 1; + $x -= 2; + $this->dir = -1; + if($x == 6) { + $x--; + $y -= 8; + } + } + } + if($x < 0 || $y < 0) return null; + + $this->x = $x; + $this->y = $y; + + } while(ord($this->frame[$y][$x]) & 0x80); + + return array('x'=>$x, 'y'=>$y); + } + + } ; + + //########################################################################## + + class QRencode { + + public $casesensitive = true; + public $eightbit = false; + + public $version = 0; + public $size = 3; + public $margin = 4; + + public $structured = 0; // not supported yet + + public $level = QR_ECLEVEL_L; + public $hint = QR_MODE_8; + + //---------------------------------------------------------------------- + public static function factory($level = QR_ECLEVEL_L, $size = 3, $margin = 4) + { + $enc = new QRencode(); + $enc->size = $size; + $enc->margin = $margin; + + switch ($level.'') { + case '0': + case '1': + case '2': + case '3': + $enc->level = $level; + break; + case 'l': + case 'L': + $enc->level = QR_ECLEVEL_L; + break; + case 'm': + case 'M': + $enc->level = QR_ECLEVEL_M; + break; + case 'q': + case 'Q': + $enc->level = QR_ECLEVEL_Q; + break; + case 'h': + case 'H': + $enc->level = QR_ECLEVEL_H; + break; + } + + return $enc; + } + + //---------------------------------------------------------------------- + public function encodeRAW($intext, $outfile = false) + { + $code = new QRcode(); + + if($this->eightbit) { + $code->encodeString8bit($intext, $this->version, $this->level); + } else { + $code->encodeString($intext, $this->version, $this->level, $this->hint, $this->casesensitive); + } + + return $code->data; + } + + //---------------------------------------------------------------------- + public function encode($intext, $outfile = false) + { + $code = new QRcode(); + + if($this->eightbit) { + $code->encodeString8bit($intext, $this->version, $this->level); + } else { + $code->encodeString($intext, $this->version, $this->level, $this->hint, $this->casesensitive); + } + + QRtools::markTime('after_encode'); + + if ($outfile!== false) { + file_put_contents($outfile, join("\n", QRtools::binarize($code->data))); + } else { + return QRtools::binarize($code->data); + } + } + + //---------------------------------------------------------------------- + public function encodePNG($intext, $outfile = false,$saveandprint=false) + { + try { + + ob_start(); + $tab = $this->encode($intext); + $err = ob_get_contents(); + ob_end_clean(); + + if ($err != '') + QRtools::log($outfile, $err); + + $maxSize = (int)(QR_PNG_MAXIMUM_SIZE / (count($tab)+2*$this->margin)); + + QRimage::png($tab, $outfile, min(max(1, $this->size), $maxSize), $this->margin,$saveandprint); + + } catch (Exception $e) { + + QRtools::log($outfile, $e->getMessage()); + + } + } + } + + diff --git a/niucloud/core/util/Queue.php b/niucloud/core/util/Queue.php index 743908f49..9c68c9860 100644 --- a/niucloud/core/util/Queue.php +++ b/niucloud/core/util/Queue.php @@ -11,8 +11,9 @@ namespace core\util; -use think\facade\Queue as ThinkQueue; +use Exception; use think\facade\Log; +use think\facade\Queue as ThinkQueue; /** * Class Queue @@ -78,6 +79,7 @@ class Queue * @var static */ protected static $instance; + protected function __construct() { $this->default_method = $this->method; @@ -122,7 +124,7 @@ class Queue if (!$res) { $res = ThinkQueue::{$this->action()}(...$jodValue); if (!$res) { - Log::error('队列推送失败,参数:' . json_encode($jodValue)); + Log::error('队列推送失败,参数:' . json_encode($jodValue, JSON_THROW_ON_ERROR)); } } $this->clean(); @@ -161,7 +163,7 @@ class Queue $jobData['method'] = $this->method; $jobData['error_count'] = $this->error_count; if ($this->method != $this->default_method) { - $this->job .= '@'.$this->method; + $this->job .= '@' . $this->method; } if ($this->secs) { return [$this->secs, $this->job, $jobData, $this->queue_name]; @@ -172,9 +174,12 @@ class Queue /** * 不可访问时调用 - * @param $name + * @param $method * @param $arguments * @return $this + * @throws Exception + * @throws Exception + * @throws Exception */ public function __call($method, $arguments) { @@ -186,7 +191,7 @@ class Queue } return $this; } else { - throw new \Exception('Method does not exist' . __CLASS__ . '->' . $method . '()'); + throw new Exception('Method does not exist' . __CLASS__ . '->' . $method . '()'); } } diff --git a/niucloud/core/util/Snowflake.php b/niucloud/core/util/Snowflake.php index 52717f1cd..84f2322c4 100644 --- a/niucloud/core/util/Snowflake.php +++ b/niucloud/core/util/Snowflake.php @@ -1,5 +1,9 @@ data_center_id = $data_center_id; - $this->machine_id = $machine_id; +// $this->data_center_id = $data_center_id; +// $this->machine_id = $machine_id; $this->last_timestamp = 0; $this->sequence = 0; } + /** + * @throws Exception + */ public function generateId() { $timestamp = $this->getTimestamp(); @@ -60,11 +67,10 @@ class Snowflake $this->last_timestamp = $timestamp; - $id = (($timestamp - self::START_EPOCH) << (self::SEQUENCE_BITS)) + return (($timestamp - self::START_EPOCH) << (self::SEQUENCE_BITS)) // | ($this->data_center_id << (self::SEQUENCE_BITS + self::MACHINE_ID_BITS)) // | ($this->machine_id << self::SEQUENCE_BITS) | $this->sequence; - return $id; } private function getTimestamp() diff --git a/niucloud/core/util/Terminal.php b/niucloud/core/util/Terminal.php index 3495a931c..964097e88 100644 --- a/niucloud/core/util/Terminal.php +++ b/niucloud/core/util/Terminal.php @@ -9,9 +9,10 @@ class Terminal * 执行命令 * @param string $cwd 要执行命令的初始工作目录 * @param string $command 要执行的命令 - * @return \think\Response + * @return string|true */ - public static function execute(string $cwd, string $command){ + public static function execute(string $cwd, string $command) + { if (!function_exists('proc_open') || !function_exists('proc_close')) return 'Function proc_open or proc_close disabled'; // 设置执行时长 @@ -47,7 +48,7 @@ class Terminal // 判断命令的执行结果 if ($status === 0) { - return strpos($output, 'Command failed') !== false ? $output : true; + return str_contains($output, 'Command failed') ? $output : true; } else { return $output; } diff --git a/niucloud/core/util/TokenAuth.php b/niucloud/core/util/TokenAuth.php index 8e988699f..f01be510f 100644 --- a/niucloud/core/util/TokenAuth.php +++ b/niucloud/core/util/TokenAuth.php @@ -14,6 +14,7 @@ namespace core\util; use Firebase\JWT\JWT; use think\facade\Cache; use think\facade\Env; +use think\Response; /** @@ -23,7 +24,6 @@ use think\facade\Env; */ class TokenAuth { - private $token; /** *创建token @@ -69,7 +69,7 @@ class TokenAuth { $payload = JWT::decode($token, Env::get('app.app_key', 'niucloud456$%^'), ['HS256']); if (!empty($payload)) { - $token_info = json_decode(json_encode($payload), true); + $token_info = json_decode(json_encode($payload), true, 512, JSON_THROW_ON_ERROR); if (explode("_", $token_info['jti'])[1] != $type) { return []; @@ -87,6 +87,8 @@ class TokenAuth * 清理token * @param int $id * @param string $type + * @param string|null $token + * @return Response */ public static function clearToken(int $id, string $type, ?string $token = '') { diff --git a/niucloud/core/util/barcode/class/BCGArgumentException.php b/niucloud/core/util/barcode/class/BCGArgumentException.php new file mode 100644 index 000000000..030f3e46b --- /dev/null +++ b/niucloud/core/util/barcode/class/BCGArgumentException.php @@ -0,0 +1,25 @@ +param = $param; + parent::__construct($message, 20000); + } +} +?> \ No newline at end of file diff --git a/niucloud/core/util/barcode/class/BCGBarcode.php b/niucloud/core/util/barcode/class/BCGBarcode.php new file mode 100644 index 000000000..317e773b7 --- /dev/null +++ b/niucloud/core/util/barcode/class/BCGBarcode.php @@ -0,0 +1,436 @@ +setOffsetX(0); + $this->setOffsetY(0); + $this->setForegroundColor(0x000000); + $this->setBackgroundColor(0xffffff); + $this->setScale(1); + } + + /** + * Parses the text before displaying it. + * + * @param mixed $text + */ + public function parse($text) { + } + + /** + * Gets the foreground color of the barcode. + * + * @return BCGColor + */ + public function getForegroundColor() { + return $this->colorFg; + } + + /** + * Sets the foreground color of the barcode. It could be a BCGColor + * value or simply a language code (white, black, yellow...) or hex value. + * + * @param mixed $code + */ + public function setForegroundColor($code) { + if ($code instanceof BCGColor) { + $this->colorFg = $code; + } else { + $this->colorFg = new BCGColor($code); + } + } + + /** + * Gets the background color of the barcode. + * + * @return BCGColor + */ + public function getBackgroundColor() { + return $this->colorBg; + } + + /** + * Sets the background color of the barcode. It could be a BCGColor + * value or simply a language code (white, black, yellow...) or hex value. + * + * @param mixed $code + */ + public function setBackgroundColor($code) { + if ($code instanceof BCGColor) { + $this->colorBg = $code; + } else { + $this->colorBg = new BCGColor($code); + } + + foreach ($this->labels as $label) { + $label->setBackgroundColor($this->colorBg); + } + } + + /** + * Sets the color. + * + * @param mixed $fg + * @param mixed $bg + */ + public function setColor($fg, $bg) { + $this->setForegroundColor($fg); + $this->setBackgroundColor($bg); + } + + /** + * Gets the scale of the barcode. + * + * @return int + */ + public function getScale() { + return $this->scale; + } + + /** + * Sets the scale of the barcode in pixel. + * If the scale is lower than 1, an exception is raised. + * + * @param int $scale + */ + public function setScale($scale) { + $scale = intval($scale); + if ($scale <= 0) { + throw new BCGArgumentException('The scale must be larger than 0.', 'scale'); + } + + $this->scale = $scale; + } + + /** + * Abstract method that draws the barcode on the resource. + * + * @param resource $im + */ + public abstract function draw($im); + + /** + * Returns the maximal size of a barcode. + * [0]->width + * [1]->height + * + * @param int $w + * @param int $h + * @return int[] + */ + public function getDimension($w, $h) { + $labels = $this->getBiggestLabels(false); + $pixelsAround = array(0, 0, 0, 0); // TRBL + if (isset($labels[BCGLabel::POSITION_TOP])) { + $dimension = $labels[BCGLabel::POSITION_TOP]->getDimension(); + $pixelsAround[0] += $dimension[1]; + } + + if (isset($labels[BCGLabel::POSITION_RIGHT])) { + $dimension = $labels[BCGLabel::POSITION_RIGHT]->getDimension(); + $pixelsAround[1] += $dimension[0]; + } + + if (isset($labels[BCGLabel::POSITION_BOTTOM])) { + $dimension = $labels[BCGLabel::POSITION_BOTTOM]->getDimension(); + $pixelsAround[2] += $dimension[1]; + } + + if (isset($labels[BCGLabel::POSITION_LEFT])) { + $dimension = $labels[BCGLabel::POSITION_LEFT]->getDimension(); + $pixelsAround[3] += $dimension[0]; + } + + $finalW = ($w + $this->offsetX) * $this->scale; + $finalH = ($h + $this->offsetY) * $this->scale; + + // This section will check if a top/bottom label is too big for its width and left/right too big for its height + $reversedLabels = $this->getBiggestLabels(true); + foreach ($reversedLabels as $label) { + $dimension = $label->getDimension(); + $alignment = $label->getAlignment(); + if ($label->getPosition() === BCGLabel::POSITION_LEFT || $label->getPosition() === BCGLabel::POSITION_RIGHT) { + if ($alignment === BCGLabel::ALIGN_TOP) { + $pixelsAround[2] = max($pixelsAround[2], $dimension[1] - $finalH); + } elseif ($alignment === BCGLabel::ALIGN_CENTER) { + $temp = ceil(($dimension[1] - $finalH) / 2); + $pixelsAround[0] = max($pixelsAround[0], $temp); + $pixelsAround[2] = max($pixelsAround[2], $temp); + } elseif ($alignment === BCGLabel::ALIGN_BOTTOM) { + $pixelsAround[0] = max($pixelsAround[0], $dimension[1] - $finalH); + } + } else { + if ($alignment === BCGLabel::ALIGN_LEFT) { + $pixelsAround[1] = max($pixelsAround[1], $dimension[0] - $finalW); + } elseif ($alignment === BCGLabel::ALIGN_CENTER) { + $temp = ceil(($dimension[0] - $finalW) / 2); + $pixelsAround[1] = max($pixelsAround[1], $temp); + $pixelsAround[3] = max($pixelsAround[3], $temp); + } elseif ($alignment === BCGLabel::ALIGN_RIGHT) { + $pixelsAround[3] = max($pixelsAround[3], $dimension[0] - $finalW); + } + } + } + + $this->pushLabel[0] = $pixelsAround[3]; + $this->pushLabel[1] = $pixelsAround[0]; + + $finalW = ($w + $this->offsetX) * $this->scale + $pixelsAround[1] + $pixelsAround[3]; + $finalH = ($h + $this->offsetY) * $this->scale + $pixelsAround[0] + $pixelsAround[2]; + + return array($finalW, $finalH); + } + + /** + * Gets the X offset. + * + * @return int + */ + public function getOffsetX() { + return $this->offsetX; + } + + /** + * Sets the X offset. + * + * @param int $offsetX + */ + public function setOffsetX($offsetX) { + $offsetX = intval($offsetX); + if ($offsetX < 0) { + throw new BCGArgumentException('The offset X must be 0 or larger.', 'offsetX'); + } + + $this->offsetX = $offsetX; + } + + /** + * Gets the Y offset. + * + * @return int + */ + public function getOffsetY() { + return $this->offsetY; + } + + /** + * Sets the Y offset. + * + * @param int $offsetY + */ + public function setOffsetY($offsetY) { + $offsetY = intval($offsetY); + if ($offsetY < 0) { + throw new BCGArgumentException('The offset Y must be 0 or larger.', 'offsetY'); + } + + $this->offsetY = $offsetY; + } + + /** + * Adds the label to the drawing. + * + * @param BCGLabel $label + */ + public function addLabel(BCGLabel $label) { + $label->setBackgroundColor($this->colorBg); + $this->labels[] = $label; + } + + /** + * Removes the label from the drawing. + * + * @param BCGLabel $label + */ + public function removeLabel(BCGLabel $label) { + $remove = -1; + $c = count($this->labels); + for ($i = 0; $i < $c; $i++) { + if ($this->labels[$i] === $label) { + $remove = $i; + break; + } + } + + if ($remove > -1) { + array_splice($this->labels, $remove, 1); + } + } + + /** + * Clears the labels. + */ + public function clearLabels() { + $this->labels = array(); + } + + /** + * Draws the text. + * The coordinate passed are the positions of the barcode. + * $x1 and $y1 represent the top left corner. + * $x2 and $y2 represent the bottom right corner. + * + * @param resource $im + * @param int $x1 + * @param int $y1 + * @param int $x2 + * @param int $y2 + */ + protected function drawText($im, $x1, $y1, $x2, $y2) { + foreach ($this->labels as $label) { + $label->draw($im, + ($x1 + $this->offsetX) * $this->scale + $this->pushLabel[0], + ($y1 + $this->offsetY) * $this->scale + $this->pushLabel[1], + ($x2 + $this->offsetX) * $this->scale + $this->pushLabel[0], + ($y2 + $this->offsetY) * $this->scale + $this->pushLabel[1]); + } + } + + /** + * Draws 1 pixel on the resource at a specific position with a determined color. + * + * @param resource $im + * @param int $x + * @param int $y + * @param int $color + */ + protected function drawPixel($im, $x, $y, $color = self::COLOR_FG) { + $xR = ($x + $this->offsetX) * $this->scale + $this->pushLabel[0]; + $yR = ($y + $this->offsetY) * $this->scale + $this->pushLabel[1]; + + // We always draw a rectangle + imagefilledrectangle($im, + $xR, + $yR, + $xR + $this->scale - 1, + $yR + $this->scale - 1, + $this->getColor($im, $color)); + } + + /** + * Draws an empty rectangle on the resource at a specific position with a determined color. + * + * @param resource $im + * @param int $x1 + * @param int $y1 + * @param int $x2 + * @param int $y2 + * @param int $color + */ + protected function drawRectangle($im, $x1, $y1, $x2, $y2, $color = self::COLOR_FG) { + if ($this->scale === 1) { + imagefilledrectangle($im, + ($x1 + $this->offsetX) + $this->pushLabel[0], + ($y1 + $this->offsetY) + $this->pushLabel[1], + ($x2 + $this->offsetX) + $this->pushLabel[0], + ($y2 + $this->offsetY) + $this->pushLabel[1], + $this->getColor($im, $color)); + } else { + imagefilledrectangle($im, ($x1 + $this->offsetX) * $this->scale + $this->pushLabel[0], ($y1 + $this->offsetY) * $this->scale + $this->pushLabel[1], ($x2 + $this->offsetX) * $this->scale + $this->pushLabel[0] + $this->scale - 1, ($y1 + $this->offsetY) * $this->scale + $this->pushLabel[1] + $this->scale - 1, $this->getColor($im, $color)); + imagefilledrectangle($im, ($x1 + $this->offsetX) * $this->scale + $this->pushLabel[0], ($y1 + $this->offsetY) * $this->scale + $this->pushLabel[1], ($x1 + $this->offsetX) * $this->scale + $this->pushLabel[0] + $this->scale - 1, ($y2 + $this->offsetY) * $this->scale + $this->pushLabel[1] + $this->scale - 1, $this->getColor($im, $color)); + imagefilledrectangle($im, ($x2 + $this->offsetX) * $this->scale + $this->pushLabel[0], ($y1 + $this->offsetY) * $this->scale + $this->pushLabel[1], ($x2 + $this->offsetX) * $this->scale + $this->pushLabel[0] + $this->scale - 1, ($y2 + $this->offsetY) * $this->scale + $this->pushLabel[1] + $this->scale - 1, $this->getColor($im, $color)); + imagefilledrectangle($im, ($x1 + $this->offsetX) * $this->scale + $this->pushLabel[0], ($y2 + $this->offsetY) * $this->scale + $this->pushLabel[1], ($x2 + $this->offsetX) * $this->scale + $this->pushLabel[0] + $this->scale - 1, ($y2 + $this->offsetY) * $this->scale + $this->pushLabel[1] + $this->scale - 1, $this->getColor($im, $color)); + } + } + + /** + * Draws a filled rectangle on the resource at a specific position with a determined color. + * + * @param resource $im + * @param int $x1 + * @param int $y1 + * @param int $x2 + * @param int $y2 + * @param int $color + */ + protected function drawFilledRectangle($im, $x1, $y1, $x2, $y2, $color = self::COLOR_FG) { + if ($x1 > $x2) { // Swap + $x1 ^= $x2 ^= $x1 ^= $x2; + } + + if ($y1 > $y2) { // Swap + $y1 ^= $y2 ^= $y1 ^= $y2; + } + + imagefilledrectangle($im, + ($x1 + $this->offsetX) * $this->scale + $this->pushLabel[0], + ($y1 + $this->offsetY) * $this->scale + $this->pushLabel[1], + ($x2 + $this->offsetX) * $this->scale + $this->pushLabel[0] + $this->scale - 1, + ($y2 + $this->offsetY) * $this->scale + $this->pushLabel[1] + $this->scale - 1, + $this->getColor($im, $color)); + } + + /** + * Allocates the color based on the integer. + * + * @param resource $im + * @param int $color + * @return resource + */ + protected function getColor($im, $color) { + if ($color === self::COLOR_BG) { + return $this->colorBg->allocate($im); + } else { + return $this->colorFg->allocate($im); + } + } + + /** + * Returning the biggest label widths for LEFT/RIGHT and heights for TOP/BOTTOM. + * + * @param bool $reversed + * @return BCGLabel[] + */ + private function getBiggestLabels($reversed = false) { + $searchLR = $reversed ? 1 : 0; + $searchTB = $reversed ? 0 : 1; + + $labels = array(); + foreach ($this->labels as $label) { + $position = $label->getPosition(); + if (isset($labels[$position])) { + $savedDimension = $labels[$position]->getDimension(); + $dimension = $label->getDimension(); + if ($position === BCGLabel::POSITION_LEFT || $position === BCGLabel::POSITION_RIGHT) { + if ($dimension[$searchLR] > $savedDimension[$searchLR]) { + $labels[$position] = $label; + } + } else { + if ($dimension[$searchTB] > $savedDimension[$searchTB]) { + $labels[$position] = $label; + } + } + } else { + $labels[$position] = $label; + } + } + + return $labels; + } +} +?> \ No newline at end of file diff --git a/niucloud/core/util/barcode/class/BCGBarcode1D.php b/niucloud/core/util/barcode/class/BCGBarcode1D.php new file mode 100644 index 000000000..7202a8cbe --- /dev/null +++ b/niucloud/core/util/barcode/class/BCGBarcode1D.php @@ -0,0 +1,259 @@ +setThickness(30); + + $this->defaultLabel = new BCGLabel(); + $this->defaultLabel->setPosition(BCGLabel::POSITION_BOTTOM); + $this->setLabel(self::AUTO_LABEL); + $this->setFont(new BCGFontPhp(5)); + + $this->text = ''; + $this->checksumValue = false; + $this->positionX = 0; + } + + /** + * Gets the thickness. + * + * @return int + */ + public function getThickness() { + return $this->thickness; + } + + /** + * Sets the thickness. + * + * @param int $thickness + */ + public function setThickness($thickness) { + $thickness = intval($thickness); + if ($thickness <= 0) { + throw new BCGArgumentException('The thickness must be larger than 0.', 'thickness'); + } + + $this->thickness = $thickness; + } + + /** + * Gets the label. + * If the label was set to BCGBarcode1D::AUTO_LABEL, the label will display the value from the text parsed. + * + * @return string + */ + public function getLabel() { + $label = $this->label; + if ($this->label === self::AUTO_LABEL) { + $label = $this->text; + if ($this->displayChecksum === true && ($checksum = $this->processChecksum()) !== false) { + $label .= $checksum; + } + } + + return $label; + } + + /** + * Sets the label. + * You can use BCGBarcode::AUTO_LABEL to have the label automatically written based on the parsed text. + * + * @param string $label + */ + public function setLabel($label) { + $this->label = $label; + } + + /** + * Gets the font. + * + * @return BCGFont + */ + public function getFont() { + return $this->font; + } + + /** + * Sets the font. + * + * @param mixed $font BCGFont or int + */ + public function setFont($font) { + if (is_int($font)) { + if ($font === 0) { + $font = null; + } else { + $font = new BCGFontPhp($font); + } + } + + $this->font = $font; + } + + /** + * Parses the text before displaying it. + * + * @param mixed $text + */ + public function parse($text) { + $this->text = $text; + $this->checksumValue = false; // Reset checksumValue + $this->validate(); + + parent::parse($text); + + $this->addDefaultLabel(); + } + + /** + * Gets the checksum of a Barcode. + * If no checksum is available, return FALSE. + * + * @return string + */ + public function getChecksum() { + return $this->processChecksum(); + } + + /** + * Sets if the checksum is displayed with the label or not. + * The checksum must be activated in some case to make this variable effective. + * + * @param boolean $displayChecksum + */ + public function setDisplayChecksum($displayChecksum) { + $this->displayChecksum = (bool)$displayChecksum; + } + + /** + * Adds the default label. + */ + protected function addDefaultLabel() { + $label = $this->getLabel(); + $font = $this->font; + if ($label !== null && $label !== '' && $font !== null && $this->defaultLabel !== null) { + $this->defaultLabel->setText($label); + $this->defaultLabel->setFont($font); + $this->addLabel($this->defaultLabel); + } + } + + /** + * Validates the input + */ + protected function validate() { + // No validation in the abstract class. + } + + /** + * Returns the index in $keys (useful for checksum). + * + * @param mixed $var + * @return mixed + */ + protected function findIndex($var) { + return array_search($var, $this->keys); + } + + /** + * Returns the code of the char (useful for drawing bars). + * + * @param mixed $var + * @return string + */ + protected function findCode($var) { + return $this->code[$this->findIndex($var)]; + } + + /** + * Draws all chars thanks to $code. If $startBar is true, the line begins by a space. + * If $startBar is false, the line begins by a bar. + * + * @param resource $im + * @param string $code + * @param boolean $startBar + */ + protected function drawChar($im, $code, $startBar = true) { + $colors = array(BCGBarcode::COLOR_FG, BCGBarcode::COLOR_BG); + $currentColor = $startBar ? 0 : 1; + $c = strlen($code); + for ($i = 0; $i < $c; $i++) { + for ($j = 0; $j < intval($code[$i]) + 1; $j++) { + $this->drawSingleBar($im, $colors[$currentColor]); + $this->nextX(); + } + + $currentColor = ($currentColor + 1) % 2; + } + } + + /** + * Draws a Bar of $color depending of the resolution. + * + * @param resource $img + * @param int $color + */ + protected function drawSingleBar($im, $color) { + $this->drawFilledRectangle($im, $this->positionX, 0, $this->positionX, $this->thickness - 1, $color); + } + + /** + * Moving the pointer right to write a bar. + */ + protected function nextX() { + $this->positionX++; + } + + /** + * Method that saves FALSE into the checksumValue. This means no checksum + * but this method should be overriden when needed. + */ + protected function calculateChecksum() { + $this->checksumValue = false; + } + + /** + * Returns FALSE because there is no checksum. This method should be + * overriden to return correctly the checksum in string with checksumValue. + * + * @return string + */ + protected function processChecksum() { + return false; + } +} +?> \ No newline at end of file diff --git a/niucloud/core/util/barcode/class/BCGColor.php b/niucloud/core/util/barcode/class/BCGColor.php new file mode 100644 index 000000000..7bd0650d4 --- /dev/null +++ b/niucloud/core/util/barcode/class/BCGColor.php @@ -0,0 +1,154 @@ +r = intval($args[0]); + $this->g = intval($args[1]); + $this->b = intval($args[2]); + } elseif ($c === 1) { + if (is_string($args[0]) && strlen($args[0]) === 7 && $args[0][0] === '#') { // Hex Value in String + $this->r = intval(substr($args[0], 1, 2), 16); + $this->g = intval(substr($args[0], 3, 2), 16); + $this->b = intval(substr($args[0], 5, 2), 16); + } else { + if (is_string($args[0])) { + $args[0] = self::getColor($args[0]); + } + + $args[0] = intval($args[0]); + $this->r = ($args[0] & 0xff0000) >> 16; + $this->g = ($args[0] & 0x00ff00) >> 8; + $this->b = ($args[0] & 0x0000ff); + } + } else { + $this->r = $this->g = $this->b = 0; + } + } + + /** + * Sets the color transparent. + * + * @param bool $transparent + */ + public function setTransparent($transparent) { + $this->transparent = $transparent; + } + + /** + * Returns Red Color. + * + * @return int + */ + public function r() { + return $this->r; + } + + /** + * Returns Green Color. + * + * @return int + */ + public function g() { + return $this->g; + } + + /** + * Returns Blue Color. + * + * @return int + */ + public function b() { + return $this->b; + } + + /** + * Returns the int value for PHP color. + * + * @param resource $im + * @return int + */ + public function allocate(&$im) { + $allocated = imagecolorallocate($im, $this->r, $this->g, $this->b); + if ($this->transparent) { + return imagecolortransparent($im, $allocated); + } else { + return $allocated; + } + } + + /** + * Returns class of BCGColor depending of the string color. + * + * If the color doens't exist, it takes the default one. + * + * @param string $code + * @param string $default + */ + public static function getColor($code, $default = 'white') { + switch(strtolower($code)) { + case '': + case 'white': + return 0xffffff; + case 'black': + return 0x000000; + case 'maroon': + return 0x800000; + case 'red': + return 0xff0000; + case 'orange': + return 0xffa500; + case 'yellow': + return 0xffff00; + case 'olive': + return 0x808000; + case 'purple': + return 0x800080; + case 'fuchsia': + return 0xff00ff; + case 'lime': + return 0x00ff00; + case 'green': + return 0x008000; + case 'navy': + return 0x000080; + case 'blue': + return 0x0000ff; + case 'aqua': + return 0x00ffff; + case 'teal': + return 0x008080; + case 'silver': + return 0xc0c0c0; + case 'gray': + return 0x808080; + default: + return self::getColor($default, 'white'); + } + } +} +?> \ No newline at end of file diff --git a/niucloud/core/util/barcode/class/BCGDrawException.php b/niucloud/core/util/barcode/class/BCGDrawException.php new file mode 100644 index 000000000..792732d31 --- /dev/null +++ b/niucloud/core/util/barcode/class/BCGDrawException.php @@ -0,0 +1,21 @@ + \ No newline at end of file diff --git a/niucloud/core/util/barcode/class/BCGDrawing.php b/niucloud/core/util/barcode/class/BCGDrawing.php new file mode 100644 index 000000000..612522cfd --- /dev/null +++ b/niucloud/core/util/barcode/class/BCGDrawing.php @@ -0,0 +1,248 @@ +im = null; + $this->setFilename($filename); + $this->color = $color; + $this->dpi = null; + $this->rotateDegree = 0.0; + } + + /** + * Destructor. + */ + public function __destruct() { + $this->destroy(); + } + + /** + * Gets the filename. + * + * @return string + */ + public function getFilename() { + return $this->filename; + } + + /** + * Sets the filename. + * + * @param string $filaneme + */ + public function setFilename($filename) { + $this->filename = $filename; + } + + /** + * @return resource. + */ + public function get_im() { + return $this->im; + } + + /** + * Sets the image. + * + * @param resource $im + */ + public function set_im($im) { + $this->im = $im; + } + + /** + * Gets Barcode for drawing. + * + * @return BCGBarcode + */ + public function getBarcode() { + return $this->barcode; + } + + /** + * Sets Barcode for drawing. + * + * @param BCGBarcode $Barcode + */ + public function setBarcode(BCGBarcode $barcode) { + $this->barcode = $barcode; + } + + /** + * Gets the DPI for supported filetype. + * + * @return float + */ + public function getDPI() { + return $this->dpi; + } + + /** + * Sets the DPI for supported filetype. + * + * @param float $dpi + */ + public function setDPI($dpi) { + $this->dpi = $dpi; + } + + /** + * Gets the rotation angle in degree clockwise. + * + * @return float + */ + public function getRotationAngle() { + return $this->rotateDegree; + } + + /** + * Sets the rotation angle in degree clockwise. + * + * @param float $degree + */ + public function setRotationAngle($degree) { + $this->rotateDegree = (float)$degree; + } + + /** + * Draws the Barcode on the image $im. + */ + public function draw() { + $size = $this->barcode->getDimension(0, 0); + $this->w = max(1, $size[0]); + $this->h = max(1, $size[1]); + $this->init(); + $this->barcode->draw($this->im); + } + + /** + * Saves $im into the file (many format available). + * + * @param int $image_style + * @param int $quality + */ + public function finish($image_style = self::IMG_FORMAT_PNG, $quality = 100) { + $drawer = null; + + $im = $this->im; + if ($this->rotateDegree > 0.0) { + if (function_exists('imagerotate')) { + $im = imagerotate($this->im, 360 - $this->rotateDegree, $this->color->allocate($this->im)); + } else { + throw new BCGDrawException('The method imagerotate doesn\'t exist on your server. Do not use any rotation.'); + } + } + + if ($image_style === self::IMG_FORMAT_PNG) { + $drawer = new BCGDrawPNG($im); + $drawer->setFilename($this->filename); + $drawer->setDPI($this->dpi); + } elseif ($image_style === self::IMG_FORMAT_JPEG) { + $drawer = new BCGDrawJPG($im); + $drawer->setFilename($this->filename); + $drawer->setDPI($this->dpi); + $drawer->setQuality($quality); + } elseif ($image_style === self::IMG_FORMAT_GIF) { + // Some PHP versions have a bug if passing 2nd argument as null. + if ($this->filename === null || $this->filename === '') { + imagegif($im); + } else { + imagegif($im, $this->filename); + } + } elseif ($image_style === self::IMG_FORMAT_WBMP) { + imagewbmp($im, $this->filename); + } + + if ($drawer !== null) { + $drawer->draw(); + } + } + + /** + * Writes the Error on the picture. + * + * @param Exception $exception + */ + public function drawException($exception) { + $this->w = 1; + $this->h = 1; + $this->init(); + + // Is the image big enough? + $w = imagesx($this->im); + $h = imagesy($this->im); + + $text = 'Error: ' . $exception->getMessage(); + + $width = imagefontwidth(2) * strlen($text); + $height = imagefontheight(2); + if ($width > $w || $height > $h) { + $width = max($w, $width); + $height = max($h, $height); + + // We change the size of the image + $newimg = imagecreatetruecolor($width, $height); + imagefill($newimg, 0, 0, imagecolorat($this->im, 0, 0)); + imagecopy($newimg, $this->im, 0, 0, 0, 0, $w, $h); + $this->im = $newimg; + } + + $black = new BCGColor('black'); + imagestring($this->im, 2, 0, 0, $text, $black->allocate($this->im)); + } + + /** + * Free the memory of PHP (called also by destructor). + */ + public function destroy() { + @imagedestroy($this->im); + } + + /** + * Init Image and color background. + */ + private function init() { + if ($this->im === null) { + $this->im = imagecreatetruecolor($this->w, $this->h) + or die('Can\'t Initialize the GD Libraty'); + imagefilledrectangle($this->im, 0, 0, $this->w - 1, $this->h - 1, $this->color->allocate($this->im)); + } + } +} +?> \ No newline at end of file diff --git a/niucloud/core/util/barcode/class/BCGFont.php b/niucloud/core/util/barcode/class/BCGFont.php new file mode 100644 index 000000000..c58c0de3d --- /dev/null +++ b/niucloud/core/util/barcode/class/BCGFont.php @@ -0,0 +1,23 @@ + \ No newline at end of file diff --git a/niucloud/core/util/barcode/class/BCGFontFile.php b/niucloud/core/util/barcode/class/BCGFontFile.php new file mode 100644 index 000000000..4c304eb54 --- /dev/null +++ b/niucloud/core/util/barcode/class/BCGFontFile.php @@ -0,0 +1,209 @@ +path = $fontPath; + $this->size = $size; + $this->foregroundColor = new BCGColor('black'); + $this->setRotationAngle(0); + $this->setBoxFix(self::PHP_BOX_FIX); + } + + /** + * Gets the text associated to the font. + * + * @return string + */ + public function getText() { + return $this->text; + } + + /** + * Sets the text associated to the font. + * + * @param string text + */ + public function setText($text) { + $this->text = $text; + $this->box = null; + } + + /** + * Gets the rotation in degree. + * + * @return int + */ + public function getRotationAngle() { + return (360 - $this->rotationAngle) % 360; + } + + /** + * Sets the rotation in degree. + * + * @param int + */ + public function setRotationAngle($rotationAngle) { + $this->rotationAngle = (int)$rotationAngle; + if ($this->rotationAngle !== 90 && $this->rotationAngle !== 180 && $this->rotationAngle !== 270) { + $this->rotationAngle = 0; + } + + $this->rotationAngle = (360 - $this->rotationAngle) % 360; + + $this->box = null; + } + + /** + * Gets the background color. + * + * @return BCGColor + */ + public function getBackgroundColor() { + } + + /** + * Sets the background color. + * + * @param BCGColor $backgroundColor + */ + public function setBackgroundColor($backgroundColor) { + } + + /** + * Gets the foreground color. + * + * @return BCGColor + */ + public function getForegroundColor() { + return $this->foregroundColor; + } + + /** + * Sets the foreground color. + * + * @param BCGColor $foregroundColor + */ + public function setForegroundColor($foregroundColor) { + $this->foregroundColor = $foregroundColor; + } + + /** + * Gets the box fix information. + * + * @return int + */ + public function getBoxFix() { + return $this->boxFix; + } + + /** + * Sets the box fix information. + * + * @param int $value + */ + public function setBoxFix($value) { + $this->boxFix = intval($value); + } + + /** + * Returns the width and height that the text takes to be written. + * + * @return int[] + */ + public function getDimension() { + $w = 0.0; + $h = 0.0; + $box = $this->getBox(); + + if ($box !== null) { + $minX = min(array($box[0], $box[2], $box[4], $box[6])); + $maxX = max(array($box[0], $box[2], $box[4], $box[6])); + $minY = min(array($box[1], $box[3], $box[5], $box[7])); + $maxY = max(array($box[1], $box[3], $box[5], $box[7])); + + $w = $maxX - $minX; + $h = $maxY - $minY; + } + + $rotationAngle = $this->getRotationAngle(); + if ($rotationAngle === 90 || $rotationAngle === 270) { + return array($h + self::PHP_BOX_FIX, $w); + } else { + return array($w + self::PHP_BOX_FIX, $h); + } + } + + /** + * Draws the text on the image at a specific position. + * $x and $y represent the left bottom corner. + * + * @param resource $im + * @param int $x + * @param int $y + */ + public function draw($im, $x, $y) { + $drawingPosition = $this->getDrawingPosition($x, $y); + imagettftext($im, $this->size, $this->rotationAngle, $drawingPosition[0], $drawingPosition[1], $this->foregroundColor->allocate($im), $this->path, $this->text); + } + + private function getDrawingPosition($x, $y) { + $dimension = $this->getDimension(); + $box = $this->getBox(); + $rotationAngle = $this->getRotationAngle(); + if ($rotationAngle === 0) { + $y += abs(min($box[5], $box[7])); + } elseif ($rotationAngle === 90) { + $x += abs(min($box[5], $box[7])); + $y += $dimension[1]; + } elseif ($rotationAngle === 180) { + $x += $dimension[0]; + $y += abs(max($box[1], $box[3])); + } elseif ($rotationAngle === 270) { + $x += abs(max($box[1], $box[3])); + } + + return array($x, $y); + } + + private function getBox() { + if ($this->box === null) { + $gd = imagecreate(1, 1); + $this->box = imagettftext($gd, $this->size, 0, 0, 0, 0, $this->path, $this->text); + } + + return $this->box; + } +} +?> \ No newline at end of file diff --git a/niucloud/core/util/barcode/class/BCGFontPhp.php b/niucloud/core/util/barcode/class/BCGFontPhp.php new file mode 100644 index 000000000..a2f8ba805 --- /dev/null +++ b/niucloud/core/util/barcode/class/BCGFontPhp.php @@ -0,0 +1,153 @@ +font = max(0, intval($font)); + $this->backgroundColor = new BCGColor('white'); + $this->foregroundColor = new BCGColor('black'); + $this->setRotationAngle(0); + } + + /** + * Gets the text associated to the font. + * + * @return string + */ + public function getText() { + return $this->text; + } + + /** + * Sets the text associated to the font. + * + * @param string text + */ + public function setText($text) { + $this->text = $text; + } + + /** + * Gets the rotation in degree. + * + * @return int + */ + public function getRotationAngle() { + return (360 - $this->rotationAngle) % 360; + } + + /** + * Sets the rotation in degree. + * + * @param int + */ + public function setRotationAngle($rotationAngle) { + $this->rotationAngle = (int)$rotationAngle; + if ($this->rotationAngle !== 90 && $this->rotationAngle !== 180 && $this->rotationAngle !== 270) { + $this->rotationAngle = 0; + } + + $this->rotationAngle = (360 - $this->rotationAngle) % 360; + } + + /** + * Gets the background color. + * + * @return BCGColor + */ + public function getBackgroundColor() { + return $this->backgroundColor; + } + + /** + * Sets the background color. + * + * @param BCGColor $backgroundColor + */ + public function setBackgroundColor($backgroundColor) { + $this->backgroundColor = $backgroundColor; + } + + /** + * Gets the foreground color. + * + * @return BCGColor + */ + public function getForegroundColor() { + return $this->foregroundColor; + } + + /** + * Sets the foreground color. + * + * @param BCGColor $foregroundColor + */ + public function setForegroundColor($foregroundColor) { + $this->foregroundColor = $foregroundColor; + } + + /** + * Returns the width and height that the text takes to be written. + * + * @return int[] + */ + public function getDimension() { + $w = imagefontwidth($this->font) * strlen($this->text); + $h = imagefontheight($this->font); + + $rotationAngle = $this->getRotationAngle(); + if ($rotationAngle === 90 || $rotationAngle === 270) { + return array($h, $w); + } else { + return array($w, $h); + } + } + + /** + * Draws the text on the image at a specific position. + * $x and $y represent the left bottom corner. + * + * @param resource $im + * @param int $x + * @param int $y + */ + public function draw($im, $x, $y) { + if ($this->getRotationAngle() !== 0) { + if (!function_exists('imagerotate')) { + throw new BCGDrawException('The method imagerotate doesn\'t exist on your server. Do not use any rotation.'); + } + + $w = imagefontwidth($this->font) * strlen($this->text); + $h = imagefontheight($this->font); + $gd = imagecreatetruecolor($w, $h); + imagefilledrectangle($gd, 0, 0, $w - 1, $h - 1, $this->backgroundColor->allocate($gd)); + imagestring($gd, $this->font, 0, 0, $this->text, $this->foregroundColor->allocate($gd)); + $gd = imagerotate($gd, $this->rotationAngle, 0); + imagecopy($im, $gd, $x, $y, 0, 0, imagesx($gd), imagesy($gd)); + } else { + imagestring($im, $this->font, $x, $y, $this->text, $this->foregroundColor->allocate($im)); + } + } +} +?> \ No newline at end of file diff --git a/niucloud/core/util/barcode/class/BCGLabel.php b/niucloud/core/util/barcode/class/BCGLabel.php new file mode 100644 index 000000000..7c933c743 --- /dev/null +++ b/niucloud/core/util/barcode/class/BCGLabel.php @@ -0,0 +1,320 @@ +setFont($font); + $this->setText($text); + $this->setPosition($position); + $this->setAlignment($alignment); + $this->setSpacing(4); + $this->setOffset(0); + $this->setRotationAngle(0); + $this->setBackgroundColor(new BCGColor('white')); + $this->setForegroundColor(new BCGColor('black')); + } + + /** + * Gets the text. + * + * @return string + */ + public function getText() { + return $this->font->getText(); + } + + /** + * Sets the text. + * + * @param string $text + */ + public function setText($text) { + $this->text = $text; + $this->font->setText($this->text); + } + + /** + * Gets the font. + * + * @return BCGFont + */ + public function getFont() { + return $this->font; + } + + /** + * Sets the font. + * + * @param BCGFont $font + */ + public function setFont($font) { + if ($font === null) { + throw new BCGArgumentException('Font cannot be null.', 'font'); + } + + $this->font = clone $font; + $this->font->setText($this->text); + $this->font->setRotationAngle($this->rotationAngle); + $this->font->setBackgroundColor($this->backgroundColor); + $this->font->setForegroundColor($this->foregroundColor); + } + + /** + * Gets the text position for drawing. + * + * @return int + */ + public function getPosition() { + return $this->position; + } + + /** + * Sets the text position for drawing. + * + * @param int $position + */ + public function setPosition($position) { + $position = intval($position); + if ($position !== self::POSITION_TOP && $position !== self::POSITION_RIGHT && $position !== self::POSITION_BOTTOM && $position !== self::POSITION_LEFT) { + throw new BCGArgumentException('The text position must be one of a valid constant.', 'position'); + } + + $this->position = $position; + } + + /** + * Gets the text alignment for drawing. + * + * @return int + */ + public function getAlignment() { + return $this->alignment; + } + + /** + * Sets the text alignment for drawing. + * + * @param int $alignment + */ + public function setAlignment($alignment) { + $alignment = intval($alignment); + if ($alignment !== self::ALIGN_LEFT && $alignment !== self::ALIGN_TOP && $alignment !== self::ALIGN_CENTER && $alignment !== self::ALIGN_RIGHT && $alignment !== self::ALIGN_BOTTOM) { + throw new BCGArgumentException('The text alignment must be one of a valid constant.', 'alignment'); + } + + $this->alignment = $alignment; + } + + /** + * Gets the offset. + * + * @return int + */ + public function getOffset() { + return $this->offset; + } + + /** + * Sets the offset. + * + * @param int $offset + */ + public function setOffset($offset) { + $this->offset = intval($offset); + } + + /** + * Gets the spacing. + * + * @return int + */ + public function getSpacing() { + return $this->spacing; + } + + /** + * Sets the spacing. + * + * @param int $spacing + */ + public function setSpacing($spacing) { + $this->spacing = max(0, intval($spacing)); + } + + /** + * Gets the rotation angle in degree. + * + * @return int + */ + public function getRotationAngle() { + return $this->font->getRotationAngle(); + } + + /** + * Sets the rotation angle in degree. + * + * @param int $rotationAngle + */ + public function setRotationAngle($rotationAngle) { + $this->rotationAngle = intval($rotationAngle); + $this->font->setRotationAngle($this->rotationAngle); + } + + /** + * Gets the background color in case of rotation. + * + * @return BCGColor + */ + public function getBackgroundColor() { + return $this->backgroundColor; + } + + /** + * Sets the background color in case of rotation. + * + * @param BCGColor $backgroundColor + */ + public /*internal*/ function setBackgroundColor($backgroundColor) { + $this->backgroundColor = $backgroundColor; + $this->font->setBackgroundColor($this->backgroundColor); + } + + /** + * Gets the foreground color. + * + * @return BCGColor + */ + public function getForegroundColor() { + return $this->font->getForegroundColor(); + } + + /** + * Sets the foreground color. + * + * @param BCGColor $foregroundColor + */ + public function setForegroundColor($foregroundColor) { + $this->foregroundColor = $foregroundColor; + $this->font->setForegroundColor($this->foregroundColor); + } + + /** + * Gets the dimension taken by the label, including the spacing and offset. + * [0]: width + * [1]: height + * + * @return int[] + */ + public function getDimension() { + $w = 0; + $h = 0; + + $dimension = $this->font->getDimension(); + $w = $dimension[0]; + $h = $dimension[1]; + + if ($this->position === self::POSITION_TOP || $this->position === self::POSITION_BOTTOM) { + $h += $this->spacing; + $w += max(0, $this->offset); + } else { + $w += $this->spacing; + $h += max(0, $this->offset); + } + + return array($w, $h); + } + + /** + * Draws the text. + * The coordinate passed are the positions of the barcode. + * $x1 and $y1 represent the top left corner. + * $x2 and $y2 represent the bottom right corner. + * + * @param resource $im + * @param int $x1 + * @param int $y1 + * @param int $x2 + * @param int $y2 + */ + public /*internal*/ function draw($im, $x1, $y1, $x2, $y2) { + $x = 0; + $y = 0; + + $fontDimension = $this->font->getDimension(); + + if ($this->position === self::POSITION_TOP || $this->position === self::POSITION_BOTTOM) { + if ($this->position === self::POSITION_TOP) { + $y = $y1 - $this->spacing - $fontDimension[1]; + } elseif ($this->position === self::POSITION_BOTTOM) { + $y = $y2 + $this->spacing; + } + + if ($this->alignment === self::ALIGN_CENTER) { + $x = ($x2 - $x1) / 2 + $x1 - $fontDimension[0] / 2 + $this->offset; + } elseif ($this->alignment === self::ALIGN_LEFT) { + $x = $x1 + $this->offset; + } else { + $x = $x2 + $this->offset - $fontDimension[0]; + } + } else { + if ($this->position === self::POSITION_LEFT) { + $x = $x1 - $this->spacing - $fontDimension[0]; + } elseif ($this->position === self::POSITION_RIGHT) { + $x = $x2 + $this->spacing; + } + + if ($this->alignment === self::ALIGN_CENTER) { + $y = ($y2 - $y1) / 2 + $y1 - $fontDimension[1] / 2 + $this->offset; + } elseif ($this->alignment === self::ALIGN_TOP) { + $y = $y1 + $this->offset; + } else { + $y = $y2 + $this->offset - $fontDimension[1]; + } + } + + $this->font->setText($this->text); + $this->font->draw($im, $x, $y); + } +} +?> \ No newline at end of file diff --git a/niucloud/core/util/barcode/class/BCGParseException.php b/niucloud/core/util/barcode/class/BCGParseException.php new file mode 100644 index 000000000..ce4eeb9f1 --- /dev/null +++ b/niucloud/core/util/barcode/class/BCGParseException.php @@ -0,0 +1,25 @@ +barcode = $barcode; + parent::__construct($message, 10000); + } +} +?> \ No newline at end of file diff --git a/niucloud/core/util/barcode/class/BCGcodabar.barcode.php b/niucloud/core/util/barcode/class/BCGcodabar.barcode.php new file mode 100644 index 000000000..91189fede --- /dev/null +++ b/niucloud/core/util/barcode/class/BCGcodabar.barcode.php @@ -0,0 +1,122 @@ +keys = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '$', ':', '/', '.', '+', 'A', 'B', 'C', 'D'); + $this->code = array( // 0 added to add an extra space + '00000110', /* 0 */ + '00001100', /* 1 */ + '00010010', /* 2 */ + '11000000', /* 3 */ + '00100100', /* 4 */ + '10000100', /* 5 */ + '01000010', /* 6 */ + '01001000', /* 7 */ + '01100000', /* 8 */ + '10010000', /* 9 */ + '00011000', /* - */ + '00110000', /* $ */ + '10001010', /* : */ + '10100010', /* / */ + '10101000', /* . */ + '00111110', /* + */ + '00110100', /* A */ + '01010010', /* B */ + '00010110', /* C */ + '00011100' /* D */ + ); + } + + /** + * Parses the text before displaying it. + * + * @param mixed $text + */ + public function parse($text) { + parent::parse(strtoupper($text)); // Only Capital Letters are Allowed + } + + /** + * Draws the barcode. + * + * @param resource $im + */ + public function draw($im) { + $c = strlen($this->text); + for ($i = 0; $i < $c; $i++) { + $this->drawChar($im, $this->findCode($this->text[$i]), true); + } + + $this->drawText($im, 0, 0, $this->positionX, $this->thickness); + } + + /** + * Returns the maximal size of a barcode. + * + * @param int $w + * @param int $h + * @return int[] + */ + public function getDimension($w, $h) { + $textLength = 0; + $c = strlen($this->text); + for ($i = 0; $i < $c; $i++) { + $index = $this->findIndex($this->text[$i]); + if ($index !== false) { + $textLength += 8; + $textLength += substr_count($this->code[$index], '1'); + } + } + + $w += $textLength; + $h += $this->thickness; + return parent::getDimension($w, $h); + } + + /** + * Validates the input. + */ + protected function validate() { + $c = strlen($this->text); + if ($c === 0) { + throw new BCGParseException('codabar', 'No data has been entered.'); + } + + // Checking if all chars are allowed + for ($i = 0; $i < $c; $i++) { + if (array_search($this->text[$i], $this->keys) === false) { + throw new BCGParseException('codabar', 'The character \'' . $this->text[$i] . '\' is not allowed.'); + } + } + + // Must start by A, B, C or D + if ($c == 0 || ($this->text[0] !== 'A' && $this->text[0] !== 'B' && $this->text[0] !== 'C' && $this->text[0] !== 'D')) { + throw new BCGParseException('codabar', 'The text must start by the character A, B, C, or D.'); + } + + // Must end by A, B, C or D + $c2 = $c - 1; + if ($c2 === 0 || ($this->text[$c2] !== 'A' && $this->text[$c2] !== 'B' && $this->text[$c2] !== 'C' && $this->text[$c2] !== 'D')) { + throw new BCGParseException('codabar', 'The text must end by the character A, B, C, or D.'); + } + + parent::validate(); + } +} +?> \ No newline at end of file diff --git a/niucloud/core/util/barcode/class/BCGcode11.barcode.php b/niucloud/core/util/barcode/class/BCGcode11.barcode.php new file mode 100644 index 000000000..7c11a22c0 --- /dev/null +++ b/niucloud/core/util/barcode/class/BCGcode11.barcode.php @@ -0,0 +1,185 @@ +keys = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-'); + $this->code = array( // 0 added to add an extra space + '000010', /* 0 */ + '100010', /* 1 */ + '010010', /* 2 */ + '110000', /* 3 */ + '001010', /* 4 */ + '101000', /* 5 */ + '011000', /* 6 */ + '000110', /* 7 */ + '100100', /* 8 */ + '100000', /* 9 */ + '001000' /* - */ + ); + } + + /** + * Draws the barcode. + * + * @param resource $im + */ + public function draw($im) { + // Starting Code + $this->drawChar($im, '001100', true); + + // Chars + $c = strlen($this->text); + for ($i = 0; $i < $c; $i++) { + $this->drawChar($im, $this->findCode($this->text[$i]), true); + } + + // Checksum + $this->calculateChecksum(); + $c = count($this->checksumValue); + for ($i = 0; $i < $c; $i++) { + $this->drawChar($im, $this->code[$this->checksumValue[$i]], true); + } + + // Ending Code + $this->drawChar($im, '00110', true); + $this->drawText($im, 0, 0, $this->positionX, $this->thickness); + } + + /** + * Returns the maximal size of a barcode. + * + * @param int $w + * @param int $h + * @return int[] + */ + public function getDimension($w, $h) { + $startlength = 8; + + $textlength = 0; + $c = strlen($this->text); + for ($i = 0; $i < $c; $i++) { + $textlength += $this->getIndexLength($this->findIndex($this->text[$i])); + } + + $checksumlength = 0; + $this->calculateChecksum(); + $c = count($this->checksumValue); + for ($i = 0; $i < $c; $i++) { + $checksumlength += $this->getIndexLength($this->checksumValue[$i]); + } + + $endlength = 7; + + $w += $startlength + $textlength + $checksumlength + $endlength; + $h += $this->thickness; + + return parent::getDimension($w, $h); + } + + /** + * Validates the input. + */ + protected function validate() { + $c = strlen($this->text); + if ($c === 0) { + throw new BCGParseException('code11', 'No data has been entered.'); + } + + // Checking if all chars are allowed + for ($i = 0; $i < $c; $i++) { + if (array_search($this->text[$i], $this->keys) === false) { + throw new BCGParseException('code11', 'The character \'' . $this->text[$i] . '\' is not allowed.'); + } + } + + parent::validate(); + } + + /** + * Overloaded method to calculate checksum. + */ + protected function calculateChecksum() { + // Checksum + // First CheckSUM "C" + // The "C" checksum character is the modulo 11 remainder of the sum of the weighted + // value of the data characters. The weighting value starts at "1" for the right-most + // data character, 2 for the second to last, 3 for the third-to-last, and so on up to 20. + // After 10, the sequence wraps around back to 1. + + // Second CheckSUM "K" + // Same as CheckSUM "C" but we count the CheckSum "C" at the end + // After 9, the sequence wraps around back to 1. + $sequence_multiplier = array(10, 9); + $temp_text = $this->text; + $this->checksumValue = array(); + for ($z = 0; $z < 2; $z++) { + $c = strlen($temp_text); + + // We don't display the K CheckSum if the original text had a length less than 10 + if ($c <= 10 && $z === 1) { + break; + } + + $checksum = 0; + for ($i = $c, $j = 0; $i > 0; $i--, $j++) { + $multiplier = $i % $sequence_multiplier[$z]; + if ($multiplier === 0) { + $multiplier = $sequence_multiplier[$z]; + } + + $checksum += $this->findIndex($temp_text[$j]) * $multiplier; + } + + $this->checksumValue[$z] = $checksum % 11; + $temp_text .= $this->keys[$this->checksumValue[$z]]; + } + } + + /** + * Overloaded method to display the checksum. + */ + protected function processChecksum() { + if ($this->checksumValue === false) { // Calculate the checksum only once + $this->calculateChecksum(); + } + + if ($this->checksumValue !== false) { + $ret = ''; + $c = count($this->checksumValue); + for ($i = 0; $i < $c; $i++) { + $ret .= $this->keys[$this->checksumValue[$i]]; + } + + return $ret; + } + + return false; + } + + private function getIndexLength($index) { + $length = 0; + if ($index !== false) { + $length += 6; + $length += substr_count($this->code[$index], '1'); + } + + return $length; + } +} +?> \ No newline at end of file diff --git a/niucloud/core/util/barcode/class/BCGcode128.barcode.php b/niucloud/core/util/barcode/class/BCGcode128.barcode.php new file mode 100644 index 000000000..0cfeed6ff --- /dev/null +++ b/niucloud/core/util/barcode/class/BCGcode128.barcode.php @@ -0,0 +1,885 @@ +keysA = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_'; + for ($i = 0; $i < 32; $i++) { + $this->keysA .= chr($i); + } + + /* CODE 128 B */ + $this->keysB = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~' . chr(127); + + /* CODE 128 C */ + $this->keysC = '0123456789'; + + $this->code = array( + '101111', /* 00 */ + '111011', /* 01 */ + '111110', /* 02 */ + '010112', /* 03 */ + '010211', /* 04 */ + '020111', /* 05 */ + '011102', /* 06 */ + '011201', /* 07 */ + '021101', /* 08 */ + '110102', /* 09 */ + '110201', /* 10 */ + '120101', /* 11 */ + '001121', /* 12 */ + '011021', /* 13 */ + '011120', /* 14 */ + '002111', /* 15 */ + '012011', /* 16 */ + '012110', /* 17 */ + '112100', /* 18 */ + '110021', /* 19 */ + '110120', /* 20 */ + '102101', /* 21 */ + '112001', /* 22 */ + '201020', /* 23 */ + '200111', /* 24 */ + '210011', /* 25 */ + '210110', /* 26 */ + '201101', /* 27 */ + '211001', /* 28 */ + '211100', /* 29 */ + '101012', /* 30 */ + '101210', /* 31 */ + '121010', /* 32 */ + '000212', /* 33 */ + '020012', /* 34 */ + '020210', /* 35 */ + '001202', /* 36 */ + '021002', /* 37 */ + '021200', /* 38 */ + '100202', /* 39 */ + '120002', /* 40 */ + '120200', /* 41 */ + '001022', /* 42 */ + '001220', /* 43 */ + '021020', /* 44 */ + '002012', /* 45 */ + '002210', /* 46 */ + '022010', /* 47 */ + '202010', /* 48 */ + '100220', /* 49 */ + '120020', /* 50 */ + '102002', /* 51 */ + '102200', /* 52 */ + '102020', /* 53 */ + '200012', /* 54 */ + '200210', /* 55 */ + '220010', /* 56 */ + '201002', /* 57 */ + '201200', /* 58 */ + '221000', /* 59 */ + '203000', /* 60 */ + '110300', /* 61 */ + '320000', /* 62 */ + '000113', /* 63 */ + '000311', /* 64 */ + '010013', /* 65 */ + '010310', /* 66 */ + '030011', /* 67 */ + '030110', /* 68 */ + '001103', /* 69 */ + '001301', /* 70 */ + '011003', /* 71 */ + '011300', /* 72 */ + '031001', /* 73 */ + '031100', /* 74 */ + '130100', /* 75 */ + '110003', /* 76 */ + '302000', /* 77 */ + '130001', /* 78 */ + '023000', /* 79 */ + '000131', /* 80 */ + '010031', /* 81 */ + '010130', /* 82 */ + '003101', /* 83 */ + '013001', /* 84 */ + '013100', /* 85 */ + '300101', /* 86 */ + '310001', /* 87 */ + '310100', /* 88 */ + '101030', /* 89 */ + '103010', /* 90 */ + '301010', /* 91 */ + '000032', /* 92 */ + '000230', /* 93 */ + '020030', /* 94 */ + '003002', /* 95 */ + '003200', /* 96 */ + '300002', /* 97 */ + '300200', /* 98 */ + '002030', /* 99 */ + '003020', /* 100*/ + '200030', /* 101*/ + '300020', /* 102*/ + '100301', /* 103*/ + '100103', /* 104*/ + '100121', /* 105*/ + '122000' /*STOP*/ + ); + $this->setStart($start); + $this->setTilde(true); + + // Latches and Shifts + $this->latch = array( + array(null, self::KEYA_CODEB, self::KEYA_CODEC), + array(self::KEYB_CODEA, null, self::KEYB_CODEC), + array(self::KEYC_CODEA, self::KEYC_CODEB, null) + ); + $this->shift = array( + array(null, self::KEYA_SHIFT), + array(self::KEYB_SHIFT, null) + ); + $this->fnc = array( + array(self::KEYA_FNC1, self::KEYA_FNC2, self::KEYA_FNC3, self::KEYA_FNC4), + array(self::KEYB_FNC1, self::KEYB_FNC2, self::KEYB_FNC3, self::KEYB_FNC4), + array(self::KEYC_FNC1, null, null, null) + ); + + // Method available + $this->METHOD = array(CODE128_A => 'A', CODE128_B => 'B', CODE128_C => 'C'); + } + + /** + * Specifies the start code. Can be 'A', 'B', 'C', or null + * - Table A: Capitals + ASCII 0-31 + punct + * - Table B: Capitals + LowerCase + punct + * - Table C: Numbers + * + * If null is specified, the table selection is automatically made. + * The default is null. + * + * @param string $table + */ + public function setStart($table) { + if ($table !== 'A' && $table !== 'B' && $table !== 'C' && $table !== null) { + throw new BCGArgumentException('The starting table must be A, B, C or null.', 'table'); + } + + $this->starting_text = $table; + } + + /** + * Gets the tilde. + * + * @return bool + */ + public function getTilde() { + return $this->tilde; + } + + /** + * Accepts tilde to be process as a special character. + * If true, you can do this: + * - ~~ : to make ONE tilde + * - ~Fx : to insert FCNx. x is equal from 1 to 4. + * + * @param boolean $accept + */ + public function setTilde($accept) { + $this->tilde = (bool)$accept; + } + + /** + * Parses the text before displaying it. + * + * @param mixed $text + */ + public function parse($text) { + $this->setStartFromText($text); + + $this->text = ''; + $seq = ''; + + $currentMode = $this->starting_text; + + // Here, we format correctly what the user gives. + if (!is_array($text)) { + $seq = $this->getSequence($text, $currentMode); + $this->text = $text; + } else { + // This loop checks for UnknownText AND raises an exception if a character is not allowed in a table + reset($text); + while (list($key1, $val1) = each($text)) { // We take each value + if (!is_array($val1)) { // This is not a table + if (is_string($val1)) { // If it's a string, parse as unknown + $seq .= $this->getSequence($val1, $currentMode); + $this->text .= $val1; + } else { + // it's the case of "array(ENCODING, 'text')" + // We got ENCODING in $val1, calling 'each' again will get 'text' in $val2 + list($key2, $val2) = each($text); + $seq .= $this->{'setParse' . $this->METHOD[$val1]}($val2, $currentMode); + $this->text .= $val2; + } + } else { // The method is specified + // $val1[0] = ENCODING + // $val1[1] = 'text' + $value = isset($val1[1]) ? $val1[1] : ''; // If data available + $seq .= $this->{'setParse' . $this->METHOD[$val1[0]]}($value, $currentMode); + $this->text .= $value; + } + } + } + + if ($seq !== '') { + $bitstream = $this->createBinaryStream($this->text, $seq); + $this->setData($bitstream); + } + + $this->addDefaultLabel(); + } + + /** + * Draws the barcode. + * + * @param resource $im + */ + public function draw($im) { + $c = count($this->data); + for ($i = 0; $i < $c; $i++) { + $this->drawChar($im, $this->data[$i], true); + } + + $this->drawChar($im, '1', true); + $this->drawText($im, 0, 0, $this->positionX, $this->thickness); + } + + /** + * Returns the maximal size of a barcode. + * + * @param int $w + * @param int $h + * @return int[] + */ + public function getDimension($w, $h) { + // Contains start + text + checksum + stop + $textlength = count($this->data) * 11; + $endlength = 2; // + final bar + + $w += $textlength + $endlength; + $h += $this->thickness; + return parent::getDimension($w, $h); + } + + /** + * Validates the input. + */ + protected function validate() { + $c = count($this->data); + if ($c === 0) { + throw new BCGParseException('code128', 'No data has been entered.'); + } + + parent::validate(); + } + + /** + * Overloaded method to calculate checksum. + */ + protected function calculateChecksum() { + // Checksum + // First Char (START) + // + Starting with the first data character following the start character, + // take the value of the character (between 0 and 102, inclusive) multiply + // it by its character position (1) and add that to the running checksum. + // Modulated 103 + $this->checksumValue = $this->indcheck[0]; + $c = count($this->indcheck); + for ($i = 1; $i < $c; $i++) { + $this->checksumValue += $this->indcheck[$i] * $i; + } + + $this->checksumValue = $this->checksumValue % 103; + } + + /** + * Overloaded method to display the checksum. + */ + protected function processChecksum() { + if ($this->checksumValue === false) { // Calculate the checksum only once + $this->calculateChecksum(); + } + + if ($this->checksumValue !== false) { + if ($this->lastTable === 'C') { + return (string)$this->checksumValue; + } + + return $this->{'keys' . $this->lastTable}[$this->checksumValue]; + } + + return false; + } + + /** + * Specifies the starting_text table if none has been specified earlier. + * + * @param string $text + */ + private function setStartFromText($text) { + if ($this->starting_text === null) { + // If we have a forced table at the start, we get that one... + if (is_array($text)) { + if (is_array($text[0])) { + // Code like array(array(ENCODING, '')) + $this->starting_text = $this->METHOD[$text[0][0]]; + return; + } else { + if (is_string($text[0])) { + // Code like array('test') (Automatic text) + $text = $text[0]; + } else { + // Code like array(ENCODING, '') + $this->starting_text = $this->METHOD[$text[0]]; + return; + } + } + } + + // At this point, we had an "automatic" table selection... + // If we can get at least 4 numbers, go in C; otherwise go in B. + $tmp = preg_quote($this->keysC, '/'); + $length = strlen($text); + if ($length >= 4 && preg_match('/[' . $tmp . ']/', substr($text, 0, 4))) { + $this->starting_text = 'C'; + } else { + if ($length > 0 && strpos($this->keysB, $text[0]) !== false) { + $this->starting_text = 'B'; + } else { + $this->starting_text = 'A'; + } + } + } + } + + /** + * Extracts the ~ value from the $text at the $pos. + * If the tilde is not ~~, ~F1, ~F2, ~F3, ~F4; an error is raised. + * + * @param string $text + * @param int $pos + * @return string + */ + private static function extractTilde($text, $pos) { + if ($text[$pos] === '~') { + if (isset($text[$pos + 1])) { + // Do we have a tilde? + if ($text[$pos + 1] === '~') { + return '~~'; + } elseif ($text[$pos + 1] === 'F') { + // Do we have a number after? + if (isset($text[$pos + 2])) { + $v = intval($text[$pos + 2]); + if ($v >= 1 && $v <= 4) { + return '~F' . $v; + } else { + throw new BCGParseException('code128', 'Bad ~F. You must provide a number from 1 to 4.'); + } + } else { + throw new BCGParseException('code128', 'Bad ~F. You must provide a number from 1 to 4.'); + } + } else { + throw new BCGParseException('code128', 'Wrong code after the ~.'); + } + } else { + throw new BCGParseException('code128', 'Wrong code after the ~.'); + } + } else { + throw new BCGParseException('code128', 'There is no ~ at this location.'); + } + } + + /** + * Gets the "dotted" sequence for the $text based on the $currentMode. + * There is also a check if we use the special tilde ~ + * + * @param string $text + * @param string $currentMode + * @return string + */ + private function getSequenceParsed($text, $currentMode) { + if ($this->tilde) { + $sequence = ''; + $previousPos = 0; + while (($pos = strpos($text, '~', $previousPos)) !== false) { + $tildeData = self::extractTilde($text, $pos); + + $simpleTilde = ($tildeData === '~~'); + if ($simpleTilde && $currentMode !== 'B') { + throw new BCGParseException('code128', 'The Table ' . $currentMode . ' doesn\'t contain the character ~.'); + } + + // At this point, we know we have ~Fx + if ($tildeData !== '~F1' && $currentMode === 'C') { + // The mode C doesn't support ~F2, ~F3, ~F4 + throw new BCGParseException('code128', 'The Table C doesn\'t contain the function ' . $tildeData . '.'); + } + + $length = $pos - $previousPos; + if ($currentMode === 'C') { + if ($length % 2 === 1) { + throw new BCGParseException('code128', 'The text "' . $text . '" must have an even number of character to be encoded in Table C.'); + } + } + + $sequence .= str_repeat('.', $length); + $sequence .= '.'; + $sequence .= (!$simpleTilde) ? 'F' : ''; + $previousPos = $pos + strlen($tildeData); + } + + // Flushing + $length = strlen($text) - $previousPos; + if ($currentMode === 'C') { + if ($length % 2 === 1) { + throw new BCGParseException('code128', 'The text "' . $text . '" must have an even number of character to be encoded in Table C.'); + } + } + + $sequence .= str_repeat('.', $length); + + return $sequence; + } else { + return str_repeat('.', strlen($text)); + } + } + + /** + * Parses the text and returns the appropriate sequence for the Table A. + * + * @param string $text + * @param string $currentMode + * @return string + */ + private function setParseA($text, &$currentMode) { + $tmp = preg_quote($this->keysA, '/'); + + // If we accept the ~ for special character, we must allow it. + if ($this->tilde) { + $tmp .= '~'; + } + + $match = array(); + if (preg_match('/[^' . $tmp . ']/', $text, $match) === 1) { + // We found something not allowed + throw new BCGParseException('code128', 'The text "' . $text . '" can\'t be parsed with the Table A. The character "' . $match[0] . '" is not allowed.'); + } else { + $latch = ($currentMode === 'A') ? '' : '0'; + $currentMode = 'A'; + + return $latch . $this->getSequenceParsed($text, $currentMode); + } + } + + /** + * Parses the text and returns the appropriate sequence for the Table B. + * + * @param string $text + * @param string $currentMode + * @return string + */ + private function setParseB($text, &$currentMode) { + $tmp = preg_quote($this->keysB, '/'); + + $match = array(); + if (preg_match('/[^' . $tmp . ']/', $text, $match) === 1) { + // We found something not allowed + throw new BCGParseException('code128', 'The text "' . $text . '" can\'t be parsed with the Table B. The character "' . $match[0] . '" is not allowed.'); + } else { + $latch = ($currentMode === 'B') ? '' : '1'; + $currentMode = 'B'; + + return $latch . $this->getSequenceParsed($text, $currentMode); + } + } + + /** + * Parses the text and returns the appropriate sequence for the Table C. + * + * @param string $text + * @param string $currentMode + * @return string + */ + private function setParseC($text, &$currentMode) { + $tmp = preg_quote($this->keysC, '/'); + + // If we accept the ~ for special character, we must allow it. + if ($this->tilde) { + $tmp .= '~F'; + } + + $match = array(); + if (preg_match('/[^' . $tmp . ']/', $text, $match) === 1) { + // We found something not allowed + throw new BCGParseException('code128', 'The text "' . $text . '" can\'t be parsed with the Table C. The character "' . $match[0] . '" is not allowed.'); + } else { + $latch = ($currentMode === 'C') ? '' : '2'; + $currentMode = 'C'; + + return $latch . $this->getSequenceParsed($text, $currentMode); + } + } + + /** + * Depending on the $text, it will return the correct + * sequence to encode the text. + * + * @param string $text + * @param string $starting_text + * @return string + */ + private function getSequence($text, &$starting_text) { + $e = 10000; + $latLen = array( + array(0, 1, 1), + array(1, 0, 1), + array(1, 1, 0) + ); + $shftLen = array( + array($e, 1, $e), + array(1, $e, $e), + array($e, $e, $e) + ); + $charSiz = array(2, 2, 1); + + $startA = $e; + $startB = $e; + $startC = $e; + if ($starting_text === 'A') { $startA = 0; } + if ($starting_text === 'B') { $startB = 0; } + if ($starting_text === 'C') { $startC = 0; } + + $curLen = array($startA, $startB, $startC); + $curSeq = array(null, null, null); + + $nextNumber = false; + + $x = 0; + $xLen = strlen($text); + for ($x = 0; $x < $xLen; $x++) { + $input = $text[$x]; + + // 1. + for ($i = 0; $i < 3; $i++) { + for ($j = 0; $j < 3; $j++) { + if (($curLen[$i] + $latLen[$i][$j]) < $curLen[$j]) { + $curLen[$j] = $curLen[$i] + $latLen[$i][$j]; + $curSeq[$j] = $curSeq[$i] . $j; + } + } + } + + // 2. + $nxtLen = array($e, $e, $e); + $nxtSeq = array(); + + // 3. + $flag = false; + $posArray = array(); + + // Special case, we do have a tilde and we process them + if ($this->tilde && $input === '~') { + $tildeData = self::extractTilde($text, $x); + + if ($tildeData === '~~') { + // We simply skip a tilde + $posArray[] = 1; + $x++; + } elseif (substr($tildeData, 0, 2) === '~F') { + $v = intval($tildeData[2]); + $posArray[] = 0; + $posArray[] = 1; + if ($v === 1) { + $posArray[] = 2; + } + + $x += 2; + $flag = true; + } + } else { + $pos = strpos($this->keysA, $input); + if ($pos !== false) { + $posArray[] = 0; + } + + $pos = strpos($this->keysB, $input); + if ($pos !== false) { + $posArray[] = 1; + } + + // Do we have the next char a number?? OR a ~F1 + $pos = strpos($this->keysC, $input); + if ($nextNumber || ($pos !== false && isset($text[$x + 1]) && strpos($this->keysC, $text[$x + 1]) !== false)) { + $nextNumber = !$nextNumber; + $posArray[] = 2; + } + } + + $c = count($posArray); + for ($i = 0; $i < $c; $i++) { + if (($curLen[$posArray[$i]] + $charSiz[$posArray[$i]]) < $nxtLen[$posArray[$i]]) { + $nxtLen[$posArray[$i]] = $curLen[$posArray[$i]] + $charSiz[$posArray[$i]]; + $nxtSeq[$posArray[$i]] = $curSeq[$posArray[$i]] . '.'; + } + + for ($j = 0; $j < 2; $j++) { + if ($j === $posArray[$i]) { continue; } + if (($curLen[$j] + $shftLen[$j][$posArray[$i]] + $charSiz[$posArray[$i]]) < $nxtLen[$j]) { + $nxtLen[$j] = $curLen[$j] + $shftLen[$j][$posArray[$i]] + $charSiz[$posArray[$i]]; + $nxtSeq[$j] = $curSeq[$j] . chr($posArray[$i] + 65) . '.'; + } + } + } + + if ($c === 0) { + // We found an unsuported character + throw new BCGParseException('code128', 'Character ' . $input . ' not supported.'); + } + + if ($flag) { + for ($i = 0; $i < 5; $i++) { + if (isset($nxtSeq[$i])) { + $nxtSeq[$i] .= 'F'; + } + } + } + + // 4. + for ($i = 0; $i < 3; $i++) { + $curLen[$i] = $nxtLen[$i]; + if (isset($nxtSeq[$i])) { + $curSeq[$i] = $nxtSeq[$i]; + } + } + } + + // Every curLen under $e is possible but we take the smallest + $m = $e; + $k = -1; + for ($i = 0; $i < 3; $i++) { + if ($curLen[$i] < $m) { + $k = $i; + $m = $curLen[$i]; + } + } + + if ($k === -1) { + return ''; + } + + return $curSeq[$k]; + } + + /** + * Depending on the sequence $seq given (returned from getSequence()), + * this method will return the code stream in an array. Each char will be a + * string of bit based on the Code 128. + * + * Each letter from the sequence represents bits. + * + * 0 to 2 are latches + * A to B are Shift + Letter + * . is a char in the current encoding + * + * @param string $text + * @param string $seq + * @return string[][] + */ + private function createBinaryStream($text, $seq) { + $c = strlen($seq); + + $data = array(); // code stream + $indcheck = array(); // index for checksum + + $currentEncoding = 0; + if ($this->starting_text === 'A') { + $currentEncoding = 0; + $indcheck[] = self::KEY_STARTA; + $this->lastTable = 'A'; + } elseif ($this->starting_text === 'B') { + $currentEncoding = 1; + $indcheck[] = self::KEY_STARTB; + $this->lastTable = 'B'; + } elseif ($this->starting_text === 'C') { + $currentEncoding = 2; + $indcheck[] = self::KEY_STARTC; + $this->lastTable = 'C'; + } + + $data[] = $this->code[103 + $currentEncoding]; + + $temporaryEncoding = -1; + for ($i = 0, $counter = 0; $i < $c; $i++) { + $input = $seq[$i]; + $inputI = intval($input); + if ($input === '.') { + $this->encodeChar($data, $currentEncoding, $seq, $text, $i, $counter, $indcheck); + if ($temporaryEncoding !== -1) { + $currentEncoding = $temporaryEncoding; + $temporaryEncoding = -1; + } + } elseif ($input >= 'A' && $input <= 'B') { + // We shift + $encoding = ord($input) - 65; + $shift = $this->shift[$currentEncoding][$encoding]; + $indcheck[] = $shift; + $data[] = $this->code[$shift]; + if ($temporaryEncoding === -1) { + $temporaryEncoding = $currentEncoding; + } + + $currentEncoding = $encoding; + } elseif ($inputI >= 0 && $inputI < 3) { + $temporaryEncoding = -1; + + // We latch + $latch = $this->latch[$currentEncoding][$inputI]; + if ($latch !== null) { + $indcheck[] = $latch; + $this->lastTable = chr(65 + $inputI); + $data[] = $this->code[$latch]; + $currentEncoding = $inputI; + } + } + } + + return array($indcheck, $data); + } + + /** + * Encodes characters, base on its encoding and sequence + * + * @param int[] $data + * @param int $encoding + * @param string $seq + * @param string $text + * @param int $i + * @param int $counter + * @param int[] $indcheck + */ + private function encodeChar(&$data, $encoding, $seq, $text, &$i, &$counter, &$indcheck) { + if (isset($seq[$i + 1]) && $seq[$i + 1] === 'F') { + // We have a flag !! + if ($text[$counter + 1] === 'F') { + $number = $text[$counter + 2]; + $fnc = $this->fnc[$encoding][$number - 1]; + $indcheck[] = $fnc; + $data[] = $this->code[$fnc]; + + // Skip F + number + $counter += 2; + } else { + // Not supposed + } + + $i++; + } else { + if ($encoding === 2) { + // We take 2 numbers in the same time + $code = (int)substr($text, $counter, 2); + $indcheck[] = $code; + $data[] = $this->code[$code]; + $counter++; + $i++; + } else { + $keys = ($encoding === 0) ? $this->keysA : $this->keysB; + $pos = strpos($keys, $text[$counter]); + $indcheck[] = $pos; + $data[] = $this->code[$pos]; + } + } + + $counter++; + } + + /** + * Saves data into the classes. + * + * This method will save data, calculate real column number + * (if -1 was selected), the real error level (if -1 was + * selected)... It will add Padding to the end and generate + * the error codes. + * + * @param array $data + */ + private function setData($data) { + $this->indcheck = $data[0]; + $this->data = $data[1]; + $this->calculateChecksum(); + $this->data[] = $this->code[$this->checksumValue]; + $this->data[] = $this->code[self::KEY_STOP]; + } +} +?> \ No newline at end of file diff --git a/niucloud/core/util/barcode/class/BCGcode39.barcode.php b/niucloud/core/util/barcode/class/BCGcode39.barcode.php new file mode 100644 index 000000000..11e371245 --- /dev/null +++ b/niucloud/core/util/barcode/class/BCGcode39.barcode.php @@ -0,0 +1,193 @@ +starting = $this->ending = 43; + $this->keys = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '-', '.', ' ', '$', '/', '+', '%', '*'); + $this->code = array( // 0 added to add an extra space + '0001101000', /* 0 */ + '1001000010', /* 1 */ + '0011000010', /* 2 */ + '1011000000', /* 3 */ + '0001100010', /* 4 */ + '1001100000', /* 5 */ + '0011100000', /* 6 */ + '0001001010', /* 7 */ + '1001001000', /* 8 */ + '0011001000', /* 9 */ + '1000010010', /* A */ + '0010010010', /* B */ + '1010010000', /* C */ + '0000110010', /* D */ + '1000110000', /* E */ + '0010110000', /* F */ + '0000011010', /* G */ + '1000011000', /* H */ + '0010011000', /* I */ + '0000111000', /* J */ + '1000000110', /* K */ + '0010000110', /* L */ + '1010000100', /* M */ + '0000100110', /* N */ + '1000100100', /* O */ + '0010100100', /* P */ + '0000001110', /* Q */ + '1000001100', /* R */ + '0010001100', /* S */ + '0000101100', /* T */ + '1100000010', /* U */ + '0110000010', /* V */ + '1110000000', /* W */ + '0100100010', /* X */ + '1100100000', /* Y */ + '0110100000', /* Z */ + '0100001010', /* - */ + '1100001000', /* . */ + '0110001000', /* */ + '0101010000', /* $ */ + '0101000100', /* / */ + '0100010100', /* + */ + '0001010100', /* % */ + '0100101000' /* * */ + ); + + $this->setChecksum(false); + } + + /** + * Sets if we display the checksum. + * + * @param bool $checksum + */ + public function setChecksum($checksum) { + $this->checksum = (bool)$checksum; + } + + /** + * Parses the text before displaying it. + * + * @param mixed $text + */ + public function parse($text) { + parent::parse(strtoupper($text)); // Only Capital Letters are Allowed + } + + /** + * Draws the Barcode. + * + * @param resource $im + */ + public function draw($im) { + // Starting * + $this->drawChar($im, $this->code[$this->starting], true); + + // Chars + $c = strlen($this->text); + for ($i = 0; $i < $c; $i++) { + $this->drawChar($im, $this->findCode($this->text[$i]), true); + } + + // Checksum (rarely used) + if ($this->checksum === true) { + $this->calculateChecksum(); + $this->drawChar($im, $this->code[$this->checksumValue % 43], true); + } + + // Ending * + $this->drawChar($im, $this->code[$this->ending], true); + $this->drawText($im, 0, 0, $this->positionX, $this->thickness); + } + + /** + * Returns the maximal size of a Barcode. + * + * @param int $w + * @param int $h + * @return int[] + */ + public function getDimension($w, $h) { + $textlength = 13 * strlen($this->text); + $startlength = 13; + $checksumlength = 0; + if ($this->checksum === true) { + $checksumlength = 13; + } + + $endlength = 13; + + $w += $startlength + $textlength + $checksumlength + $endlength; + $h += $this->thickness; + return parent::getDimension($w, $h); + } + + /** + * Validates the input. + */ + protected function validate() { + $c = strlen($this->text); + if ($c === 0) { + throw new BCGParseException('code39', 'No data has been entered.'); + } + + // Checking if all chars are allowed + for ($i = 0; $i < $c; $i++) { + if (array_search($this->text[$i], $this->keys) === false) { + throw new BCGParseException('code39', 'The character \'' . $this->text[$i] . '\' is not allowed.'); + } + } + + if (strpos($this->text, '*') !== false) { + throw new BCGParseException('code39', 'The character \'*\' is not allowed.'); + } + + parent::validate(); + } + + /** + * Overloaded method to calculate checksum. + */ + protected function calculateChecksum() { + $this->checksumValue = 0; + $c = strlen($this->text); + for ($i = 0; $i < $c; $i++) { + $this->checksumValue += $this->findIndex($this->text[$i]); + } + + $this->checksumValue = $this->checksumValue % 43; + } + + /** + * Overloaded method to display the checksum. + */ + protected function processChecksum() { + if ($this->checksumValue === false) { // Calculate the checksum only once + $this->calculateChecksum(); + } + + if ($this->checksumValue !== false) { + return $this->keys[$this->checksumValue]; + } + + return false; + } +} +?> \ No newline at end of file diff --git a/niucloud/core/util/barcode/class/BCGcode39extended.barcode.php b/niucloud/core/util/barcode/class/BCGcode39extended.barcode.php new file mode 100644 index 000000000..fca6f1a26 --- /dev/null +++ b/niucloud/core/util/barcode/class/BCGcode39extended.barcode.php @@ -0,0 +1,208 @@ +keys[self::EXTENDED_1] = '($)'; + $this->keys[self::EXTENDED_2] = '(/)'; + $this->keys[self::EXTENDED_3] = '(+)'; + $this->keys[self::EXTENDED_4] = '(%)'; + } + + /** + * Parses the text before displaying it. + * + * @param mixed $text + */ + public function parse($text) { + $this->text = $text; + + $data = array(); + $indcheck = array(); + + $c = strlen($this->text); + for ($i = 0; $i < $c; $i++) { + $pos = array_search($this->text[$i], $this->keys); + if ($pos === false) { + // Search in extended? + $extended = self::getExtendedVersion($this->text[$i]); + if ($extended === false) { + throw new BCGParseException('code39extended', 'The character \'' . $this->text[$i] . '\' is not allowed.'); + } else { + $extc = strlen($extended); + for ($j = 0; $j < $extc; $j++) { + $v = $extended[$j]; + if ($v === '$') { + $indcheck[] = self::EXTENDED_1; + $data[] = $this->code[self::EXTENDED_1]; + } elseif ($v === '%') { + $indcheck[] = self::EXTENDED_2; + $data[] = $this->code[self::EXTENDED_2]; + } elseif ($v === '/') { + $indcheck[] = self::EXTENDED_3; + $data[] = $this->code[self::EXTENDED_3]; + } elseif ($v === '+') { + $indcheck[] = self::EXTENDED_4; + $data[] = $this->code[self::EXTENDED_4]; + } else { + $pos2 = array_search($v, $this->keys); + $indcheck[] = $pos2; + $data[] = $this->code[$pos2]; + } + } + } + } else { + $indcheck[] = $pos; + $data[] = $this->code[$pos]; + } + } + + $this->setData(array($indcheck, $data)); + $this->addDefaultLabel(); + } + + /** + * Draws the barcode. + * + * @param resource $im + */ + public function draw($im) { + // Starting * + $this->drawChar($im, $this->code[$this->starting], true); + $c = count($this->data); + for ($i = 0; $i < $c; $i++) { + $this->drawChar($im, $this->data[$i], true); + } + + // Checksum (rarely used) + if ($this->checksum === true) { + $this->drawChar($im, $this->code[$this->checksumValue % 43], true); + } + + // Ending * + $this->drawChar($im, $this->code[$this->ending], true); + $this->drawText($im, 0, 0, $this->positionX, $this->thickness); + } + + /** + * Returns the maximal size of a barcode. + * + * @param int $w + * @param int $h + * @return int[] + */ + public function getDimension($w, $h) { + $textlength = 13 * count($this->data); + $startlength = 13; + $checksumlength = 0; + if ($this->checksum === true) { + $checksumlength = 13; + } + + $endlength = 13; + + $w += $startlength + $textlength + $checksumlength + $endlength; + $h += $this->thickness; + return BCGBarcode1D::getDimension($w, $h); + } + + /** + * Validates the input. + */ + protected function validate() { + $c = count($this->data); + if ($c === 0) { + throw new BCGParseException('code39extended', 'No data has been entered.'); + } + + parent::validate(); + } + + /** + * Overloaded method to calculate checksum. + */ + protected function calculateChecksum() { + $this->checksumValue = 0; + $c = count($this->indcheck); + for ($i = 0; $i < $c; $i++) { + $this->checksumValue += $this->indcheck[$i]; + } + + $this->checksumValue = $this->checksumValue % 43; + } + + /** + * Saves data into the classes. + * + * This method will save data, calculate real column number + * (if -1 was selected), the real error level (if -1 was + * selected)... It will add Padding to the end and generate + * the error codes. + * + * @param array $data + */ + private function setData($data) { + $this->indcheck = $data[0]; + $this->data = $data[1]; + $this->calculateChecksum(); + } + + /** + * Returns the extended reprensentation of the character. + * + * @param string $char + * @return string + */ + private static function getExtendedVersion($char) { + $o = ord($char); + if ($o === 0) { + return '%U'; + } elseif ($o >= 1 && $o <= 26) { + return '$' . chr($o + 64); + } elseif (($o >= 33 && $o <= 44) || $o === 47 || $o === 48) { + return '/' . chr($o + 32); + } elseif ($o >= 97 && $o <= 122) { + return '+' . chr($o - 32); + } elseif ($o >= 27 && $o <= 31) { + return '%' . chr($o + 38); + } elseif ($o >= 59 && $o <= 63) { + return '%' . chr($o + 11); + } elseif ($o >= 91 && $o <= 95) { + return '%' . chr($o - 16); + } elseif ($o >= 123 && $o <= 127) { + return '%' . chr($o - 43); + } elseif ($o === 64) { + return '%V'; + } elseif ($o === 96) { + return '%W'; + } elseif ($o > 127) { + return false; + } else { + return $char; + } + } +} +?> \ No newline at end of file diff --git a/niucloud/core/util/barcode/class/BCGcode93.barcode.php b/niucloud/core/util/barcode/class/BCGcode93.barcode.php new file mode 100644 index 000000000..480e2c8fa --- /dev/null +++ b/niucloud/core/util/barcode/class/BCGcode93.barcode.php @@ -0,0 +1,301 @@ +starting = $this->ending = 47; /* * */ + $this->keys = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '-', '.', ' ', '$', '/', '+', '%', '($)', '(%)', '(/)', '(+)', '(*)'); + $this->code = array( + '020001', /* 0 */ + '000102', /* 1 */ + '000201', /* 2 */ + '000300', /* 3 */ + '010002', /* 4 */ + '010101', /* 5 */ + '010200', /* 6 */ + '000003', /* 7 */ + '020100', /* 8 */ + '030000', /* 9 */ + '100002', /* A */ + '100101', /* B */ + '100200', /* C */ + '110001', /* D */ + '110100', /* E */ + '120000', /* F */ + '001002', /* G */ + '001101', /* H */ + '001200', /* I */ + '011001', /* J */ + '021000', /* K */ + '000012', /* L */ + '000111', /* M */ + '000210', /* N */ + '010011', /* O */ + '020010', /* P */ + '101001', /* Q */ + '101100', /* R */ + '100011', /* S */ + '100110', /* T */ + '110010', /* U */ + '111000', /* V */ + '001011', /* W */ + '001110', /* X */ + '011010', /* Y */ + '012000', /* Z */ + '010020', /* - */ + '200001', /* . */ + '200100', /* */ + '210000', /* $ */ + '001020', /* / */ + '002010', /* + */ + '100020', /* % */ + '010110', /*($)*/ + '201000', /*(%)*/ + '200010', /*(/)*/ + '011100', /*(+)*/ + '000030' /*(*)*/ + ); + } + + /** + * Parses the text before displaying it. + * + * @param mixed $text + */ + public function parse($text) { + $this->text = $text; + + $data = array(); + $indcheck = array(); + + $c = strlen($this->text); + for ($i = 0; $i < $c; $i++) { + $pos = array_search($this->text[$i], $this->keys); + if ($pos === false) { + // Search in extended? + $extended = self::getExtendedVersion($this->text[$i]); + if ($extended === false) { + throw new BCGParseException('code93', 'The character \'' . $this->text[$i] . '\' is not allowed.'); + } else { + $extc = strlen($extended); + for ($j = 0; $j < $extc; $j++) { + $v = $extended[$j]; + if ($v === '$') { + $indcheck[] = self::EXTENDED_1; + $data[] = $this->code[self::EXTENDED_1]; + } elseif ($v === '%') { + $indcheck[] = self::EXTENDED_2; + $data[] = $this->code[self::EXTENDED_2]; + } elseif ($v === '/') { + $indcheck[] = self::EXTENDED_3; + $data[] = $this->code[self::EXTENDED_3]; + } elseif ($v === '+') { + $indcheck[] = self::EXTENDED_4; + $data[] = $this->code[self::EXTENDED_4]; + } else { + $pos2 = array_search($v, $this->keys); + $indcheck[] = $pos2; + $data[] = $this->code[$pos2]; + } + } + } + } else { + $indcheck[] = $pos; + $data[] = $this->code[$pos]; + } + } + + $this->setData(array($indcheck, $data)); + $this->addDefaultLabel(); + } + + /** + * Draws the barcode. + * + * @param resource $im + */ + public function draw($im) { + // Starting * + $this->drawChar($im, $this->code[$this->starting], true); + $c = count($this->data); + for ($i = 0; $i < $c; $i++) { + $this->drawChar($im, $this->data[$i], true); + } + + // Checksum + $c = count($this->checksumValue); + for ($i = 0; $i < $c; $i++) { + $this->drawChar($im, $this->code[$this->checksumValue[$i]], true); + } + + // Ending * + $this->drawChar($im, $this->code[$this->ending], true); + + // Draw a Final Bar + $this->drawChar($im, '0', true); + $this->drawText($im, 0, 0, $this->positionX, $this->thickness); + } + + /** + * Returns the maximal size of a barcode. + * + * @param int $w + * @param int $h + * @return int[] + */ + public function getDimension($w, $h) { + $startlength = 9; + $textlength = 9 * count($this->data); + $checksumlength = 2 * 9; + $endlength = 9 + 1; // + final bar + + $w += $startlength + $textlength + $checksumlength + $endlength; + $h += $this->thickness; + return parent::getDimension($w, $h); + } + + /** + * Validates the input. + */ + protected function validate() { + $c = count($this->data); + if ($c === 0) { + throw new BCGParseException('code93', 'No data has been entered.'); + } + + parent::validate(); + } + + /** + * Overloaded method to calculate checksum. + */ + protected function calculateChecksum() { + // Checksum + // First CheckSUM "C" + // The "C" checksum character is the modulo 47 remainder of the sum of the weighted + // value of the data characters. The weighting value starts at "1" for the right-most + // data character, 2 for the second to last, 3 for the third-to-last, and so on up to 20. + // After 20, the sequence wraps around back to 1. + + // Second CheckSUM "K" + // Same as CheckSUM "C" but we count the CheckSum "C" at the end + // After 15, the sequence wraps around back to 1. + $sequence_multiplier = array(20, 15); + $this->checksumValue = array(); + $indcheck = $this->indcheck; + for ($z = 0; $z < 2; $z++) { + $checksum = 0; + for ($i = count($indcheck), $j = 0; $i > 0; $i--, $j++) { + $multiplier = $i % $sequence_multiplier[$z]; + if ($multiplier === 0) { + $multiplier = $sequence_multiplier[$z]; + } + + $checksum += $indcheck[$j] * $multiplier; + } + + $this->checksumValue[$z] = $checksum % 47; + $indcheck[] = $this->checksumValue[$z]; + } + } + + /** + * Overloaded method to display the checksum. + */ + protected function processChecksum() { + if ($this->checksumValue === false) { // Calculate the checksum only once + $this->calculateChecksum(); + } + + if ($this->checksumValue !== false) { + $ret = ''; + $c = count($this->checksumValue); + for ($i = 0; $i < $c; $i++) { + $ret .= $this->keys[$this->checksumValue[$i]]; + } + + return $ret; + } + + return false; + } + + /** + * Saves data into the classes. + * + * This method will save data, calculate real column number + * (if -1 was selected), the real error level (if -1 was + * selected)... It will add Padding to the end and generate + * the error codes. + * + * @param array $data + */ + private function setData($data) { + $this->indcheck = $data[0]; + $this->data = $data[1]; + $this->calculateChecksum(); + } + + /** + * Returns the extended reprensentation of the character. + * + * @param string $char + * @return string + */ + private static function getExtendedVersion($char) { + $o = ord($char); + if ($o === 0) { + return '%U'; + } elseif ($o >= 1 && $o <= 26) { + return '$' . chr($o + 64); + } elseif (($o >= 33 && $o <= 44) || $o === 47 || $o === 48) { + return '/' . chr($o + 32); + } elseif ($o >= 97 && $o <= 122) { + return '+' . chr($o - 32); + } elseif ($o >= 27 && $o <= 31) { + return '%' . chr($o + 38); + } elseif ($o >= 59 && $o <= 63) { + return '%' . chr($o + 11); + } elseif ($o >= 91 && $o <= 95) { + return '%' . chr($o - 16); + } elseif ($o >= 123 && $o <= 127) { + return '%' . chr($o - 43); + } elseif ($o === 64) { + return '%V'; + } elseif ($o === 96) { + return '%W'; + } elseif ($o > 127) { + return false; + } else { + return $char; + } + } +} +?> \ No newline at end of file diff --git a/niucloud/core/util/barcode/class/BCGean13.barcode.php b/niucloud/core/util/barcode/class/BCGean13.barcode.php new file mode 100644 index 000000000..5289183e7 --- /dev/null +++ b/niucloud/core/util/barcode/class/BCGean13.barcode.php @@ -0,0 +1,322 @@ +keys = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'); + + // Left-Hand Odd Parity starting with a space + // Left-Hand Even Parity is the inverse (0=0012) starting with a space + // Right-Hand is the same of Left-Hand starting with a bar + $this->code = array( + '2100', /* 0 */ + '1110', /* 1 */ + '1011', /* 2 */ + '0300', /* 3 */ + '0021', /* 4 */ + '0120', /* 5 */ + '0003', /* 6 */ + '0201', /* 7 */ + '0102', /* 8 */ + '2001' /* 9 */ + ); + + // Parity, 0=Odd, 1=Even for manufacturer code. Depending on 1st System Digit + $this->codeParity = array( + array(0, 0, 0, 0, 0), /* 0 */ + array(0, 1, 0, 1, 1), /* 1 */ + array(0, 1, 1, 0, 1), /* 2 */ + array(0, 1, 1, 1, 0), /* 3 */ + array(1, 0, 0, 1, 1), /* 4 */ + array(1, 1, 0, 0, 1), /* 5 */ + array(1, 1, 1, 0, 0), /* 6 */ + array(1, 0, 1, 0, 1), /* 7 */ + array(1, 0, 1, 1, 0), /* 8 */ + array(1, 1, 0, 1, 0) /* 9 */ + ); + + $this->alignDefaultLabel(true); + } + + public function alignDefaultLabel($align) { + $this->alignLabel = (bool)$align; + } + + /** + * Draws the barcode. + * + * @param resource $im + */ + public function draw($im) { + $this->drawBars($im); + $this->drawText($im, 0, 0, $this->positionX, $this->thickness); + + if ($this->isDefaultEanLabelEnabled()) { + $dimension = $this->labelCenter1->getDimension(); + $this->drawExtendedBars($im, $dimension[1] - 2); + } + } + + /** + * Returns the maximal size of a barcode. + * + * @param int $w + * @param int $h + * @return int[] + */ + public function getDimension($w, $h) { + $startlength = 3; + $centerlength = 5; + $textlength = 12 * 7; + $endlength = 3; + + $w += $startlength + $centerlength + $textlength + $endlength; + $h += $this->thickness; + return parent::getDimension($w, $h); + } + + /** + * Adds the default label. + */ + protected function addDefaultLabel() { + if ($this->isDefaultEanLabelEnabled()) { + $this->processChecksum(); + $label = $this->getLabel(); + $font = $this->font; + + $this->labelLeft = new BCGLabel(substr($label, 0, 1), $font, BCGLabel::POSITION_LEFT, BCGLabel::ALIGN_BOTTOM); + $this->labelLeft->setSpacing(4 * $this->scale); + + $this->labelCenter1 = new BCGLabel(substr($label, 1, 6), $font, BCGLabel::POSITION_BOTTOM, BCGLabel::ALIGN_LEFT); + $labelCenter1Dimension = $this->labelCenter1->getDimension(); + $this->labelCenter1->setOffset(($this->scale * 44 - $labelCenter1Dimension[0]) / 2 + $this->scale * 2); + + $this->labelCenter2 = new BCGLabel(substr($label, 7, 5) . $this->keys[$this->checksumValue], $font, BCGLabel::POSITION_BOTTOM, BCGLabel::ALIGN_LEFT); + $this->labelCenter2->setOffset(($this->scale * 44 - $labelCenter1Dimension[0]) / 2 + $this->scale * 48); + + if ($this->alignLabel) { + $labelDimension = $this->labelCenter1->getDimension(); + $this->labelLeft->setOffset($labelDimension[1]); + } else { + $labelDimension = $this->labelLeft->getDimension(); + $this->labelLeft->setOffset($labelDimension[1] / 2); + } + + $this->addLabel($this->labelLeft); + $this->addLabel($this->labelCenter1); + $this->addLabel($this->labelCenter2); + } + } + + /** + * Checks if the default ean label is enabled. + * + * @return bool + */ + protected function isDefaultEanLabelEnabled() { + $label = $this->getLabel(); + $font = $this->font; + return $label !== null && $label !== '' && $font !== null && $this->defaultLabel !== null; + } + + /** + * Validates the input. + */ + protected function validate() { + $c = strlen($this->text); + if ($c === 0) { + throw new BCGParseException('ean13', 'No data has been entered.'); + } + + $this->checkCharsAllowed(); + $this->checkCorrectLength(); + + parent::validate(); + } + + /** + * Check chars allowed. + */ + protected function checkCharsAllowed() { + // Checking if all chars are allowed + $c = strlen($this->text); + for ($i = 0; $i < $c; $i++) { + if (array_search($this->text[$i], $this->keys) === false) { + throw new BCGParseException('ean13', 'The character \'' . $this->text[$i] . '\' is not allowed.'); + } + } + } + + /** + * Check correct length. + */ + protected function checkCorrectLength() { + // If we have 13 chars, just flush the last one without throwing anything + $c = strlen($this->text); + if ($c === 13) { + $this->text = substr($this->text, 0, 12); + } elseif ($c !== 12) { + throw new BCGParseException('ean13', 'Must contain 12 digits, the 13th digit is automatically added.'); + } + } + + /** + * Overloaded method to calculate checksum. + */ + protected function calculateChecksum() { + // Calculating Checksum + // Consider the right-most digit of the message to be in an "odd" position, + // and assign odd/even to each character moving from right to left + // Odd Position = 3, Even Position = 1 + // Multiply it by the number + // Add all of that and do 10-(?mod10) + $odd = true; + $this->checksumValue = 0; + $c = strlen($this->text); + for ($i = $c; $i > 0; $i--) { + if ($odd === true) { + $multiplier = 3; + $odd = false; + } else { + $multiplier = 1; + $odd = true; + } + + if (!isset($this->keys[$this->text[$i - 1]])) { + return; + } + + $this->checksumValue += $this->keys[$this->text[$i - 1]] * $multiplier; + } + + $this->checksumValue = (10 - $this->checksumValue % 10) % 10; + } + + /** + * Overloaded method to display the checksum. + */ + protected function processChecksum() { + if ($this->checksumValue === false) { // Calculate the checksum only once + $this->calculateChecksum(); + } + + if ($this->checksumValue !== false) { + return $this->keys[$this->checksumValue]; + } + + return false; + } + + /** + * Draws the bars + * + * @param resource $im + */ + protected function drawBars($im) { + // Checksum + $this->calculateChecksum(); + $temp_text = $this->text . $this->keys[$this->checksumValue]; + + // Starting Code + $this->drawChar($im, '000', true); + + // Draw Second Code + $this->drawChar($im, $this->findCode($temp_text[1]), false); + + // Draw Manufacturer Code + for ($i = 0; $i < 5; $i++) { + $this->drawChar($im, self::inverse($this->findCode($temp_text[$i + 2]), $this->codeParity[(int)$temp_text[0]][$i]), false); + } + + // Draw Center Guard Bar + $this->drawChar($im, '00000', false); + + // Draw Product Code + for ($i = 7; $i < 13; $i++) { + $this->drawChar($im, $this->findCode($temp_text[$i]), true); + } + + // Draw Right Guard Bar + $this->drawChar($im, '000', true); + } + + /** + * Draws the extended bars on the image. + * + * @param resource $im + * @param int $plus + */ + protected function drawExtendedBars($im, $plus) { + $rememberX = $this->positionX; + $rememberH = $this->thickness; + + // We increase the bars + $this->thickness = $this->thickness + intval($plus / $this->scale); + $this->positionX = 0; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + $this->positionX += 2; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + + // Center Guard Bar + $this->positionX += 44; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + $this->positionX += 2; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + + // Last Bars + $this->positionX += 44; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + $this->positionX += 2; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + + $this->positionX = $rememberX; + $this->thickness = $rememberH; + } + + /** + * Inverses the string when the $inverse parameter is equal to 1. + * + * @param string $text + * @param int $inverse + * @return string + */ + private static function inverse($text, $inverse = 1) { + if ($inverse === 1) { + $text = strrev($text); + } + + return $text; + } +} +?> \ No newline at end of file diff --git a/niucloud/core/util/barcode/class/BCGean8.barcode.php b/niucloud/core/util/barcode/class/BCGean8.barcode.php new file mode 100644 index 000000000..b89eb77b9 --- /dev/null +++ b/niucloud/core/util/barcode/class/BCGean8.barcode.php @@ -0,0 +1,244 @@ +keys = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'); + + // Left-Hand Odd Parity starting with a space + // Right-Hand is the same of Left-Hand starting with a bar + $this->code = array( + '2100', /* 0 */ + '1110', /* 1 */ + '1011', /* 2 */ + '0300', /* 3 */ + '0021', /* 4 */ + '0120', /* 5 */ + '0003', /* 6 */ + '0201', /* 7 */ + '0102', /* 8 */ + '2001' /* 9 */ + ); + } + + /** + * Draws the barcode. + * + * @param resource $im + */ + public function draw($im) { + // Checksum + $this->calculateChecksum(); + $temp_text = $this->text . $this->keys[$this->checksumValue]; + + // Starting Code + $this->drawChar($im, '000', true); + + // Draw First 4 Chars (Left-Hand) + for ($i = 0; $i < 4; $i++) { + $this->drawChar($im, $this->findCode($temp_text[$i]), false); + } + + // Draw Center Guard Bar + $this->drawChar($im, '00000', false); + + // Draw Last 4 Chars (Right-Hand) + for ($i = 4; $i < 8; $i++) { + $this->drawChar($im, $this->findCode($temp_text[$i]), true); + } + + // Draw Right Guard Bar + $this->drawChar($im, '000', true); + $this->drawText($im, 0, 0, $this->positionX, $this->thickness); + + if ($this->isDefaultEanLabelEnabled()) { + $dimension = $this->labelRight->getDimension(); + $this->drawExtendedBars($im, $dimension[1] - 2); + } + } + + /** + * Returns the maximal size of a barcode. + * + * @param int $w + * @param int $h + * @return int[] + */ + public function getDimension($w, $h) { + $startlength = 3; + $centerlength = 5; + $textlength = 8 * 7; + $endlength = 3; + + $w += $startlength + $centerlength + $textlength + $endlength; + $h += $this->thickness; + return parent::getDimension($w, $h); + } + + /** + * Adds the default label. + */ + protected function addDefaultLabel() { + if ($this->isDefaultEanLabelEnabled()) { + $this->processChecksum(); + $label = $this->getLabel(); + $font = $this->font; + + $this->labelLeft = new BCGLabel(substr($label, 0, 4), $font, BCGLabel::POSITION_BOTTOM, BCGLabel::ALIGN_LEFT); + $labelLeftDimension = $this->labelLeft->getDimension(); + $this->labelLeft->setOffset(($this->scale * 30 - $labelLeftDimension[0]) / 2 + $this->scale * 2); + + $this->labelRight = new BCGLabel(substr($label, 4, 3) . $this->keys[$this->checksumValue], $font, BCGLabel::POSITION_BOTTOM, BCGLabel::ALIGN_LEFT); + $labelRightDimension = $this->labelRight->getDimension(); + $this->labelRight->setOffset(($this->scale * 30 - $labelRightDimension[0]) / 2 + $this->scale * 34); + + $this->addLabel($this->labelLeft); + $this->addLabel($this->labelRight); + } + } + + /** + * Checks if the default ean label is enabled. + * + * @return bool + */ + protected function isDefaultEanLabelEnabled() { + $label = $this->getLabel(); + $font = $this->font; + return $label !== null && $label !== '' && $font !== null && $this->defaultLabel !== null; + } + + /** + * Validates the input. + */ + protected function validate() { + $c = strlen($this->text); + if ($c === 0) { + throw new BCGParseException('ean8', 'No data has been entered.'); + } + + // Checking if all chars are allowed + for ($i = 0; $i < $c; $i++) { + if (array_search($this->text[$i], $this->keys) === false) { + throw new BCGParseException('ean8', 'The character \'' . $this->text[$i] . '\' is not allowed.'); + } + } + + // If we have 8 chars just flush the last one + if ($c === 8) { + $this->text = substr($this->text, 0, 7); + } elseif ($c !== 7) { + throw new BCGParseException('ean8', 'Must contain 7 digits, the 8th digit is automatically added.'); + } + + parent::validate(); + } + + /** + * Overloaded method to calculate checksum. + */ + protected function calculateChecksum() { + // Calculating Checksum + // Consider the right-most digit of the message to be in an "odd" position, + // and assign odd/even to each character moving from right to left + // Odd Position = 3, Even Position = 1 + // Multiply it by the number + // Add all of that and do 10-(?mod10) + $odd = true; + $this->checksumValue = 0; + $c = strlen($this->text); + for ($i = $c; $i > 0; $i--) { + if ($odd === true) { + $multiplier = 3; + $odd = false; + } else { + $multiplier = 1; + $odd = true; + } + + if (!isset($this->keys[$this->text[$i - 1]])) { + return; + } + + $this->checksumValue += $this->keys[$this->text[$i - 1]] * $multiplier; + } + + $this->checksumValue = (10 - $this->checksumValue % 10) % 10; + } + + /** + * Overloaded method to display the checksum. + */ + protected function processChecksum() { + if ($this->checksumValue === false) { // Calculate the checksum only once + $this->calculateChecksum(); + } + + if ($this->checksumValue !== false) { + return $this->keys[$this->checksumValue]; + } + + return false; + } + + /** + * Draws the extended bars on the image. + * + * @param resource $im + * @param int $plus + */ + private function drawExtendedBars($im, $plus) { + $rememberX = $this->positionX; + $rememberH = $this->thickness; + + // We increase the bars + $this->thickness = $this->thickness + intval($plus / $this->scale); + $this->positionX = 0; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + $this->positionX += 2; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + + // Center Guard Bar + $this->positionX += 30; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + $this->positionX += 2; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + + // Last Bars + $this->positionX += 30; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + $this->positionX += 2; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + + $this->positionX = $rememberX; + $this->thickness = $rememberH; + } +} +?> \ No newline at end of file diff --git a/niucloud/core/util/barcode/class/BCGgs1128.barcode.php b/niucloud/core/util/barcode/class/BCGgs1128.barcode.php new file mode 100644 index 000000000..0393f245b --- /dev/null +++ b/niucloud/core/util/barcode/class/BCGgs1128.barcode.php @@ -0,0 +1,679 @@ +identifiersAi = array( + '00' => array(self::NUMERIC, 18, 18, true), + '01' => array(self::NUMERIC, 14, 14, true), + '02' => array(self::NUMERIC, 14, 14, true), + '10' => array(self::ALPHA_NUMERIC, 1, 20, false), + '11' => array(self::DATE_YYMMDD, 6, 6, false), + '12' => array(self::DATE_YYMMDD, 6, 6, false), + '13' => array(self::DATE_YYMMDD, 6, 6, false), + '15' => array(self::DATE_YYMMDD, 6, 6, false), + '17' => array(self::DATE_YYMMDD, 6, 6, false), + '20' => array(self::NUMERIC, 2, 2, false), + '21' => array(self::ALPHA_NUMERIC, 1, 20, false), + '240' => array(self::ALPHA_NUMERIC, 1, 30, false), + '241' => array(self::ALPHA_NUMERIC, 1, 30, false), + '250' => array(self::ALPHA_NUMERIC, 1, 30, false), + '251' => array(self::ALPHA_NUMERIC, 1, 30, false), + '253' => array(self::NUMERIC, 14, 30, false), + '30' => array(self::NUMERIC, 1, 8, false), + '310y' => array(self::NUMERIC, 6, 6, false), + '311y' => array(self::NUMERIC, 6, 6, false), + '312y' => array(self::NUMERIC, 6, 6, false), + '313y' => array(self::NUMERIC, 6, 6, false), + '314y' => array(self::NUMERIC, 6, 6, false), + '315y' => array(self::NUMERIC, 6, 6, false), + '316y' => array(self::NUMERIC, 6, 6, false), + '320y' => array(self::NUMERIC, 6, 6, false), + '321y' => array(self::NUMERIC, 6, 6, false), + '322y' => array(self::NUMERIC, 6, 6, false), + '323y' => array(self::NUMERIC, 6, 6, false), + '324y' => array(self::NUMERIC, 6, 6, false), + '325y' => array(self::NUMERIC, 6, 6, false), + '326y' => array(self::NUMERIC, 6, 6, false), + '327y' => array(self::NUMERIC, 6, 6, false), + '328y' => array(self::NUMERIC, 6, 6, false), + '329y' => array(self::NUMERIC, 6, 6, false), + '330y' => array(self::NUMERIC, 6, 6, false), + '331y' => array(self::NUMERIC, 6, 6, false), + '332y' => array(self::NUMERIC, 6, 6, false), + '333y' => array(self::NUMERIC, 6, 6, false), + '334y' => array(self::NUMERIC, 6, 6, false), + '335y' => array(self::NUMERIC, 6, 6, false), + '336y' => array(self::NUMERIC, 6, 6, false), + '337y' => array(self::NUMERIC, 6, 6, false), + '340y' => array(self::NUMERIC, 6, 6, false), + '341y' => array(self::NUMERIC, 6, 6, false), + '342y' => array(self::NUMERIC, 6, 6, false), + '343y' => array(self::NUMERIC, 6, 6, false), + '344y' => array(self::NUMERIC, 6, 6, false), + '345y' => array(self::NUMERIC, 6, 6, false), + '346y' => array(self::NUMERIC, 6, 6, false), + '347y' => array(self::NUMERIC, 6, 6, false), + '348y' => array(self::NUMERIC, 6, 6, false), + '349y' => array(self::NUMERIC, 6, 6, false), + '350y' => array(self::NUMERIC, 6, 6, false), + '351y' => array(self::NUMERIC, 6, 6, false), + '352y' => array(self::NUMERIC, 6, 6, false), + '353y' => array(self::NUMERIC, 6, 6, false), + '354y' => array(self::NUMERIC, 6, 6, false), + '355y' => array(self::NUMERIC, 6, 6, false), + '356y' => array(self::NUMERIC, 6, 6, false), + '357y' => array(self::NUMERIC, 6, 6, false), + '360y' => array(self::NUMERIC, 6, 6, false), + '361y' => array(self::NUMERIC, 6, 6, false), + '362y' => array(self::NUMERIC, 6, 6, false), + '363y' => array(self::NUMERIC, 6, 6, false), + '364y' => array(self::NUMERIC, 6, 6, false), + '365y' => array(self::NUMERIC, 6, 6, false), + '366y' => array(self::NUMERIC, 6, 6, false), + '367y' => array(self::NUMERIC, 6, 6, false), + '368y' => array(self::NUMERIC, 6, 6, false), + '369y' => array(self::NUMERIC, 6, 6, false), + '37' => array(self::NUMERIC, 1, 8, false), + '390y' => array(self::NUMERIC, 1, 15, false), + '391y' => array(self::NUMERIC, 4, 18, false), + '392y' => array(self::NUMERIC, 1, 15, false), + '393y' => array(self::NUMERIC, 4, 18, false), + '400' => array(self::ALPHA_NUMERIC, 1, 30, false), + '401' => array(self::ALPHA_NUMERIC, 1, 30, false), + '402' => array(self::NUMERIC, 17, 17, false), + '403' => array(self::ALPHA_NUMERIC, 1, 30, false), + '410' => array(self::NUMERIC, 13, 13, true), + '411' => array(self::NUMERIC, 13, 13, true), + '412' => array(self::NUMERIC, 13, 13, true), + '413' => array(self::NUMERIC, 13, 13, true), + '414' => array(self::NUMERIC, 13, 13, true), + '415' => array(self::NUMERIC, 13, 13, true), + '420' => array(self::ALPHA_NUMERIC, 1, 20, false), + '421' => array(self::ALPHA_NUMERIC, 4, 12, false), + '422' => array(self::NUMERIC, 3, 3, false), + '8001' => array(self::NUMERIC, 14, 14, false), + '8002' => array(self::ALPHA_NUMERIC, 1, 20, false), + '8003' => array(self::ALPHA_NUMERIC, 15, 30, false), + '8004' => array(self::ALPHA_NUMERIC, 1, 30, false), + '8005' => array(self::NUMERIC, 6, 6, false), + '8006' => array(self::NUMERIC, 18, 18, false), + '8007' => array(self::ALPHA_NUMERIC, 1, 30, false), + '8018' => array(self::NUMERIC, 18, 18, false), + '8020' => array(self::ALPHA_NUMERIC, 1, 25, false), + '8100' => array(self::NUMERIC, 6, 6, false), + '8101' => array(self::NUMERIC, 10, 10, false), + '8102' => array(self::NUMERIC, 2, 2, false), + '90' => array(self::ALPHA_NUMERIC, 1, 30, false), + '91' => array(self::ALPHA_NUMERIC, 1, 30, false), + '92' => array(self::ALPHA_NUMERIC, 1, 30, false), + '93' => array(self::ALPHA_NUMERIC, 1, 30, false), + '94' => array(self::ALPHA_NUMERIC, 1, 30, false), + '95' => array(self::ALPHA_NUMERIC, 1, 30, false), + '96' => array(self::ALPHA_NUMERIC, 1, 30, false), + '97' => array(self::ALPHA_NUMERIC, 1, 30, false), + '98' => array(self::ALPHA_NUMERIC, 1, 30, false), + '99' => array(self::ALPHA_NUMERIC, 1, 30, false) + ); + + $this->setStrictMode(true); + $this->setTilde(true); + $this->setAllowsUnknownIdentifier(false); + $this->setNoLengthLimit(false); + } + + /** + * Gets the content checksum for an identifier. + * Do not pass the identifier code. + * + * @param string $content + * @return int + */ + public static function getAiContentChecksum($content) { + return self::calculateChecksumMod10($content); + } + + /** + * Enables or disables the strict mode. + * + * @param bool $strictMode + */ + public function setStrictMode($strictMode) { + $this->strictMode = $strictMode; + } + + /** + * Gets if the strict mode is activated. + * + * @return bool + */ + public function getStrictMode() { + return $this->strictMode; + } + + /** + * Allows unknown identifiers. + * + * @param bool $allow + */ + public function setAllowsUnknownIdentifier($allow) { + $this->allowsUnknownIdentifier = (bool)$allow; + } + + /** + * Gets if unkmown identifiers are allowed. + * + * @return bool + */ + public function getAllowsUnknownIdentifier() { + return $this->allowsUnknownIdentifier; + } + + /** + * Removes the limit of 48 characters. + * + * @param bool $noLengthLimit + */ + public function setNoLengthLimit($noLengthLimit) { + $this->noLengthLimit = (bool)$noLengthLimit; + } + + /** + * Gets if the limit of 48 characters is removed. + * + * @return bool + */ + public function getNoLengthLimit() { + return $this->noLengthLimit; + } + + /** + * Parses Text. + * + * @param string $text + */ + public function parse($text) { + parent::parse($this->parseGs1128($text)); + } + + /** + * Formats data for gs1-128. + * + * @return string + */ + private function formatGs1128() { + $formatedText = '~F1'; + $formatedLabel = ''; + $c = count($this->identifiersId); + + for ($i = 0; $i < $c; $i++) { + if ($i > 0) { + $formatedLabel .= ' '; + } + + if ($this->identifiersId[$i] !== null) { + $formatedLabel .= '(' . $this->identifiersId[$i] . ')'; + } + + $formatedText .= $this->identifiersId[$i]; + + $formatedLabel .= $this->identifiersContent[$i]; + $formatedText .= $this->identifiersContent[$i]; + + if (isset($this->identifiersAi[$this->identifiersId[$i]])) { + $ai_data = $this->identifiersAi[$this->identifiersId[$i]]; + } elseif (isset($this->identifiersId[$i][3])) { + $identifierWithVar = substr($this->identifiersId[$i], 0, -1) . 'y'; + $ai_data = isset($this->identifiersAi[$identifierWithVar]) ? $this->identifiersAi[$identifierWithVar] : null; + } else { + $ai_data = null; + } + + /* We'll check if we need to add a ~F1 () char */ + /* If we use the legacy mode, we always add a ~F1 () char between AIs */ + if ($ai_data !== null) { + if ((strlen($this->identifiersContent[$i]) < $ai_data[self::MAXLENGTH] && ($i + 1) !== $c) || (!$this->strictMode && ($i + 1) !== $c)) { + $formatedText .= '~F1'; + } + } elseif ($this->allowsUnknownIdentifier && $this->identifiersId[$i] === null && ($i + 1) !== $c) { + /* If this id is unknown, we add a ~F1 () char */ + $formatedText .= '~F1'; + } + } + + if ($this->noLengthLimit === false && (strlen(str_replace('~F1', chr(29), $formatedText)) - 1) > self::MAX_GS1128_CHARS) { + throw new BCGParseException('gs1128', 'The barcode can\'t contain more than ' . self::MAX_GS1128_CHARS . ' characters.'); + } + + $this->label = $formatedLabel; + return $formatedText; + } + + /** + * Parses the text to gs1-128. + * + * @param mixed $text + * @return mixed + */ + private function parseGs1128($text) { + /* We format correctly what the user gives */ + if (is_array($text)) { + $formatArray = array(); + foreach ($text as $content) { + if (is_array($content)) { /* double array */ + if (count($content) === 2) { + if (is_array($content[self::ID]) || is_array($content[self::CONTENT])) { + throw new BCGParseException('gs1128', 'Double arrays can\'t contain arrays.'); + } else { + $formatArray[] = '(' . $content[self::ID] . ')' . $content[self::CONTENT]; + } + } else { + throw new BCGParseException('gs1128', 'Double arrays must contain 2 values.'); + } + } else { /* simple array */ + $formatArray[] = $content; + } + } + + unset($text); + $text = $formatArray; + } else { /* string */ + $text = array($text); + } + + $textCount = count($text); + for ($cmpt = 0; $cmpt < $textCount; $cmpt++) { + /* We parse the content of the array */ + if (!$this->parseContent($text[$cmpt])) { + return; + } + } + + return $this->formatGs1128(); + } + + /** + * Splits the id and the content for each application identifiers (AIs). + * + * @param string $text + * @param int $cmpt + * @return bool + */ + private function parseContent($text) { + /* $yAlreadySet has 3 states: */ + /* null: There is no variable in the ID; true: the variable is already set; false: the variable is not set yet; */ + $content = null; + $yAlreadySet = null; + $realNameId = null; + $separatorsFound = 0; + $checksumAdded = 0; + $decimalPointRemoved = 0; + $toParse = str_replace('~F1', chr(29), $text); + $nbCharToParse = strlen($toParse); + $nbCharId = 0; + $isFormated = $toParse[0] === '(' ? true : false; + $maxCharId = $isFormated ? self::MAX_ID_FORMATED : self::MAX_ID_NOT_FORMATED; + $id = strtolower(substr($toParse, 0, min($maxCharId, $nbCharToParse))); + $id = $isFormated ? $this->findIdFormated($id, $yAlreadySet, $realNameId) : $this->findIdNotFormated($id, $yAlreadySet, $realNameId); + + if ($id === false) { + if ($this->allowsUnknownIdentifier === false) { + return false; + } + + $id = null; + $nbCharId = 0; + $content = $toParse; + } else { + $nbCharId = strlen($id) + ($isFormated ? 2 : 0); + $n = min($this->identifiersAi[$realNameId][self::MAXLENGTH], $nbCharToParse); + $content = substr($toParse, $nbCharId, $n); + } + + if ($id !== null) { + /* If we have an AI with an "y" var, we check if there is a decimal point in the next *MAXLENGTH* characters */ + /* if there is one, we take an extra character */ + if ($yAlreadySet !== null) { + if (strpos($content, '.') !== false || strpos($content, ',') !== false) { + $n++; + if ($n <= $nbCharToParse) { + /* We take an extra char */ + $content = substr($toParse, $nbCharId, $n); + } + } + } + } + + /* We check for separator */ + $separator = strpos($content, chr(29)); + if ($separator !== false) { + $content = substr($content, 0, $separator); + $separatorsFound++; + } + + if ($id !== null) { + /* We check the conformity */ + if (!$this->checkConformity($content, $id, $realNameId)) { + return false; + } + + /* We check the checksum */ + if (!$this->checkChecksum($content, $id, $realNameId, $checksumAdded)) { + return false; + } + + /* We check the vars */ + if (!$this->checkVars($content, $id, $yAlreadySet, $decimalPointRemoved)) { + return false; + } + } + + $this->identifiersId[] = $id; + $this->identifiersContent[] = $content; + + $nbCharLastContent = (((strlen($content) + $nbCharId) - $checksumAdded) + $decimalPointRemoved) + $separatorsFound; + if ($nbCharToParse - $nbCharLastContent > 0) { + /* If there is more than one content in this array, we parse again */ + $otherContent = substr($toParse, $nbCharLastContent, $nbCharToParse); + $nbCharOtherContent = strlen($otherContent); + + if ($otherContent[0] === chr(29)) { + $otherContent = substr($otherContent, 1); + $nbCharOtherContent--; + } + + if ($nbCharOtherContent > 0) { + $text = $otherContent; + return $this->parseContent($text); + } + } + + return true; + } + + /** + * Checks if an id exists. + * + * @param string $id + * @param bool $yAlreadySet + * @param string $realNameId + * @return bool + */ + private function idExists($id, &$yAlreadySet, &$realNameId) { + $yFound = isset($id[3]) && $id[3] === 'y'; + $idVarAdded = substr($id, 0, -1) . 'y'; + + if (isset($this->identifiersAi[$id])) { + if ($yFound) { + $yAlreadySet = false; + } + + $realNameId = $id; + return true; + } elseif (!$yFound && isset($this->identifiersAi[$idVarAdded])) { + /* if the id don't exist, we try to find this id with "y" at the last char */ + $yAlreadySet = true; + $realNameId = $idVarAdded; + return true; + } + + return false; + } + + /** + * Finds ID with formated content. + * + * @param string $id + * @param bool $yAlreadySet + * @param string $realNameId + * @return mixed + */ + private function findIdFormated($id, &$yAlreadySet, &$realNameId) { + $pos = strpos($id, ')'); + if ($pos === false) { + throw new BCGParseException('gs1128', 'Identifiers must have no more than 4 characters.'); + } else { + if ($pos < 3) { + throw new BCGParseException('gs1128', 'Identifiers must have at least 2 characters.'); + } + + $id = substr($id, 1, $pos - 1); + if ($this->idExists($id, $yAlreadySet, $realNameId)) { + return $id; + } + + if ($this->allowsUnknownIdentifier === false) { + throw new BCGParseException('gs1128', 'The identifier ' . $id . ' doesn\'t exist.'); + } + + return false; + } + } + + /** + * Finds ID with non-formated content. + * + * @param string $id + * @param bool $yAlreadySet + * @param string $realNameId + * @return mixed + */ + private function findIdNotFormated($id, &$yAlreadySet, &$realNameId) { + $tofind = $id; + + while (strlen($tofind) >= 2) { + if ($this->idExists($tofind, $yAlreadySet, $realNameId)) { + return $tofind; + } else { + $tofind = substr($tofind, 0, -1); + } + } + + if ($this->allowsUnknownIdentifier === false) { + throw new BCGParseException('gs1128', 'Error in formatting, can\'t find an identifier.'); + } + + return false; + } + + /** + * Checks confirmity of the content. + * + * @param string $content + * @param string $id + * @param string $realNameId + * @return bool + */ + private function checkConformity(&$content, $id, $realNameId) { + switch ($this->identifiersAi[$realNameId][self::KIND_OF_DATA]) { + case self::NUMERIC: + $content = str_replace(',', '.', $content); + if (!preg_match("/^[0-9.]+$/", $content)) { + throw new BCGParseException('gs1128', 'The value of "' . $id . '" must be numerical.'); + } + + break; + case self::DATE_YYMMDD: + $valid_date = true; + if (preg_match("/^[0-9]{6}$/", $content)) { + $year = substr($content, 0, 2); + $month = substr($content, 2, 2); + $day = substr($content, 4, 2); + + /* day can be 00 if we only need month and year */ + if (intval($month) < 1 || intval($month) > 12 || intval($day) < 0 || intval($day) > 31) { + $valid_date = false; + } + } else { + $valid_date = false; + } + + if (!$valid_date) { + throw new BCGParseException('gs1128', 'The value of "' . $id . '" must be in YYMMDD format.'); + } + + break; + } + + // We check the length of the content + $nbCharContent = strlen($content); + $checksumChar = 0; + $minlengthContent = $this->identifiersAi[$realNameId][self::MINLENGTH]; + $maxlengthContent = $this->identifiersAi[$realNameId][self::MAXLENGTH]; + + if ($this->identifiersAi[$realNameId][self::CHECKSUM]) { + $checksumChar++; + } + + if ($nbCharContent < ($minlengthContent - $checksumChar)) { + if ($minlengthContent === $maxlengthContent) { + throw new BCGParseException('gs1128', 'The value of "' . $id . '" must contain ' . $minlengthContent . ' character(s).'); + } else { + throw new BCGParseException('gs1128', 'The value of "' . $id . '" must contain between ' . $minlengthContent . ' and ' . $maxlengthContent . ' character(s).'); + } + } + + return true; + } + + /** + * Verifies the checksum. + * + * @param string $content + * @param string $id + * @param int $realNameId + * @param int $checksumAdded + * @return bool + */ + private function checkChecksum(&$content, $id, $realNameId, &$checksumAdded) { + if ($this->identifiersAi[$realNameId][self::CHECKSUM]) { + $nbCharContent = strlen($content); + $minlengthContent = $this->identifiersAi[$realNameId][self::MINLENGTH]; + if ($nbCharContent === ($minlengthContent - 1)) { + /* we need to calculate the checksum */ + $content .= self::getAiContentChecksum($content); + $checksumAdded++; + } elseif ($nbCharContent === $minlengthContent) { + /* we need to check the checksum */ + $checksum = self::getAiContentChecksum(substr($content, 0, -1)); + if (intval($content[$nbCharContent - 1]) !== $checksum) { + throw new BCGParseException('gs1128', 'The checksum of "(' . $id . ') ' . $content . '" must be: ' . $checksum); + } + } + } + + return true; + } + + /** + * Checks vars "y". + * + * @param string $content + * @param string $id + * @param bool $yAlreadySet + * @param int $decimalPointRemoved + * @return bool + */ + private function checkVars(&$content, &$id, $yAlreadySet, &$decimalPointRemoved) { + $nbCharContent = strlen($content); + /* We check for "y" var in AI */ + if ($yAlreadySet) { + /* We'll check if we have a decimal point */ + if (strpos($content, '.') !== false) { + throw new BCGParseException('gs1128', 'If you do not use any "y" variable, you have to insert a whole number.'); + } + } elseif ($yAlreadySet !== null) { + /* We need to replace the "y" var with the position of the decimal point */ + $pos = strpos($content, '.'); + if ($pos === false) { + $pos = $nbCharContent - 1; + } + + $id = str_replace('y', $nbCharContent - ($pos + 1), strtolower($id)); + $content = str_replace('.', '', $content); + $decimalPointRemoved++; + } + + return true; + } + + /** + * Checksum Mod10. + * + * @param int $content + * @return int + */ + private static function calculateChecksumMod10($content) { + // Calculating Checksum + // Consider the right-most digit of the message to be in an "odd" position, + // and assign odd/even to each character moving from right to left + // Odd Position = 3, Even Position = 1 + // Multiply it by the number + // Add all of that and do 10-(?mod10) + $odd = true; + $checksumValue = 0; + $c = strlen($content); + + for ($i = $c; $i > 0; $i--) { + if ($odd === true) { + $multiplier = 3; + $odd = false; + } else { + $multiplier = 1; + $odd = true; + } + + $checksumValue += ($content[$i - 1] * $multiplier); + } + + return (10 - $checksumValue % 10) % 10; + } +} +?> \ No newline at end of file diff --git a/niucloud/core/util/barcode/class/BCGi25.barcode.php b/niucloud/core/util/barcode/class/BCGi25.barcode.php new file mode 100644 index 000000000..d4ee00c6d --- /dev/null +++ b/niucloud/core/util/barcode/class/BCGi25.barcode.php @@ -0,0 +1,203 @@ +keys = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'); + $this->code = array( + '00110', /* 0 */ + '10001', /* 1 */ + '01001', /* 2 */ + '11000', /* 3 */ + '00101', /* 4 */ + '10100', /* 5 */ + '01100', /* 6 */ + '00011', /* 7 */ + '10010', /* 8 */ + '01010' /* 9 */ + ); + + $this->setChecksum(false); + $this->setRatio(2); + } + + /** + * Sets the checksum. + * + * @param bool $checksum + */ + public function setChecksum($checksum) { + $this->checksum = (bool)$checksum; + } + + /** + * Sets the ratio of the black bar compared to the white bars. + * + * @param int $ratio + */ + public function setRatio($ratio) { + $this->ratio = $ratio; + } + + /** + * Draws the barcode. + * + * @param resource $im + */ + public function draw($im) { + $temp_text = $this->text; + + // Checksum + if ($this->checksum === true) { + $this->calculateChecksum(); + $temp_text .= $this->keys[$this->checksumValue]; + } + + // Starting Code + $this->drawChar($im, '0000', true); + + // Chars + $c = strlen($temp_text); + for ($i = 0; $i < $c; $i += 2) { + $temp_bar = ''; + $c2 = strlen($this->findCode($temp_text[$i])); + for ($j = 0; $j < $c2; $j++) { + $temp_bar .= substr($this->findCode($temp_text[$i]), $j, 1); + $temp_bar .= substr($this->findCode($temp_text[$i + 1]), $j, 1); + } + + $this->drawChar($im, $this->changeBars($temp_bar), true); + } + + // Ending Code + $this->drawChar($im, $this->changeBars('100'), true); + $this->drawText($im, 0, 0, $this->positionX, $this->thickness); + } + + /** + * Returns the maximal size of a barcode. + * + * @param int $w + * @param int $h + * @return int[] + */ + public function getDimension($w, $h) { + $textlength = (3 + ($this->ratio + 1) * 2) * strlen($this->text); + $startlength = 4; + $checksumlength = 0; + if ($this->checksum === true) { + $checksumlength = (3 + ($this->ratio + 1) * 2); + } + + $endlength = 2 + ($this->ratio + 1); + + $w += $startlength + $textlength + $checksumlength + $endlength; + $h += $this->thickness; + return parent::getDimension($w, $h); + } + + /** + * Validates the input. + */ + protected function validate() { + $c = strlen($this->text); + if ($c === 0) { + throw new BCGParseException('i25', 'No data has been entered.'); + } + + // Checking if all chars are allowed + for ($i = 0; $i < $c; $i++) { + if (array_search($this->text[$i], $this->keys) === false) { + throw new BCGParseException('i25', 'The character \'' . $this->text[$i] . '\' is not allowed.'); + } + } + + // Must be even + if ($c % 2 !== 0 && $this->checksum === false) { + throw new BCGParseException('i25', 'i25 must contain an even amount of digits if checksum is false.'); + } elseif ($c % 2 === 0 && $this->checksum === true) { + throw new BCGParseException('i25', 'i25 must contain an odd amount of digits if checksum is true.'); + } + + parent::validate(); + } + + /** + * Overloaded method to calculate checksum. + */ + protected function calculateChecksum() { + // Calculating Checksum + // Consider the right-most digit of the message to be in an "even" position, + // and assign odd/even to each character moving from right to left + // Even Position = 3, Odd Position = 1 + // Multiply it by the number + // Add all of that and do 10-(?mod10) + $even = true; + $this->checksumValue = 0; + $c = strlen($this->text); + for ($i = $c; $i > 0; $i--) { + if ($even === true) { + $multiplier = 3; + $even = false; + } else { + $multiplier = 1; + $even = true; + } + + $this->checksumValue += $this->keys[$this->text[$i - 1]] * $multiplier; + } + + $this->checksumValue = (10 - $this->checksumValue % 10) % 10; + } + + /** + * Overloaded method to display the checksum. + */ + protected function processChecksum() { + if ($this->checksumValue === false) { // Calculate the checksum only once + $this->calculateChecksum(); + } + + if ($this->checksumValue !== false) { + return $this->keys[$this->checksumValue]; + } + + return false; + } + + /** + * Changes the size of the bars based on the ratio + * + * @param string $in + * @return string + */ + private function changeBars($in) { + if ($this->ratio > 1) { + $c = strlen($in); + for ($i = 0; $i < $c; $i++) { + $in[$i] = $in[$i] === '1' ? $this->ratio : $in[$i]; + } + } + + return $in; + } +} +?> \ No newline at end of file diff --git a/niucloud/core/util/barcode/class/BCGintelligentmail.barcode.php b/niucloud/core/util/barcode/class/BCGintelligentmail.barcode.php new file mode 100644 index 000000000..cb2a5f3cb --- /dev/null +++ b/niucloud/core/util/barcode/class/BCGintelligentmail.barcode.php @@ -0,0 +1,649 @@ +setQuietZone(true); + $this->setThickness(9); + } + + /** + * Gets the Quiet zone. + * + * @return bool + */ + public function getQuietZone() { + return $this->quietZone; + } + + /** + * Sets the Quiet zone. + * + * @param bool $quietZone + */ + public function setQuietZone($quietZone) { + $this->quietZone = (bool)$quietZone; + } + + /** + * Sets the tracking code. + * + * @param int $barcodeIdentifier 2-digit number. 2nd digit must be 0-4 + * @param int $serviceTypeIdentifier 3 digits + * @param int $mailerIdentifier 6 or 9 digits + * @param int $serialNumber 9 (if mailerId is 6) or 6 digits (if mailerId is 9) + */ + public function setTrackingCode($barcodeIdentifier, $serviceTypeIdentifier, $mailerIdentifier, $serialNumber) { + $barcodeIdentifier = (string)(int)$barcodeIdentifier; + $serviceTypeIdentifier = (int)$serviceTypeIdentifier; + $mailerIdentifier = (int)$mailerIdentifier; + $serialNumber = (string)(int)$serialNumber; + + $barcodeIdentifier = str_pad($barcodeIdentifier, 2, '0', STR_PAD_LEFT); + + if (strlen($barcodeIdentifier) !== 2) { + throw new BCGArgumentException('Barcode Identifier must contain 2 digits.', 'barcodeIdentifier'); + } + + $barcodeIdentifierSecondNumber = $barcodeIdentifier[1]; + if ($barcodeIdentifierSecondNumber !== '0' && $barcodeIdentifierSecondNumber !== '1' && $barcodeIdentifierSecondNumber !== '2' && $barcodeIdentifierSecondNumber !== '3' && $barcodeIdentifierSecondNumber !== '4') { + throw new BCGArgumentException('Barcode Identifier second digit must be a number between 0 and 4.', 'barcodeIdentifier'); + } + + if ($serviceTypeIdentifier < 0 || $serviceTypeIdentifier > 999) { + throw new BCGArgumentException('Service Type Identifier must be between 0 and 999.', 'serviceTypeIdentifier'); + } + + $mailerIdentifierLength = 6; + if ($mailerIdentifier > 899999) { + $mailerIdentifierLength = 9; + } + + if ($mailerIdentifierLength === 9 && strlen($serialNumber) > 6) { + throw new BCGArgumentException('If the Serial Number has more than 6 digits, the Mailer Identifier must be lower than 900000.', 'mailerIdentifier'); + } + + if ($mailerIdentifierLength === 9) { + if ($mailerIdentifierLength < 0 || $mailerIdentifier > 999999999) { + throw new BCGArgumentException('Mailer Identifier must be between 0 and 999999999.', 'mailerIdentifier'); + } + } + + $this->barcodeIdentifier = $barcodeIdentifier; + $this->serviceTypeIdentifier = str_pad($serviceTypeIdentifier, 3, '0', STR_PAD_LEFT); + $this->mailerIdentifier = str_pad($mailerIdentifier, $mailerIdentifierLength, '0', STR_PAD_LEFT); + $this->serialNumber = str_pad((int)$serialNumber, $mailerIdentifierLength === 6 ? 9 : 6, '0', STR_PAD_LEFT); + } + + /** + * Parses the text before displaying it. + * + * @param mixed $text + */ + public function parse($text) { + parent::parse($text); + + $number = self::executeStep1($this->text, $this->barcodeIdentifier, $this->serviceTypeIdentifier, $this->mailerIdentifier, $this->serialNumber); + $crc = self::executeStep2($number); + $codewords = self::executeStep3($number); + $codewords = self::executeStep4($codewords, $crc); + $characters = self::executeStep5($codewords, $crc); + $this->data = self::executeStep6($characters); + } + + /** + * Draws the barcode. + * + * @param resource $im + */ + public function draw($im) { + if ($this->quietZone) { + $this->positionX += 9; + } + + $c = strlen($this->data); + for ($i = 0; $i < $c; $i++) { + $this->drawChar($im, $this->data[$i]); + } + + $this->drawText($im, 0, 0, $this->positionX, $this->thickness + ($this->quietZone ? 4 : 0)); + } + + /** + * Returns the maximal size of a barcode. + * + * @param int $w + * @param int $h + * @return int[] + */ + public function getDimension($w, $h) { + $w += 65 * 3; + $h += $this->thickness; + + // We remove the white on the right + $w -= 1.56; + + if ($this->quietZone) { + $w += 18; + $h += 4; + } + + return parent::getDimension($w, $h); + } + + /** + * Validates the input. + */ + protected function validate() { + // Tracking must have been entered + if ($this->barcodeIdentifier === null || $this->serviceTypeIdentifier === null || $this->mailerIdentifier === null || $this->serialNumber === null) { + throw new BCGParseException('intelligentmail', 'The tracking code must be set before calling the parse method.'); + } + + // Checking if all chars are allowed + $match = array(); + if (preg_match('/[^0-9]/', $this->text, $match)) { + throw new BCGParseException('intelligentmail', 'The character \'' . $match[0] . '\' is not allowed.'); + } + + // Must contain 0, 5, 9 or 11 chars + $c = strlen($this->text); + if ($c !== 0 && $c !== 5 && $c !== 9 && $c !== 11) { + throw new BCGParseException('intelligentmail', 'Must contain 0, 5, 9, or 11 characters.'); + } + + parent::validate(); + } + + /** + * Overloaded method for drawing special barcode. + * + * @param resource $im + * @param string $code + * @param boolean $startBar + */ + protected function drawChar($im, $code, $startBar = true) { + $y1 = 0; + $y2 = 0; + switch ($code) { + case 'A': + $y1 = 0; + $y2 = $this->thickness - ($this->thickness / 2.5); + break; + case 'D': + $y1 = 3.096; + $y2 = $this->thickness - 1; + break; + case 'F': + $y1 = 0; + $y2 = $this->thickness - 1; + break; + case 'T': + $y1 = 3.096; + $y2 = $this->thickness - ($this->thickness / 2.5); + break; + } + + if ($this->quietZone) { + $y1 += 2; + $y2 += 2; + } + + $this->drawFilledRectangle($im, $this->positionX, $y1, $this->positionX + 0.44, $y2, BCGBarcode::COLOR_FG); + $this->positionX += 3; + } + + /** + * Executes Step 1: Conversion of Data Fields into Binary Data + * + * @param string $text + * @param string $barcodeIdentifier + * @param string $serviceTypeIdentifier + * @param string $mailerIdentifier + * @param string $serialNumber + * @return string BCNumber + */ + private static function executeStep1($text, $barcodeIdentifier, $serviceTypeIdentifier, $mailerIdentifier, $serialNumber) { + $number = self::conversionRoutingCode($text); + $number = self::conversionTrackingCode($number, $barcodeIdentifier, $serviceTypeIdentifier, $mailerIdentifier, $serialNumber); + + return $number; + } + + /** + * Executes Step 2: Generation of 11-Bit CRC on Binary Data + * + * @param $number BCNumber + * @return int + */ + private static function executeStep2($number) { + $byteArray = str_pad(self::bcdecuc($number), 13, chr(0), STR_PAD_LEFT); + + $generatorPolynomial = 0x0f35; + $frameCheckSequence = 0x07ff; + $data = 0; + $byteIndex = 0; + $bit = 0; + + $data = (ord($byteArray[$byteIndex]) << 5) & 0xffff; + for ($bit = 2; $bit < 8; $bit++) { + if (($frameCheckSequence ^ $data) & 0x400) { + $frameCheckSequence = ($frameCheckSequence << 1) ^ $generatorPolynomial; + } else { + $frameCheckSequence = ($frameCheckSequence << 1); + } + + $frameCheckSequence &= 0x7ff; + $data <<= 1; + $data &= 0xffff; + } + + for ($byteIndex = 1; $byteIndex < 13; $byteIndex++) { + $data = (ord($byteArray[$byteIndex]) << 3) & 0xffff; + for ($bit = 0; $bit < 8; $bit++) { + if (($frameCheckSequence ^ $data) & 0x0400) { + $frameCheckSequence = ($frameCheckSequence << 1) ^ $generatorPolynomial; + } else { + $frameCheckSequence = ($frameCheckSequence << 1); + } + + $frameCheckSequence &= 0x7ff; + $data <<= 1; + $data &= 0xffff; + } + } + + return $frameCheckSequence; + } + + /** + * Executes Step 3: Conversion from Binary Data to Codewords + * + * @param string $number BCNumber + * @return int[] + */ + private static function executeStep3($number) { + $codewords = array(); + $codewords[9] = (int)bcmod($number, '636'); + $number = bcdiv($number, '636', 0); + + for ($i = 8; $i >= 0; $i--) { + $codewords[$i] = (int)bcmod($number, '1365'); + $number = bcdiv($number, '1365', 0); + } + + return $codewords; + } + + /** + * Executes Step 4: Inserting Additional Information into Codewords + * + * @param int[] $codewords + * @param int $crc + * @return int[] + */ + private static function executeStep4($codewords, $crc) { + $codewords[9] *= 2; + if ($crc & 0x400) { + $codewords[0] += 659; + } + + return $codewords; + } + + /** + * Executes Step 5: Conversion from Codewords to Characters + * + * @param int[] $codewords + * @param int $crc + * @return int[] + */ + private static function executeStep5($codewords, $crc) { + $characters = array(); + for ($i = 0; $i < 10; $i++) { + if ($codewords[$i] <= 1286) { + $characters[$i] = self::$characterTable1[$codewords[$i]]; + } else { + $characters[$i] = self::$characterTable2[$codewords[$i] - 1287]; + } + } + + for ($i = 0; $i < 10; $i++) { + $mask = 1 << $i; + if ($crc & $mask) { + $characters[$i] ^= 0x1fff; + } + } + + return $characters; + } + + /** + * Executes Step 6: Conversion from Characters to the Intelligent Mail Barcode + * + * @param int[] $characters + * @return string + */ + private static function executeStep6($characters) { + $bars = ''; + for ($i = 0; $i < 65; $i++) { + $barPosition = self::$barPositions[$i]; + $descender = $barPosition[0]; + $ascender = $barPosition[1]; + $extenderDescender = !!($characters[$descender[0]] & (1 << $descender[1])); + $extenderAscender = !!($characters[$ascender[0]] & (1 << $ascender[1])); + + if ($extenderDescender && $extenderAscender) { + $bars .= 'F'; + } elseif ($extenderDescender) { + $bars .= 'D'; + } elseif ($extenderAscender) { + $bars .= 'A'; + } else { + $bars .= 'T'; + } + } + + return $bars; + } + + /** + * Converts the routing code zipcode. + * + * @param string $zipcode + * @return string BCNumber + */ + private static function conversionRoutingCode($zipcode) { + $number = $zipcode; + switch (strlen($zipcode)) { + case 11: + $number = bcadd($number, '1000000000', 0); + case 9: + $number = bcadd($number, '100000', 0); + case 5: + $number = bcadd($number, '1', 0); + default: + return $number; + } + } + + /** + * Converts the tracking code number. + * + * @param string $number BCNumber + * @param string $barcodeIdentifier + * @param string $serviceTypeIdentifier + * @param string $mailerIdentifier + * @param string $serialNumber + * @return string BCNumber + */ + private static function conversionTrackingCode($number, $barcodeIdentifier, $serviceTypeIdentifier, $mailerIdentifier, $serialNumber) { + $number = bcmul($number, 10, 0); + $number = bcadd($number, $barcodeIdentifier[0], 0); + $number = bcmul($number, 5, 0); + $number = bcadd($number, $barcodeIdentifier[1], 0); + + $temp = $serviceTypeIdentifier . $mailerIdentifier . $serialNumber; + for ($i = 0; $i < 18; $i++) { + $number = bcmul($number, 10, 0); + $number = bcadd($number, $temp[$i], 0); + } + + return $number; + } + + /** + * Transforms a BCNumber into unsigned char*. + * + * @param string $dec BCNumber + * @param string + */ + private static function bcdecuc($dec) { + $last = bcmod($dec, 256); + $remain = bcdiv(bcsub($dec, $last), 256, 0); + + if ($remain == 0) { + return pack('C', $last); + } else { + return self::bcdecuc($remain) . pack('C', $last); + } + } +} +?> \ No newline at end of file diff --git a/niucloud/core/util/barcode/class/BCGisbn.barcode.php b/niucloud/core/util/barcode/class/BCGisbn.barcode.php new file mode 100644 index 000000000..867cb0f74 --- /dev/null +++ b/niucloud/core/util/barcode/class/BCGisbn.barcode.php @@ -0,0 +1,164 @@ +setGS1($gs1); + } + + /** + * Adds the default label. + */ + protected function addDefaultLabel() { + if ($this->isDefaultEanLabelEnabled()) { + $isbn = $this->createISBNText(); + $font = $this->font; + + $topLabel = new BCGLabel($isbn, $font, BCGLabel::POSITION_TOP, BCGLabel::ALIGN_CENTER); + + $this->addLabel($topLabel); + } + + parent::addDefaultLabel(); + } + + /** + * Sets the first numbers of the barcode. + * - GS1_AUTO: Adds 978 before the code + * - GS1_PREFIX978: Adds 978 before the code + * - GS1_PREFIX979: Adds 979 before the code + * + * @param int $gs1 + */ + public function setGS1($gs1) { + $gs1 = (int)$gs1; + if ($gs1 !== self::GS1_AUTO && $gs1 !== self::GS1_PREFIX978 && $gs1 !== self::GS1_PREFIX979) { + throw new BCGArgumentException('The GS1 argument must be BCGisbn::GS1_AUTO, BCGisbn::GS1_PREFIX978, or BCGisbn::GS1_PREFIX979', 'gs1'); + } + + $this->gs1 = $gs1; + } + + /** + * Check chars allowed. + */ + protected function checkCharsAllowed() { + $c = strlen($this->text); + + // Special case, if we have 10 digits, the last one can be X + if ($c === 10) { + if (array_search($this->text[9], $this->keys) === false && $this->text[9] !== 'X') { + throw new BCGParseException('isbn', 'The character \'' . $this->text[9] . '\' is not allowed.'); + } + + // Drop the last char + $this->text = substr($this->text, 0, 9); + } + + return parent::checkCharsAllowed(); + } + + /** + * Check correct length. + */ + protected function checkCorrectLength() { + $c = strlen($this->text); + + // If we have 13 chars just flush the last one + if ($c === 13) { + $this->text = substr($this->text, 0, 12); + } elseif ($c === 9 || $c === 10) { + if ($c === 10) { + // Before dropping it, we check if it's legal + if (array_search($this->text[9], $this->keys) === false && $this->text[9] !== 'X') { + throw new BCGParseException('isbn', 'The character \'' . $this->text[9] . '\' is not allowed.'); + } + + $this->text = substr($this->text, 0, 9); + } + + if ($this->gs1 === self::GS1_AUTO || $this->gs1 === self::GS1_PREFIX978) { + $this->text = '978' . $this->text; + } elseif ($this->gs1 === self::GS1_PREFIX979) { + $this->text = '979' . $this->text; + } + } elseif ($c !== 12) { + throw new BCGParseException('isbn', 'The code parsed must be 9, 10, 12, or 13 digits long.'); + } + } + + /** + * Creates the ISBN text. + * + * @return string + */ + private function createISBNText() { + $isbn = ''; + if (!empty($this->text)) { + // We try to create the ISBN Text... the hyphen really depends the ISBN agency. + // We just put one before the checksum and one after the GS1 if present. + $c = strlen($this->text); + if ($c === 12 || $c === 13) { + // If we have 13 characters now, just transform it temporarily to find the checksum... + // Further in the code we take care of that anyway. + $lastCharacter = ''; + if ($c === 13) { + $lastCharacter = $this->text[12]; + $this->text = substr($this->text, 0, 12); + } + + $checksum = $this->processChecksum(); + $isbn = 'ISBN ' . substr($this->text, 0, 3) . '-' . substr($this->text, 3, 9) . '-' . $checksum; + + // Put the last character back + if ($c === 13) { + $this->text .= $lastCharacter; + } + } elseif ($c === 9 || $c === 10) { + $checksum = 0; + for ($i = 10; $i >= 2; $i--) { + $checksum += $this->text[10 - $i] * $i; + } + + $checksum = 11 - $checksum % 11; + if ($checksum === 10) { + $checksum = 'X'; // Changing type + } + + $isbn = 'ISBN ' . substr($this->text, 0, 9) . '-' . $checksum; + } + } + + return $isbn; + } +} +?> \ No newline at end of file diff --git a/niucloud/core/util/barcode/class/BCGmsi.barcode.php b/niucloud/core/util/barcode/class/BCGmsi.barcode.php new file mode 100644 index 000000000..a322d8294 --- /dev/null +++ b/niucloud/core/util/barcode/class/BCGmsi.barcode.php @@ -0,0 +1,184 @@ +keys = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'); + $this->code = array( + '01010101', /* 0 */ + '01010110', /* 1 */ + '01011001', /* 2 */ + '01011010', /* 3 */ + '01100101', /* 4 */ + '01100110', /* 5 */ + '01101001', /* 6 */ + '01101010', /* 7 */ + '10010101', /* 8 */ + '10010110' /* 9 */ + ); + + $this->setChecksum(0); + } + + /** + * Sets how many checksums we display. 0 to 2. + * + * @param int $checksum + */ + public function setChecksum($checksum) { + $checksum = intval($checksum); + if ($checksum < 0 && $checksum > 2) { + throw new BCGArgumentException('The checksum must be between 0 and 2 included.', 'checksum'); + } + + $this->checksum = $checksum; + } + + /** + * Draws the barcode. + * + * @param resource $im + */ + public function draw($im) { + // Checksum + $this->calculateChecksum(); + + // Starting Code + $this->drawChar($im, '10', true); + + // Chars + $c = strlen($this->text); + for ($i = 0; $i < $c; $i++) { + $this->drawChar($im, $this->findCode($this->text[$i]), true); + } + + $c = count($this->checksumValue); + for ($i = 0; $i < $c; $i++) { + $this->drawChar($im, $this->findCode($this->checksumValue[$i]), true); + } + + // Ending Code + $this->drawChar($im, '010', true); + $this->drawText($im, 0, 0, $this->positionX, $this->thickness); + } + + /** + * Returns the maximal size of a barcode. + * + * @param int $w + * @param int $h + * @return int[] + */ + public function getDimension($w, $h) { + $textlength = 12 * strlen($this->text); + $startlength = 3; + $checksumlength = $this->checksum * 12; + $endlength = 4; + + $w += $startlength + $textlength + $checksumlength + $endlength; + $h += $this->thickness; + return parent::getDimension($w, $h); + } + + /** + * Validates the input. + */ + protected function validate() { + $c = strlen($this->text); + if ($c === 0) { + throw new BCGParseException('msi', 'No data has been entered.'); + } + + // Checking if all chars are allowed + for ($i = 0; $i < $c; $i++) { + if (array_search($this->text[$i], $this->keys) === false) { + throw new BCGParseException('msi', 'The character \'' . $this->text[$i] . '\' is not allowed.'); + } + } + } + + /** + * Overloaded method to calculate checksum. + */ + protected function calculateChecksum() { + // Forming a new number + // If the original number is even, we take all even position + // If the original number is odd, we take all odd position + // 123456 = 246 + // 12345 = 135 + // Multiply by 2 + // Add up all the digit in the result (270 : 2+7+0) + // Add up other digit not used. + // 10 - (? Modulo 10). If result = 10, change to 0 + $last_text = $this->text; + $this->checksumValue = array(); + for ($i = 0; $i < $this->checksum; $i++) { + $new_text = ''; + $new_number = 0; + $c = strlen($last_text); + if ($c % 2 === 0) { // Even + $starting = 1; + } else { + $starting = 0; + } + + for ($j = $starting; $j < $c; $j += 2) { + $new_text .= $last_text[$j]; + } + + $new_text = strval(intval($new_text) * 2); + $c2 = strlen($new_text); + for ($j = 0; $j < $c2; $j++) { + $new_number += intval($new_text[$j]); + } + + for ($j = ($starting === 0) ? 1 : 0; $j < $c; $j += 2) { + $new_number += intval($last_text[$j]); + } + + $new_number = (10 - $new_number % 10) % 10; + $this->checksumValue[] = $new_number; + $last_text .= $new_number; + } + } + + /** + * Overloaded method to display the checksum. + */ + protected function processChecksum() { + if ($this->checksumValue === false) { // Calculate the checksum only once + $this->calculateChecksum(); + } + + if ($this->checksumValue !== false) { + $ret = ''; + $c = count($this->checksumValue); + for ($i = 0; $i < $c; $i++) { + $ret .= $this->keys[$this->checksumValue[$i]]; + } + + return $ret; + } + + return false; + } +} +?> \ No newline at end of file diff --git a/niucloud/core/util/barcode/class/BCGothercode.barcode.php b/niucloud/core/util/barcode/class/BCGothercode.barcode.php new file mode 100644 index 000000000..a9ae2eda6 --- /dev/null +++ b/niucloud/core/util/barcode/class/BCGothercode.barcode.php @@ -0,0 +1,88 @@ +keys = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'); + } + + /** + * Draws the barcode. + * + * @param resource $im + */ + public function draw($im) { + $this->drawChar($im, $this->text, true); + $this->drawText($im, 0, 0, $this->positionX, $this->thickness); + } + + /** + * Gets the label. + * If the label was set to BCGBarcode1D::AUTO_LABEL, the label will display the value from the text parsed. + * + * @return string + */ + public function getLabel() { + $label = $this->label; + if ($this->label === BCGBarcode1D::AUTO_LABEL) { + $label = ''; + } + + return $label; + } + + /** + * Returns the maximal size of a barcode. + * + * @param int $w + * @param int $h + * @return int[] + */ + public function getDimension($w, $h) { + $array = str_split($this->text, 1); + $textlength = array_sum($array) + count($array); + + $w += $textlength; + $h += $this->thickness; + return parent::getDimension($w, $h); + } + + /** + * Validates the input. + */ + protected function validate() { + $c = strlen($this->text); + if ($c === 0) { + throw new BCGParseException('othercode', 'No data has been entered.'); + } + + // Checking if all chars are allowed + for ($i = 0; $i < $c; $i++) { + if (array_search($this->text[$i], $this->keys) === false) { + throw new BCGParseException('othercode', 'The character \'' . $this->text[$i] . '\' is not allowed.'); + } + } + + parent::validate(); + } +} +?> \ No newline at end of file diff --git a/niucloud/core/util/barcode/class/BCGpostnet.barcode.php b/niucloud/core/util/barcode/class/BCGpostnet.barcode.php new file mode 100644 index 000000000..1988b0844 --- /dev/null +++ b/niucloud/core/util/barcode/class/BCGpostnet.barcode.php @@ -0,0 +1,138 @@ +keys = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'); + $this->code = array( + '11000', /* 0 */ + '00011', /* 1 */ + '00101', /* 2 */ + '00110', /* 3 */ + '01001', /* 4 */ + '01010', /* 5 */ + '01100', /* 6 */ + '10001', /* 7 */ + '10010', /* 8 */ + '10100' /* 9 */ + ); + + $this->setThickness(9); + } + + /** + * Draws the barcode. + * + * @param resource $im + */ + public function draw($im) { + // Checksum + $checksum = 0; + $c = strlen($this->text); + for ($i = 0; $i < $c; $i++) { + $checksum += intval($this->text[$i]); + } + + $checksum = 10 - ($checksum % 10); + + // Starting Code + $this->drawChar($im, '1'); + + // Code + for ($i = 0; $i < $c; $i++) { + $this->drawChar($im, $this->findCode($this->text[$i])); + } + + // Checksum + $this->drawChar($im, $this->findCode($checksum)); + + // Ending Code + $this->drawChar($im, '1'); + $this->drawText($im, 0, 0, $this->positionX, $this->thickness); + } + + /** + * Returns the maximal size of a barcode. + * + * @param int $w + * @param int $h + * @return int[] + */ + public function getDimension($w, $h) { + $c = strlen($this->text); + $startlength = 3; + $textlength = $c * 5 * 3; + $checksumlength = 5 * 3; + $endlength = 3; + + // We remove the white on the right + $removelength = -1.56; + + $w += $startlength + $textlength + $checksumlength + $endlength + $removelength; + $h += $this->thickness; + return parent::getDimension($w, $h); + } + + /** + * Validates the input. + */ + protected function validate() { + $c = strlen($this->text); + if ($c === 0) { + throw new BCGParseException('postnet', 'No data has been entered.'); + } + + // Checking if all chars are allowed + for ($i = 0; $i < $c; $i++) { + if (array_search($this->text[$i], $this->keys) === false) { + throw new BCGParseException('postnet', 'The character \'' . $this->text[$i] . '\' is not allowed.'); + } + } + + // Must contain 5, 9 or 11 chars + if ($c !== 5 && $c !== 9 && $c !== 11) { + throw new BCGParseException('postnet', 'Must contain 5, 9, or 11 characters.'); + } + + parent::validate(); + } + + /** + * Overloaded method for drawing special barcode. + * + * @param resource $im + * @param string $code + * @param boolean $startBar + */ + protected function drawChar($im, $code, $startBar = true) { + $c = strlen($code); + for ($i = 0; $i < $c; $i++) { + if ($code[$i] === '0') { + $posY = $this->thickness - ($this->thickness / 2.5); + } else { + $posY = 0; + } + + $this->drawFilledRectangle($im, $this->positionX, $posY, $this->positionX + 0.44, $this->thickness - 1, BCGBarcode::COLOR_FG); + $this->positionX += 3; + } + } +} +?> \ No newline at end of file diff --git a/niucloud/core/util/barcode/class/BCGs25.barcode.php b/niucloud/core/util/barcode/class/BCGs25.barcode.php new file mode 100644 index 000000000..3312b2cd8 --- /dev/null +++ b/niucloud/core/util/barcode/class/BCGs25.barcode.php @@ -0,0 +1,170 @@ + 1/3 or 1/2 for the big bar + * + *-------------------------------------------------------------------- + * Copyright (C) Jean-Sebastien Goupil + * http://www.barcodephp.com + */ +include_once('BCGParseException.php'); +include_once('BCGBarcode1D.php'); + +class BCGs25 extends BCGBarcode1D { + private $checksum; + + /** + * Constructor. + */ + public function __construct() { + parent::__construct(); + + $this->keys = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'); + $this->code = array( + '0000202000', /* 0 */ + '2000000020', /* 1 */ + '0020000020', /* 2 */ + '2020000000', /* 3 */ + '0000200020', /* 4 */ + '2000200000', /* 5 */ + '0020200000', /* 6 */ + '0000002020', /* 7 */ + '2000002000', /* 8 */ + '0020002000' /* 9 */ + ); + + $this->setChecksum(false); + } + + /** + * Sets if we display the checksum. + * + * @param bool $checksum + */ + public function setChecksum($checksum) { + $this->checksum = (bool)$checksum; + } + + /** + * Draws the barcode. + * + * @param resource $im + */ + public function draw($im) { + $temp_text = $this->text; + + // Checksum + if ($this->checksum === true) { + $this->calculateChecksum(); + $temp_text .= $this->keys[$this->checksumValue]; + } + + // Starting Code + $this->drawChar($im, '101000', true); + + // Chars + $c = strlen($temp_text); + for ($i = 0; $i < $c; $i++) { + $this->drawChar($im, $this->findCode($temp_text[$i]), true); + } + + // Ending Code + $this->drawChar($im, '10001', true); + $this->drawText($im, 0, 0, $this->positionX, $this->thickness); + } + + /** + * Returns the maximal size of a barcode. + * + * @param int $w + * @param int $h + * @return int[] + */ + public function getDimension($w, $h) { + $c = strlen($this->text); + $startlength = 8; + $textlength = $c * 14; + $checksumlength = 0; + if ($c % 2 !== 0) { + $checksumlength = 14; + } + + $endlength = 7; + + $w += $startlength + $textlength + $checksumlength + $endlength; + $h += $this->thickness; + return parent::getDimension($w, $h); + } + + /** + * Validates the input. + */ + protected function validate() { + $c = strlen($this->text); + if ($c === 0) { + throw new BCGParseException('s25', 'No data has been entered.'); + } + + // Checking if all chars are allowed + for ($i = 0; $i < $c; $i++) { + if (array_search($this->text[$i], $this->keys) === false) { + throw new BCGParseException('s25', 'The character \'' . $this->text[$i] . '\' is not allowed.'); + } + } + + // Must be even + if ($c % 2 !== 0 && $this->checksum === false) { + throw new BCGParseException('s25', 's25 must contain an even amount of digits if checksum is false.'); + } elseif ($c % 2 === 0 && $this->checksum === true) { + throw new BCGParseException('s25', 's25 must contain an odd amount of digits if checksum is true.'); + } + + parent::validate(); + } + + /** + * Overloaded method to calculate checksum. + */ + protected function calculateChecksum() { + // Calculating Checksum + // Consider the right-most digit of the message to be in an "even" position, + // and assign odd/even to each character moving from right to left + // Even Position = 3, Odd Position = 1 + // Multiply it by the number + // Add all of that and do 10-(?mod10) + $even = true; + $this->checksumValue = 0; + $c = strlen($this->text); + for ($i = $c; $i > 0; $i--) { + if ($even === true) { + $multiplier = 3; + $even = false; + } else { + $multiplier = 1; + $even = true; + } + + $this->checksumValue += $this->keys[$this->text[$i - 1]] * $multiplier; + } + $this->checksumValue = (10 - $this->checksumValue % 10) % 10; + } + + /** + * Overloaded method to display the checksum. + */ + protected function processChecksum() { + if ($this->checksumValue === false) { // Calculate the checksum only once + $this->calculateChecksum(); + } + + if ($this->checksumValue !== false) { + return $this->keys[$this->checksumValue]; + } + + return false; + } +} +?> \ No newline at end of file diff --git a/niucloud/core/util/barcode/class/BCGupca.barcode.php b/niucloud/core/util/barcode/class/BCGupca.barcode.php new file mode 100644 index 000000000..37794331b --- /dev/null +++ b/niucloud/core/util/barcode/class/BCGupca.barcode.php @@ -0,0 +1,146 @@ +text = '0' . $this->text; // We will remove it at the end... don't worry + + parent::draw($im); + + // We remove the 0 in front, as we said :) + $this->text = substr($this->text, 1); + } + + /** + * Draws the extended bars on the image. + * + * @param resource $im + * @param int $plus + */ + protected function drawExtendedBars($im, $plus) { + $temp_text = $this->text . $this->keys[$this->checksumValue]; + $rememberX = $this->positionX; + $rememberH = $this->thickness; + + // We increase the bars + // First 2 Bars + $this->thickness = $this->thickness + intval($plus / $this->scale); + $this->positionX = 0; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + $this->positionX += 2; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + + // Attemping to increase the 2 following bars + $this->positionX += 1; + $temp_value = $this->findCode($temp_text[1]); + $this->drawChar($im, $temp_value, false); + + // Center Guard Bar + $this->positionX += 36; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + $this->positionX += 2; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + + // Attemping to increase the 2 last bars + $this->positionX += 37; + $temp_value = $this->findCode($temp_text[12]); + $this->drawChar($im, $temp_value, true); + + // Completly last bars + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + $this->positionX += 2; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + + $this->positionX = $rememberX; + $this->thickness = $rememberH; + } + + /** + * Adds the default label. + */ + protected function addDefaultLabel() { + if ($this->isDefaultEanLabelEnabled()) { + $this->processChecksum(); + $label = $this->getLabel(); + $font = $this->font; + + $this->labelLeft = new BCGLabel(substr($label, 0, 1), $font, BCGLabel::POSITION_LEFT, BCGLabel::ALIGN_BOTTOM); + $this->labelLeft->setSpacing(4 * $this->scale); + + $this->labelCenter1 = new BCGLabel(substr($label, 1, 5), $font, BCGLabel::POSITION_BOTTOM, BCGLabel::ALIGN_LEFT); + $labelCenter1Dimension = $this->labelCenter1->getDimension(); + $this->labelCenter1->setOffset(($this->scale * 44 - $labelCenter1Dimension[0]) / 2 + $this->scale * 6); + + $this->labelCenter2 = new BCGLabel(substr($label, 6, 5), $font, BCGLabel::POSITION_BOTTOM, BCGLabel::ALIGN_LEFT); + $this->labelCenter2->setOffset(($this->scale * 44 - $labelCenter1Dimension[0]) / 2 + $this->scale * 45); + + $this->labelRight = new BCGLabel($this->keys[$this->checksumValue], $font, BCGLabel::POSITION_RIGHT, BCGLabel::ALIGN_BOTTOM); + $this->labelRight->setSpacing(4 * $this->scale); + + if ($this->alignLabel) { + $labelDimension = $this->labelCenter1->getDimension(); + $this->labelLeft->setOffset($labelDimension[1]); + $this->labelRight->setOffset($labelDimension[1]); + } else { + $labelDimension = $this->labelLeft->getDimension(); + $this->labelLeft->setOffset($labelDimension[1] / 2); + $labelDimension = $this->labelLeft->getDimension(); + $this->labelRight->setOffset($labelDimension[1] / 2); + } + + $this->addLabel($this->labelLeft); + $this->addLabel($this->labelCenter1); + $this->addLabel($this->labelCenter2); + $this->addLabel($this->labelRight); + } + } + + /** + * Check correct length. + */ + protected function checkCorrectLength() { + // If we have 12 chars, just flush the last one without throwing anything + $c = strlen($this->text); + if ($c === 12) { + $this->text = substr($this->text, 0, 11); + } elseif ($c !== 11) { + throw new BCGParseException('upca', 'Must contain 11 digits, the 12th digit is automatically added.'); + } + } +} +?> \ No newline at end of file diff --git a/niucloud/core/util/barcode/class/BCGupce.barcode.php b/niucloud/core/util/barcode/class/BCGupce.barcode.php new file mode 100644 index 000000000..5b3492898 --- /dev/null +++ b/niucloud/core/util/barcode/class/BCGupce.barcode.php @@ -0,0 +1,336 @@ +keys = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'); + + // Odd Parity starting with a space + // Even Parity is the inverse (0=0012) starting with a space + $this->code = array( + '2100', /* 0 */ + '1110', /* 1 */ + '1011', /* 2 */ + '0300', /* 3 */ + '0021', /* 4 */ + '0120', /* 5 */ + '0003', /* 6 */ + '0201', /* 7 */ + '0102', /* 8 */ + '2001' /* 9 */ + ); + + // Parity, 0=Odd, 1=Even for manufacturer code. Depending on 1st System Digit and Checksum + $this->codeParity = array( + array( + array(1, 1, 1, 0, 0, 0), /* 0,0 */ + array(1, 1, 0, 1, 0, 0), /* 0,1 */ + array(1, 1, 0, 0, 1, 0), /* 0,2 */ + array(1, 1, 0, 0, 0, 1), /* 0,3 */ + array(1, 0, 1, 1, 0, 0), /* 0,4 */ + array(1, 0, 0, 1, 1, 0), /* 0,5 */ + array(1, 0, 0, 0, 1, 1), /* 0,6 */ + array(1, 0, 1, 0, 1, 0), /* 0,7 */ + array(1, 0, 1, 0, 0, 1), /* 0,8 */ + array(1, 0, 0, 1, 0, 1) /* 0,9 */ + ), + array( + array(0, 0, 0, 1, 1, 1), /* 0,0 */ + array(0, 0, 1, 0, 1, 1), /* 0,1 */ + array(0, 0, 1, 1, 0, 1), /* 0,2 */ + array(0, 0, 1, 1, 1, 0), /* 0,3 */ + array(0, 1, 0, 0, 1, 1), /* 0,4 */ + array(0, 1, 1, 0, 0, 1), /* 0,5 */ + array(0, 1, 1, 1, 0, 0), /* 0,6 */ + array(0, 1, 0, 1, 0, 1), /* 0,7 */ + array(0, 1, 0, 1, 1, 0), /* 0,8 */ + array(0, 1, 1, 0, 1, 0) /* 0,9 */ + ) + ); + } + + /** + * Draws the barcode. + * + * @param resource $im + */ + public function draw($im) { + $this->calculateChecksum(); + + // Starting Code + $this->drawChar($im, '000', true); + $c = strlen($this->upce); + for ($i = 0; $i < $c; $i++) { + $this->drawChar($im, self::inverse($this->findCode($this->upce[$i]), $this->codeParity[intval($this->text[0])][$this->checksumValue][$i]), false); + } + + // Draw Center Guard Bar + $this->drawChar($im, '00000', false); + + // Draw Right Bar + $this->drawChar($im, '0', true); + $this->text = $this->text[0] . $this->upce; + $this->drawText($im, 0, 0, $this->positionX, $this->thickness); + + if ($this->isDefaultEanLabelEnabled()) { + $dimension = $this->labelCenter->getDimension(); + $this->drawExtendedBars($im, $dimension[1] - 2); + } + } + + /** + * Returns the maximal size of a barcode. + * + * @param int $w + * @param int $h + * @return int[] + */ + public function getDimension($w, $h) { + $startlength = 3; + $centerlength = 5; + $textlength = 6 * 7; + $endlength = 1; + + $w += $startlength + $centerlength + $textlength + $endlength; + $h += $this->thickness; + return parent::getDimension($w, $h); + } + + /** + * Adds the default label. + */ + protected function addDefaultLabel() { + if ($this->isDefaultEanLabelEnabled()) { + $this->processChecksum(); + $font = $this->font; + + $this->labelLeft = new BCGLabel(substr($this->text, 0, 1), $font, BCGLabel::POSITION_LEFT, BCGLabel::ALIGN_BOTTOM); + $labelLeftDimension = $this->labelLeft->getDimension(); + $this->labelLeft->setSpacing(8); + $this->labelLeft->setOffset($labelLeftDimension[1] / 2); + + $this->labelCenter = new BCGLabel($this->upce, $font, BCGLabel::POSITION_BOTTOM, BCGLabel::ALIGN_LEFT); + $labelCenterDimension = $this->labelCenter->getDimension(); + $this->labelCenter->setOffset(($this->scale * 46 - $labelCenterDimension[0]) / 2 + $this->scale * 2); + + $this->labelRight = new BCGLabel($this->keys[$this->checksumValue], $font, BCGLabel::POSITION_RIGHT, BCGLabel::ALIGN_BOTTOM); + $labelRightDimension = $this->labelRight->getDimension(); + $this->labelRight->setSpacing(8); + $this->labelRight->setOffset($labelRightDimension[1] / 2); + + $this->addLabel($this->labelLeft); + $this->addLabel($this->labelCenter); + $this->addLabel($this->labelRight); + } + } + + /** + * Checks if the default ean label is enabled. + * + * @return bool + */ + protected function isDefaultEanLabelEnabled() { + $label = $this->getLabel(); + $font = $this->font; + return $label !== null && $label !== '' && $font !== null && $this->defaultLabel !== null; + } + + /** + * Validates the input. + */ + protected function validate() { + $c = strlen($this->text); + if ($c === 0) { + throw new BCGParseException('upce', 'No data has been entered.'); + } + + // Checking if all chars are allowed + for ($i = 0; $i < $c; $i++) { + if (array_search($this->text[$i], $this->keys) === false) { + throw new BCGParseException('upce', 'The character \'' . $this->text[$i] . '\' is not allowed.'); + } + } + + // Must contain 11 chars + // Must contain 6 chars (if starting with upce directly) + // First Chars must be 0 or 1 + if ($c !== 11 && $c !== 6) { + throw new BCGParseException('upce', 'You must provide a UPC-A (11 characters) or a UPC-E (6 characters).'); + } elseif ($this->text[0] !== '0' && $this->text[0] !== '1' && $c !== 6) { + throw new BCGParseException('upce', 'UPC-A must start with 0 or 1 to be converted to UPC-E.'); + } + + // Convert part + $this->upce = ''; + if ($c !== 6) { + // Checking if UPC-A is convertible + $temp1 = substr($this->text, 3, 3); + if ($temp1 === '000' || $temp1 === '100' || $temp1 === '200') { // manufacturer code ends with 100, 200 or 300 + if (substr($this->text, 6, 2) === '00') { // Product must start with 00 + $this->upce = substr($this->text, 1, 2) . substr($this->text, 8, 3) . substr($this->text, 3, 1); + } + } elseif (substr($this->text, 4, 2) === '00') { // manufacturer code ends with 00 + if (substr($this->text, 6, 3) === '000') { // Product must start with 000 + $this->upce = substr($this->text, 1, 3) . substr($this->text, 9, 2) . '3'; + } + } elseif (substr($this->text, 5, 1) === '0') { // manufacturer code ends with 0 + if (substr($this->text, 6, 4) === '0000') { // Product must start with 0000 + $this->upce = substr($this->text, 1, 4) . substr($this->text, 10, 1) . '4'; + } + } else { // No zero leading at manufacturer code + $temp2 = intval(substr($this->text, 10, 1)); + if (substr($this->text, 6, 4) === '0000' && $temp2 >= 5 && $temp2 <= 9) { // Product must start with 0000 and must end by 5, 6, 7, 8 or 9 + $this->upce = substr($this->text, 1, 5) . substr($this->text, 10, 1); + } + } + } else { + $this->upce = $this->text; + } + + if ($this->upce === '') { + throw new BCGParseException('upce', 'Your UPC-A can\'t be converted to UPC-E.'); + } + + if ($c === 6) { + $upca = ''; + + // We convert UPC-E to UPC-A to find the checksum + if ($this->text[5] === '0' || $this->text[5] === '1' || $this->text[5] === '2') { + $upca = substr($this->text, 0, 2) . $this->text[5] . '0000' . substr($this->text, 2, 3); + } elseif ($this->text[5] === '3') { + $upca = substr($this->text, 0, 3) . '00000' . substr($this->text, 3, 2); + } elseif ($this->text[5] === '4') { + $upca = substr($this->text, 0, 4) . '00000' . $this->text[4]; + } else { + $upca = substr($this->text, 0, 5) . '0000' . $this->text[5]; + } + + $this->text = '0' . $upca; + } + + parent::validate(); + } + + /** + * Overloaded method to calculate checksum. + */ + protected function calculateChecksum() { + // Calculating Checksum + // Consider the right-most digit of the message to be in an "odd" position, + // and assign odd/even to each character moving from right to left + // Odd Position = 3, Even Position = 1 + // Multiply it by the number + // Add all of that and do 10-(?mod10) + $odd = true; + $this->checksumValue = 0; + $c = strlen($this->text); + for ($i = $c; $i > 0; $i--) { + if ($odd === true) { + $multiplier = 3; + $odd = false; + } else { + $multiplier = 1; + $odd = true; + } + + if (!isset($this->keys[$this->text[$i - 1]])) { + return; + } + + $this->checksumValue += $this->keys[$this->text[$i - 1]] * $multiplier; + } + + $this->checksumValue = (10 - $this->checksumValue % 10) % 10; + } + + /** + * Overloaded method to display the checksum. + */ + protected function processChecksum() { + if ($this->checksumValue === false) { // Calculate the checksum only once + $this->calculateChecksum(); + } + + if ($this->checksumValue !== false) { + return $this->keys[$this->checksumValue]; + } + + return false; + } + + /** + * Draws the extended bars on the image. + * + * @param resource $im + * @param int $plus + */ + protected function drawExtendedBars($im, $plus) { + $rememberX = $this->positionX; + $rememberH = $this->thickness; + + // We increase the bars + $this->thickness = $this->thickness + intval($plus / $this->scale); + $this->positionX = 0; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + $this->positionX += 2; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + + // Last Bars + $this->positionX += 46; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + $this->positionX += 2; + $this->drawSingleBar($im, BCGBarcode::COLOR_FG); + + $this->positionX = $rememberX; + $this->thickness = $rememberH; + } + + /** + * Inverses the string when the $inverse parameter is equal to 1. + * + * @param string $text + * @param int $inverse + * @return string + */ + private static function inverse($text, $inverse = 1) { + if ($inverse === 1) { + $text = strrev($text); + } + + return $text; + } +} +?> \ No newline at end of file diff --git a/niucloud/core/util/barcode/class/BCGupcext2.barcode.php b/niucloud/core/util/barcode/class/BCGupcext2.barcode.php new file mode 100644 index 000000000..4399e0e6e --- /dev/null +++ b/niucloud/core/util/barcode/class/BCGupcext2.barcode.php @@ -0,0 +1,138 @@ +keys = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'); + $this->code = array( + '2100', /* 0 */ + '1110', /* 1 */ + '1011', /* 2 */ + '0300', /* 3 */ + '0021', /* 4 */ + '0120', /* 5 */ + '0003', /* 6 */ + '0201', /* 7 */ + '0102', /* 8 */ + '2001' /* 9 */ + ); + + // Parity, 0=Odd, 1=Even. Depending on ?%4 + $this->codeParity = array( + array(0, 0), /* 0 */ + array(0, 1), /* 1 */ + array(1, 0), /* 2 */ + array(1, 1) /* 3 */ + ); + } + + /** + * Draws the barcode. + * + * @param resource $im + */ + public function draw($im) { + // Starting Code + $this->drawChar($im, '001', true); + + // Code + for ($i = 0; $i < 2; $i++) { + $this->drawChar($im, self::inverse($this->findCode($this->text[$i]), $this->codeParity[intval($this->text) % 4][$i]), false); + if ($i === 0) { + $this->drawChar($im, '00', false); // Inter-char + } + } + + $this->drawText($im, 0, 0, $this->positionX, $this->thickness); + } + + /** + * Returns the maximal size of a barcode. + * + * @param int $w + * @param int $h + * @return int[] + */ + public function getDimension($w, $h) { + $startlength = 4; + $textlength = 2 * 7; + $intercharlength = 2; + + $w += $startlength + $textlength + $intercharlength; + $h += $this->thickness; + return parent::getDimension($w, $h); + } + + /** + * Adds the default label. + */ + protected function addDefaultLabel() { + parent::addDefaultLabel(); + + if ($this->defaultLabel !== null) { + $this->defaultLabel->setPosition(BCGLabel::POSITION_TOP); + } + } + + /** + * Validates the input. + */ + protected function validate() { + $c = strlen($this->text); + if ($c === 0) { + throw new BCGParseException('upcext2', 'No data has been entered.'); + } + + // Checking if all chars are allowed + for ($i = 0; $i < $c; $i++) { + if (array_search($this->text[$i], $this->keys) === false) { + throw new BCGParseException('upcext2', 'The character \'' . $this->text[$i] . '\' is not allowed.'); + } + } + + // Must contain 2 digits + if ($c !== 2) { + throw new BCGParseException('upcext2', 'Must contain 2 digits.'); + } + + parent::validate(); + } + + /** + * Inverses the string when the $inverse parameter is equal to 1. + * + * @param string $text + * @param int $inverse + * @return string + */ + private static function inverse($text, $inverse = 1) { + if ($inverse === 1) { + $text = strrev($text); + } + + return $text; + } +} +?> \ No newline at end of file diff --git a/niucloud/core/util/barcode/class/BCGupcext5.barcode.php b/niucloud/core/util/barcode/class/BCGupcext5.barcode.php new file mode 100644 index 000000000..cea96609a --- /dev/null +++ b/niucloud/core/util/barcode/class/BCGupcext5.barcode.php @@ -0,0 +1,200 @@ + No suggested Retail Price + * If 99991 -> Book Complimentary (normally free) + * If 90001 to 98999 -> Internal Purpose of Publisher + * If 99990 -> Used by the National Association of College Stores to mark used books + * If 0xxxx -> Price Expressed in British Pounds (xx.xx) + * If 5xxxx -> Price Expressed in U.S. dollars (US$xx.xx) + * + *-------------------------------------------------------------------- + * Copyright (C) Jean-Sebastien Goupil + * http://www.barcodephp.com + */ +include_once('BCGParseException.php'); +include_once('BCGBarcode1D.php'); +include_once('BCGLabel.php'); + +class BCGupcext5 extends BCGBarcode1D { + protected $codeParity = array(); + + /** + * Constructor. + */ + public function __construct() { + parent::__construct(); + + $this->keys = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'); + $this->code = array( + '2100', /* 0 */ + '1110', /* 1 */ + '1011', /* 2 */ + '0300', /* 3 */ + '0021', /* 4 */ + '0120', /* 5 */ + '0003', /* 6 */ + '0201', /* 7 */ + '0102', /* 8 */ + '2001' /* 9 */ + ); + + // Parity, 0=Odd, 1=Even. Depending Checksum + $this->codeParity = array( + array(1, 1, 0, 0, 0), /* 0 */ + array(1, 0, 1, 0, 0), /* 1 */ + array(1, 0, 0, 1, 0), /* 2 */ + array(1, 0, 0, 0, 1), /* 3 */ + array(0, 1, 1, 0, 0), /* 4 */ + array(0, 0, 1, 1, 0), /* 5 */ + array(0, 0, 0, 1, 1), /* 6 */ + array(0, 1, 0, 1, 0), /* 7 */ + array(0, 1, 0, 0, 1), /* 8 */ + array(0, 0, 1, 0, 1) /* 9 */ + ); + } + + /** + * Draws the barcode. + * + * @param resource $im + */ + public function draw($im) { + // Checksum + $this->calculateChecksum(); + + // Starting Code + $this->drawChar($im, '001', true); + + // Code + for ($i = 0; $i < 5; $i++) { + $this->drawChar($im, self::inverse($this->findCode($this->text[$i]), $this->codeParity[$this->checksumValue][$i]), false); + if ($i < 4) { + $this->drawChar($im, '00', false); // Inter-char + } + } + + $this->drawText($im, 0, 0, $this->positionX, $this->thickness); + } + + /** + * Returns the maximal size of a barcode. + * + * @param int $w + * @param int $h + * @return int[] + */ + public function getDimension($w, $h) { + $startlength = 4; + $textlength = 5 * 7; + $intercharlength = 2 * 4; + + $w += $startlength + $textlength + $intercharlength; + $h += $this->thickness; + return parent::getDimension($w, $h); + } + + /** + * Adds the default label. + */ + protected function addDefaultLabel() { + parent::addDefaultLabel(); + + if ($this->defaultLabel !== null) { + $this->defaultLabel->setPosition(BCGLabel::POSITION_TOP); + } + } + + /** + * Validates the input. + */ + protected function validate() { + $c = strlen($this->text); + if ($c === 0) { + throw new BCGParseException('upcext5', 'No data has been entered.'); + } + + // Checking if all chars are allowed + for ($i = 0; $i < $c; $i++) { + if (array_search($this->text[$i], $this->keys) === false) { + throw new BCGParseException('upcext5', 'The character \'' . $this->text[$i] . '\' is not allowed.'); + } + } + + // Must contain 5 digits + if ($c !== 5) { + throw new BCGParseException('upcext5', 'Must contain 5 digits.'); + } + + parent::validate(); + } + + /** + * Overloaded method to calculate checksum. + */ + protected function calculateChecksum() { + // Calculating Checksum + // Consider the right-most digit of the message to be in an "odd" position, + // and assign odd/even to each character moving from right to left + // Odd Position = 3, Even Position = 9 + // Multiply it by the number + // Add all of that and do ?mod10 + $odd = true; + $this->checksumValue = 0; + $c = strlen($this->text); + for ($i = $c; $i > 0; $i--) { + if ($odd === true) { + $multiplier = 3; + $odd = false; + } else { + $multiplier = 9; + $odd = true; + } + + if (!isset($this->keys[$this->text[$i - 1]])) { + return; + } + + $this->checksumValue += $this->keys[$this->text[$i - 1]] * $multiplier; + } + + $this->checksumValue = $this->checksumValue % 10; + } + + /** + * Overloaded method to display the checksum. + */ + protected function processChecksum() { + if ($this->checksumValue === false) { // Calculate the checksum only once + $this->calculateChecksum(); + } + + if ($this->checksumValue !== false) { + return $this->keys[$this->checksumValue]; + } + + return false; + } + + /** + * Inverses the string when the $inverse parameter is equal to 1. + * + * @param string $text + * @param int $inverse + * @return string + */ + private static function inverse($text, $inverse = 1) { + if ($inverse === 1) { + $text = strrev($text); + } + + return $text; + } +} +?> \ No newline at end of file diff --git a/niucloud/core/util/barcode/class/JoinDraw.php b/niucloud/core/util/barcode/class/JoinDraw.php new file mode 100644 index 000000000..2d3c35fa7 --- /dev/null +++ b/niucloud/core/util/barcode/class/JoinDraw.php @@ -0,0 +1,194 @@ +image1 = $image1->get_im(); + } else { + $this->image1 = $image1; + } + if ($image2 instanceof BCGDrawing) { + $this->image2 = $image2->get_im(); + } else { + $this->image2 = $image2; + } + + $this->background = $background; + $this->space = (int)$space; + $this->position = (int)$position; + $this->alignment = (int)$alignment; + + $this->createIm(); + } + + /** + * Destroys the image. + */ + public function __destruct() { + imagedestroy($this->im); + } + + /** + * Finds the position where the barcode should be aligned. + * + * @param int $size1 + * @param int $size2 + * @param int $ailgnment + * @return int + */ + private function findPosition($size1, $size2, $alignment) { + $rsize1 = max($size1, $size2); + $rsize2 = min($size1, $size2); + + if ($alignment === self::ALIGN_LEFT) { // Or TOP + return 0; + } elseif ($alignment === self::ALIGN_CENTER) { + return $rsize1 / 2 - $rsize2 / 2; + } else { // RIGHT or TOP + return $rsize1 - $rsize2; + } + } + + /** + * Change the alignments. + * + * @param int $alignment + * @return int + */ + private function changeAlignment($alignment) { + if ($alignment === 0) { + return 1; + } elseif ($alignment === 1) { + return 0; + } else { + return 2; + } + } + + /** + * Creates the image. + */ + private function createIm() { + $w1 = imagesx($this->image1); + $w2 = imagesx($this->image2); + $h1 = imagesy($this->image1); + $h2 = imagesy($this->image2); + + if ($this->position === self::POSITION_LEFT || $this->position === self::POSITION_RIGHT) { + $w = $w1 + $w2 + $this->space; + $h = max($h1, $h2); + } else { + $w = max($w1, $w2); + $h = $h1 + $h2 + $this->space; + } + + $this->im = imagecreatetruecolor($w, $h); + imagefill($this->im, 0, 0, $this->background->allocate($this->im)); + + // We start defining position of images + if ($this->position === self::POSITION_TOP) { + if ($w1 > $w2) { + $posX1 = 0; + $posX2 = $this->findPosition($w1, $w2, $this->alignment); + } else { + $a = $this->changeAlignment($this->alignment); + $posX1 = $this->findPosition($w1, $w2, $a); + $posX2 = 0; + } + + $posY2 = 0; + $posY1 = $h2 + $this->space; + } elseif ($this->position === self::POSITION_LEFT) { + if ($w1 > $w2) { + $posY1 = 0; + $posY2 = $this->findPosition($h1, $h2, $this->alignment); + } else { + $a = $this->changeAlignment($this->alignment); + $posY2 = 0; + $posY1 = $this->findPosition($h1, $h2, $a); + } + + $posX2 = 0; + $posX1 = $w2 + $this->space; + } elseif ($this->position === self::POSITION_BOTTOM) { + if ($w1 > $w2) { + $posX2 = $this->findPosition($w1, $w2, $this->alignment); + $posX1 = 0; + } else { + $a = $this->changeAlignment($this->alignment); + $posX2 = 0; + $posX1 = $this->findPosition($w1, $w2, $a); + } + + $posY1 = 0; + $posY2 = $h1 + $this->space; + } else { // defaults to RIGHT + if ($w1 > $w2) { + $posY2 = $this->findPosition($h1, $h2, $this->alignment); + $posY1 = 0; + } else { + $a = $this->changeAlignment($this->alignment); + $posY2 = 0; + $posY1 = $this->findPosition($h1, $h2, $a); + } + + $posX1 = 0; + $posX2 = $w1 + $this->space; + } + + imagecopy($this->im, $this->image1, $posX1, $posY1, 0, 0, $w1, $h1); + imagecopy($this->im, $this->image2, $posX2, $posY2, 0, 0, $w2, $h2); + } + + /** + * Returns the new $im created. + * + * @return resource + */ + public function get_im() { + return $this->im; + } +} +?> \ No newline at end of file diff --git a/niucloud/core/util/barcode/class/drawer/BCGDraw.php b/niucloud/core/util/barcode/class/drawer/BCGDraw.php new file mode 100644 index 000000000..2082b5dab --- /dev/null +++ b/niucloud/core/util/barcode/class/drawer/BCGDraw.php @@ -0,0 +1,38 @@ +im = $im; + } + + /** + * Sets the filename. + * + * @param string $filename + */ + public function setFilename($filename) { + $this->filename = $filename; + } + + /** + * Method needed to draw the image based on its specification (JPG, GIF, etc.). + */ + abstract public function draw(); +} +?> \ No newline at end of file diff --git a/niucloud/core/util/barcode/class/drawer/BCGDrawJPG.php b/niucloud/core/util/barcode/class/drawer/BCGDrawJPG.php new file mode 100644 index 000000000..2e2c9398b --- /dev/null +++ b/niucloud/core/util/barcode/class/drawer/BCGDrawJPG.php @@ -0,0 +1,102 @@ +dpi = max(1, $dpi); + } else { + $this->dpi = null; + } + } + + /** + * Sets the quality of the JPG. + * + * @param int $quality + */ + public function setQuality($quality) { + $this->quality = $quality; + } + + /** + * Draws the JPG on the screen or in a file. + */ + public function draw() { + ob_start(); + imagejpeg($this->im, null, $this->quality); + $bin = ob_get_contents(); + ob_end_clean(); + + $this->setInternalProperties($bin); + + if (empty($this->filename)) { + echo $bin; + } else { + file_put_contents($this->filename, $bin); + } + } + + private function setInternalProperties(&$bin) { + $this->internalSetDPI($bin); + $this->internalSetC($bin); + } + + private function internalSetDPI(&$bin) { + if ($this->dpi !== null) { + $bin = substr_replace($bin, pack("Cnn", 0x01, $this->dpi, $this->dpi), 13, 5); + } + } + + private function internalSetC(&$bin) { + if(strcmp(substr($bin, 0, 4), pack('H*', 'FFD8FFE0')) === 0) { + $offset = 4 + (ord($bin[4]) << 8 | ord($bin[5])); + $firstPart = substr($bin, 0, $offset); + $secondPart = substr($bin, $offset); + $cr = pack('H*', 'FFFE004447656E657261746564207769746820426172636F64652047656E657261746F7220666F722050485020687474703A2F2F7777772E626172636F64657068702E636F6D'); + $bin = $firstPart; + $bin .= $cr; + $bin .= $secondPart; + } + } +} +?> \ No newline at end of file diff --git a/niucloud/core/util/barcode/class/drawer/BCGDrawPNG.php b/niucloud/core/util/barcode/class/drawer/BCGDrawPNG.php new file mode 100644 index 000000000..5b65a3aa9 --- /dev/null +++ b/niucloud/core/util/barcode/class/drawer/BCGDrawPNG.php @@ -0,0 +1,202 @@ +dpi = max(1, $dpi); + } else { + $this->dpi = null; + } + } + + /** + * Draws the PNG on the screen or in a file. + */ + public function draw() { + ob_start(); + imagepng($this->im); + $bin = ob_get_contents(); + ob_end_clean(); + + $this->setInternalProperties($bin); + + if (empty($this->filename)) { + echo $bin; + } else { + file_put_contents($this->filename, $bin); + } + } + + private function setInternalProperties(&$bin) { + // Scan all the ChunkType + if (strcmp(substr($bin, 0, 8), pack('H*', '89504E470D0A1A0A')) === 0) { + $chunks = $this->detectChunks($bin); + + $this->internalSetDPI($bin, $chunks); + $this->internalSetC($bin, $chunks); + } + } + + private function detectChunks($bin) { + $data = substr($bin, 8); + $chunks = array(); + $c = strlen($data); + + $offset = 0; + while ($offset < $c) { + $packed = unpack('Nsize/a4chunk', $data); + $size = $packed['size']; + $chunk = $packed['chunk']; + + $chunks[] = array('offset' => $offset + 8, 'size' => $size, 'chunk' => $chunk); + $jump = $size + 12; + $offset += $jump; + $data = substr($data, $jump); + } + + return $chunks; + } + + private function internalSetDPI(&$bin, &$chunks) { + if ($this->dpi !== null) { + $meters = (int)($this->dpi * 39.37007874); + + $found = -1; + $c = count($chunks); + for($i = 0; $i < $c; $i++) { + // We already have a pHYs + if($chunks[$i]['chunk'] === 'pHYs') { + $found = $i; + break; + } + } + + $data = 'pHYs' . pack('NNC', $meters, $meters, 0x01); + $crc = self::crc($data, 13); + $cr = pack('Na13N', 9, $data, $crc); + + // We didn't have a pHYs + if($found == -1) { + // Don't do anything if we have a bad PNG + if($c >= 2 && $chunks[0]['chunk'] === 'IHDR') { + array_splice($chunks, 1, 0, array(array('offset' => 33, 'size' => 9, 'chunk' => 'pHYs'))); + + // Push the data + for($i = 2; $i < $c; $i++) { + $chunks[$i]['offset'] += 21; + } + + $firstPart = substr($bin, 0, 33); + $secondPart = substr($bin, 33); + $bin = $firstPart; + $bin .= $cr; + $bin .= $secondPart; + } + } else { + $bin = substr_replace($bin, $cr, $chunks[$i]['offset'], 21); + } + } + } + + private function internalSetC(&$bin, &$chunks) { + if (count($chunks) >= 2 && $chunks[0]['chunk'] === 'IHDR') { + $firstPart = substr($bin, 0, 33); + $secondPart = substr($bin, 33); + $cr = pack('H*', '0000004C74455874436F707972696768740047656E657261746564207769746820426172636F64652047656E657261746F7220666F722050485020687474703A2F2F7777772E626172636F64657068702E636F6D597F70B8'); + $bin = $firstPart; + $bin .= $cr; + $bin .= $secondPart; + } + + // Chunks is dirty!! But we are done. + } + + private static $crc_table = array(); + private static $crc_table_computed = false; + + private static function make_crc_table() { + for ($n = 0; $n < 256; $n++) { + $c = $n; + for ($k = 0; $k < 8; $k++) { + if (($c & 1) == 1) { + $c = 0xedb88320 ^ (self::SHR($c, 1)); + } else { + $c = self::SHR($c, 1); + } + } + self::$crc_table[$n] = $c; + } + + self::$crc_table_computed = true; + } + + private static function SHR($x, $n) { + $mask = 0x40000000; + + if ($x < 0) { + $x &= 0x7FFFFFFF; + $mask = $mask >> ($n - 1); + return ($x >> $n) | $mask; + } + + return (int)$x >> (int)$n; + } + + private static function update_crc($crc, $buf, $len) { + $c = $crc; + + if (!self::$crc_table_computed) { + self::make_crc_table(); + } + + for ($n = 0; $n < $len; $n++) { + $c = self::$crc_table[($c ^ ord($buf[$n])) & 0xff] ^ (self::SHR($c, 8)); + } + + return $c; + } + + private static function crc($data, $len) { + return self::update_crc(-1, $data, $len) ^ -1; + } +} +?> diff --git a/niucloud/core/util/barcode/font/Arial.ttf b/niucloud/core/util/barcode/font/Arial.ttf new file mode 100644 index 000000000..886789b85 Binary files /dev/null and b/niucloud/core/util/barcode/font/Arial.ttf differ diff --git a/niucloud/core/util/niucloud/BaseNiucloudClient.php b/niucloud/core/util/niucloud/BaseNiucloudClient.php new file mode 100644 index 000000000..786bf55b0 --- /dev/null +++ b/niucloud/core/util/niucloud/BaseNiucloudClient.php @@ -0,0 +1,326 @@ +code = $code; + $this->secret = $secret; + }else{ + $auth_config = (new CoreNiucloudConfigService())->getNiucloudConfig(); + if($auth_config['auth_code'] || $auth_config['auth_secret']){ + $this->code = $auth_config['auth_code']; + $this->secret = $auth_config['auth_secret']; + }else{ + $this->code = config('niucloud.auth.code'); + $this->secret = config('niucloud.auth.secret'); + } + } + $this->access_token = $this->getAccessToken(); + $this->request = request(); + } + + /** + * @param string $url + * @param array $data + * @return array|Response|object|ResponseInterface + * @throws GuzzleException + */ + public function httpPost(string $url, array $data = []) + { + return $this->request($url, 'POST', [ + 'form_params' => $data, + ]); + } + + /** + * @param string $url + * @param string $method + * @param array $options + * @param bool $returnRaw + * + * @return ResponseInterface + * @throws GuzzleException + */ + public function request(string $url, string $method = 'GET', array $options = [], bool $returnRaw = false) + { + if (empty($this->middlewares)) { + $this->registerHttpMiddlewares(); + } + $response = $this->toRequest($url, $method, $options); + return $returnRaw ? $response : $this->responseToType($response, config('niucloud.response_type')); + } + + /** + * Register Guzzle middlewares. + */ + protected function registerHttpMiddlewares() + { + // retry + $this->pushMiddleware($this->retryMiddleware(), 'retry'); + //header + $this->pushMiddleware($this->headerMiddleware(), 'header'); + // access token + $this->pushMiddleware($this->accessTokenMiddleware(), 'access_token'); + } + + /** + * @return callable + */ + protected function retryMiddleware() + { + return Middleware::retry( + function ( + $retries, + RequestInterface $request, + ResponseInterface $response = null + ) { + // Limit the number of retries to 2 重试次数,默认 1,指定当 http 请求失败时重试的次数。 + if ($retries < config('niucloud.http.max_retries', 1) && $response && $body = $response->getBody()) { + // Retry on server errors + $response = json_decode($body, true); + if (isset($response['code'])) { + if ($response['code'] != 1) { + if (in_array(abs($response['code']), [401], true)) { + $this->clearAccessToken(); + $this->refreshAccessToken(); + } else { + throw new NiucloudException($response['msg']); + } + } + return true; + } + } + return false; + }, + function () { + //重试延迟间隔(单位:ms),默认 500 + return abs(config('niucloud.http.retry_delay', 500)); + } + ); + } + + /** + * 表头属性 + * @return Closure + */ + public function headerMiddleware(){ + return function (callable $handler) { + return function (RequestInterface $request, array $options) use ($handler) { + $domain = request()->domain(true); + $domain = str_replace('http://', '', $domain); + $domain = str_replace('https://', '', $domain); + $request = $request->withHeader('Referer', $domain); + $options['verify'] = config('niucloud.http.verify', true); + return $handler($request, $options); + }; + }; + } + + + /** + * @param string $url + * @param array $query + * @return array|object|Response|ResponseInterface + * @throws GuzzleException + */ + public function httpGet(string $url, array $query = []) + { + return $this->request($url, 'GET', [ + 'query' => $query, + ]); + } + + /** + * @return Closure + */ + protected function accessTokenMiddleware() + { + return function (callable $handler) { + return function (RequestInterface $request, array $options) use ($handler) { + if ($this->access_token) { + $request = $this->applyToRequest($request, $options); + } + return $handler($request, $options); + }; + }; + } + + /** + * @param RequestInterface $request + * @param array $requestOptions + * @return RequestInterface + */ + public function applyToRequest(RequestInterface $request, array $requestOptions = []): RequestInterface + { + return $request->withHeader($this->access_token_key, $this->access_token); + } + + /** + * @param ResponseInterface $response + * @param $type + * @return array|Response|object + */ + public function responseToType(ResponseInterface $response, $type = null) + { + $response = Response::buildFromPsrResponse($response); + $response->getBody()->rewind(); + + switch ($type ?? 'array') { + case 'collection': + return $response->toCollection(); + case 'array': + return $response->toArray(); + case 'object': + return $response->toObject(); + case 'raw': + return $response; + default: + throw new NiucloudException(sprintf('Config key "response_type" not found', $type)); + } + } + + /** + * @param string $url + * @param array $data + * @param array $query + * @return array|Response|object|ResponseInterface + * @throws GuzzleException + */ + public function httpPostJson(string $url, array $data = [], array $query = []) + { + return $this->request($url, 'POST', ['query' => $query, 'json' => $data]); + } + + /** + * @param string $url + * @param array $files + * @param array $form + * @param array $query + * @return array|Response|object|ResponseInterface + * @throws GuzzleException + */ + public function httpUpload(string $url, array $files = [], array $form = [], array $query = []) + { + $multipart = []; + $headers = []; + + if (isset($form['filename'])) { + $headers = [ + 'Content-Disposition' => 'form-data; name="media"; filename="' . $form['filename'] . '"' + ]; + } + + foreach ($files as $name => $path) { + $multipart[] = [ + 'name' => $name, + 'contents' => fopen($path, 'r'), + 'headers' => $headers + ]; + } + + foreach ($form as $name => $contents) { + $multipart[] = compact('name', 'contents'); + } + + return $this->request( + $url, + 'POST', + ['query' => $query, 'multipart' => $multipart, 'connect_timeout' => 30, 'timeout' => 30, 'read_timeout' => 30] + ); + } + + /** + * @param string $url + * @param string $method + * @param array $options + * + * @return Response + * @throws GuzzleException + */ + public function requestRaw(string $url, string $method = 'GET', array $options = []) + { + return Response::buildFromPsrResponse($this->request($url, $method, $options, true)); + } + + /** + * 下载文件 + * @param string $url + * @param array $query + * @param string $absolute_path + * @return string + * @throws GuzzleException + */ + public function download(string $url, array $query = [], string $absolute_path = '') + { + // 打开即将下载的本地文件,在该文件上打开一个流 + $resource = fopen($absolute_path, 'w'); + $res = $this->request($url, 'GET', ['sink' => $absolute_path, 'query' => $query]); + // 关闭一个已打开的文件指针 + fclose($resource); + return $absolute_path; + } + + public function getDomain($is_filter = true){ + $domain = request()->domain(true); + if($is_filter){ + $domain = str_replace('http://', '', $domain); + $domain = str_replace('https://', '', $domain); + } + return $domain; + } +} diff --git a/niucloud/core/util/niucloud/http/AccessToken.php b/niucloud/core/util/niucloud/http/AccessToken.php new file mode 100644 index 000000000..d3bb564c9 --- /dev/null +++ b/niucloud/core/util/niucloud/http/AccessToken.php @@ -0,0 +1,72 @@ +access_token = ''; + Cache::delete($this->access_token_cache); + return $this; + } + /** + * 设置access_token + * @param $access_token + * @return $this + */ + public function setAccessToken($access_token) + { + $this->access_token = $access_token; + Cache::set($this->access_token_cache, $access_token, 7200); + return $this; + } + /** + * @return mixed + */ + public function getAccessToken() + { + if (empty($this->access_token)) { + $this->access_token = Cache::get($this->access_token_cache, ''); + } + return $this->access_token; + } + + /** + * 刷新access_token + * @return void + * @throws GuzzleException + */ + public function refreshAccessToken() + { + $access_token_info = $this->httpGet('auth', ['code' => $this->code, 'secret' => $this->secret, 'token' => $this->createToken(), 'redirect_uri' => $this->getDomain(false)]); + if (isset($access_token_info['code']) && $access_token_info['code'] != 1) throw new NiucloudException($access_token_info['msg']); + } + +} diff --git a/niucloud/core/util/niucloud/http/HasHttpRequests.php b/niucloud/core/util/niucloud/http/HasHttpRequests.php new file mode 100644 index 000000000..969c0d329 --- /dev/null +++ b/niucloud/core/util/niucloud/http/HasHttpRequests.php @@ -0,0 +1,182 @@ + [ + CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4, + ], + ]; + /** + * @var ClientInterface + */ + protected $httpClient; + /** + * @var array + */ + protected array $middlewares = []; + /** + * @var HandlerStack + */ + protected $handlerStack; + + /** + * @param array $defaults + * @return void + */ + public static function setDefaultOptions(array $defaults = []) + { + self::$defaults = $defaults; + } + + /** + * @return array + */ + public static function getDefaultOptions(): array + { + return self::$defaults; + } + + /** + * @param callable $middleware + * @param string|null $name + * @return $this + */ + public function pushMiddleware(callable $middleware, string $name = null) + { + if (!is_null($name)) { + $this->middlewares[$name] = $middleware; + } else { + $this->middlewares[] = $middleware; + } + + return $this; + } + + /** + * @return array + */ + public function getMiddlewares(): array + { + return $this->middlewares; + } + + /** + * @param $url + * @param string $method + * @param array $options + * @return ResponseInterface + * @throws GuzzleException + */ + public function toRequest($url, string $method = 'GET', array $options = []): ResponseInterface + { + $method = strtoupper($method); + + $options = array_merge(self::$defaults, $options, ['handler' => $this->getHandlerStack()]); + + $options = $this->fixJsonIssue($options); + + if (property_exists($this, 'baseUri') && !is_null($this->baseUri)) { + $options['base_uri'] = $this->baseUri; + } + $response = $this->getHttpClient()->request($method, $url, $options); + $response->getBody()->rewind(); + return $response; + } + + /** + * @return HandlerStack + */ + public function getHandlerStack(): HandlerStack + { + if ($this->handlerStack) { + return $this->handlerStack; + } + + $this->handlerStack = HandlerStack::create($this->getGuzzleHandler()); + + foreach ($this->middlewares as $name => $middleware) { + $this->handlerStack->push($middleware, $name); + } + + return $this->handlerStack; + } + + /** + * @param HandlerStack $handlerStack + * + * @return $this + */ + public function setHandlerStack(HandlerStack $handlerStack) + { + $this->handlerStack = $handlerStack; + + return $this; + } + + /** + * @return callable + */ + protected function getGuzzleHandler() + { + return choose_handler(); + } + + /** + * @param array $options + * @return array + */ + protected function fixJsonIssue(array $options): array + { + if (isset($options['json']) && is_array($options['json'])) { + $options['headers'] = array_merge($options['headers'] ?? [], ['Content-Type' => 'application/json']); + + if (empty($options['json'])) { + $options['body'] = \GuzzleHttp\json_encode($options['json'], JSON_FORCE_OBJECT); + } else { + $options['body'] = \GuzzleHttp\json_encode($options['json'], JSON_UNESCAPED_UNICODE); + } + + unset($options['json']); + } + + return $options; + } + + /** + * @return ClientInterface + */ + public function getHttpClient(): ClientInterface + { + if (!($this->httpClient instanceof ClientInterface)) { + $this->httpClient = new Client(['handler' => HandlerStack::create($this->getGuzzleHandler())]); + } + + return $this->httpClient; + } + + /** + * @param ClientInterface $httpClient + * @return $this + */ + public function setHttpClient(ClientInterface $httpClient) + { + $this->httpClient = $httpClient; + + return $this; + } +} diff --git a/niucloud/core/util/niucloud/http/Response.php b/niucloud/core/util/niucloud/http/Response.php new file mode 100644 index 000000000..81e1182c2 --- /dev/null +++ b/niucloud/core/util/niucloud/http/Response.php @@ -0,0 +1,95 @@ +getStatusCode(), + $response->getHeaders(), + $response->getBody(), + $response->getProtocolVersion(), + $response->getReasonPhrase() + ); + } + + /** + * @return object + */ + public function toObject() + { + return json_decode($this->toJson()); + } + + /** + * Build to json. + * + * @return string + */ + public function toJson() + { + return json_encode($this->toArray()); + } + + /** + * Build to array. + * + * @return array + */ + public function toArray() + { + $content = $this->removeControlCharacters($this->getBodyContents()); + + if (false !== stripos($this->getHeaderLine('Content-Type'), 'xml') || 0 === stripos($content, 'getBody()->rewind(); + $contents = $this->getBody()->getContents(); + $this->getBody()->rewind(); + + return $contents; + } + + /** + * @return string + */ + public function __toString() + { + return $this->getBodyContents(); + } +} diff --git a/niucloud/core/util/niucloud/http/Token.php b/niucloud/core/util/niucloud/http/Token.php new file mode 100644 index 000000000..bb06d51c3 --- /dev/null +++ b/niucloud/core/util/niucloud/http/Token.php @@ -0,0 +1,81 @@ +request->get('signature') !== $this->signature([ + $this->getToken(), + $this->request->get('timestamp'), + $this->request->get('nonce'), + ])) { + throw new NiucloudException('Invalid request signature.'); + } + return true; + } + + /** + * 生成临时证书 + * @param array $params + * @return string + */ + protected function signature(array $params) + { + sort($params, SORT_STRING); + + return sha1(implode($params)); + } + + /** + * 获取TOKEN + * @return void + */ + public function getToken(){ + return Cache::get($this->token_cache, ''); + } + + /** + * 新创建一个token(todo 临时) + * @return void + */ + public function createToken(){ + //根据code和secret生成token + $token = md5(serialize( + [ + 'timestamp' => time(), + 'code' => $this->code, + 'secret' => $this->secret, + 'nonce' => mt_rand(0, 100) + ] + )); + $this->clearToken(); + Cache::set($this->token_cache, $token, 3600); + return $token; + } + + /** + * @return $this + */ + public function clearToken() + { + $this->access_token = ''; + Cache::delete($this->token_cache); + return $this; + } +} diff --git a/niucloud/core/util/niucloud/support/XML.php b/niucloud/core/util/niucloud/support/XML.php new file mode 100644 index 000000000..d0485bea6 --- /dev/null +++ b/niucloud/core/util/niucloud/support/XML.php @@ -0,0 +1,155 @@ + $value) { + $res = self::normalize($value); + if (('@attributes' === $key) && ($key)) { + $result = $res; + } else { + $result[$key] = $res; + } + } + } else { + $result = $obj; + } + + return $result; + } + + /** + * Delete invalid characters in XML. + * + * @see https://www.w3.org/TR/2008/REC-xml-20081126/#charsets - XML charset range + * @see http://php.net/manual/en/regexp.reference.escape.php - escape in UTF-8 mode + * + * @param string $xml + * + * @return string + */ + public static function sanitize($xml) + { + return preg_replace('/[^\x{9}\x{A}\x{D}\x{20}-\x{D7FF}\x{E000}-\x{FFFD}\x{10000}-\x{10FFFF}]+/u', '', $xml); + } + + /** + * XML encode. + * + * @param mixed $data + * @param string $root + * @param string $item + * @param string $attr + * @param string $id + * + * @return string + */ + public static function build( + $data, + $root = 'xml', + $item = 'item', + $attr = '', + $id = 'id' + ) + { + if (is_array($attr)) { + $_attr = []; + + foreach ($attr as $key => $value) { + $_attr[] = "{$key}=\"{$value}\""; + } + + $attr = implode(' ', $_attr); + } + + $attr = trim($attr); + $attr = empty($attr) ? '' : " {$attr}"; + $xml = "<{$root}{$attr}>"; + $xml .= self::data2Xml($data, $item, $id); + $xml .= ""; + + return $xml; + } + + /** + * Array to XML. + * + * @param array $data + * @param string $item + * @param string $id + * + * @return string + */ + protected static function data2Xml($data, $item = 'item', $id = 'id') + { + $xml = $attr = ''; + + foreach ($data as $key => $val) { + if (is_numeric($key)) { + $id && $attr = " {$id}=\"{$key}\""; + $key = $item; + } + + $xml .= "<{$key}{$attr}>"; + + if ((is_array($val) || is_object($val))) { + $xml .= self::data2Xml((array)$val, $item, $id); + } else { + $xml .= is_numeric($val) ? $val : self::cdata($val); + } + + $xml .= ""; + } + + return $xml; + } + + /** + * Build CDATA. + * + * @param string $string + * + * @return string + */ + public static function cdata($string) + { + return sprintf('', $string); + } +}