作者 郭鑫

傻子上传第一次

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

要显示太多修改。

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

.buildpath
.DS_Store
.project
.settings
.idea
.data
.update
composer.lock
/public/api
/public/assets/dist
/node_modules
... ...
如何贡献我的源代码
===
... ...
ThinkCMF遵循LGPL开源协议发布,并提供免费使用。
\ No newline at end of file
... ...
ThinkCMF 5.0.180123 正式版
===============
### 系列讲座
https://www.thinkcmf.com/college.html
### ThinkCMF5主要特性
* 基于全新 ThinkPHP5.0开发
* 更规范的代码,遵循PSR-2命名规范和PSR-4自动加载规范
* 更规范的数据库设计
* 前后台完全基于bootstrap3
* 增加 api 模块(需单独下载)
* 支持 composer 管理第三方库
* 核心化:独立核心代码包
* 应用化:开发者以应用的形式增加项目模模块
* 插件化:更强的插件机制,开发者以插件形式扩展功能
* 模板化:模板完全傻瓜式,用户无须改动任何代码即可在后台完成模板设计和配置
* 增加 URL美化功能,支持别名设置,更简单
* 独立的回收站功能,可以管理所有应用临时删除的数据
* 统一的资源管理,相同文件只保存一份
* 注解式的后台菜单管理功能,方便开发者代码管理后台菜单
* 文件存储插件化,默认支持七牛文件存储插件
* 模板制作标签化,内置多个cmf标签,方便小白用户
* 更人性化的导航标签,可以随意定制 html 结构
* 后台首页插件化,用户可以定制的网站后台首页
### 环境推荐
> php5.5+
> mysql 5.6+
> 打开rewrite
### 最低环境要求
> php5.4+
> mysql 5.5+ (mysql5.1安装时选择utf8编码,不支持表情符)
> 打开rewrite
### 运行环境配置教程
https://www.thinkcmf.com/topic/1502.html
### 自动安装
> 之前安装过 cmf5的同学,请手动创建`data/install.lock`文件
代码已经加入自动安装程序,如果你在安装中有任何问题请提交 issue!
1. public目录做为网站根目录,入口文件在 public/index.php
2. 配置好网站,请访问http://你的域名
enjoy your cmf~!
### 系统更新
如果您是已经安装过 cmf5的用户,请查看 update 目录下的 sql 升级文件,根据自己的下载的程序版本进行更新
### API开发 (支持app,小程序,web)
如果你需要 `api` 开发请下载:
ThinkCMF5 API :https://github.com/thinkcmf/thinkcmfapi
### 完整版目录结构
```
thinkcmf 根目录
├─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
### QQ群:
`ThinkCMF 官方交流群`:316669417
`ThinkCMF 高级交流群`:100828313 (付费)
高级群专属权益:
第一波:两个后台风格(ThinkCMF官网风格后台主题,蓝色风格后台主题)
第二波:ThinkCMF5完全开发手册离线版(PDF,EPUB,MOBI格式)
更多专属权益正在路上...
`ThinkCMF 铲屎官交流群`:415136742 (生活娱乐,为有喵的猿人准备)
### 话题专区
http://www.thinkcmf.com/topic/index/index/cat/11.html
### 反馈问题
https://github.com/thinkcmf/thinkcmf/issues
### 更新日志
#### 5.0.180123
[核心]
* 增加小程序管理插件
* 增加插件后台首页左侧菜单显示
* 增加 themes 根命名空间
* 增加模板设计图片模板变量取消功能
* 增加插件自定义处理配置功能
* 增加插件后台权限管理功能
* 增加后台模板切换
* 增加直传云存储功能
* 增强导航和子导航标签,自定义更随意
* 增加before_content,fetch_upload_view,log_write_done,switch_admin_theme钩子
* 增加PluginAdminBaseController基类
* 增加系统钩子同步
* 增加插件中可使用$site_info变量
* 增加 xml 生成函数
* 增加插件设置上传文件组件
* 优化数字验证码日志写入增加过期时间配置
* 优化数字验证码逻辑,增加数字验证码发送图片验证码,【升级时注意界面逻辑】
* 优化验证码生成功能,可增加验证码插件管理验证码生成
* 优化钩子插件管理
* 优化插件注册机制
* 优化后台首页菜单加载
* 修复模板管理变量数据为array时删除出错 #392
* 修复后台管理搜索翻页时条件丢失问题 #366
* 修复删除第三方用户时报错 #368
* 修复在使用cdn加速js时后台文章编辑器时无法加载编辑器配置
* 修复模板设计模板变量file类型不支持上传 #136
* 修复用户行为周期设置无效 #382
* 修复个人信息编辑签名验证问题
* 修复用户生日早于1970年报错
* 修复地址坐标选择搜索后无法确定坐标问题
* 优化IE8,9下的兼容问题
* 优化前台未登录时跳转方式
[安装程序]
* 增加安装时管理员密码长度限制 #334
* 增加安装时检查 rewrite设置
* 增加安装时 innodb 检测
* 更正PHP版本要求
[门户应用]
* 优化portal:articles标签可在模板里设置分页参数和样式
* 优化portal:articles标签所有属性都支持PHP变量
* 优化标签控制器支持标签名
* 增加portal:tagArticles标签
* 取消文章列表用户关联查询
* 修复文章多分类进文章列表文章重复问题
#### 5.0.170927
[核心]
* 增加是否开放注册设置
* 增加已经安装模板文件检测是否已经删除功能
* 增加模板卸载风险提示
* 增加钩子同步功能
* 增加用户操作同步功能 #291
* 增加网站信息【$site_info】变量,可以在插件中使用 #310
* 修复添加管理员不能登录 #110
* 优化 admin.js
* 优化后台模板设计排版
* 优化后台加密码设置
* 返回按钮统一优化
* 优化 url 美化时规划选择
* 修复`api`模块缺少函数报错
* 修复回收站还原提示错误 #111
* 修复原始网址和显示网址同时有参数的情况下,两个参数值相同的时候不能解析URL
* 修复模板设计数组编辑功能缺失
* 修复后台登录在双核浏览器下会使用 IE 内核问题#168
* 修复模板widget只有数组时,后台设计保存时报错
* 修复日期选择在windows firefox下报错
* 修复模板设计数据源页面清空链接错误
* 修复后台模板设计,json文件中的数组数据,不能正常显示 #222
* 修复`cmf\lib\Auth\check`方法逻辑问题 #252
* 修复后台用户登录自动退出后iframe页跳转到首页的问题
* 修复用户个人资料修改问题
* 修复绑定手机号和绑定邮箱号惟一性提示信息错
[安装程序]
* 更改安装时数据库默认为127.0.0.1
* 优化安装时链接生成
[门户应用]
* 增加前台文章控制器默认分类指定
* 增加后台文章列表所在分类列
* 增加后台文章分类必须指定分类验证
* 增加 portal:articles 标签 limit可以设置变量
* 增加模板设计页面数据源
* 完善 ApiService获取指定分类下的所有子分类方法
* 增加portal:categories,portal:subCategories,portal:allSubCategories标签
* 增加文章、页面、分类模板选择时模板文件名称查看
* 增加文章保存钩子
* 优化指定分类下所有子分类获取方法
* 修复文章分类管理中不保存选择的模板 #107
* 修复面包屑标签 self属性无法识别 false
* 修复后台编辑文件会覆盖原作者ID #175
* 修复后台文章保存后排序变化问题
* 修复添加文章分类时 path 没数据问题
[升级指导]
https://www.kancloud.cn/thinkcmf/doc/327443
#### 5.0.170607
[核心]
* 删除 app/common.php
* 规范 admin.js frontend.js函数名
* 更改后台模板设计的模板文件列表排序规则为从小到大排序
* 增加模板切换钩子,方便开发者实现复杂的模板切换功能
* 增加插件作者和演示信息
* 增加数字验证码模板编辑功能
* 增加模板变量编辑控件color
* 增加插件配置组件时间,图片,地理位置,颜色
* 优化模板配置更新
* 优化文件上传,检查已经上传文件是否存在,不存在重新上传
* 修复插件增加新配置时报错
* 修复模板变量 rule 规则存在,但没有规则时模板设计保存会报错
* 修复后台清除缓存后url生成不美化
* 修复模板设计一个页面有多个数组编辑问题
* 修复cdn设置不生效
* 修复后台菜单添加子菜单不选择上级问题
* 修复后台可能多个滚动条
* 修复后台添加、编辑角色一处文字错误
* 修复插件更新时不更新新增的钩子
[门户应用]
* 完善前台模板钩子
* 完善文章标签功能
* 增加前台模板手机注册关闭开关
* 优化文章后台文章分类链接生成
* 修复ff下文章相册图片替换和删除问题
* 修复文章分类排序功能
#### 5.0.170520
[核心]
* 完善插件后台管理
* 后台登录插件化
* 后台首页插件化
* 文件存储插件化
* 增加 URL 美化功能
* 增加后台加密码功能
* 增加用户修改头像
* 增加插件设置表单验证
* 增加前台后台通用语言包
* 增加编辑器里上传文件链接替换
* 增加应用 command.php 配置文件
* 增加后台管理员添加编辑用户名,邮箱惟一性验证
* 优化安装程序
* 优化上传文件
* 优化后台首页
* 优化回收站
* 优化插件启用禁用
* 优化小屏下后台首页不兼容问题
* 优化后台图片查看
* 修复后台菜单编辑不生效
* 修复幻灯片添加不显示问题
* 修复导航数据源数据返回为空时报错
* 修复 pathinfo 模式下后台本站用户默认头像不显示问题
* 修复后台 cdn 不能设置
* 合并asset应用到 user
[门户应用]
* 增加文章收藏功能
* 增加文章点赞限制,一个用户只能点赞一次
* 增加文章分类缩略图
* 优化文章分类管理删除
* 优化文章页和页面页内容图片样式问题
* 修复文章添加编辑默认图片错误
* 修复分类下没有文章时报错
* 修复页面模板设置无效
* 修复页面删除后仍可以访问
#### 5.0.170505
[核心]
* 完善用户注册流程
* 完善插件功能
* 增加手机验证码发送钩子
* 增加手机验证码发送演示插件
* 增加用户邮箱绑定
* 增加用户手机绑定
* 增加常用模板钩子
* 增加模板设计图片上传
* 增加用户密码修改
* 增加用户收藏功能
* 增加导航标签,子导航标签增加 `max-level` 设置
* 修复邮箱验证码发送
* 修复windows下获取模板数据时模板文件路径问题
* 修复单文件,多文件上传
* 修复后台首页用户昵称一直显示admin
* 修复 `navigation`,`subNavigation` 标签两个以上不能同时使用问题
* 修复 console 模式报错
* 取消前台有错误时界面刷新
[门户应用]
* 增加文章附件功能
* 优化文章相册
#### 5.0.170422
[核心]
* 完善幻灯片
* 完善后台控制器方法注释
* 增加调试模式下实时更新模板配置
* 增加友情链接图片上传
* 增加应用公共语言包功能
* 增加资源管理
* 增加模板设计数据源层级关系
* 更新jQuery Form版本
* 增加后台菜单类型是否有界面区分
* 增加权限验证时权限规则里没有的规则不用验证
* 增加前台网站信息获取
* 优化后台菜单导入
* 统一排序规则,按从小到大排序
* 修复后台模板管理点更新提示卸载
* 修复标签`NavigationMenu`
* 修复菜单导入时未添加权限规则
* 修复`navigationFolder`设置多个子菜单后会多循环数据
* 修复部分代码php5.4下不兼容
* 修复后台菜单不能添加编辑
[门户应用]
* 完全独立门户应用
* 完善后台页面管理
* 完善面包屑标签`breadcrumb`
* 完善文章分类管理
* 完善文章管理
* 修复文章分类`path`更新
* 优化文章列表标签`articles`
* 优化后台文章分类选择
* 增加前台文章点赞功能
* 增加前台文章搜索功能
* 增加文章列表分页总数获取
#### 5.0.170401
* 完善文件上传
* 增加回收站功能
* 完善友情链接
* 优化网站设置
* 增加后台登陆验证码
* 修复后台用户密码修改
* 修复用户管理-本站用户头像不显示
* 完善前台用户登录注册
* 增加后台菜单导入
* 修复后台菜单列表排序
* 完善导航
* 增加插件钩子管理
* 完善前台模板
... ...
<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
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[013678]|18\d)\d{8})$/', $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("退出成功!");
}
}
... ...
<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
$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
namespace api\common\exception;
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2017/11/28
* Time: 15:27
*/
use Exception;
use think\exception\Handle;
use think\exception\HttpException;
class Http extends Handle
{
public function render(Exception $e)
{
if (APP_DEBUG==true) {
return parent::render($e);
} elseif ($e instanceof ValidateException) {
$msg=$e->getMessage();
} else {
$msg= '系统错误!';
}
$code=0;
$httpCode=500;
$result = [
'code' => $code,
'msg' => $msg,
'data' => [],
];
return json($result, $httpCode);
}
}
... ...
<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------
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
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
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_ROOT . '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' => '\\api\\common\\exception\\Http',
// +----------------------------------------------------------------------
// | 日志设置
// +----------------------------------------------------------------------
'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
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
if(file_exists(ROOT_PATH."data/conf/database.php")){
$database=include ROOT_PATH."data/conf/database.php";
}else{
$database=[];
}
return $database;
... ...
<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
return [
// 应用调试模式
'app_debug' => true,
// 应用Trace
'app_trace' => true,
];
\ No newline at end of file
... ...
<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
namespace api\home\controller;
use think\Db;
use think\Validate;
use cmf\controller\RestBaseController;
class IndexController extends RestBaseController
{
// api 首页
public function index()
{
$this->success("恭喜您,API访问成功!", [
'version' => '1.0.0',
'doc' => 'http://www.kancloud.cn/thinkcmf/cmf5api'
]);
}
}
... ...
<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
// 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.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: wuwu <15093565100@163.com>
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | 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 (empty($data) || $data['items']->isEmpty()) {
$this->error('该组幻灯片显示数据为空');
}
if (isset($this->apiVersion)) {
$response = $data;
} else {
$response = [$data];
}
$this->success("该组幻灯片获取成功!", $response);
}
}
... ...
<?php
// +----------------------------------------------------------------------
// | 文件说明:用户-幻灯片
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: wuwu <15093565100@163.com>
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | 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.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: wuwu <15093565100@163.com>
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | 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')->order('list_order ASC');
}
/**
* [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)->find();
return $data;
}
}
... ...
<?php
use think\Route;
Route::resource('home/slides', 'home/Slides');
\ No newline at end of file
... ...
<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace api\portal\controller;
//use cmf\controller\HomeBaseController;
use app\portal\model\MemberModel;
use app\portal\model\UserModel;
use app\portal\service\PostService;
use think\Db;
use think\Request;
use think\Loader;
/**
* @title 文章接口
* @description 接口说明
* @group 接口分组
*/
class ArticleController extends CommonController
{
/**
* @title 文章列表
* @description 接口说明
* @author 开发者
* @url /api/portal/Article/index
* @method POST
* @param name:articleType type:int require:1 default: other: desc:类型
* @param name:page type:int require:1 default: other: desc:页码
* @return data:''@
* @data post_id:文章id
* @data category_id:类型id
* @data name:类型名
* @data post_title:文章标题
*
*/
public function index(Request $request)
{
$page = $request->param('page');
$where_connect['j.status'] = 1;
$where_connect['p.post_status'] = 1;
$where_connect['j.category_id'] = $_POST['articleType'];
$article_list = Db::name('PortalCategoryPost')->alias('j')
->where($where_connect)
->field("j.post_id,j.category_id , c.name , p.post_title")
->join("PortalCategory c","c.id = j.category_id")
->join("PortalPost p","p.id = j.post_id")
->page("$page,5")
->select()->toArray();
if(empty($article_list)){
$this->apiResponse('1','暂无数据');
}
$this->apiResponse('1','成功',$article_list);
}
/**
* @title 文章详情
* @description 接口说明
* @author 开发者
* @url /api/portal/Article/index
* @method POST
*
* @param name:post_id type:int require:1 default: other: desc:文章id
*
* @return content:''@!
* @content thumb:文章图片
* @content title:文章标题
* @content content:文章内容
* @content update_time:创建时间
* @content category_id:类型id
* @content name:类型名
* @return hot:''@
* @hot title:文章标题
* @hot article_id:文章id
*
*/
public function detail(Request $request)
{
$where_art['p.id'] = $request->param('post_id');
$where_art['p.post_status'] = 1;
$article_list = Db::name('PortalCategoryPost')
->alias('j')
->where($where_art)
->field("p.post_title as title,p.post_content as content,p.more,p.update_time ,
c.name,c.id as category_id")
->join("PortalCategory c","c.id = j.category_id")
->join("PortalPost p","p.id = j.post_id")
->find();
if(empty($article_list)){
$this->apiResponse('1','暂无数据');
}
// 处理图片
$thumb = json_decode($article_list['more'],true);
$article_list['thumb'] = $thumb['thumbnail'];
unset($article_list['more']);
// 处理内容
$article_list['content'] = htmlspecialchars_decode($article_list['content']);
$article_list['create_time'] = date('Y-m-d',$article_list['update_time']);
$final['content'] = $article_list;
// 热门文章
$where_hot['p.recommended'] = 1;
$where_hot['p.post_status'] = 1;
$hotArticle = Db::name('PortalCategoryPost')
->alias('j')
->where($where_hot)
->field("p.post_title as title,p.id as article_id")
// ->join("PortalCategory c","c.id = j.category_id")
->join("PortalPost p","p.id = j.post_id")
->select();
$final['hot'] = $hotArticle;
$this->apiResponse('1','成功',$final);
}
}
... ...
<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------
namespace api\portal\controller;
use cmf\controller\RestBaseController;
use api\portal\model\PortalPostModel;
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);
if (isset($this->apiVersion)) {
$response = ['list' => $data,];
} else {
$response = $data;
}
$this->success('请求成功!', $response);
}
/**
* 获取指定的文章
* @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->postModel->where('id', $id)->setInc('post_hits');
$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('搜索关键词不能为空!');
}
}
public function doLike()
{
$userId = $this->getUserId();
$articleId = $this->request->param('id', 0, 'intval');
$canLike = cmf_check_user_action(['object' => "posts$articleId", 'user_id' => $userId], 1);
if ($canLike) {
$this->postModel->where(['id' => $articleId])->setInc('post_like');
$likeCount = $this->postModel->where('id', $articleId)->value('post_like');
$this->success("赞好啦!", ['post_like' => $likeCount]);
} else {
$this->error("您已赞过啦!");
}
}
}
\ No newline at end of file
... ...
<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------
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);
}
/**
* 获取指定分类的子分类列表
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
*/
public function subCategories()
{
$id = $this->request->get('category_id', 0, 'intval');
$categories = $this->categoryModel->where(['parent_id' => $id])->select();
$this->success('请求成功', ['categories' => $categories]);
}
}
\ No newline at end of file
... ...
<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace api\portal\controller;
use cmf\controller\HomeBaseController;
use think\Db;
use think\Request;
use think\Loader;
use SmsDemo;
class CommonController extends HomeBaseController
{
/**
* API返回信息格式函数 ;0失败,1成功,-1需要登录
* @param string $code
* @param string $message
* @param array $data
*/
public function apiResponse($code = '0', $message = '',$data = array(),$nums =0){
header('Access-Control-Allow-Origin: *');
header('Content-Type:application/json; charset=utf-8');
$result = array(
'code'=>$code,
'message'=>$message,
'data'=>$data,
'nums'=>''.$nums
);
die(json_encode($result,JSON_UNESCAPED_UNICODE));
}
// 加密
public function md5($number){
$final = sha1(md5($number));
return $final;
}
// 短信验证码
public function sendLogin($tel,$code,$modelVal){
require_once VENDOR_PATH."aliyun-dysms-php-sdk/api_demo/SmsDemo.php";
set_time_limit(0);
header('Content-Type: text/plain; charset=utf-8');
$response = SmsDemo::sendSms($tel,$code,$modelVal);
return $response;
}
// 用户登录
public function isLogin(){
if($_SESSION['user_id']){
$where_firstLogin['id'] = $_SESSION['user_id'];
$firstMember = Db::name('Member')->where($where_firstLogin)->find();
if($firstMember['update_time'] >= (time()+604800) ){
$this->apiResponse('0','请先登录');
}
}else{
$this->apiResponse('0','请先登录');
}
}
}
... ...
<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace api\portal\controller;
use think\Controller;
//use api\portal\model\MemberModel;
//use api\portal\model\UserModel;
//use api\portal\service\PostService;
use think\Db;
use think\Request;
use think\Loader;
/**
* @title 首页接口
* @description 接口说明
* @group 接口分组
*/
class IndexController extends CommonController
{
/**
* @title 首页
* @description 接口说明
* @author 开发者
* @url /api/portal/Index/index
* @method POST
* @param name:chooseType type:int require:1 default: other: desc:类型:1手机站,2PC站
*/
public function index(Request $request)
{
// 1.首页轮播
$where_banner['status'] = 1;
$final['banner'] = Db::name('Banner')->where($where_banner)
->field("pic")
->order("score desc,create_time desc")->select()->toArray();
// 2.交易流程
$where_process['status'] = 1;
$where_process['type'] = $request->param('type');
$final['process'] = Db::name('Process')->where($where_process)
->field("content")
->order('create_time desc')
->find();
$final['process']['content'] = htmlspecialchars_decode($final['process']['content']);
// 3. 最新成交
// 4. 合作企业
$where_coo['status'] = 1;
$final['coop'] = Db::name('Cooperation')->where($where_coo)->order("score desc , create_time desc")->field('pic,jump')->select()->toArray();
// 5. 文章
$where_cate['c.delete_time'] = 0;
$where_cate['c.status'] = 1;
$where_cate['j.status'] = 1;
// 分类
$connect = Db::name('PortalCategoryPost')->alias('j')
->where($where_cate)
->join("PortalCategory c",'c.id = j.category_id')
// ->join("PortalPost p",'p.id = j.post_id')
// ->group('j.category_id')
->field("j.id as jid ,j.post_id,j.category_id,c.name")
->select()->toArray();
$cate_arr = array();
$post_arr = array();
$connect_arr = array();
// 处理分类id
foreach ($connect as $conk=>$conv){
$cate_arr[] = $conv['category_id'];
$post_arr[] = $conv['post_id'];
$connect_arr[$conk]['category_id'] = $conv['category_id'];
$connect_arr[$conk]['post_id'] = $conv['post_id'];
}
$cate_arr = array_values(array_unique($cate_arr));
// 查询分类
$where_cateNext['id'] = array('in',$cate_arr);
$cateNext_list = Db::name('PortalCategory')->where($where_cateNext)->field('id,name')->select()->toArray();
// 查文章
$where_arr['post_status'] = 1;
$where_arr['id'] = array('in',$post_arr);
$artcile = Db::name('PortalPost')
->where($where_arr)
->field('id,post_title')
->order("create_time desc")
->select()->toArray();
$middle =array();
// 拼数组
// 循环关联
foreach ($connect_arr as $conNextk=>$conNextv){
// 循环类
foreach ($cateNext_list as $catNextk=>$catNextv){
$middle[$catNextk]['id'] = $catNextv['id'];
$middle[$catNextk]['name'] = $catNextv['name'];
// 循环文章
foreach ($artcile as $artNextk=>$artNextv){
if($conNextv['category_id'] == $catNextv['id']){
// $key = $catNextv['name'];
if($conNextv['post_id'] == $artNextv['id']){
// $middle[$key][$artNextk]['title'] = $artNextv['post_title'];
// $middle[$key][$artNextk]['id'] = $artNextv['id'];
$middle[$catNextk]['list'][$artNextk]['id'] = $artNextv['id'];
$middle[$catNextk]['list'][$artNextk]['title'] = $artNextv['post_title'];
}
}
}
}
}
$final['article'] = $middle;
$this->apiResponse('1','成功',$final);
}
}
... ...
<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: wuwu <15093565100@163.com>
// +----------------------------------------------------------------------
namespace api\portal\controller;
use api\portal\model\PortalPostModel;
use cmf\controller\RestBaseController;
use think\Db;
use think\Request;
use think\Loader;
/**
* @title 用户接口
* @description 接口说明
* @group 接口分组
*/
class IntermediaryController extends CommonController
{
protected $postModel;
public function __construct(PortalPostModel $postModel)
{
parent::__construct();
$this->postModel = $postModel;
}
// 登录,注册
//tel 手机号
//password 密码
//sure_password 确认密码
//name 真实姓名
/**
* @title 房产中介注册
* @description 接口说明
* @author 开发者
* @url /api/portal/Intermediary/join
* @method POST
* @param name:name type:int require:1 default: other: desc:姓名
* @param name:tel type:int require:1 default: other: desc:手机号
* @param name:password type:int require:1 default: other: desc:密码
*/
public function join(Request $request)
{
if($request->Post()){
// 验证
$validate = Loader::validate('Intermediary');
if(!$validate->scene('add')->check($_POST)){
return json(array('code'=>0,'msg'=>$validate->getError()));
}
// 密码
$_POST['password'] = $this->md5($_POST['password']);
// 确认密码
if($_POST['password'] != $_POST['sure_password']){
$this->apiResponse('0','两次密码不一致');
}
// 短信验证码(未完)
// 判断手机号是否已注册
$user = new MemberModel($_POST);
$where_user['tel'] = $_POST['tel'];
$is_isset = $user->where($where_user)->find();
if($is_isset){
$this->apiResponse('0','您已注册过,请直接登录');
}
echo "<pre/>";
print_r('1111');
die;
$str = rand('1000,9999').time().rand('100,999');
$_POST['token'] = $this->md5($str);
$add = $user->allowField(true)->save();
if($add){
echo "<pre/>";
print_r('1');
die;
}else{
echo "<pre/>";
print_r('2');
die;
}
}else{
// 服务协议
// $service = new PostService();
// $list = $service->publishedArticle(1,1)->toArray();
$where_pro['status'] = 1;
$where_pro['type'] = 2;
$list = Db::name('Protocol')->where($where_pro)->order("update_time desc")->find();
// 推荐人(未完)
if($list){
$this->apiResponse('1','成功',$list);
}else{
$this->apiResponse('0','暂无内容');
}
}
}
// 登录
public function login(Request $request){
if($request->post()){
// 登录验证
// 判空
$tel = $request->param('tel');
$password = $request->param('password');
$true = $request->param('true');
$token = $request->param('token');
if(empty($tel)){
$this->apiResponse('0','手机号不能为空');
}else if(empty($password)){
$this->apiResponse('0','密码不能为空');
}else if(empty($true)){
$this->apiResponse('0','验证码不能为空');
}
// 验证
$where_member['tel'] = $tel;
$where_member['password'] = $password;
// $where_member['token'] = $token;
$member = Db::name('Member')->where($where_member)->find();
if($member){
if($member['token'] != $token){
$this->apiResponse('0','登录失败');
}
if($member['update_time'] >= (time()+604800)){
$this->apiResponse('0','请重新登录');
}else{
$this->apiResponse('1','登录成功');
}
}else{
$this->apiResponse('0','您输入的账号或密码不正确');
}
}else{
// 返回验证码图片
}
}
}
... ...
<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: wuwu <15093565100@163.com>
// +----------------------------------------------------------------------
namespace api\portal\controller;
use api\portal\model\MemberModel;
use api\portal\model\PortalPostModel;
use cmf\controller\RestBaseController;
use think\Db;
use think\Request;
use think\Loader;
use think\Config;
use think\captcha\Captcha;
use think\Url;
use SmsDemo;
//use think\Route;
/**
* @title 用户接口
* @description 接口说明
* @group 接口分组
*/
class IntermediaryNeedController extends CommonController
{
protected $postModel;
public function __construct(PortalPostModel $postModel)
{
parent::__construct();
$this->postModel = $postModel;
}
/**
* @title 用户发布需求的保证金
* @description 接口说明
* @author 开发者
* @url /api/portal/UserNeed/payMoney
* @method POST
* @param name:city type:int require:1 default: other: desc:地区
* @param name:quarters type:int require:1 default: other: desc:小区
* @param name:password type:int require:1 default: other: desc:密码
*/
public function payMoney(Request $request){
$data = $request->param();
if(!$data['city'] || !$data['area'] ){
$this->apiResponse('0','城市、面积不能为空');
}
$city = $data['city'];
$area = $data['area'];
$where_money[''] =
Db::name('MoneyRule')->where()
}
/**
* @title 用户发布需求
* @description 接口说明
* @author 开发者
* @url /api/portal/UserNeed/send
* @method POST
* @param name:city type:int require:1 default: other: desc:地区
* @param name:quarters type:int require:1 default: other: desc:小区
* @param name:password type:int require:1 default: other: desc:密码
*/
public function send(Request $request)
{
if($request->Post()){
$data = $request->param();
// 判空,处理
// 加数据库
}else{
// 问答内容
$where_pro['status'] = 1;
$list = Db::name('NeedAnswer')->where($where_pro)->order("update_time desc")->find();
if($list){
$this->apiResponse('1','成功',$list);
}else{
$this->apiResponse('0','暂无内容');
}
}
}
}
... ...
<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: wuwu <15093565100@163.com>
// +----------------------------------------------------------------------
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
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------
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
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------
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
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------
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
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: wuwu <15093565100@163.com>
// +----------------------------------------------------------------------
namespace api\portal\controller;
use api\portal\model\MemberModel;
use api\portal\model\PortalPostModel;
use cmf\controller\RestBaseController;
use think\Db;
use think\Request;
use think\Loader;
use think\Config;
use think\captcha\Captcha;
use think\Url;
use SmsDemo;
//use think\Route;
/**
* @title 用户接口
* @description 接口说明
* @group 接口分组
*/
class UserController extends CommonController
{
protected $postModel;
public function __construct(PortalPostModel $postModel)
{
parent::__construct();
$this->postModel = $postModel;
}
// 验证码图片
function getImgUrl($id = "")
{
\think\Route::get('captcha/[:id]', "\\think\\captcha\\CaptchaController@index");
\think\Validate::extend('captcha', function ($value, $id = "") {
return captcha_check($value, $id, (array)\think\Config::get('captcha'));
});
$middle_url = \think\Url::build('/captcha/new' . ($id ? "/{$id}" : ''));
$rand = str_replace(".","",substr(microtime(true),-5)).rand(1000,9999);
$imgUrl = $middle_url."&time=".$rand;
return $imgUrl;
}
// 获取短信验证码
public function getSmsResult(Request $request){
// 短信验证码
$tel = $request->param('tel');
$code = 'SMS_137416617';
$modelVal = rand(1000,9999);
$sendResult = $this->sendLogin($tel,$code,$modelVal);
if(($sendResult->Code) != 'OK'){
$this->apiResponse('0','注册失败');
}else{
$_SESSION('code',$modelVal);
$_SESSION('tel',$tel);
}
}
/**
* @title 用户注册
* @description 接口说明
* @author 开发者
* @url /api/portal/User/join
* @method POST
* @param name:name type:int require:1 default: other: desc:姓名
* @param name:tel type:int require:1 default: other: desc:手机号
* @param name:password type:int require:1 default: other: desc:密码
* @param name:sure_password type:int require:1 default: other: desc:确认密码
*/
public function join(Request $request)
{
if($request->Post()){
// 验证
$validate = Loader::validate('User');
if(!$validate->scene('add')->check($_POST)){
return json(array('code'=>0,'msg'=>$validate->getError()));
}
$data['password'] = $this->md5($_POST['password']);
$sure_password = $this->md5($_POST['sure_password']);
// 确认密码
if($data['password'] != $sure_password){
$this->apiResponse('0','两次密码不一致');
}
// 密码
// 短信验证码
// $tel = $request->param('tel');
// $code = 'SMS_137416617';
// $modelVal = rand(1000,9999);
// $sendResult = $this->sendLogin($tel,$code,$modelVal);
// if(($sendResult->Code) != 'OK'){
// $this->apiResponse('0','注册失败');
// }
$data['tel'] = $_POST['tel'];
$code = $request->param('code');
if($data['tel'] != $_SESSION['tel']){
$this->apiResponse('0','验证码错误,请重新获取');
}else{
if($code != $_SESSION['code']){
$this->apiResponse('0','验证码错误,请重新获取');
}
}
unset($_SESSION['code']);
$data['name'] = $_POST['name'];
// 判断手机号是否已注册
$user = new MemberModel();
$where_user['tel'] = $data['tel'];
$is_isset = $user->where($where_user)->find();
if($is_isset){
$this->apiResponse('0','您已注册过,请直接登录');
}
$str = rand(1000,9999).time().rand(100,999);
$data['token'] = $this->md5($str);
$add = $user->allowField(true)->save($data);
if($add){
$this->apiResponse('1','注册成功');
}else{
$this->apiResponse('0','注册失败');
}
}else{
// 服务协议
// $service = new PostService();
// $list = $service->publishedArticle(1,1)->toArray();
$where_pro['status'] = 1;
$where_pro['type'] = 1;
$list = Db::name('Protocol')->where($where_pro)->order("update_time desc")->field("title,content")->find();
// 推荐人(未完)
if($list){
$this->apiResponse('1','成功',$list);
}else{
$this->apiResponse('0','暂无内容');
}
}
}
// 登录
public function login(Request $request){
if($request->post()){
// 登录验证
// 判空
$tel = $request->param('tel');
$password = $request->param('password');
$true = $request->param('true');
$token = $request->param('token');
if(empty($tel)){
$this->apiResponse('0','手机号不能为空');
}else if(empty($password)){
$this->apiResponse('0','密码不能为空');
}else if(empty($true)){
$this->apiResponse('0','验证码不能为空');
}
// 验证
$where_member['tel'] = $tel;
$where_member['password'] = $password;
// $where_member['token'] = $token;
$member = Db::name('Member')->where($where_member)->find();
if($member){
if($member['token'] != $token){
$this->apiResponse('0','登录失败');
}
if($member['update_time'] >= (time()+604800)){
$this->apiResponse('0','请重新登录');
}else{
$this->apiResponse('1','登录成功');
}
}else{
$this->apiResponse('0','您输入的账号或密码不正确');
}
}else{
// 返回验证码图片
}
}
// 退出登录
public function outLogin(Request $request){
// 重置token
$str = rand('1000,9999').time().rand('100,999');
$change['token'] = $this->md5($str);
$where_member['id'] = $request->param('user_id');
$where_member['token'] = $request->param('token');
$model = new MemberModel();
$member = $model->where($where_member)->find();
if($member){
$change['id'] = $request->param('user_id');
$update = $model->isUpdate(true)->allowField(true)->save($change);
if($update){
unset($_SESSION['user_id']);
$this->apiResponse('1','退出成功');
}else{
$this->apiResponse('0','退出失败');
}
}else{
$this->apiResponse('0','用户信息错误');
}
}
// 修改密码
}
... ...
<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: wuwu <15093565100@163.com>
// +----------------------------------------------------------------------
namespace api\portal\controller;
use api\portal\model\MemberModel;
use api\portal\model\PortalPostModel;
use cmf\controller\RestBaseController;
use think\Db;
use think\Request;
use think\Loader;
use think\Config;
use think\captcha\Captcha;
use think\Url;
use SmsDemo;
//use think\Route;
/**
* @title 用户接口
* @description 接口说明
* @group 接口分组
*/
class UserNeedController extends CommonController
{
protected $postModel;
public function __construct(PortalPostModel $postModel)
{
parent::__construct();
$this->postModel = $postModel;
}
/**
* @title 用户发布需求的保证金
* @description 接口说明
* @author 开发者
* @url /api/portal/UserNeed/payMoney
* @method POST
* @param name:city type:int require:1 default: other: desc:地区
* @param name:quarters type:int require:1 default: other: desc:小区
* @param name:password type:int require:1 default: other: desc:密码
*/
public function payMoney(Request $request){
$data = $request->param();
if(!$data['city'] || !$data['area'] ){
$this->apiResponse('0','城市、面积不能为空');
}
$city = $data['city'];
$area = $data['area'];
}
/**
* @title 用户发布需求
* @description 接口说明
* @author 开发者
* @url /api/portal/UserNeed/send
* @method POST
* @param name:city type:int require:1 default: other: desc:地区
* @param name:quarters type:int require:1 default: other: desc:小区
* @param name:password type:int require:1 default: other: desc:密码
*/
public function send(Request $request)
{
if($request->Post()){
$data = $request->param();
// 判空,处理
// 加数据库
}else{
// 问答内容
$where_pro['status'] = 1;
$list = Db::name('NeedAnswer')->where($where_pro)->order("update_time desc")->find();
if($list){
$this->apiResponse('1','成功',$list);
}else{
$this->apiResponse('0','暂无内容');
}
}
}
}
... ...
<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------
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','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
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------
namespace api\portal\model;
use api\common\model\CommonModel;
class IntermediaryModel extends CommonModel
{
//可查询字段
// protected $visible = [
// 'articles.id', 'user_nickname', 'avatar', 'signature','user'
// ];
//模型关联方法
protected $relationFilter = ['user'];
/**
* 基础查询
*/
protected function base($query)
{
$query->alias('user')->where('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
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace api\portal\model;
use think\Model;
class MemberModel extends Model
{
protected $autoWriteTimestamp = true;
// protected $auto = [];
protected $insert = ['create_time'];
protected $update = [''];
protected function setCreateTimeAttr()
{
return time();
}
}
\ No newline at end of file
... ...
<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------
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
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: wuwu <15093565100@163.com>
// +----------------------------------------------------------------------
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
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------
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)
{
// 兼容老版本 1.0.0的客户端
$apiVersion = request()->header('XX-Api-Version');
if (empty($apiVersion)) {
return date('Y-m-d H:i:s', $value);
} else {
return $value;
}
}
/**
* published_time 自动转化
* @param $value
* @return int
*/
public function setPublishedTimeAttr($value)
{
if (is_numeric($value)) {
return $value;
}
return strtotime($value);
}
public function getPostTitleAttr($value)
{
return htmlspecialchars_decode($value);
}
public function getPostExcerptAttr($value)
{
return htmlspecialchars_decode($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_file_download_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 true;
} else {
return false;
}
}
/**
* 过滤属于当前用户的文章,超级管理员除外
* @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
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------
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
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------
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
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------
namespace api\portal\model;
use think\Model;
class RecycleBinModel extends Model
{
}
... ...
<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------
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->alias('user')->where('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::get('portal/categories/subCategories', 'portal/Categories/subCategories');
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::post('portal/articles/doLike', 'portal/Articles/doLike');
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
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------
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
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
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
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace api\portal\validate;
use think\Validate;
class IntermediaryValidate extends Validate
{
protected $rule = [
'name' => ['require','length:2,4','chs'],
'password' => ['require','length:6,16'],
'tel' => ['regex'=>'/13[123569]{1}\d{8}|15[1235689]\d{8}|188\d{8}/','require'],
];
protected $message = [
'name.require' => '姓名不能为空!',
'name.length' => '姓名为2-4个汉字!',
'name.chs' => '姓名只能是汉字!',
'tel.require' => '手机号不能为空!',
'tel.regex' => '手机号格式不正确!',
'password.require' => '密码不能为空!',
'password.length' => '密码长度为6-16位!',
];
protected $scene = [
'add' => ['name','tel','password'],
'edit' => ['tel','password','name'],
];
}
\ No newline at end of file
... ...
<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace api\portal\validate;
use think\Validate;
class UserValidate extends Validate
{
protected $rule = [
'name' => ['require','length:2,4','chs'],
'password' => ['require','length:6,16'],
'tel' => ['regex'=>'/13[123569]{1}\d{8}|15[1235689]\d{8}|18\d{9}/','require'],
'sure_password' => 'require'
];
protected $message = [
'name.require' => '姓名不能为空!',
'name.length' => '姓名为2-4个汉字!',
'name.chs' => '姓名只能是汉字!',
'tel.require' => '手机号不能为空!',
'tel.regex' => '手机号格式不正确!',
'password.require' => '密码不能为空!',
'password.length' => '密码长度为6-16位!',
'sure_password.require' => '确认密码不能为空!',
];
protected $scene = [
'add' => ['name','tel','password','sure_password'],
'edit' => ['tel','password','name','sure_password'],
];
}
\ No newline at end of file
... ...
<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
return [
// 应用调试模式
'app_debug' => false,
// 应用Trace
'app_trace' => false,
];
\ No newline at end of file
... ...
<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
$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
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
// 应用行为扩展定义文件
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.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: wuwu <15093565100@163.com>
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | 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
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------
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(['user_id' => $this->getUserId(), 'object_id' => $input['object_id']])->where('table_name', $input['table_name'])->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($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
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
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[013678]|18\d)\d{8})$/', $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('修改失败!');
}
}
}
}
... ...