作者 lihan

萨米户外公众号搭建

正在显示 61 个修改的文件 包含 4688 行增加0 行删除

要显示太多修改。

为保证性能只显示 61 of 61+ 个文件。

.buildpath
.DS_Store
.project
.settings
.idea
composer.lock
... ...
如何贡献我的源代码
===
... ...
bronet遵循LGPL开源协议发布,并提供免费使用。
\ No newline at end of file
... ...
ThinkBRO 1.0
===============
以客户为中心 以奋斗者为本
### 环境推荐
> php5.5+
> mysql 5.6+
> 打开rewrite
### 最低环境要求
> php5.4+
> mysql 5.5+ (mysql5.1安装时选择utf8编码,不支持表情符)
> 打开rewrite
### 自动安装
> 之前安装过的同学,请手动创建`data/install.lock`文件
代码已经加入自动安装程序,如果你在安装中有任何问题请提交 issue!
1. public目录做为网站根目录,入口文件在 public/index.php
2. 配置好网站,请访问http://你的域名
### 完整版目录结构
```
bronet 根目录
├─api api目录(核心版不带)
├─app 应用目录
│ ├─portal 门户应用目录
│ │ ├─config.php 应用配置文件
│ │ ├─common.php 模块函数文件
│ │ ├─controller 控制器目录
│ │ ├─model 模型目录
│ │ └─ ... 更多类库目录
│ ├─ ... 更多应用
│ ├─command.php 命令行工具配置文件
│ ├─common.php 应用公共(函数)文件
│ ├─config.php 应用(公共)配置文件
│ ├─database.php 数据库配置文件
│ ├─tags.php 应用行为扩展定义文件
│ └─route.php 路由配置文件
├─data 数据目录
│ ├─conf 动态配置目录
│ ├─runtime 应用的运行时目录(可写)
│ └─ ... 更多
├─public WEB 部署目录(对外访问目录)
│ ├─api api入口目录(核心版不带)
│ ├─plugins 插件目录
│ ├─static 静态资源存放目录(css,js,image)
│ ├─themes 前后台主题目录
│ │ ├─admin_simpleboot3 后台默认主题
│ │ └─simpleboot3 前台默认主题
│ ├─upload 文件上传目录
│ ├─index.php 入口文件
│ ├─robots.txt 爬虫协议文件
│ ├─router.php 快速测试文件
│ └─.htaccess apache重写文件
├─simplewind
│ ├─cmf CMF核心库目录
│ ├─extend 扩展类库目录
│ ├─thinkphp thinkphp目录
│ └─vendor 第三方类库目录(Composer)
├─composer.json composer 定义文件
├─LICENSE.txt 授权说明文件
├─README.md README 文件
├─think 命令行入口文件
```
### 开发手册
http://www.kancloud.cn/thinkcmf/doc
### 贴别注意
>本环境下已经引入微信SDK
使用手册:https://www.easywechat.com/docs/3.x
微信开发所需要的功能一般情况都涵盖了,以下是封装的公众号开发常用的功能
1. 微信公众号授权已经封装好,只要调用WeChatBaseController下的checkWeChatUserLogin()即可
2. 在user/PayController下整理了微信支付,支付回调,退款,企业支付,红包,订单查询等DEMO
各位同学可参考使用,更多内容还再持续更新中...
各位同学有什么好的想法、意见请及时反馈!
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
namespace api\admin\controller;
use cmf\controller\RestBaseController;
use think\Db;
use think\Validate;
class PublicController extends RestBaseController
{
// 用户登录 TODO 增加最后登录信息记录,如 ip
public function login()
{
$validate = new Validate([
'username' => 'require',
'password' => 'require'
]);
$validate->message([
'username.require' => '请输入手机号,邮箱或用户名!',
'password.require' => '请输入您的密码!'
]);
$data = $this->request->param();
if (!$validate->check($data)) {
$this->error($validate->getError());
}
$userQuery = Db::name("user");
if (Validate::is($data['username'], 'email')) {
$userQuery = $userQuery->where('user_email', $data['username']);
} else if (preg_match('/(^(13\d|15[^4\D]|17[13678]|18\d)\d{8}|170[^346\D]\d{7})$/', $data['username'])) {
$userQuery = $userQuery->where('mobile', $data['username']);
} else {
$userQuery = $userQuery->where('user_login', $data['username']);
}
$findUser = $userQuery->find();
if (empty($findUser)) {
$this->error("用户不存在!");
} else {
switch ($findUser['user_status']) {
case 0:
$this->error('您已被拉黑!');
case 2:
$this->error('账户还没有验证成功!');
}
if (!cmf_compare_password($data['password'], $findUser['user_pass'])) {
$this->error("密码不正确!");
}
}
$allowedDeviceTypes = ['mobile', 'android', 'iphone', 'ipad', 'web', 'pc', 'mac'];
if (empty($data['device_type']) || !in_array($data['device_type'], $allowedDeviceTypes)) {
$this->error("请求错误,未知设备!");
}
$userTokenQuery = Db::name("user_token")
->where('user_id', $findUser['id'])
->where('device_type', $data['device_type']);
$findUserToken = $userTokenQuery->find();
$currentTime = time();
$expireTime = $currentTime + 24 * 3600 * 180;
$token = md5(uniqid()) . md5(uniqid());
if (empty($findUserToken)) {
$result = $userTokenQuery->insert([
'token' => $token,
'user_id' => $findUser['id'],
'expire_time' => $expireTime,
'create_time' => $currentTime,
'device_type' => $data['device_type']
]);
} else {
$result = $userTokenQuery
->where('user_id', $findUser['id'])
->where('device_type', $data['device_type'])
->update([
'token' => $token,
'expire_time' => $expireTime,
'create_time' => $currentTime
]);
}
if (empty($result)) {
$this->error("登录失败!");
}
$this->success("登录成功!", ['token' => $token]);
}
// 管理员退出
public function logout()
{
$userId = $this->getUserId();
Db::name('user_token')->where([
'token' => $this->token,
'user_id' => $userId,
'device_type' => $this->deviceType
])->update(['token' => '']);
$this->success("退出成功!");
$this->success("退出成功!");
}
}
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
$apps = cmf_scan_dir(APP_PATH . '*', GLOB_ONLYDIR);
$returnCommands = [];
foreach ($apps as $app) {
$commandFile = APP_PATH . $app . '/command.php';
if (file_exists($commandFile)) {
$commands = include $commandFile;
$returnCommands = array_merge($returnCommands, $commands);
}
}
return $returnCommands;
\ No newline at end of file
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
namespace api\common\model;
use think\Model;
use think\Loader;
class CommonModel extends Model
{
// 关联模型过滤
protected $relationFilter = [];
/**
* @access public
* @param array $params 过滤参数
* @return array|collection 查询结果
*/
public function getDatas($params = [])
{
if (empty($params)) {
return $this->select();
}
$this->setCondition($params);
if (!empty($params['id'])) {
$datas = $this->find();
} else {
$datas = $this->select();
}
if (!empty($params['relation'])) {
$allowedRelations = $this->allowedRelations($params['relation']);
if (!empty($allowedRelations)) {
if (!empty($params['id'])) {
if (!empty($datas)) {
$datas->append($allowedRelations);
}
} else {
if (count($datas) > 0) {
$datas->load($allowedRelations);
$datas->append($allowedRelations);
}
}
}
}
return $datas;
}
/**
* @access public
* @param array $params 过滤参数
* @return $this
*/
public function setCondition($params)
{
if (empty($params)) {
return $this;
}
if (!empty($params['relation'])) {
$allowedRelations = $this->allowedRelations($params['relation']);
if (!empty($allowedRelations)) {
if (!empty($params['id']) && count($allowedRelations) == 1) {
$this->paramsFilter($params);
} else {
$this->paramsFilter($params);//->with($allowedRelations);
}
}
} else {
$this->paramsFilter($params);
}
return $this;
}
/**
* @access public
* @param array $params 过滤参数
* @param model $model 关联模型
* @return model|array $this|链式查询条件数组
*/
public function paramsFilter($params, $model = null)
{
if (!empty($model)) {
$_this = $model;
} else {
$_this = $this;
}
if (isset($_this->visible)) {
$whiteParams = $_this->visible;
}
// 设置field字段过滤
if (!empty($params['field'])) {
$filterParams = $this->strToArr($params['field']);
if (!empty($whiteParams)) {
$mixedField = array_intersect($filterParams, $whiteParams);
} else {
$mixedField = $filterParams;
}
if (!empty($mixedField)) {
$_this->field($mixedField);
}
}
// 设置id,ids
if (!empty($params['ids'])) {
$ids = $this->strToArr($params['ids']);
foreach ($ids as $key => $value) {
$ids[$key] = intval($value);
}
}
if (!empty($params['id'])) {
$id = intval($params['id']);
if (!empty($id)) {
return $_this->where('id', $id);
}
} elseif (!empty($ids)) {
$_this->where('id', 'in', $ids);
}
if (!empty($params['where'])) {
if (empty($model)) {
$_this->where($params['where']);
}
}
// 设置分页
if (!empty($params['page'])) {
$pageArr = $this->strToArr($params['page']);
$page = [];
foreach ($pageArr as $value) {
$page[] = intval($value);
}
if (count($page) == 1) {
$_this->page($page[0]);
} elseif (count($page) == 2) {
$_this->page($page[0], $page[1]);
}
} elseif (!empty($params['limit'])) { // 设置limit查询
$limitArr = $this->strToArr($params['limit']);
$limit = [];
foreach ($limitArr as $value) {
$limit[] = intval($value);
}
if (count($limit) == 1) {
$_this->limit($limit[0]);
} elseif (count($limit) == 2) {
$_this->limit($limit[0], $limit[1]);
}
} else {
$_this->limit(10);
}
//设置排序
if (!empty($params['order'])) {
$order = $this->strToArr($params['order']);
foreach ($order as $key => $value) {
$upDwn = substr($value, 0, 1);
$orderType = $upDwn == '-' ? 'desc' : 'asc';
$orderField = substr($value, 1);
if (!empty($whiteParams)) {
if (in_array($orderField, $whiteParams)) {
$orderWhere[$orderField] = $orderType;
}
} else {
$orderWhere[$orderField] = $orderType;
}
}
if (!empty($orderWhere)) {
$_this->order($orderWhere);
}
}
return $_this;
}
/**
* 设置链式查询
* @access public
* @param array $params 链式查询条件
* @param model $model 模型
* @return $this
*/
public function setParamsQuery($params, $model = null)
{
if (!empty($model)) {
$_this = $model;
} else {
$_this = $this;
}
$_this->alias('articles');
if (!empty($params['field'])) {
$_this->field($params['field']);
}
if (!empty($params['ids'])) {
$_this->where('articles.id', $params['ids'][1], $params['ids'][2]);
}
if (!empty($params['limit'])) {
$_this->limit($params['limit']);
}
if (!empty($params['page'])) {
$_this->page($params['page']);
}
if (!empty($params['order'])) {
$_this->order($params['order']);
}
return $_this;
}
public function allowedRelations($relations)
{
if (is_string($relations)) {
$relations = explode(',', $relations);
}
if (!is_array($relations)) {
return false;
}
return array_intersect($this->relationFilter, $relations);
}
/**
* 是否允许关联
* @access public
* @param string $relationName 模型关联方法名
* @return boolean
*/
public function isWhite($relationName)
{
if (!is_string($relationName)) {
return false;
}
$name = Loader::parseName($relationName, 1, false);
if (in_array($name, $this->relationFilter)) {
return true;
} else {
return false;
}
}
/**
* 懒人函数
* @access public
* @param string $value 字符串
* @return array
*/
public function strToArr($string)
{
return is_string($string) ? explode(',', $string) : $string;
}
}
\ No newline at end of file
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
return [
// +----------------------------------------------------------------------
// | 应用设置
// +----------------------------------------------------------------------
// 应用命名空间
'app_namespace' => 'api',
// 应用模式状态
'app_status' => APP_DEBUG ? 'debug' : 'release',
// 是否支持多模块
'app_multi_module' => true,
// 入口自动绑定模块
'auto_bind_module' => false,
// 注册的根命名空间
'root_namespace' => ['cmf' => CMF_PATH, 'plugins' => PLUGINS_PATH, 'app' => CMF_PATH . 'app/'],
// 扩展函数文件
'extra_file_list' => [THINK_PATH . 'helper' . EXT, CMF_PATH . 'common' . EXT],
// 默认输出类型
'default_return_type' => 'json',
// 默认AJAX 数据返回格式,可选json xml ...
'default_ajax_return' => 'json',
// 默认JSONP格式返回的处理方法
'default_jsonp_handler' => 'jsonpReturn',
// 默认JSONP处理方法
'var_jsonp_handler' => 'callback',
// 默认时区
'default_timezone' => 'PRC',
// 是否开启多语言
'lang_switch_on' => false,
// 默认全局过滤方法 用逗号分隔多个
'default_filter' => 'htmlspecialchars',
// 默认语言
'default_lang' => 'zh-cn',
// 应用类库后缀
'class_suffix' => true,
// 控制器类后缀
'controller_suffix' => true,
// +----------------------------------------------------------------------
// | 模块设置
// +----------------------------------------------------------------------
// 默认模块名
'default_module' => 'home',
// 禁止访问模块
'deny_module_list' => ['common'],
// 默认控制器名
'default_controller' => 'Index',
// 默认操作名
'default_action' => 'index',
// 默认验证器
'default_validate' => '',
// 默认的空控制器名
'empty_controller' => 'Error',
// 自动搜索控制器
'controller_auto_search' => false,
// +----------------------------------------------------------------------
// | URL设置
// +----------------------------------------------------------------------
'pathinfo_depr' => '/',
// URL伪静态后缀
'url_html_suffix' => 'html',
// URL普通方式参数 用于自动生成
'url_common_param' => false,
// URL参数方式 0 按名称成对解析 1 按顺序解析
'url_param_type' => 0,
// 是否开启路由
'url_route_on' => true,
// 路由配置文件(支持配置多个)
'route_config_file' => ['route'],
// 是否强制使用路由
'url_route_must' => false,
// 域名部署
'url_domain_deploy' => false,
// 域名根,如thinkphp.cn
'url_domain_root' => '',
// 是否自动转换URL中的控制器和操作名
'url_convert' => true,
// 默认的访问控制器层
'url_controller_layer' => 'controller',
// 表单请求类型伪装变量
'var_method' => '_method',
// +----------------------------------------------------------------------
// | 模板设置
// +----------------------------------------------------------------------
'template' => [
// 模板引擎类型 支持 php think 支持扩展
'type' => 'Think',
// 视图根目录
'view_base' => '',
// 模板路径
'view_path' => '',
// 模板后缀
'view_suffix' => 'html',
// 模板文件名分隔符
'view_depr' => DS,
// 模板引擎普通标签开始标记
'tpl_begin' => '{',
// 模板引擎普通标签结束标记
'tpl_end' => '}',
// 标签库标签开始标记
'taglib_begin' => '<',
// 标签库标签结束标记
'taglib_end' => '>',
],
// 视图输出字符串内容替换
'view_replace_str' => [],
// 默认跳转页面对应的模板文件
'dispatch_success_tmpl' => THINK_PATH . 'tpl' . DS . 'dispatch_jump.tpl',
'dispatch_error_tmpl' => THINK_PATH . 'tpl' . DS . 'dispatch_jump.tpl',
// +----------------------------------------------------------------------
// | 异常及错误设置
// +----------------------------------------------------------------------
// 异常页面的模板文件
'exception_tmpl' => THINK_PATH . 'tpl' . DS . 'think_exception.tpl',
// 错误显示信息,非调试模式有效
'error_message' => '页面错误!请稍后再试~',
// 显示错误信息
'show_error_msg' => false,
// 异常处理handle类 留空使用 \think\exception\Handle
'exception_handle' => '',
// +----------------------------------------------------------------------
// | 日志设置
// +----------------------------------------------------------------------
'log' => [
// 日志记录方式,内置 file socket 支持扩展
'type' => 'File',
// 日志保存目录
'path' => LOG_PATH,
// 日志记录级别
'level' => [],
],
// +----------------------------------------------------------------------
// | Trace设置 开启 app_trace 后 有效
// +----------------------------------------------------------------------
'trace' => [
// 内置Html Console 支持扩展
'type' => 'Html',
],
// +----------------------------------------------------------------------
// | 缓存设置
// +----------------------------------------------------------------------
'cache' => [
// 驱动方式
'type' => 'File',
// 缓存保存目录
'path' => CACHE_PATH,
// 缓存前缀
'prefix' => '',
// 缓存有效期 0表示永久缓存
'expire' => 0,
],
// +----------------------------------------------------------------------
// | 会话设置
// +----------------------------------------------------------------------
'session' => [
'id' => '',
// SESSION_ID的提交变量,解决flash上传跨域
'var_session_id' => '',
// SESSION 前缀
'prefix' => 'think',
// 驱动方式 支持redis memcache memcached
'type' => '',
// 是否自动开启 SESSION
'auto_start' => true,
],
// +----------------------------------------------------------------------
// | Cookie设置
// +----------------------------------------------------------------------
'cookie' => [
// cookie 名称前缀
'prefix' => '',
// cookie 保存时间
'expire' => 0,
// cookie 保存路径
'path' => '/',
// cookie 有效域名
'domain' => '',
// cookie 启用安全传输
'secure' => false,
// httponly设置
'httponly' => '',
// 是否使用 setcookie
'setcookie' => true,
],
// +----------------------------------------------------------------------
// | 数据库设置
// +----------------------------------------------------------------------
'database' => [
// 数据库调试模式
'debug' => true,
// 数据集返回类型
'resultset_type' => 'collection',
// 自动写入时间戳字段
'auto_timestamp' => false,
// 时间字段取出后的默认时间格式
'datetime_format' => false,
// 是否需要进行SQL性能分析
'sql_explain' => false,
],
//分页配置
'paginate' => [
'type' => 'bootstrap',
'var_page' => 'page',
'list_rows' => 15,
],
//图片验证码
'captcha' => [
// 验证码字符集合
'codeSet' => '2345678abcdefhijkmnpqrstuvwxyzABCDEFGHJKLMNPQRTUVWXY',
// 验证码字体大小(px)
'fontSize' => 25,
// 是否画混淆曲线
'useCurve' => true,
// 验证码图片高度
'imageH' => 30,
// 验证码图片宽度
'imageW' => 100,
// 验证码位数
'length' => 5,
// 验证成功后是否重置
'reset' => true
],
// +----------------------------------------------------------------------
// | CMF 设置
// +----------------------------------------------------------------------
'cmf_theme_path' => 'themes/home/',
'cmf_default_theme' => 'simpleboot3',
'cmf_admin_theme_path' => 'themes/admin/',
'cmf_admin_default_theme' => 'simpleboot3',
];
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
if(file_exists(ROOT_PATH."data/conf/database.php")){
$database=include ROOT_PATH."data/conf/database.php";
}else{
$database=[];
}
return $database;
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
return [
// 应用调试模式
'app_debug' => true,
// 应用Trace
'app_trace' => true,
];
\ No newline at end of file
... ...
<?php
namespace api\home\controller;
use cmf\controller\RestBaseController;
/**
* @title 欢迎页
* @description 欢迎使用在线接口文档
*/
class IndexController extends RestBaseController
{
/**
* @title 首页
* @description 默认访问接口
* @author Tiger Yang
* @url /home/index/index
* @method GET
*
* @return version:版本号
* @return code:错误码
*/
public function index()
{
$data=[
'version' => '1.0.0',
'code'=>[
'20000' => '默认成功返回码',
'40000' => '默认错误返回码',
'40001' => '未登录或登录失效',
'40002' => '签名验证失败',
'40003' => '缺少必要参数或参数格式错误',
'40004' => '登录失败',
]
];
$this->success("恭喜您,API访问成功!", $data);
}
}
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
// API 模板文件,可以复制
namespace api\home\controller;
use cmf\controller\RestBaseController;
class RestController extends RestBaseController
{
/**
* 显示资源列表
*/
public function index()
{
}
/**
* 保存新建的资源
*/
public function save()
{
}
/**
* 显示指定的资源
*
* @param int $id
*/
public function read($id)
{
}
/**
* 保存更新的资源
*
* @param int $id
*/
public function update($id)
{
}
/**
* 删除指定资源
*
* @param int $id
*/
public function delete($id)
{
}
}
... ...
<?php
// +----------------------------------------------------------------------
// | 文件说明:幻灯片
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
// | Date: 2017-5-25
// +----------------------------------------------------------------------
namespace api\home\controller;
use api\home\model\SlideModel;
use cmf\controller\RestBaseController;
class SlidesController extends RestBaseController
{
/**
* [获取幻灯片]
* @Author: wuwu<15093565100@163.com>
* @DateTime: 2017-05-25T20:48:53+0800
* @since: 1.0
*/
public function read()
{
//slide为空或不存在抛出异常
$id = $this->request->param('id', 0, 'intval');
if (empty($id)) {
$this->error('缺少ID参数');
}
$map['id'] = $id;
$obj = new SlideModel();
$data = $obj->SlideList($map);
//剔除分类状态隐藏 剔除分类下显示数据为空
if ($data->isEmpty() || empty($data->toArray()[0]['items'])) {
$this->error('该组幻灯片显示数据为空');
}
$this->success("该组幻灯片获取成功!", $data);
}
}
... ...
<?php
// +----------------------------------------------------------------------
// | 文件说明:用户-幻灯片
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
// | Date: 2017-5-25
// +----------------------------------------------------------------------
namespace api\home\model;
use think\Model;
class SlideItemModel extends Model
{
/**
* [base 全局查询范围status=1显示状态]
* @Author: wuwu<15093565100@163.com>
* @DateTime: 2017-05-25T21:54:03+0800
* @since: 1.0
*/
protected function base($query)
{
$query->where('status', 1);
}
/**
* image 自动转化
* @param $value
* @return array
*/
public function getImageAttr($value)
{
return cmf_get_image_url($value);
}
}
... ...
<?php
// +----------------------------------------------------------------------
// | 文件说明:用户-幻灯片
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
// | Date: 2017-5-25
// +----------------------------------------------------------------------
namespace api\home\model;
use think\Model;
class SlideModel extends Model
{
/**
* [base 全局查询范围status=1显示状态]
* @Author: wuwu<15093565100@163.com>
* @DateTime: 2017-05-25T21:54:03+0800
* @since: 1.0
*/
protected function base($query)
{
$query->where('status', 1)->where('delete_time', 0);
}
/**
* [SlideItemModel 一对一关联模型 关联分类下的幻灯片]
* @Author: wuwu<15093565100@163.com>
* @DateTime: 2017-05-25T23:30:27+0800
* @since: 1.0
*/
protected function items()
{
return $this->hasMany('SlideItemModel');
}
/**
* [SlideList 幻灯片获取]
* @Author: wuwu<15093565100@163.com>
* @DateTime: 2017-05-25T20:52:27+0800
* @since: 1.0
*/
public function SlideList($map)
{
$data = $this->relation('items')->field(true)->where($map)->select();
return $data;
}
}
... ...
<?php
use think\Route;
Route::resource('home/slides', 'home/Slides');
\ No newline at end of file
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
namespace api\portal\controller;
use cmf\controller\RestBaseController;
use api\portal\model\PortalPostModel;
use api\portal\model\PortalTagPostModel;
class ArticlesController extends RestBaseController
{
protected $postModel;
public function __construct(PortalPostModel $postModel)
{
parent::__construct();
$this->postModel = $postModel;
}
/**
* 文章列表
*/
public function index()
{
$params = $this->request->get();
$params['where']['post_type'] = 1;
$data = $this->postModel->getDatas($params);
$this->success('请求成功!', $data);
}
/**
* 获取指定的文章
* @param int $id
*/
public function read($id)
{
if (intval($id) === 0) {
$this->error('无效的文章id!');
} else {
$params = $this->request->get();
$params['where']['post_type'] = 1;
$params['id'] = $id;
$data = $this->postModel->getDatas($params);
if (empty($data)) {
$this->error('文章不存在!');
} else {
$this->success('请求成功!', $data);
}
}
}
/**
* 我的文章列表
*/
public function my()
{
$params = $this->request->get();
$userId = $this->getUserId();
$data = $this->postModel->getUserArticles($userId, $params);
$this->success('请求成功!', $data);
}
/**
* 添加文章
*/
public function save()
{
$data = $this->request->post();
$data['user_id'] = $this->getUserId();
$result = $this->validate($data, 'Articles.article');
if ($result !== true) {
$this->error($result);
}
if (empty($data['published_time'])) {
$data['published_time'] = time();
}
$this->postModel->addArticle($data);
$this->success('添加成功!');
}
/**
* 更新文章
* @param int $id
*/
public function update($id)
{
$data = $this->request->put();
$result = $this->validate($data, 'Articles.article');
if ($result !== true) {
$this->error($result);
}
if (empty($id)) {
$this->error('无效的文章id');
}
$result = $this->postModel->editArticle($data, $id, $this->getUserId());
if ($result === false) {
$this->error('编辑失败!');
} else {
$this->success('编辑成功!');
}
}
/**
* 删除文章
* @param int $id
*/
public function delete($id)
{
if (empty($id)) {
$this->error('无效的文章id');
}
$result = $this->postModel->deleteArticle($id, $this->getUserId());
if ($result == -1) {
$this->error('文章已删除');
}
if ($result) {
$this->success('删除成功!');
} else {
$this->error('删除失败!');
}
}
/**
* 批量删除文章
*/
public function deletes()
{
$ids = $this->request->post('ids/a');
if (empty($ids)) {
$this->error('文章id不能为空');
}
$result = $this->postModel->deleteArticle($ids, $this->getUserId());
if ($result == -1) {
$this->error('文章已删除');
}
if ($result) {
$this->success('删除成功!');
} else {
$this->error('删除失败!');
}
}
public function search()
{
$params = $this->request->get();
if (!empty($params['keyword'])) {
$params['where'] = [
'post_type' => 1,
'post_title|post_keywords|post_excerpt' => ['like', '%' . $params['keyword'] . '%']
];
$data = $this->postModel->getDatas($params);
$this->success('请求成功!', $data);
} else {
$this->error('搜索关键词不能为空!');
}
}
}
\ No newline at end of file
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
namespace api\portal\controller;
use cmf\controller\RestBaseController;
use api\portal\model\PortalCategoryModel;
class CategoriesController extends RestBaseController
{
protected $categoryModel;
public function __construct(PortalCategoryModel $categoryModel)
{
parent::__construct();
$this->categoryModel = $categoryModel;
}
/**
* 获取分类列表
*/
public function index()
{
$params = $this->request->get();
$data = $this->categoryModel->getDatas($params);
$this->success('请求成功!', $data);
}
/**
* 显示指定的分类
* @param int $id
*/
public function read($id)
{
$params = $this->request->get();
$params['id'] = $id;
$data = $this->categoryModel->getDatas($params);
$this->success('请求成功!', $data);
}
}
\ No newline at end of file
... ...
<?php
namespace api\portal\controller;
use think\Controller;
/**
* @title 测试demo
* @description 接口说明
* @header name:key require:1 default: desc:秘钥(区别设置)
* @param name:public type:int require:1 default:1 other: desc:公共参数(区别设置)
*/
class DemoController extends Controller
{
/**
* @title 测试demo接口
* @description 接口说明
* @author 开发者
* @url /portal/demo/index
* @method GET
* @module 测试模块
* @header name:device require:1 default: desc:设备号
*
* @param name:id type:int require:1 default:1 other: desc:唯一ID
*
* @return name:名称
* @return mobile:手机号
* @return list_messages:消息列表@
* @list_messages message_id:消息ID content:消息内容
* @return object:对象信息@!
* @object attribute1:对象属性1 attribute2:对象属性2
* @return array:数组值#
* @return list_user:用户列表@
* @list_user name:名称 mobile:手机号 list_follow:关注列表@
* @list_follow user_id:用户id name:名称
*/
public function index()
{
//接口代码
$device = $this->request->header('device');
echo json_encode(["code"=>200, "message"=>"success", "data"=>['device'=>$device]]);
}
/**
* @title 登录接口
* @description 接口说明
* @author 开发者
* @url /api/demo
* @method GET
* @module 用户模块
* @param name:name type:int require:1 default:1 other: desc:用户名
* @param name:pass type:int require:1 default:1 other: desc:密码
*
* @return name:名称
* @return mobile:手机号
*
*/
public function login(Request $request)
{
//接口代码
$device = $request->header('device');
echo json_encode(["code"=>200, "message"=>"success", "data"=>['device'=>$device]]);
}
}
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
namespace api\portal\controller;
use api\portal\model\PortalCategoryModel;
use api\portal\model\PortalPostModel;
use cmf\controller\RestBaseController;
class ListsController extends RestBaseController
{
/**
* [推荐文章列表]
* @Author: wuwu<15093565100@163.com>
* @DateTime: 2017-07-17T11:36:51+0800
* @since: 1.0
*/
public function recommended()
{
$param = $this->request->param();
$portalPostModel = new PortalPostModel();
$param['where'] = ['recommended' => 1];
$articles = $portalPostModel->getDatas($param);
$this->success('ok', ['list' => $articles]);
}
/**
* [getCategoryPostLists 分类文章列表]
* @Author: wuwu<15093565100@163.com>
* @DateTime: 2017-07-17T15:22:41+0800
* @since: 1.0
*/
public function getCategoryPostLists()
{
$categoryId = $this->request->param('category_id', 0, 'intval');
$portalCategoryModel = new PortalCategoryModel();
$findCategory = $portalCategoryModel->where('id', $categoryId)->find();
//分类是否存在
if (empty($findCategory)) {
$this->error('分类不存在!');
}
$param = $this->request->param();
$articles = $portalCategoryModel->paramsFilter($param, $findCategory->articles()->alias('post'))->select();
if (!empty($param['relation'])) {
if (count($articles) > 0) {
$articles->load('user');
$articles->append(['user']);
}
}
$this->success('ok', ['list' => $articles]);
}
}
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
namespace api\portal\controller;
use cmf\controller\RestBaseController;
use api\portal\model\PortalPostModel;
class PagesController extends RestBaseController
{
protected $postModel;
public function __construct(PortalPostModel $postModel)
{
parent::__construct();
$this->postModel = $postModel;
}
/**
* 页面列表
*/
public function index()
{
$params = $this->request->get();
$params['where']['post_type'] = 2;
$data = $this->postModel->getDatas($params);
$this->success('请求成功!', $data);
}
/**
* 获取页面
* @param int $id
*/
public function read($id)
{
$params = $this->request->get();
$params['where']['post_type'] = 2;
$params['id'] = $id;
$data = $this->postModel->getDatas($params);
$this->success('请求成功!', $data);
}
}
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
namespace api\portal\controller;
use api\portal\model\PortalPostModel;
use cmf\controller\RestBaseController;
use api\portal\model\PortalTagModel;
class TagsController extends RestBaseController
{
protected $tagModel;
public function __construct(PortalTagModel $tagModel)
{
parent::__construct();
$this->tagModel = $tagModel;
}
/**
* 获取标签列表
*/
public function index()
{
$params = $this->request->get();
$data = $this->tagModel->getDatas($params);
$this->success('请求成功!', $data);
}
/**
* 获取热门标签列表
*/
public function hotTags()
{
$params = $this->request->get();
$params['where']['recommended'] = 1;
$data = $this->tagModel->getDatas($params);
$this->success('请求成功!', $data);
}
/**
* 获取标签文章列表
* @param int $id
*/
public function articles($id)
{
if (intval($id) === 0) {
$this->error('无效的标签id!');
} else {
$params = $this->request->param();
$params['id'] = $id;
$params['relation'] = 'articles';
$postModel = new PortalPostModel();
$articles = $postModel->setCondition($params)->alias('a')->join('__PORTAL_TAG_POST__ tp', 'a.id = tp.post_id')
->where(['tag_id' => $id])->select();
$this->success('请求成功!', ['articles' => $articles]);
}
}
}
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
namespace api\portal\controller;
use cmf\controller\RestUserBaseController;
use api\portal\logic\PortalPostModel;
class UserArticlesController extends RestUserBaseController
{
protected $postModel;
public function __construct(PortalPostModel $postModel)
{
parent::__construct();
$this->postModel = $postModel;
}
/**
* 显示资源列表
*/
public function index()
{
$params = $this->request->get();
$userId = $this->getUserId();
$datas = $this->postModel->getUserArticles($userId,$params);
$this->success('请求成功!', $datas);
}
/**
* 保存新建的资源
*/
public function save()
{
$datas = $this->request->post();
$datas['user_id'] = $this->getUserId();
$result = $this->validate($datas, 'Articles.article');
if ($result !== true) {
$this->error($result);
}
if (empty($datas['published_time'])) {
$datas['published_time'] = time();
}
$this->postModel->addArticle($datas);
$this->success('添加成功!');
}
/**
* 显示指定的资源
*
* @param int $id
*/
public function read($id)
{
if (empty($id)) {
$this->error('无效的文章id');
}
$params = $this->request->get();
$params['id'] = $id;
$userId = $this->getUserId();
$datas = $this->postModel->getUserArticles($userId,$params);
$this->success('请求成功!', $datas);
}
/**
* 保存更新的资源
*
* @param int $id
*/
public function update($id)
{
$data = $this->request->put();
$result = $this->validate($data, 'Articles.article');
if ($result !== true) {
$this->error($result);
}
if (empty($id)) {
$this->error('无效的文章id');
}
$result = $this->postModel->editArticle($data,$id,$this->getUserId());
if ($result === false) {
$this->error('编辑失败!');
} else {
$this->success('编辑成功!');
}
}
/**
* 删除指定资源
*
* @param int $id
*/
public function delete($id)
{
if (empty($id)) {
$this->error('无效的文章id');
}
$result = $this->postModel->deleteArticle($id,$this->getUserId());
if ($result == -1) {
$this->error('文章已删除');
}
if ($result) {
$this->success('删除成功!');
} else {
$this->error('删除失败!');
}
}
/**
* 批量删除文章
*/
public function deletes()
{
$ids = $this->request->post('ids/a');
if (empty($ids)) {
$this->error('文章id不能为空');
}
$result = $this->postModel->deleteArticle($ids,$this->getUserId());
if ($result == -1) {
$this->error('文章已删除');
}
if ($result) {
$this->success('删除成功!');
} else {
$this->error('删除失败!');
}
}
/**
* 我的文章列表
*/
public function my()
{
$params = $this->request->get();
$userId = $this->getUserId();
$data = $this->postModel->getUserArticles($userId, $params);
$this->success('请求成功!', $data);
}
}
\ No newline at end of file
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
namespace api\portal\controller;
use api\portal\model\PortalPostModel;
use cmf\controller\RestBaseController;
class UserController extends RestBaseController
{
protected $postModel;
public function __construct(PortalPostModel $postModel)
{
parent::__construct();
$this->postModel = $postModel;
}
/**
* 会员文章列表
*/
public function articles()
{
$userId = $this->request->param('user_id', 0, 'intval');
if(empty($userId)){
$this->error('用户id不能空!');
}
$data = $this->request->param();
$articles = $this->postModel->setCondition($data)->where(['user_id' => $userId])->select();
if (count($articles) == 0) {
$this->error('没有数据');
} else {
$this->success('ok', ['list' => $articles]);
}
}
}
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
namespace api\portal\logic;
use api\portal\model\PortalPostModel as PortalPost;
use think\Db;
class PortalPostModel extends PortalPost
{
/**
* 获取相关文章
* @param int|string|array $postIds 文章id
* @return array
*/
public function getRelationPosts($postIds)
{
$posts = $this->with('articleUser')
->field('id,post_title,user_id,is_top,post_hits,post_like,comment_count,more')
->whereIn('id', $postIds)
->select();
foreach ($posts as $post) {
$post->appendRelationAttr('articleUser', 'user_nickname');
}
return $posts;
}
/**
* 获取用户文章
*/
public function getUserArticles($userId, $params)
{
$where = [
'post_type' => 1,
'user_id' => $userId
];
if (!empty($params)) {
$this->paramsFilter($params);
}
return $this->where($where)->select();
}
/**
* 会员添加文章
* @param array $data 文章数据
* @return $this
*/
public function addArticle($data)
{
//设置图片附件,写入字段过滤
$dataField = $this->setMoreField($data);
$data = $dataField[0];
array_push($dataField[1],'user_id');
$this->readonly = array_diff(['user_id'],$this->readonly);
$this->allowField($dataField[1])->data($data, true)->isUpdate(false)->save();
$categories = $this->strToArr($data['categories']);
$this->categories()->attach($categories);
if (!empty($data['post_keywords']) && is_string($data['post_keywords'])) {
//加入标签
$data['post_keywords'] = str_replace(',', ',', $data['post_keywords']);
$keywords = explode(',', $data['post_keywords']);
$this->addTags($keywords, $this->id);
}
return $this;
}
/**
* 会员文章编辑
* @param array $data 文章数据
* @param int $id 文章id
* @param int $userId 文章所属用户id [可选]
* @return boolean 成功 true 失败 false
*/
public function editArticle($data, $id, $userId = '')
{
if (!empty($userId)) {
$isBelong = $this->isuserPost($id, $userId);
if ($isBelong === false) {
return $isBelong;
}
}
//设置图片附件,写入字段过滤
$dataField = $this->setMoreField($data);
$data = $dataField[0];
$data['id'] = $id;
$this->allowField($dataField[1])->data($data, true)->isUpdate(true)->save();
$categories = $this->strToArr($data['categories']);
$oldCategoryIds = $this->categories()->column('category_id');
$sameCategoryIds = array_intersect($categories, $oldCategoryIds);
$needDeleteCategoryIds = array_diff($oldCategoryIds, $sameCategoryIds);
$newCategoryIds = array_diff($categories, $sameCategoryIds);
if (!empty($needDeleteCategoryIds)) {
$this->categories()->detach($needDeleteCategoryIds);
}
if (!empty($newCategoryIds)) {
$this->categories()->attach(array_values($newCategoryIds));
}
if (!isset($data['post_keywords'])) {
$keywords = [];
} elseif (is_string($data['post_keywords'])) {
//加入标签
$data['post_keywords'] = str_replace(',', ',', $data['post_keywords']);
$keywords = explode(',', $data['post_keywords']);
}
$this->addTags($keywords, $data['id']);
return $this;
}
/**
* 根据文章关键字,增加标签
* @param array $keywords 文章关键字数组
* @param int $articleId 文章id
* @return void
*/
public function addTags($keywords, $articleId)
{
foreach ($keywords as $key => $value) {
$keywords[$key] = trim($value);
}
$continue = true;
$names = $this->tags()->column('name');
if (!empty($keywords) || !empty($names)) {
if (!empty($names)) {
$sameNames = array_intersect($keywords, $names);
$keywords = array_diff($keywords, $sameNames);
$shouldDeleteNames = array_diff($names, $sameNames);
if (!empty($shouldDeleteNames)) {
$tagIdNames = $this->tags()
->where('name', 'in', $shouldDeleteNames)
->column('pivot.id', 'tag_id');
$tagIds = array_keys($tagIdNames);
$tagPostIds = array_values($tagIdNames);
$tagPosts = DB::name('portal_tag_post')->where('tag_id', 'in', $tagIds)
->field('id,tag_id,post_id')
->select();
$keepTagIds = [];
foreach ($tagPosts as $key => $tagPost) {
if ($articleId != $tagPost['post_id']) {
array_push($keepTagIds, $tagPost['tag_id']);
}
}
$keepTagIds = array_unique($keepTagIds);
$shouldDeleteTagIds = array_diff($tagIds, $keepTagIds);
DB::name('PortalTag')->delete($shouldDeleteTagIds);
DB::name('PortalTagPost')->delete($tagPostIds);
}
} else {
$tagIdNames = DB::name('portal_tag')->where('name', 'in', $keywords)->column('name', 'id');
if (!empty($tagIdNames)) {
$tagIds = array_keys($tagIdNames);
$this->tags()->attach($tagIds);
$keywords = array_diff($keywords, array_values($tagIdNames));
if (empty($keywords)) {
$continue = false;
}
}
}
if ($continue) {
foreach ($keywords as $key => $value) {
if (!empty($value)) {
$this->tags()->attach(['name' => $value]);
}
}
}
}
}
/**
* 设置缩略图,图片,附件
* 懒人方法
* @param $data 表单数据
*/
public function setMoreField($data)
{
$allowField = [
'post_title','post_keywords','post_source',
'post_excerpt','post_content','thumbnail','more',
'published_time'
];
if (!empty($data['more'])) {
$data['more'] = $this->setMoreUrl($data['more']);
}
if (!empty($data['thumbnail'])) {
$data['more']['thumbnail'] = cmf_asset_relative_url($data['thumbnail']);
}
return [$data,$allowField];
}
/**
* 获取图片附件url相对地址
* 默认上传名字 *_names 地址 *_urls
* @param $annex 上传附件
* @return array
*/
public function setMoreUrl($annex)
{
$more = [];
if (!empty($annex)) {
foreach ($annex as $key => $value) {
$nameArr = $key . '_names';
$urlArr = $key . '_urls';
if (is_string($value[$nameArr]) && is_string($value[$urlArr])) {
$more[$key] = [$value[$nameArr], $value[$urlArr]];
} elseif (!empty($value[$nameArr]) && !empty($value[$urlArr])) {
$more[$key] = [];
foreach ($value[$urlArr] as $k => $url) {
$url = cmf_asset_relative_url($url);
array_push($more[$key], ['url' => $url, 'name' => $value[$nameArr][$k]]);
}
}
}
}
return $more;
}
/**
* 删除文章
* @param $ids int|array 文章id
* @param int $userId 文章所属用户id [可选]
* @return bool|int 删除结果 true 成功 false 失败 -1 文章不存在
*/
public function deleteArticle($ids, $userId)
{
$time = time();
$result = false;
$where = [];
if (!empty($userId)) {
if (is_numeric($ids)) {
$article = $this->find($ids);
if (!empty($article)) {
if ($this->isUserPost($ids, $userId) || $userId == 1) {
$where['id'] = $ids;
}
}
} else {
$ids = $this->strToArr($ids);
$articles = $this->where('id', 'in', $ids)->select();
if (!empty($articles)) {
$deleteIds = $this->isUserPosts($ids, $userId);
if (!empty($deleteIds)) {
$where['id'] = ['in', $deleteIds];
}
}
}
} else {
if (is_numeric($ids)) {
$article = $this->find($ids);
if (!empty($article)) {
$where['id'] = $ids;
}
} else {
$ids = $this->strToArr($ids);
$articles = $this->where('id', 'in', $ids)->select();
if (!empty($articles)) {
$where['id'] = ['in', $ids];
}
}
}
if (empty($article) && empty($articles)) {
return -1;
}
if (!empty($where)) {
$result = $this->useGlobalScope(false)
->where($where)
->setField('delete_time', $time);
}
if ($result) {
$data = [
'create_time' => $time,
'table_name' => 'portal_post'
];
if (!empty($article)) {
$data['name'] = $article['post_title'];
$article->recycleBin()->save($data);
}
if (!empty($articles)) {
foreach ($articles as $article) {
$data['name'] = $article['post_title'];
$article->recycleBin()->save($data);
}
}
}
return $result;
}
/**
* 判断文章所属用户是否为当前用户,超级管理员除外
* @params int $id 文章id
* @param int $userId 当前用户id
* @return boolean 是 true , 否 false
*/
public function isUserPost($id, $userId)
{
$postUserId = $this->useGlobalScope(false)
->getFieldById($id, 'user_id');
if ($postUserId != $userId || $userId != 1) {
return false;
} else {
return true;
}
}
/**
* 过滤属于当前用户的文章,超级管理员除外
* @params array $ids 文章id的数组
* @param int $userId 当前用户id
* @return array 属于当前用户的文章id
*/
public function isUserPosts($ids, $userId)
{
$postIds = $this->useGlobalScope(false)
->where('user_id', $userId)
->where('id', 'in', $ids)
->column('id');
return array_intersect($ids, $postIds);
}
}
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
namespace api\portal\model;
use api\common\model\CommonModel;
class PortalCategoryModel extends CommonModel
{
//类型转换
protected $type = [
'more' => 'array',
];
//可查询字段
protected $visible = [
'id', 'name', 'description', 'post_count',
'seo_title', 'seo_keywords', 'seo_description',
'more', 'PostIds', 'articles'
];
//模型关联方法
protected $relationFilter = ['articles'];
/**
* 基础查询
*/
protected function base($query)
{
$query->alias('portal_category')->where('delete_time', 0)
->where('portal_category.status', 1);
}
/**
* more 自动转化
* @param $value
* @return array
*/
public function getMoreAttr($value)
{
$more = json_decode($value, true);
if (!empty($more['thumbnail'])) {
$more['thumbnail'] = cmf_get_image_url($more['thumbnail']);
}
if (!empty($more['photos'])) {
foreach ($more['photos'] as $key => $value) {
$more['photos'][$key]['url'] = cmf_get_image_url($value['url']);
}
}
return $more;
}
/**
* 关联文章表
* @return $this
*/
public function articles()
{
return $this->belongsToMany('PortalPostModel', 'portal_category_post', 'post_id', 'category_id');
}
/**
* [PostIds 关联]
* @Author: wuwu<15093565100@163.com>
* @DateTime: 2017-07-17T15:20:31+0800
* @since: 1.0
*/
public function PostIds()
{
return self::hasMany('PortalCategoryPostModel', 'category_id', 'id');
}
/**
* [categoryPostIds 此类文章id数组]
* @Author: wuwu<15093565100@163.com>
* @DateTime: 2017-07-17T15:21:08+0800
* @since: 1.0
* @param [type] $category_id [分类ID]
* @return [type] [文章id数组]
*/
public static function categoryPostIds($category_id)
{
$ids = [];
$post_ids = self::relation('PostIds')->field(true)->where('id', $category_id)->find();
foreach ($post_ids['PostIds'] as $key => $id) {
$ids[] = $id['post_id'];
}
$post_ids['PostIds'] = $ids;
return $post_ids;
}
}
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
namespace api\portal\model;
use think\Model;
class PortalCategoryPostModel extends Model
{
/**
* 基础查询
*/
protected function base($query)
{
$query->where('status', 1);
}
}
\ No newline at end of file
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
namespace api\portal\model;
use think\Db;
use api\common\model\CommonModel;
class PortalPostModel extends CommonModel
{
//可查询字段
protected $visible = [
'id', 'articles.id', 'user_id', 'post_id', 'post_type', 'comment_status',
'is_top', 'recommended', 'post_hits', 'post_like', 'comment_count',
'create_time', 'update_time', 'published_time', 'post_title', 'post_keywords',
'post_excerpt', 'post_source', 'post_content', 'more', 'user_nickname',
'user', 'category_id'
];
//设置只读字段
protected $readonly = ['user_id'];
// 开启自动写入时间戳字段
protected $autoWriteTimestamp = true;
//类型转换
protected $type = [
'more' => 'array',
];
//模型关联方法
protected $relationFilter = ['user', 'categories'];
/**
* 基础查询
*/
protected function base($query)
{
$query->where('delete_time', 0)
->where('post_status', 1)
->whereTime('published_time', 'between', [1, time()]);
}
/**
* 关联 user表
* @return $this
*/
public function user()
{
return $this->belongsTo('api\portal\model\UserModel', 'user_id');
}
/**
* 关联 user表
* @return $this
*/
public function articleUser()
{
return $this->belongsTo('api\portal\model\UserModel', 'user_id')->field('id,user_nickname');
}
/**
* 关联分类表
* @return $this
*/
public function categories()
{
return $this->belongsToMany('api\portal\model\PortalCategoryModel', 'portal_category_post', 'category_id', 'post_id');
}
/**
* 关联标签表
* @return $this
*/
public function tags()
{
return $this->belongsToMany('api\portal\model\PortalTagModel', 'portal_tag_post', 'tag_id', 'post_id');
}
/**
* 关联 回收站 表
*/
public function recycleBin()
{
return $this->hasOne('api\portal\model\RecycleBinModel', 'object_id');
}
/**
* published_time 自动转化
* @param $value
* @return string
*/
public function getPublishedTimeAttr($value)
{
return date('Y-m-d H:i:s', $value);
}
/**
* published_time 自动转化
* @param $value
* @return int
*/
public function setPublishedTimeAttr($value)
{
if (is_numeric($value)) {
return $value;
}
return strtotime($value);
}
/**
* post_content 自动转化
* @param $value
* @return string
*/
public function getPostContentAttr($value)
{
return cmf_replace_content_file_url(htmlspecialchars_decode($value));
}
/**
* post_content 自动转化
* @param $value
* @return string
*/
public function setPostContentAttr($value)
{
return htmlspecialchars(cmf_replace_content_file_url(htmlspecialchars_decode($value), true));
}
/**
* more 自动转化
* @param $value
* @return array
*/
public function getMoreAttr($value)
{
$more = json_decode($value, true);
if (!empty($more['thumbnail'])) {
$more['thumbnail'] = cmf_get_image_url($more['thumbnail']);
}
if (!empty($more['photos'])) {
foreach ($more['photos'] as $key => $value) {
$more['photos'][$key]['url'] = cmf_get_image_url($value['url']);
}
}
if (!empty($more['files'])) {
foreach ($more['files'] as $key => $value) {
$more['files'][$key]['url'] = cmf_get_image_url($value['url']);
}
}
return $more;
}
/**
* 获取用户文章
*/
public function getUserArticles($userId, $params)
{
$where = [
'post_type' => 1,
'user_id' => $userId
];
$params['where'] = $where;
return $this->getDatas($params);;
}
/**
* 会员添加文章
* @param array $data 文章数据
* @return $this
*/
public function addArticle($data)
{
if (!empty($data['more'])) {
$data['more'] = $this->setMoreUrl($data['more']);
}
if (!empty($data['thumbnail'])) {
$data['more']['thumbnail'] = cmf_asset_relative_url($data['thumbnail']);
}
$this->allowField(true)->data($data, true)->isUpdate(false)->save();
$categories = $this->strToArr($data['categories']);
$this->categories()->attach($categories);
if (!empty($data['post_keywords']) && is_string($data['post_keywords'])) {
//加入标签
$data['post_keywords'] = str_replace(',', ',', $data['post_keywords']);
$keywords = explode(',', $data['post_keywords']);
$this->addTags($keywords, $this->id);
}
return $this;
}
/**
* 会员文章编辑
* @param array $data 文章数据
* @param int $id 文章id
* @param int $userId 文章所属用户id [可选]
* @return boolean 成功 true 失败 false
*/
public function editArticle($data, $id, $userId = '')
{
if (!empty($userId)) {
$isBelong = $this->isuserPost($id, $userId);
if ($isBelong === false) {
return $isBelong;
}
}
if (!empty($data['more'])) {
$data['more'] = $this->setMoreUrl($data['more']);
}
if (!empty($data['thumbnail'])) {
$data['more']['thumbnail'] = cmf_asset_relative_url($data['thumbnail']);
}
$data['id'] = $id;
$data['post_status'] = empty($data['post_status']) ? 0 : 1;
$data['is_top'] = empty($data['is_top']) ? 0 : 1;
$data['recommended'] = empty($data['recommended']) ? 0 : 1;
$this->allowField(true)->data($data, true)->isUpdate(true)->save();
$categories = $this->strToArr($data['categories']);
$oldCategoryIds = $this->categories()->column('category_id');
$sameCategoryIds = array_intersect($categories, $oldCategoryIds);
$needDeleteCategoryIds = array_diff($oldCategoryIds, $sameCategoryIds);
$newCategoryIds = array_diff($categories, $sameCategoryIds);
if (!empty($needDeleteCategoryIds)) {
$this->categories()->detach($needDeleteCategoryIds);
}
if (!empty($newCategoryIds)) {
$this->categories()->attach(array_values($newCategoryIds));
}
$keywords = [];
if (!empty($data['post_keywords'])) {
if (is_string($data['post_keywords'])) {
//加入标签
$data['post_keywords'] = str_replace(',', ',', $data['post_keywords']);
$keywords = explode(',', $data['post_keywords']);
}
}
$this->addTags($keywords, $data['id']);
return $this;
}
/**
* 根据文章关键字,增加标签
* @param array $keywords 文章关键字数组
* @param int $articleId 文章id
* @return void
*/
public function addTags($keywords, $articleId)
{
foreach ($keywords as $key => $value) {
$keywords[$key] = trim($value);
}
$continue = true;
$names = $this->tags()->column('name');
if (!empty($keywords) || !empty($names)) {
if (!empty($names)) {
$sameNames = array_intersect($keywords, $names);
$keywords = array_diff($keywords, $sameNames);
$shouldDeleteNames = array_diff($names, $sameNames);
if (!empty($shouldDeleteNames)) {
$tagIdNames = $this->tags()
->where('name', 'in', $shouldDeleteNames)
->column('pivot.id', 'tag_id');
$tagIds = array_keys($tagIdNames);
$tagPostIds = array_values($tagIdNames);
$tagPosts = DB::name('portal_tag_post')->where('tag_id', 'in', $tagIds)
->field('id,tag_id,post_id')
->select();
$keepTagIds = [];
foreach ($tagPosts as $key => $tagPost) {
if ($articleId != $tagPost['post_id']) {
array_push($keepTagIds, $tagPost['tag_id']);
}
}
$keepTagIds = array_unique($keepTagIds);
$shouldDeleteTagIds = array_diff($tagIds, $keepTagIds);
DB::name('PortalTag')->delete($shouldDeleteTagIds);
DB::name('PortalTagPost')->delete($tagPostIds);
}
} else {
$tagIdNames = DB::name('portal_tag')->where('name', 'in', $keywords)->column('name', 'id');
if (!empty($tagIdNames)) {
$tagIds = array_keys($tagIdNames);
$this->tags()->attach($tagIds);
$keywords = array_diff($keywords, array_values($tagIdNames));
if (empty($keywords)) {
$continue = false;
}
}
}
if ($continue) {
foreach ($keywords as $key => $value) {
if (!empty($value)) {
$this->tags()->attach(['name' => $value]);
}
}
}
}
}
/**
* 获取图片附件url相对地址
* 默认上传名字 *_names 地址 *_urls
* @param $annex 上传附件
* @return array
*/
public function setMoreUrl($annex)
{
$more = [];
if (!empty($annex)) {
foreach ($annex as $key => $value) {
$nameArr = $key . '_names';
$urlArr = $key . '_urls';
if (is_string($value[$nameArr]) && is_string($value[$urlArr])) {
$more[$key] = [$value[$nameArr], $value[$urlArr]];
} elseif (!empty($value[$nameArr]) && !empty($value[$urlArr])) {
$more[$key] = [];
foreach ($value[$urlArr] as $k => $url) {
$url = cmf_asset_relative_url($url);
array_push($more[$key], ['url' => $url, 'name' => $value[$nameArr][$k]]);
}
}
}
}
return $more;
}
/**
* 删除文章
* @param $ids int|array 文章id
* @param int $userId 文章所属用户id [可选]
* @return bool|int 删除结果 true 成功 false 失败 -1 文章不存在
*/
public function deleteArticle($ids, $userId = '')
{
$time = time();
$result = false;
$where = [];
if (!empty($userId)) {
if (is_numeric($ids)) {
$article = $this->find($ids);
if (!empty($article)) {
if ($this->isUserPost($ids, $userId) || $userId == 1) {
$where['id'] = $ids;
}
}
} else {
$ids = $this->strToArr($ids);
$articles = $this->where('id', 'in', $ids)->select();
if (!empty($articles)) {
$deleteIds = $this->isUserPosts($ids, $userId);
if (!empty($deleteIds)) {
$where['id'] = ['in', $deleteIds];
}
}
}
} else {
if (is_numeric($ids)) {
$article = $this->find($ids);
if (!empty($article)) {
$where['id'] = $ids;
}
} else {
$ids = $this->strToArr($ids);
$articles = $this->where('id', 'in', $ids)->select();
if (!empty($articles)) {
$where['id'] = ['in', $ids];
}
}
}
if (empty($article) && empty($articles)) {
return -1;
}
if (!empty($where)) {
$result = $this->useGlobalScope(false)
->where($where)
->setField('delete_time', $time);
}
if ($result) {
$data = [
'create_time' => $time,
'table_name' => 'portal_post'
];
if (!empty($article)) {
$data['name'] = $article['post_title'];
$article->recycleBin()->save($data);
}
if (!empty($articles)) {
foreach ($articles as $article) {
$data['name'] = $article['post_title'];
$article->recycleBin()->save($data);
}
}
}
return $result;
}
/**
* 判断文章所属用户是否为当前用户,超级管理员除外
* @params int $id 文章id
* @param int $userId 当前用户id
* @return boolean 是 true , 否 false
*/
public function isUserPost($id, $userId)
{
$postUserId = $this->useGlobalScope(false)
->getFieldById($id, 'user_id');
if ($postUserId != $userId || $userId != 1) {
return false;
} else {
return true;
}
}
/**
* 过滤属于当前用户的文章,超级管理员除外
* @params array $ids 文章id的数组
* @param int $userId 当前用户id
* @return array 属于当前用户的文章id
*/
public function isUserPosts($ids, $userId)
{
$postIds = $this->useGlobalScope(false)
->where('user_id', $userId)
->where('id', 'in', $ids)
->column('id');
return array_intersect($ids, $postIds);
}
}
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
namespace api\portal\model;
use api\common\model\CommonModel;
class PortalTagModel extends CommonModel
{
//可查询字段
protected $visible = [
'id','articles.id','recommended', 'post_count', 'name','articles'
];
//模型关联方法
protected $relationFilter = ['articles'];
/**
* 基础查询
*/
protected function base($query)
{
$query->alias('post_tag')->where('post_tag.status', 1);
}
/**
* 关联 文章表
* @return $this
*/
public function articles()
{
return $this->belongsToMany('PortalPostModel','portal_tag_post','post_id','tag_id');
}
}
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
namespace api\portal\model;
use think\Model;
class PortalTagPostModel extends Model
{
/**
* 获取指定id相关的文章id数组
* @param $post_id 文章id
* @return array 相关的文章id
*/
function getRelationPostIds($post_id)
{
$tagIds = $this->where('post_id', $post_id)
->column('tag_id');
$postIds = $this->whereIn('tag_id', $tagIds)
->column('post_id');
return array_unique($postIds);
}
}
\ No newline at end of file
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
namespace api\portal\model;
use think\Model;
class RecycleBinModel extends Model
{
}
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
namespace api\portal\model;
use api\common\model\CommonModel;
class UserModel extends CommonModel
{
//可查询字段
// protected $visible = [
// 'articles.id', 'user_nickname', 'avatar', 'signature','user'
// ];
//模型关联方法
protected $relationFilter = ['user'];
/**
* 基础查询
*/
protected function base($query)
{
$query->where('cmf_user.user_status', 1);
}
/**
* more 自动转化
* @param $value
* @return array
*/
public function getAvatarAttr($value)
{
$value = !empty($value) ? cmf_get_image_url($value) : $value;
return $value;
}
/**
* 关联 user表
* @return $this
*/
public function user()
{
return $this->belongsTo('UserModel', 'user_id')->setEagerlyType(1);
}
}
... ...
<?php
use think\Route;
Route::resource('portal/categories', 'portal/Categories');
Route::resource('portal/articles', 'portal/Articles');
Route::resource('portal/pages', 'portal/Pages');
Route::resource('portal/userArticles', 'portal/UserArticles');
Route::get('portal/search','portal/Articles/search');
Route::get('portal/articles/my', 'portal/Articles/my');
Route::get('portal/tags/:id/articles', 'portal/Tags/articles');
Route::get('portal/tags', 'portal/Tags/index');
Route::post('portal/userArticles/deletes','portal/UserArticles/deletes');
\ No newline at end of file
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
namespace api\portal\service;
use api\portal\model\PortalPostModel as PortalPost;
use api\portal\model\PortalCategoryModel as PortalCategory;
class PortalPostModel extends PortalPost
{
protected $name = "portal_post";
/**
* [recommendedList 推荐列表]
* @Author: wuwu<15093565100@163.com>
* @DateTime: 2017-07-17T11:06:47+0800
* @since: 1.0
* @param integer $next_id [最后索引值]
* @param integer $num [一页多少条 默认10]
* @return [type] [数据]
*/
public static function recommendedList($next_id = 0, $num = 10)
{
$limit = "{$next_id},{$num}";
$field = 'id,recommended,user_id,post_like,post_hits,comment_count,create_time,update_time,published_time,post_title,post_excerpt,more';
$list = self::with('user')->field($field)->where('recommended', 1)->order('published_time DESC')->limit($limit)->select();
return $list;
}
/**
* [categoryPostList 分类文章列表]
* @Author: wuwu<15093565100@163.com>
* @DateTime: 2017-07-17T15:16:26+0800
* @since: 1.0
* @param [type] $category_id [分类ID]
* @param integer $next_id [limit索引]
* @param integer $num [limit每页数量]
* @return [type] [description]
*/
public static function categoryPostList($category_id, $next_id = 0, $num = 10)
{
$limit = "{$next_id},{$num}";
$Postlist = PortalCategory::categoryPostIds($category_id);
$field = 'id,recommended,user_id,post_like,post_hits,comment_count,create_time,update_time,published_time,post_title,post_excerpt,more';
$list = self::with('user')->field($field)->whereIn('id', $Postlist['PostIds'])->order('published_time DESC')->limit($limit)->select()->toJson();
return $list;
}
}
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
namespace api\portal\validate;
use think\Validate;
class ArticlesValidate extends Validate
{
protected $rule = [
'post_title' => 'require',
'post_content' => 'require',
'categories' => 'require'
];
protected $message = [
'post_title.require' => '文章标题不能为空',
'post_content.require' => '内容不能为空',
'categories.require' => '文章分类不能为空'
];
protected $scene = [
'article' => [ 'post_title' , 'post_content' , 'categories' ],
'page' => ['post_title']
];
}
\ No newline at end of file
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
return [
// 应用调试模式
'app_debug' => false,
// 应用Trace
'app_trace' => false,
];
\ No newline at end of file
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
$apps = cmf_scan_dir(APP_PATH . '*', GLOB_ONLYDIR);
foreach ($apps as $app) {
$routeFile = APP_PATH . $app . '/route.php';
if (file_exists($routeFile)) {
include_once $routeFile;
}
}
return [
];
\ No newline at end of file
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
// 应用行为扩展定义文件
return [
// 应用初始化
'app_init' => [
'cmf\\behavior\\InitHookBehavior',
],
// 应用开始
'app_begin' => [
'cmf\\behavior\\LangBehavior',
],
// 模块初始化
'module_init' => [],
// 操作开始执行
'action_begin' => [],
// 视图内容过滤
'view_filter' => [],
// 日志写入
'log_write' => [],
// 应用结束
'app_end' => [],
];
... ...
<?php
// +----------------------------------------------------------------------
// | 文件说明:评论
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
// | Date: 2017-7-26
// +----------------------------------------------------------------------
namespace api\user\controller;
use api\user\model\CommentModel as Comment;
use api\user\model\UserModel as User;
use cmf\controller\RestUserBaseController;
class CommentsController extends RestUserBaseController
{
/**
* [getUserComments 获取用户评论]
* @Author: wuwu<15093565100@163.com>
* @DateTime: 2017-05-25T20:48:53+0800
* @since: 1.0
* @return [array_json] [获取Comment]
*/
public function getUserComments()
{
$input = $this->request->param();
$comment = new Comment();
$map['where']['user_id'] = $this->getUserId();
$map['order'] = '-create_time';
$map['relation'] = 'user,to_user';
if (!empty($input['page'])) {
$map['page'] = $input['page'];
}
//处理不同的情况
$data = $comment->getDatas($map);
$this->success('请求成功', $data);
}
/**
* [getComments 获取评论]
* @Author: wuwu<15093565100@163.com>
* @DateTime: 2017-05-25T20:48:53+0800
* @since: 1.0
* @return [array_json] [获取Comment]
*/
public function getComments()
{
$input = $this->request->param();
$id = $this->request->has('object_id') ? $input['object_id'] : $this->error('id参数不存在');
$table = $this->request->has('table_name') ? $input['table_name'] : $this->error('table参数不存在');
$comment = new Comment();
$map['where'] = [
'object_id' => $id,
'table_name' => $table
];
$map['relation'] = 'user,to_user';
if (!empty($input['page'])) {
$map['page'] = $input['page'];
}
$data = $comment->getDatas($map);
//数据是否存在
if ($data->isEmpty()) {
$this->error('评论数据为空');
} else {
$this->success('评论获取成功!', $data);
}
}
/**
* [delComments 删除评论]
* @Author: wuwu<15093565100@163.com>
* @DateTime: 2017-08-11T22:08:56+0800
* @since: 1.0
* @return
*/
public function delComments()
{
$input = $this->request->param();
$id = $this->request->has('id') ? intval($input['id']) : $this->error('id参数不存在');
$userId = $this->getUserId();
Comment::destroy(['id' => $id, 'user_id' => $userId]);
$this->success('删除成功');
}
/**
* [setComments 添加评论]
* @Author: wuwu<15093565100@163.com>
* @DateTime: 2017-08-16T01:07:44+0800
* @since: 1.0
*/
public function setComments()
{
$data = $this->_setComments();
if ($res = Comment::setComment($data)) {
$this->success('评论成功', $res);
} else {
$this->error('评论失败');
}
}
/**
* [_setComments 评论数据组织]
* @Author: wuwu<15093565100@163.com>
* @DateTime: 2017-08-16T01:00:02+0800
* @since: 1.0
*/
protected function _setComments()
{
$input = $this->request->param();
$data['object_id'] = $this->request->has('object_id') ? $input['object_id'] : $this->error('object_id参数不存在');
$data['table_name'] = $this->request->has('table_name') ? $input['table_name'] : $this->error('table_name参数不存在');
$data['url'] = $this->request->has('url') ? $input['url'] : $this->error('url参数不存在');
$data['content'] = $this->request->has('content') ? $input['content'] : $this->error('内容不为空');
$data['parent_id'] = $this->request->has('parent_id') ? $input['parent_id'] : 0;
$result = $this->validate($data,
[
'object_id' => 'require|number',
'content' => 'require',
]);
if (true !== $result) {
// 验证失败 输出错误信息
$this->error($result);
}
$data['delete_time'] = 0;
$data['create_time'] = time();
if ($data['parent_id']) {
$res = Comment::field('parent_id', 'path', 'user_id')->find($data['parent_id']);
if ($res) {
$data['path'] = $res['path'] . $data['parent_id'] . ',';
$data['to_user_id'] = $res['user_id'];
} else {
$this->error('回复的评论不存在');
}
} else {
$data['path'] = '0,';
}
$data['user_id'] = $this->getUserId();
$userData = User::field(true)->find($data['user_id']);
if (!$userData) {
$this->error('评论用户不存在');
}
$data['full_name'] = $userData['user_nickname'];
$data['email'] = $userData['user_email'];
return $data;
}
}
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
namespace api\user\controller;
use api\user\model\UserFavoriteModel;
use cmf\controller\RestUserBaseController;
class FavoritesController extends RestUserBaseController
{
protected $userFavoriteModel;
public function __construct(UserFavoriteModel $userFavoriteModel)
{
parent::__construct();
$this->userFavoriteModel = $userFavoriteModel;
}
/**
* 显示收藏列表
*/
public function getFavorites()
{
$userId = $this->getUserId();
$param = $this->request->param();
$param['where'] = [
'user_id' => $userId
];
$param['order'] = '-create_time';
$favoriteData = $this->userFavoriteModel->getDatas($param);
$this->success('请求成功', $favoriteData);
}
/**
* [setFavorites 添加收藏]
* @Author: wuwu<15093565100@163.com>
* @DateTime: 2017-08-03T09:03:40+0800
* @since: 1.0
*/
public function setFavorites()
{
$input = $this->request->param();
//组装数据
$data = $this->_FavoritesObject($input['title'], $input['url'], $input['description'], $input['table_name'], $input['object_id']);
if (!$data) {
$this->error('收藏失败');
}
if ($this->userFavoriteModel->where('object_id', $input['object_id'])->where('table_name', $input['table'])->count() > 0) {
$this->error('已收藏');
}
if ($this->userFavoriteModel->setFavorite($data)) {
$this->success('收藏成功');
} else {
$this->error('收藏失败');
}
}
/**
* [_FavoritesObject 收藏数据组装]
* @Author: wuwu<15093565100@163.com>
* @DateTime: 2017-08-03T09:39:06+0800
* @since: 1.0
* @return [type] [description]
*/
protected function _FavoritesObject($title, $url, $description, $table_name, $object_id)
{
$data['user_id'] = $this->getUserId();
$data['create_time'] = THINK_START_TIME;
if (empty($title)) {
return false;
} else if (empty($url)) {
return false;
} elseif (empty($description)) {
return false;
} elseif (empty($table_name)) {
return false;
} elseif (empty($object_id)) {
return false;
}
$data['title'] = $title;
$data['url'] = htmlspecialchars_decode($url);
$data['description'] = $description;
$data['table_name'] = $table_name;
$data['object_id'] = $object_id;
return $data;
}
/**
* [unsetFavorites 取消收藏]
* @Author: wuwu<15093565100@163.com>
* @DateTime: 2017-08-03T09:04:31+0800
* @since: 1.0
* @return [type] [description]
*/
public function unsetFavorites()
{
$id = $this->request->param('id', 0, 'intval');
$userId = $this->getUserId();
$count = $this->userFavoriteModel->where(['id' => $id, 'user_id' => $userId])->count();
if ($count == 0) {
$this->error('收藏不存在,无法取消');
}
$this->userFavoriteModel->where(['id' => $id])->delete();
$this->success('取消成功');
}
}
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
namespace api\user\controller;
use cmf\controller\RestUserBaseController;
use think\Db;
use think\Validate;
class ProfileController extends RestUserBaseController
{
// 用户密码修改
public function changePassword()
{
$validate = new Validate([
'old_password' => 'require',
'password' => 'require',
'confirm_password' => 'require|confirm:password'
]);
$validate->message([
'old_password.require' => '请输入您的旧密码!',
'password.require' => '请输入您的新密码!',
'confirm_password.require' => '请输入确认密码!',
'confirm_password.confirm' => '两次输入的密码不一致!'
]);
$data = $this->request->param();
if (!$validate->check($data)) {
$this->error($validate->getError());
}
$userId = $this->getUserId();
$userPassword = Db::name("user")->where('id', $userId)->value('user_pass');
if (!cmf_compare_password($data['old_password'], $userPassword)) {
$this->error('旧密码不正确!');
}
Db::name("user")->where('id', $userId)->update(['user_pass' => cmf_password($data['password'])]);
$this->success("密码修改成功!");
}
// 用户绑定邮箱
public function bindingEmail()
{
$validate = new Validate([
'email' => 'require|email|unique:user,user_email',
'verification_code' => 'require'
]);
$validate->message([
'email.require' => '请输入您的邮箱!',
'email.email' => '请输入正确的邮箱格式!',
'email.unique' => '正确账号已存在!',
'verification_code.require' => '请输入数字验证码!'
]);
$data = $this->request->param();
if (!$validate->check($data)) {
$this->error($validate->getError());
}
$userId = $this->getUserId();
$userEmail = Db::name("user")->where('id', $userId)->value('user_email');
if (!empty($userEmail)) {
$this->error("您已经绑定邮箱!");
}
$errMsg = cmf_check_verification_code($data['email'], $data['verification_code']);
if (!empty($errMsg)) {
$this->error($errMsg);
}
Db::name("user")->where('id', $userId)->update(['user_email' => $data['email']]);
$this->success("绑定成功!");
}
// 用户绑定手机号
public function bindingMobile()
{
$validate = new Validate([
'mobile' => 'require|unique:user,mobile',
'verification_code' => 'require'
]);
$validate->message([
'mobile.require' => '请输入您的手机号!',
'mobile.unique' => '手机号已经存在!',
'verification_code.require' => '请输入数字验证码!'
]);
$data = $this->request->param();
if (!$validate->check($data)) {
$this->error($validate->getError());
}
if (!preg_match('/(^(13\d|15[^4\D]|17[13678]|18\d)\d{8}|170[^346\D]\d{7})$/', $data['mobile'])) {
$this->error("请输入正确的手机格式!");
}
$userId = $this->getUserId();
$mobile = Db::name("user")->where('id', $userId)->value('mobile');
if (!empty($mobile)) {
$this->error("您已经绑定手机!");
}
$errMsg = cmf_check_verification_code($data['mobile'], $data['verification_code']);
if (!empty($errMsg)) {
$this->error($errMsg);
}
Db::name("user")->where('id', $userId)->update(['mobile' => $data['mobile']]);
$this->success("绑定成功!");
}
/**
* 用户基本信息获取及修改
* @param 请求为GET 获取信息
* @param [string] $[field] [要获取的一个或多个字段名] 可选
* @return 带参数,返回某个或多个字段信息。不带参数,返回所有信息
* @param 请求为POST 修改信息
*/
public function userInfo($field = '')
{
//判断请求为GET,获取信息
if ($this->request->isGet()) {
$userId = $this->getUserId();
$fieldStr = 'user_type,user_login,mobile,user_email,user_nickname,avatar,signature,user_url,sex,birthday,score,coin,user_status,user_activation_key,create_time,last_login_time,last_login_ip';
if (empty($field)) {
$userData = Db::name("user")->field($fieldStr)->find($userId);
} else {
$fieldArr = explode(',', $fieldStr);
$postFieldArr = explode(',', $field);
$mixedField = array_intersect($fieldArr, $postFieldArr);
if (empty($mixedField)) {
$this->error('您查询的信息不存在!');
}
if (count($mixedField) > 1) {
$fieldStr = implode(',', $mixedField);
$userData = Db::name("user")->field($fieldStr)->find($userId);
} else {
$userData = Db::name("user")->where('id', $userId)->value($mixedField);
}
}
$this->success('获取成功!', $userData);
}
//判断请求为POST,修改信息
if ($this->request->isPost()) {
$userId = $this->getUserId();
$fieldStr = 'user_nickname,avatar,signature,user_url,sex,birthday';
$data = $this->request->post();
if (empty($data)) {
$this->error('修改失败,提交表单为空!');
}
if (!empty($data['birthday'])) {
$data['birthday'] = strtotime($data['birthday']);
}
$upData = Db::name("user")->where('id', $userId)->field($fieldStr)->update($data);
if ($upData !== false) {
$this->success('修改成功!');
} else {
$this->error('修改失败!');
}
}
}
}
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
namespace api\user\controller;
use think\Db;
use think\Validate;
use cmf\controller\RestBaseController;
class PublicController extends RestBaseController
{
// 用户注册
public function register()
{
$validate = new Validate([
'username' => 'require',
'password' => 'require',
'verification_code' => 'require'
]);
$validate->message([
'username.require' => '请输入手机号,邮箱!',
'password.require' => '请输入您的密码!',
'verification_code.require' => '请输入数字验证码!'
]);
$data = $this->request->param();
if (!$validate->check($data)) {
$this->error($validate->getError());
}
$user = [];
$userQuery = Db::name("user");
if (Validate::is($data['username'], 'email')) {
$user['user_email'] = $data['username'];
//$userQuery = $userQuery->where('user_email', $data['username']);
} else if (preg_match('/(^(13\d|15[^4\D]|17[13678]|18\d)\d{8}|170[^346\D]\d{7})$/', $data['username'])) {
$user['mobile'] = $data['username'];
//$userQuery = $userQuery->where('mobile', $data['username']);
} else {
$this->error("请输入正确的手机或者邮箱格式!");
}
$errMsg = cmf_check_verification_code($data['username'], $data['verification_code']);
if (!empty($errMsg)) {
$this->error($errMsg);
}
$findUserCount = $userQuery->count();
if ($findUserCount > 0) {
$this->error("此账号已存在!");
}
$user['create_time'] = time();
$user['user_status'] = 1;
$user['user_type'] = 2;
$user['user_pass'] = cmf_password($data['password']);
$result = $userQuery->insert($user);
if (empty($result)) {
$this->error("注册失败,请重试!");
}
$this->success("注册并激活成功,请登录!");
}
// 用户登录 TODO 增加最后登录信息记录,如 ip
public function login()
{
$validate = new Validate([
'username' => 'require',
'password' => 'require'
]);
$validate->message([
'username.require' => '请输入手机号,邮箱或用户名!',
'password.require' => '请输入您的密码!'
]);
$data = $this->request->param();
if (!$validate->check($data)) {
$this->error($validate->getError());
}
$userQuery = Db::name("user");
if (Validate::is($data['username'], 'email')) {
$userQuery = $userQuery->where('user_email', $data['username']);
} else if (preg_match('/(^(13\d|15[^4\D]|17[13678]|18\d)\d{8}|170[^346\D]\d{7})$/', $data['username'])) {
$userQuery = $userQuery->where('mobile', $data['username']);
} else {
$userQuery = $userQuery->where('user_login', $data['username']);
}
$findUser = $userQuery->find();
if (empty($findUser)) {
$this->error("用户不存在!");
} else {
switch ($findUser['user_status']) {
case 0:
$this->error('您已被拉黑!');
case 2:
$this->error('账户还没有验证成功!');
}
if (!cmf_compare_password($data['password'], $findUser['user_pass'])) {
$this->error("密码不正确!");
}
}
$allowedDeviceTypes = ['mobile', 'android', 'iphone', 'ipad', 'web', 'pc', 'mac'];
if (empty($data['device_type']) || !in_array($data['device_type'], $allowedDeviceTypes)) {
$this->error("请求错误,未知设备!");
}
$userTokenQuery = Db::name("user_token")
->where('user_id', $findUser['id'])
->where('device_type', $data['device_type']);
$findUserToken = $userTokenQuery->find();
$currentTime = time();
$expireTime = $currentTime + 24 * 3600 * 180;
$token = md5(uniqid()) . md5(uniqid());
if (empty($findUserToken)) {
$result = $userTokenQuery->insert([
'token' => $token,
'user_id' => $findUser['id'],
'expire_time' => $expireTime,
'create_time' => $currentTime,
'device_type' => $data['device_type']
]);
} else {
$result = $userTokenQuery
->where('user_id', $findUser['id'])
->where('device_type', $data['device_type'])
->update([
'token' => $token,
'expire_time' => $expireTime,
'create_time' => $currentTime
]);
}
if (empty($result)) {
$this->error("登录失败!");
}
$this->success("登录成功!", ['token' => $token]);
}
// 用户退出
public function logout()
{
$userId = $this->getUserId();
Db::name('user_token')->where([
'token' => $this->token,
'user_id' => $userId,
'device_type' => $this->deviceType
])->update(['token' => '']);
$this->success("退出成功!");
}
// 用户密码重置
public function passwordReset()
{
$validate = new Validate([
'username' => 'require',
'password' => 'require',
'verification_code' => 'require'
]);
$validate->message([
'username.require' => '请输入手机号,邮箱!',
'password.require' => '请输入您的密码!',
'verification_code.require' => '请输入数字验证码!'
]);
$data = $this->request->param();
if (!$validate->check($data)) {
$this->error($validate->getError());
}
$userWhere = [];
if (Validate::is($data['username'], 'email')) {
$userWhere['user_email'] = $data['username'];
} else if (preg_match('/(^(13\d|15[^4\D]|17[13678]|18\d)\d{8}|170[^346\D]\d{7})$/', $data['username'])) {
$userWhere['mobile'] = $data['username'];
} else {
$this->error("请输入正确的手机或者邮箱格式!");
}
$errMsg = cmf_check_verification_code($data['username'], $data['verification_code']);
if (!empty($errMsg)) {
$this->error($errMsg);
}
$userPass = cmf_password($data['password']);
Db::name("user")->where($userWhere)->update(['user_pass' => $userPass]);
$this->success("密码重置成功,请使用新密码登录!");
}
}
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
namespace api\user\controller;
use cmf\controller\RestUserBaseController;
use think\Db;
class UploadController extends RestUserBaseController
{
// 用户密码修改
public function one()
{
$file = $this->request->file('file');
// 移动到框架应用根目录/public/upload/ 目录下
$info = $file->validate([
/*'size' => 15678,*/
'ext' => 'jpg,png,gif'
]);
$fileMd5 = $info->md5();
$fileSha1 = $info->sha1();
$findFile = Db::name("asset")->where('file_md5', $fileMd5)->where('file_sha1', $fileSha1)->find();
if (!empty($findFile)) {
$this->success("上传成功!", ['url' => $findFile['file_path'], 'filename' => $findFile['filename']]);
}
$info = $info->move(ROOT_PATH . 'public' . DS . 'upload');
if ($info) {
$saveName = $info->getSaveName();
$originalName = $info->getInfo('name');//name,type,size
$fileSize = $info->getInfo('size');
$suffix = $info->getExtension();
$fileKey = $fileMd5 . md5($fileSha1);
$userId = $this->getUserId();
Db::name('asset')->insert([
'user_id' => $userId,
'file_key' => $fileKey,
'filename' => $originalName,
'file_size' => $fileSize,
'file_path' => $saveName,
'file_md5' => $fileMd5,
'file_sha1' => $fileSha1,
'create_time' => time(),
'suffix' => $suffix
]);
$this->success("上传成功!", ['url' => $saveName, 'filename' => $originalName]);
} else {
// 上传失败获取错误信息
$this->error($file->getError());
}
}
}
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
namespace api\user\controller;
use cmf\controller\RestBaseController;
use think\Validate;
use think\View;
class VerificationCodeController extends RestBaseController
{
public function send()
{
$validate = new Validate([
'username' => 'require',
]);
$validate->message([
'username.require' => '请输入手机号或邮箱!',
]);
$data = $this->request->param();
if (!$validate->check($data)) {
$this->error($validate->getError());
}
$accountType = '';
if (Validate::is($data['username'], 'email')) {
$accountType = 'email';
} else if (preg_match('/(^(13\d|15[^4\D]|17[13678]|18\d)\d{8}|170[^346\D]\d{7})$/', $data['username'])) {
$accountType = 'mobile';
} else {
$this->error("请输入正确的手机或者邮箱格式!");
}
//TODO 限制 每个ip 的发送次数
$code = cmf_get_verification_code($data['username']);
if (empty($code)) {
$this->error("验证码发送过多,请明天再试!");
}
if ($accountType == 'email') {
$emailTemplate = cmf_get_option('email_template_verification_code');
$user = cmf_get_current_user();
$username = empty($user['user_nickname']) ? $user['user_login'] : $user['user_nickname'];
$message = htmlspecialchars_decode($emailTemplate['template']);
$view = new View();
$message = $view->display($message, ['code' => $code, 'username' => $username]);
$subject = empty($emailTemplate['subject']) ? 'bronet验证码' : $emailTemplate['subject'];
$result = cmf_send_email($data['username'], $subject, $message);
if (empty($result['error'])) {
cmf_verification_code_log($data['username'], $code);
$this->success("验证码已经发送成功!");
} else {
$this->error("邮箱验证码发送失败:" . $result['message']);
}
} else if ($accountType == 'mobile') {
$param = ['mobile' => $data['username'], 'code' => $code];
$result = hook_one("send_mobile_verification_code", $param);
if ($result !== false && !empty($result['error'])) {
$this->error($result['message']);
}
if ($result === false) {
$this->error('未安装验证码发送插件,请联系管理员!');
}
cmf_verification_code_log($data['username'], $code);
if (!empty($result['message'])) {
$this->success($result['message']);
} else {
$this->success('验证码已经发送成功!');
}
}
}
}
... ...
<?php
// +----------------------------------------------------------------------
// | 文件说明:评论
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
// | Date: 2017-7-29
// +----------------------------------------------------------------------
namespace api\user\model;
use api\common\model\CommonModel;
class CommentModel extends CommonModel
{
//模型关联方法
protected $relationFilter = ['user', 'to_user'];
/**
* 基础查询
*/
protected function base($query)
{
$query->where('delete_time', 0)
->where('status', 1);
}
/**
* post_content 自动转化
* @param $value
* @return string
*/
public function getContentAttr($value)
{
return cmf_replace_content_file_url(htmlspecialchars_decode($value));
}
/**
* more 自动转化
* @param $value
* @return array
*/
public function getMoreAttr($value)
{
$more = json_decode($value, true);
if (!empty($more['thumbnail'])) {
$more['thumbnail'] = cmf_get_image_url($more['thumbnail']);
}
if (!empty($more['photos'])) {
foreach ($more['photos'] as $key => $value) {
$more['photos'][$key]['url'] = cmf_get_image_url($value['url']);
}
}
if (!empty($more['files'])) {
foreach ($more['files'] as $key => $value) {
$more['files'][$key]['url'] = cmf_get_image_url($value['url']);
}
}
return $more;
}
/**
* 关联 user表
* @return $this
*/
public function user()
{
return $this->belongsTo('UserModel', 'user_id');
}
public function toUser()
{
return $this->belongsTo('UserModel', 'to_user_id');
}
/**
* [CommentList 评论列表获取]
* @Author: wuwu<15093565100@163.com>
* @DateTime: 2017-05-25T20:52:27+0800
* @since: 1.0
*/
public function CommentList($map, $limit, $order)
{
if (empty($map)) {
return [];
}
$data = $this->with('to_user')->field(true)->where($map)->order($order)->limit($limit)->select();
return $data;
}
/**
* [setComment 添加评论]
* @Author: wuwu<15093565100@163.com>
* @DateTime: 2017-08-15T23:57:04+0800
* @since: 1.0
*/
public static function setComment($data)
{
if (!$data) {
return false;
}
if ($obj = self::create($data)) {
return $obj->id;
} else {
return false;
}
}
}
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
namespace api\user\model;
use think\Model;
class RecycleBinModel extends Model
{
}
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
namespace api\user\model;
use api\common\model\CommonModel;
class UserFavoriteModel extends CommonModel
{
/**
* [base 基础查询条件]
*/
protected function base($query)
{
$query->field('id,title,url,description,create_time');
}
/**
* 关联表
* @param [string] $table_name [关联表名]
*/
protected function unionTable($table_name)
{
return $this->hasOne($table_name . 'Model', 'object_id');
}
/**
* url 自动转化
* @param $value
* @return string
*/
public function getUrlAttr($value)
{
$url = json_decode($value,true);
if (!empty($url)) {
$url = url($url['action'], $url['param'], true, true);
} else {
$url = '';
}
return $url;
}
/**
* 获取收藏内容
* @param [array] $data [select,find查询结果]
* @return [array] [收藏对应表的内容]
*/
public function getFavorite($data)
{
if (!is_string($data[0])) {
foreach ($data as $key => $value) {
$where[$value['table_name']][] = $value['object_id'];
}
foreach ($where as $key => $value) {
$favoriteData[] = $this->unionTable($key)->select($value);
}
} else {
$favoriteData = $this->unionTable($data['table_name'])->find($data['object_id']);
}
return $favoriteData;
}
/**
* [setFavorite 设置收藏]
* @Author: wuwu<15093565100@163.com>
* @DateTime: 2017-08-03T09:16:37+0800
* @since: 1.0
*/
public function setFavorite($data)
{
//获取收藏内容信息
$Favorite = self::create($data);
return $Favorite->id;
}
/**
* [unsetFavorite 取消收藏]
* @Author: wuwu<15093565100@163.com>
* @DateTime: 2017-08-03T09:17:30+0800
* @since: 1.0
* @return [type] [description]
*/
public function unsetFavorite($id)
{
return self::destroy($id); //执行删除
}
}
... ...
<?php
// +----------------------------------------------------------------------
// | 文件说明:用户表关联model
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: wuwu <15093565100@163.com>
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Date: 2017-7-26
// +----------------------------------------------------------------------
namespace api\user\model;
use think\Model;
class UserModel extends Model
{
//
}
... ...
<?php
// +----------------------------------------------------------------------
// | 文件说明:路由
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://www.wuwuseo.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: bronet
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Date: 2017-8-11
// +----------------------------------------------------------------------
use think\Route;
Route::get([
'user/favorites/my' => 'user/favorites/getFavorites', //获取收藏列表
'user/comments/my' => 'user/comments/getUserComments', //获取我的评论列表
'user/comments' => 'user/comments/getComments', //获评论列表
]);
Route::post([
'user/articles/deletes' => 'user/Articles/deletes',
'user/favorites' => 'user/favorites/setFavorites', //添加收藏
'user/comments' => 'user/comments/setComments', //添加评论
]);
Route::delete([
'user/favorites/:id' => 'user/favorites/unsetFavorites', //删除收藏
'user/comments/:id' => 'user/comments/delComments', //删除评论
]);
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
namespace api\wxapp\controller;
use think\Db;
use cmf\controller\RestBaseController;
use wxapp\aes\WXBizDataCrypt;
use think\Validate;
class PublicController extends RestBaseController
{
// 微信小程序用户登录 TODO 增加最后登录信息记录,如 ip
public function login()
{
$validate = new Validate([
'code' => 'require',
'encrypted_data' => 'require',
'iv' => 'require',
'raw_data' => 'require',
'signature' => 'require',
]);
$validate->message([
'code.require' => '缺少参数code!',
'encrypted_data.require' => '缺少参数encrypted_data!',
'iv.require' => '缺少参数iv!',
'raw_data.require' => '缺少参数raw_data!',
'signature.require' => '缺少参数signature!',
]);
$data = $this->request->param();
if (!$validate->check($data)) {
$this->error($validate->getError());
}
//TODO 真实逻辑实现
$code = $data['code'];
$appId = '你的 appid';
$appSecret = '你的 secket';
$response = cmf_curl_get("https://api.weixin.qq.com/sns/jscode2session?appid=$appId&secret=$appSecret&js_code=$code&grant_type=authorization_code");
$response = json_decode($response, true);
if (!empty($response['errcode'])) {
$this->error('操作失败!');
}
$openid = $response['openid'];
$sessionKey = $response['session_key'];
$pc = new WXBizDataCrypt($appId, $sessionKey);
$errCode = $pc->decryptData($data['encrypted_data'], $data['iv'], $wxUserData);
if ($errCode != 0) {
$this->error('操作失败!');
}
$findThirdPartyUser = Db::name("third_party_user")
->where('openid', $openid)
->where('app_id', $appId)
->find();
$currentTime = time();
$ip = $this->request->ip(0, true);
$wxUserData['sessionKey'] = $sessionKey;
unset($wxUserData['watermark']);
if ($findThirdPartyUser) {
$token = cmf_generate_user_token($findThirdPartyUser['user_id'], 'wxapp');
$userData = [
'last_login_ip' => $ip,
'last_login_time' => $currentTime,
'login_times' => ['exp', 'login_times+1'],
'more' => json_encode($wxUserData)
];
if (isset($wxUserData['unionId'])) {
$userData['union_id'] = $wxUserData['unionId'];
}
Db::name("third_party_user")
->where('openid', $openid)
->where('app_id', $appId)
->update($userData);
} else {
//TODO 使用事务做用户注册
$userId = Db::name("user")->insertGetId([
'create_time' => $currentTime,
'user_status' => 1,
'user_type' => 2,
'sex' => $wxUserData['gender'],
'user_nickname' => $wxUserData['nickName'],
'avatar' => $wxUserData['avatarUrl'],
'last_login_ip' => $ip,
'last_login_time' => $currentTime,
]);
Db::name("third_party_user")->insert([
'openid' => $openid,
'user_id' => $userId,
'third_party' => 'wxapp',
'app_id' => $appId,
'last_login_ip' => $ip,
'union_id' => isset($wxUserData['unionId']) ? $wxUserData['unionId'] : '',
'last_login_time' => $currentTime,
'create_time' => $currentTime,
'login_times' => 1,
'status' => 1,
'more' => json_encode($wxUserData)
]);
$token = cmf_generate_user_token($userId, 'wxapp');
}
$this->success("登录成功!", ['token' => $token]);
}
}
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
namespace api\wxapp\controller;
use cmf\controller\RestBaseController;
use wxapp\aes\WXBizDataCrypt;
class UserController extends RestBaseController
{
// 获取用户信息
public function getUserInfo()
{
}
}
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
namespace app\admin\annotation;
use mindplay\annotations\Annotation;
/**
* Specifies validation of a string, requiring a minimum and/or maximum length.
*
* @usage('method'=>true, 'inherited'=>true, 'multiple'=>false)
*/
class AdminMenuAnnotation extends Annotation
{
public $remark = '';
public $icon = '';
public $name = '';
public $param = '';
public $parent = '';
public $display = false;
public $order = 10000;
public $hasView = true;
/**
* Initialize the annotation.
* @param array $properties
*/
public function initAnnotation(array $properties)
{
parent::initAnnotation($properties);
}
}
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
namespace app\admin\annotation;
use mindplay\annotations\AnnotationException;
use mindplay\annotations\Annotation;
/**
* Specifies validation of a string, requiring a minimum and/or maximum length.
*
* @usage('class'=>true, 'inherited'=>true, 'multiple'=>true)
*/
class AdminMenuRootAnnotation extends Annotation
{
/**
* @var int|null Minimum string length (or null, if no minimum)
*/
public $remark = '';
/**
* @var int|null Maximum string length (or null, if no maximum)
*/
public $icon = '';
/**
* @var int|null Minimum string length (or null, if no minimum)
*/
public $name = '';
public $action = '';
public $param = '';
public $parent = '';
public $display = false;
public $order = 10000;
/**
* Initialize the annotation.
* @param array $properties
*/
public function initAnnotation(array $properties)
{
parent::initAnnotation($properties);
}
}
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
namespace app\admin\api;
use app\admin\model\NavModel;
class NavApi
{
// 分类列表 用于模板设计
public function index($param = [])
{
$navModel = new NavModel();
$where = [];
if (!empty($param['keyword'])) {
$where['name'] = ['like', "%{$param['keyword']}%"];
}
return $navModel->where($where)->select();
}
}
\ No newline at end of file
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
namespace app\admin\api;
use app\admin\model\NavMenuModel;
class NavMenuApi
{
// 分类列表 用于模板设计
public function index($param = [])
{
$navMenuModel = new NavMenuModel();
$where = [];
if (!empty($param['keyword'])) {
$where['name'] = ['like', "%{$param['keyword']}%"];
}
if (!empty($param['id'])) {
$where['nav_id'] = $param['id'];
}
return $navMenuModel->where($where)->select();
}
}
\ No newline at end of file
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
namespace app\admin\api;
use app\admin\model\SlideModel;
class SlideApi
{
/**
* 幻灯片列表 用于模板设计
* @param array $param
* @return false|\PDOStatement|string|\think\Collection
*/
public function index($param = [])
{
$slideModel = new SlideModel();
$where = [];
if (!empty($param['keyword'])) {
$where['name'] = ['like', "%{$param['keyword']}%"];
}
//返回的数据必须是数据集或数组,item里必须包括id,name,如果想表示层级关系请加上 parent_id
return $slideModel->where($where)->select();
}
}
\ No newline at end of file
... ...
<?php
namespace app\admin\controller;
use cmf\controller\AdminBaseController;
class BakController extends AdminBaseController {
public function index(){
$type = $this->request->param('tp');
$name = $this->request->param('name');
$sql=new \org\Baksql(config('database'));
switch ($type)
{
case "backup": //备份
$ret=$sql->backup();
if($ret['code']=1){
$this->success($ret['msg']);
}else{
$this->error($ret['msg']);
}
break;
case "dowonload": //下载
$sql->downloadFile($name);
break;
case "restore": //还原
$ret= $sql->restore($name);
if($ret['code']=1){
$this->success($ret['msg']);
}else{
$this->error($ret['msg']);
}
break;
case "del": //删除
$ret= $sql->delfilename($name);
if($ret['code']=1){
$this->success($ret['msg']);
}else{
$this->error($ret['msg']);
}
break;
default: //获取备份文件列表
return $this->fetch("index",["list"=>$sql->get_filelist()]);
}
}
}
?>
\ No newline at end of file
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
namespace app\admin\controller;
use cmf\controller\AdminBaseController;
class DialogController extends AdminBaseController
{
public function _initialize()
{
}
public function map()
{
$location = $this->request->param('location');
$location = explode(',', $location);
$lng = empty($location[0]) ? 116.424966 : $location[0];
$lat = empty($location[1]) ? 39.907851 : $location[1];
$this->assign(['lng' => $lng, 'lat' => $lat]);
return $this->fetch();
}
}
\ No newline at end of file
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
namespace app\admin\controller;
use cmf\controller\AdminBaseController;
use app\admin\model\HookModel;
use app\admin\model\PluginModel;
use app\admin\model\HookPluginModel;
use think\Db;
/**
* Class HookController 钩子管理控制器
* @package app\admin\controller
*/
class HookController extends AdminBaseController
{
/**
* 钩子管理
* @adminMenu(
* 'name' => '钩子管理',
* 'parent' => 'admin/Plugin/default',
* 'display'=> true,
* 'hasView'=> true,
* 'order' => 10000,
* 'icon' => '',
* 'remark' => '钩子管理',
* 'param' => ''
* )
*/
public function index()
{
$hookModel = new HookModel();
$hooks = $hookModel->select();
$this->assign('hooks', $hooks);
return $this->fetch();
}
/**
* 钩子插件管理
* @adminMenu(
* 'name' => '钩子插件管理',
* 'parent' => 'index',
* 'display'=> false,
* 'hasView'=> true,
* 'order' => 10000,
* 'icon' => '',
* 'remark' => '钩子插件管理',
* 'param' => ''
* )
*/
public function plugins()
{
$hook = $this->request->param('hook');
$pluginModel = new PluginModel();
$plugins = $pluginModel->field('a.*,b.hook,b.plugin,b.list_order,b.status as hook_plugin_status,b.id as hook_plugin_id')->alias('a')->join('__HOOK_PLUGIN__ b', 'a.name = b.plugin')->where('b.hook', $hook)->select();
$this->assign('plugins', $plugins);
return $this->fetch();
}
/**
* 钩子插件排序
* @adminMenu(
* 'name' => '钩子插件排序',
* 'parent' => 'index',
* 'display'=> false,
* 'hasView'=> false,
* 'order' => 10000,
* 'icon' => '',
* 'remark' => '钩子插件排序',
* 'param' => ''
* )
*/
public function pluginListOrder()
{
$hookPluginModel = new HookPluginModel();
parent::listOrders($hookPluginModel);
$this->success("排序更新成功!");
}
/**
* 同步钩子
* @adminMenu(
* 'name' => '同步钩子',
* 'parent' => 'index',
* 'display'=> false,
* 'hasView'=> true,
* 'order' => 10000,
* 'icon' => '',
* 'remark' => '同步钩子',
* 'param' => ''
* )
*/
public function sync()
{
$apps = cmf_scan_dir(APP_PATH . '*', GLOB_ONLYDIR);
foreach ($apps as $app) {
$hookConfigFile = APP_PATH . $app . '/hooks.php';
if (file_exists($hookConfigFile)) {
$hooksInFile = include $hookConfigFile;
foreach ($hooksInFile as $hookName => $hook) {
$hook['type'] = empty($hook['type']) ? 2 : $hook['type'];
if (!in_array($hook['type'], [2, 3, 4])) {
$hook['type'] = 2;
}
$findHook = Db::name('hook')->where(['hook' => $hookName])->count();
$hook['app'] = $app;
if ($findHook > 0) {
Db::name('hook')->where(['hook' => $hookName])->strict(false)->field(true)->update($hook);
} else {
$hook['hook'] = $hookName;
Db::name('hook')->insert($hook);
}
}
}
}
return $this->fetch();
}
}
\ No newline at end of file
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
namespace app\admin\controller;
use cmf\controller\AdminBaseController;
use think\Db;
use app\admin\model\AdminMenuModel;
class IndexController extends AdminBaseController
{
public function _initialize()
{
$adminSettings = cmf_get_option('admin_settings');
if (empty($adminSettings['admin_password']) || $this->request->path() == $adminSettings['admin_password']) {
$adminId = cmf_get_current_admin_id();
if (empty($adminId)) {
session("__LOGIN_BY_CMF_ADMIN_PW__", 1);//设置后台登录加密码
}
}
parent::_initialize();
}
/**
* 后台首页
*/
public function index()
{
$adminMenuModel = new AdminMenuModel();
$menus = $adminMenuModel->menuTree();
$this->assign("menus", $menus);
$admin = Db::name("user")->where('id', cmf_get_current_admin_id())->find();
$this->assign('admin', $admin);
return $this->fetch();
}
}
... ...
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
namespace app\admin\controller;
use cmf\controller\AdminBaseController;
use app\admin\model\LinkModel;
class LinkController extends AdminBaseController
{
protected $targets = ["_blank" => "新标签页打开", "_self" => "本窗口打开"];
/**
* 友情链接管理
* @adminMenu(
* 'name' => '友情链接',
* 'parent' => 'admin/Setting/default',
* 'display'=> true,
* 'hasView'=> true,
* 'order' => 50,
* 'icon' => '',
* 'remark' => '友情链接管理',
* 'param' => ''
* )
*/
public function index()
{
$linkModel = new LinkModel();
$links = $linkModel->select();
$this->assign('links', $links);
return $this->fetch();
}
/**
* 添加友情链接
* @adminMenu(
* 'name' => '添加友情链接',
* 'parent' => 'index',
* 'display'=> false,
* 'hasView'=> true,
* 'order' => 10000,
* 'icon' => '',
* 'remark' => '添加友情链接',
* 'param' => ''
* )
*/
public function add()
{
$this->assign('targets', $this->targets);
return $this->fetch();
}
/**
* 添加友情链接提交保存
* @adminMenu(
* 'name' => '添加友情链接提交保存',
* 'parent' => 'index',
* 'display'=> false,
* 'hasView'=> false,
* 'order' => 10000,
* 'icon' => '',
* 'remark' => '添加友情链接提交保存',
* 'param' => ''
* )
*/
public function addPost()
{
$data = $this->request->param();
$linkModel = new LinkModel();
$result = $linkModel->validate(true)->allowField(true)->save($data);
if ($result === false) {
$this->error($linkModel->getError());
}
$this->success("添加成功!", url("link/index"));
}
/**
* 编辑友情链接
* @adminMenu(
* 'name' => '编辑友情链接',
* 'parent' => 'index',
* 'display'=> false,
* 'hasView'=> true,
* 'order' => 10000,
* 'icon' => '',
* 'remark' => '编辑友情链接',
* 'param' => ''
* )
*/
public function edit()
{
$id = $this->request->param('id', 0, 'intval');
$linkModel = LinkModel::get($id);
$this->assign('targets', $this->targets);
$this->assign('link', $linkModel);
return $this->fetch();
}
/**
* 编辑友情链接提交保存
* @adminMenu(
* 'name' => '编辑友情链接提交保存',
* 'parent' => 'index',
* 'display'=> false,
* 'hasView'=> false,
* 'order' => 10000,
* 'icon' => '',
* 'remark' => '编辑友情链接提交保存',
* 'param' => ''
* )
*/
public function editPost()
{
$data = $this->request->param();
$linkModel = new LinkModel();
$result = $linkModel->validate(true)->allowField(true)->isUpdate(true)->save($data);
if ($result === false) {
$this->error($linkModel->getError());
}
$this->success("保存成功!", url("link/index"));
}
/**
* 删除友情链接
* @adminMenu(
* 'name' => '删除友情链接',
* 'parent' => 'index',
* 'display'=> false,
* 'hasView'=> false,
* 'order' => 10000,
* 'icon' => '',
* 'remark' => '删除友情链接',
* 'param' => ''
* )
*/
public function delete()
{
$id = $this->request->param('id', 0, 'intval');
LinkModel::destroy($id);
$this->success("删除成功!", url("link/index"));
}
/**
* 友情链接排序
* @adminMenu(
* 'name' => '友情链接排序',
* 'parent' => 'index',
* 'display'=> false,
* 'hasView'=> false,
* 'order' => 10000,
* 'icon' => '',
* 'remark' => '友情链接排序',
* 'param' => ''
* )
*/
public function listOrder()
{
$linkModel = new LinkModel();
parent::listOrders($linkModel);
$this->success("排序更新成功!");
}
/**
* 友情链接显示隐藏
* @adminMenu(
* 'name' => '友情链接显示隐藏',
* 'parent' => 'index',
* 'display'=> false,
* 'hasView'=> false,
* 'order' => 10000,
* 'icon' => '',
* 'remark' => '友情链接显示隐藏',
* 'param' => ''
* )
*/
public function toggle()
{
$data = $this->request->param();
$linkModel = new LinkModel();
if (isset($data['ids']) && !empty($data["display"])) {
$ids = $this->request->param('ids/a');
$linkModel->where(['id' => ['in', $ids]])->update(['status' => 1]);
$this->success("更新成功!");
}
if (isset($data['ids']) && !empty($data["hide"])) {
$ids = $this->request->param('ids/a');
$linkModel->where(['id' => ['in', $ids]])->update(['status' => 0]);
$this->success("更新成功!");
}
}
}
\ No newline at end of file
... ...