PortalPostModel.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Author: pl125 <xskjs888@163.com>
  8. // +----------------------------------------------------------------------
  9. namespace api\portal\model;
  10. use think\Db;
  11. use think\db\Query;
  12. use think\Model;
  13. /**
  14. * @method getFieldById($id, $string)
  15. * @property mixed id
  16. */
  17. class PortalPostModel extends Model
  18. {
  19. //设置只读字段
  20. protected $readonly = ['user_id'];
  21. // 开启自动写入时间戳字段
  22. protected $autoWriteTimestamp = true;
  23. //类型转换
  24. protected $type = [
  25. 'more' => 'array',
  26. ];
  27. /**
  28. * 关联 user表
  29. * @return \think\model\relation\BelongsTo
  30. */
  31. public function user()
  32. {
  33. return $this->belongsTo('api\portal\model\UserModel', 'user_id');
  34. }
  35. /**
  36. * 关联 user表
  37. * @return \think\model\relation\BelongsTo
  38. */
  39. public function articleUser()
  40. {
  41. return $this->belongsTo('api\portal\model\UserModel', 'user_id')->field('id,user_nickname');
  42. }
  43. /**
  44. * 关联分类表
  45. * @return \think\model\relation\BelongsToMany
  46. */
  47. public function categories()
  48. {
  49. return $this->belongsToMany('api\portal\model\PortalCategoryModel', 'portal_category_post', 'category_id', 'post_id');
  50. }
  51. /**
  52. * 关联标签表
  53. * @return \think\model\relation\BelongsToMany
  54. */
  55. public function tags()
  56. {
  57. return $this->belongsToMany('api\portal\model\PortalTagModel', 'portal_tag_post', 'tag_id', 'post_id');
  58. }
  59. /**
  60. * 关联 回收站 表
  61. * @return \think\model\relation\HasOne
  62. */
  63. public function recycleBin()
  64. {
  65. return $this->hasOne('api\portal\model\RecycleBinModel', 'object_id');
  66. }
  67. /**
  68. * published_time 自动转化
  69. * @param $value
  70. * @return string
  71. */
  72. public function getPublishedTimeAttr($value)
  73. {
  74. // 兼容老版本 1.0.0的客户端
  75. $apiVersion = request()->header('XX-Api-Version');
  76. if (empty($apiVersion)) {
  77. return date('Y-m-d H:i:s', $value);
  78. } else {
  79. return $value;
  80. }
  81. }
  82. /**
  83. * published_time 自动转化
  84. * @param $value
  85. * @return int
  86. */
  87. public function setPublishedTimeAttr($value)
  88. {
  89. if (is_numeric($value)) {
  90. return $value;
  91. }
  92. return strtotime($value);
  93. }
  94. public function getPostTitleAttr($value)
  95. {
  96. return htmlspecialchars_decode($value);
  97. }
  98. public function getPostExcerptAttr($value)
  99. {
  100. return htmlspecialchars_decode($value);
  101. }
  102. /**
  103. * post_content 自动转化
  104. * @param $value
  105. * @return string
  106. */
  107. public function getPostContentAttr($value)
  108. {
  109. return cmf_replace_content_file_url(htmlspecialchars_decode($value));
  110. }
  111. /**
  112. * post_content 自动转化
  113. * @param $value
  114. * @return string
  115. */
  116. public function setPostContentAttr($value)
  117. {
  118. return htmlspecialchars(cmf_replace_content_file_url(htmlspecialchars_decode($value), true));
  119. }
  120. /**
  121. * Thumbnail 自动转化
  122. * @param $value
  123. * @return array
  124. */
  125. public function getThumbnailAttr($value)
  126. {
  127. return cmf_get_image_url($value);
  128. }
  129. /**
  130. * more 自动转化
  131. * @param $value
  132. * @return array
  133. */
  134. public function getMoreAttr($value)
  135. {
  136. $more = json_decode($value, true);
  137. if (!empty($more['thumbnail'])) {
  138. $more['thumbnail'] = cmf_get_image_url($more['thumbnail']);
  139. }
  140. if (!empty($more['audio'])) {
  141. $more['audio'] = cmf_get_file_download_url($more['audio']);
  142. }
  143. if (!empty($more['video'])) {
  144. $more['video'] = cmf_get_file_download_url($more['video']);
  145. }
  146. if (!empty($more['photos'])) {
  147. foreach ($more['photos'] as $key => $value) {
  148. $more['photos'][$key]['url'] = cmf_get_image_url($value['url']);
  149. }
  150. }
  151. if (!empty($more['files'])) {
  152. foreach ($more['files'] as $key => $value) {
  153. $more['files'][$key]['url'] = cmf_get_file_download_url($value['url']);
  154. }
  155. }
  156. return $more;
  157. }
  158. /**
  159. * 文章查询
  160. * @param array $filter 数据
  161. * @return array|\PDOStatement|string|Model|null
  162. * @throws \think\db\exception\DataNotFoundException
  163. * @throws \think\db\exception\ModelNotFoundException
  164. * @throws \think\exception\DbException
  165. */
  166. public function articleFind($filter)
  167. {
  168. $result = $this
  169. ->where(function (Query $query) use ($filter) {
  170. if (!empty($filter['id'])) {
  171. $query->where('id', $filter['id']);
  172. }
  173. if (!empty($filter['user_id'])) {
  174. $query->where('user_id', $filter['user_id']);
  175. }
  176. })
  177. ->where('delete_time', 0)
  178. ->where('post_status', 1)
  179. ->where('post_type', 1)
  180. ->find();
  181. return $result;
  182. }
  183. /**
  184. * 会员添加文章
  185. * @param array $data 文章数据
  186. * @return $this
  187. * @throws \think\Exception
  188. */
  189. public function addArticle($data)
  190. {
  191. if (!empty($data['more'])) {
  192. $data['more'] = $this->setMoreUrl($data['more']);
  193. }
  194. if (!empty($data['thumbnail'])) {
  195. $data['more']['thumbnail'] = cmf_asset_relative_url($data['thumbnail']);
  196. }
  197. $this->allowField(true)->data($data, true)->isUpdate(false)->save();
  198. $categories = str_to_arr($data['categories']);
  199. //TODO 无法录入多个分类
  200. $this->categories()->attach($categories);
  201. if (!empty($data['post_keywords']) && is_string($data['post_keywords'])) {
  202. //加入标签
  203. $data['post_keywords'] = str_replace(',', ',', $data['post_keywords']);
  204. $keywords = explode(',', $data['post_keywords']);
  205. $this->addTags($keywords, $this->id);
  206. }
  207. return $this;
  208. }
  209. /**
  210. * 会员文章编辑
  211. * @param array $data 文章数据
  212. * @param int $id 文章id
  213. * @param string $userId 文章所属用户id [可选]
  214. * @return PortalPostModel|bool
  215. * @throws \think\Exception
  216. */
  217. public function editArticle($data, $id, $userId = '')
  218. {
  219. if (!empty($userId)) {
  220. //判断是否属于当前用户的文章
  221. $isBelong = $this->isuserPost($id, $userId);
  222. if ($isBelong === false) {
  223. return $isBelong;
  224. }
  225. }
  226. if (!empty($data['more'])) {
  227. $data['more'] = $this->setMoreUrl($data['more']);
  228. }
  229. if (!empty($data['thumbnail'])) {
  230. $data['more']['thumbnail'] = cmf_asset_relative_url($data['thumbnail']);
  231. }
  232. $data['id'] = $id;
  233. // $data['post_status'] = empty($data['post_status']) ? 0 : 1;
  234. // $data['is_top'] = empty($data['is_top']) ? 0 : 1;
  235. // $data['recommended'] = empty($data['recommended']) ? 0 : 1;
  236. $this->allowField(true)->data($data, true)->isUpdate(true)->save();
  237. $categories = str_to_arr($data['categories']);
  238. $oldCategoryIds = $this->categories()->column('category_id');
  239. $sameCategoryIds = array_intersect($categories, $oldCategoryIds);
  240. $needDeleteCategoryIds = array_diff($oldCategoryIds, $sameCategoryIds);
  241. $newCategoryIds = array_diff($categories, $sameCategoryIds);
  242. if (!empty($needDeleteCategoryIds)) {
  243. $this->categories()->detach($needDeleteCategoryIds);
  244. }
  245. if (!empty($newCategoryIds)) {
  246. $this->categories()->attach(array_values($newCategoryIds));
  247. }
  248. $keywords = [];
  249. if (!empty($data['post_keywords'])) {
  250. if (is_string($data['post_keywords'])) {
  251. //加入标签
  252. $data['post_keywords'] = str_replace(',', ',', $data['post_keywords']);
  253. $keywords = explode(',', $data['post_keywords']);
  254. }
  255. }
  256. $this->addTags($keywords, $data['id']);
  257. return $this;
  258. }
  259. /**
  260. * 根据文章关键字,增加标签
  261. * @param array $keywords 文章关键字数组
  262. * @param int $articleId 文章id
  263. * @throws \think\Exception
  264. * @throws \think\db\exception\DataNotFoundException
  265. * @throws \think\db\exception\ModelNotFoundException
  266. * @throws \think\exception\DbException
  267. * @throws \think\exception\PDOException
  268. */
  269. public function addTags($keywords, $articleId)
  270. {
  271. foreach ($keywords as $key => $value) {
  272. $keywords[$key] = trim($value);
  273. }
  274. $continue = true;
  275. $names = $this->tags()->column('name');
  276. if (!empty($keywords) || !empty($names)) {
  277. if (!empty($names)) {
  278. $sameNames = array_intersect($keywords, $names);
  279. $keywords = array_diff($keywords, $sameNames);
  280. $shouldDeleteNames = array_diff($names, $sameNames);
  281. if (!empty($shouldDeleteNames)) {
  282. $tagIdNames = $this->tags()
  283. ->where('name', 'in', $shouldDeleteNames)
  284. ->column('pivot.id', 'tag_id');
  285. $tagIds = array_keys($tagIdNames);
  286. $tagPostIds = array_values($tagIdNames);
  287. $tagPosts = DB::name('portal_tag_post')
  288. ->where('tag_id', 'in', $tagIds)
  289. ->field('id,tag_id,post_id')
  290. ->select();
  291. $keepTagIds = [];
  292. foreach ($tagPosts as $key => $tagPost) {
  293. if ($articleId != $tagPost['post_id']) {
  294. array_push($keepTagIds, $tagPost['tag_id']);
  295. }
  296. }
  297. $keepTagIds = array_unique($keepTagIds);
  298. $shouldDeleteTagIds = array_diff($tagIds, $keepTagIds);
  299. Db::name('PortalTag')->delete($shouldDeleteTagIds);
  300. Db::name('PortalTagPost')->delete($tagPostIds);
  301. }
  302. } else {
  303. $tagIdNames = DB::name('portal_tag')->where('name', 'in', $keywords)->column('name', 'id');
  304. if (!empty($tagIdNames)) {
  305. $tagIds = array_keys($tagIdNames);
  306. $this->tags()->attach($tagIds);
  307. $keywords = array_diff($keywords, array_values($tagIdNames));
  308. if (empty($keywords)) {
  309. $continue = false;
  310. }
  311. }
  312. }
  313. if ($continue) {
  314. foreach ($keywords as $key => $value) {
  315. if (!empty($value)) {
  316. $this->tags()->attach(['name' => $value]);
  317. }
  318. }
  319. }
  320. }
  321. }
  322. /**
  323. * 获取图片附件url相对地址
  324. * 默认上传名字 *_names 地址 *_urls
  325. * @param array $annex 上传附件
  326. * @return array
  327. */
  328. public function setMoreUrl($annex)
  329. {
  330. $more = [];
  331. if (!empty($annex)) {
  332. foreach ($annex as $key => $value) {
  333. $nameArr = $key . '_names';
  334. $urlArr = $key . '_urls';
  335. if (is_string($value[$nameArr]) && is_string($value[$urlArr])) {
  336. $more[$key] = [$value[$nameArr], $value[$urlArr]];
  337. } elseif (!empty($value[$nameArr]) && !empty($value[$urlArr])) {
  338. $more[$key] = [];
  339. foreach ($value[$urlArr] as $k => $url) {
  340. $url = cmf_asset_relative_url($url);
  341. array_push($more[$key], ['url' => $url, 'name' => $value[$nameArr][$k]]);
  342. }
  343. }
  344. }
  345. }
  346. return $more;
  347. }
  348. /**
  349. * 删除文章
  350. * @param int|array $ids 文章id
  351. * @param string $userId 文章所属用户id [可选]
  352. * @return bool|int 删除结果 true 成功 false 失败 -1 文章不存在
  353. * @throws \think\db\exception\DataNotFoundException
  354. * @throws \think\db\exception\ModelNotFoundException
  355. * @throws \think\exception\DbException
  356. */
  357. public function deleteArticle($ids, $userId = '')
  358. {
  359. $time = time();
  360. $result = false;
  361. $where = [];
  362. if (!empty($userId)) {
  363. if (is_numeric($ids)) {
  364. $article = $this->find($ids);
  365. if (!empty($article)) {
  366. if ($this->isUserPost($ids, $userId) || $userId == 1) {
  367. $where['id'] = $ids;
  368. }
  369. }
  370. } else {
  371. $ids = str_to_arr($ids);
  372. $articles = $this->where('id', 'in', $ids)->select();
  373. if (!empty($articles)) {
  374. $deleteIds = $this->isUserPosts($ids, $userId);
  375. if (!empty($deleteIds)) {
  376. $where['id'] = ['in', $deleteIds];
  377. }
  378. }
  379. }
  380. } else {
  381. if (is_numeric($ids)) {
  382. $article = $this->find($ids);
  383. if (!empty($article)) {
  384. $where['id'] = $ids;
  385. }
  386. } else {
  387. $ids = str_to_arr($ids);
  388. $articles = $this->where('id', 'in', $ids)->select();
  389. if (!empty($articles)) {
  390. $where['id'] = ['in', $ids];
  391. }
  392. }
  393. }
  394. if (empty($article) && empty($articles)) {
  395. return -1;
  396. }
  397. if (!empty($where)) {
  398. $result = $this->useGlobalScope(false)
  399. ->where($where)
  400. ->setField('delete_time', $time);
  401. }
  402. if ($result) {
  403. $data = [
  404. 'create_time' => $time,
  405. 'table_name' => 'portal_post'
  406. ];
  407. if (!empty($article)) {
  408. $data['name'] = $article['post_title'];
  409. $article->recycleBin()->save($data);
  410. }
  411. if (!empty($articles)) {
  412. foreach ($articles as $article) {
  413. $data['name'] = $article['post_title'];
  414. $article->recycleBin()->save($data);
  415. }
  416. }
  417. }
  418. return $result;
  419. }
  420. /**
  421. * 判断文章所属用户是否为当前用户,超级管理员除外
  422. * @param int $id 文章id
  423. * @param int $userId 当前用户id
  424. * @return boolean 是 true , 否 false
  425. */
  426. public function isUserPost($id, $userId)
  427. {
  428. $postUserId = $this->getFieldById($id, 'user_id');
  429. if ($postUserId == $userId || $userId == 1) {
  430. return true;
  431. } else {
  432. return false;
  433. }
  434. }
  435. /**
  436. * 过滤属于当前用户的文章,超级管理员除外
  437. * @param array $ids 文章id的数组
  438. * @param int $userId 当前用户id
  439. * @return array 属于当前用户的文章id
  440. */
  441. public function isUserPosts($ids, $userId)
  442. {
  443. $postIds = $this
  444. ->useGlobalScope(false)
  445. ->where('user_id', $userId)
  446. ->where('id', 'in', $ids)
  447. ->column('id');
  448. return array_intersect($ids, $postIds);
  449. }
  450. }