Просмотр файла app/Http/Controllers/AjaxController.php

Размер файла: 13.26Kb
  1. <?php
  2.  
  3. declare(strict_types=1);
  4.  
  5. namespace App\Http\Controllers;
  6.  
  7. use App\Classes\Validator;
  8. use App\Models\Article;
  9. use App\Models\BaseModel;
  10. use App\Models\Comment;
  11. use App\Models\Down;
  12. use App\Models\File;
  13. use App\Models\Guestbook;
  14. use App\Models\Item;
  15. use App\Models\Message;
  16. use App\Models\News;
  17. use App\Models\Offer;
  18. use App\Models\Photo;
  19. use App\Models\Post;
  20. use App\Models\Spam;
  21. use App\Models\Sticker;
  22. use App\Models\Wall;
  23. use Exception;
  24. use Illuminate\Http\JsonResponse;
  25. use Illuminate\Support\Facades\DB;
  26. use Illuminate\Database\Eloquent\Relations\Relation;
  27. use Illuminate\Http\Request;
  28. use Illuminate\View\View;
  29.  
  30. class AjaxController extends Controller
  31. {
  32. /**
  33. * Конструктор
  34. *
  35. * @param Request $request
  36. */
  37. public function __construct(Request $request)
  38. {
  39. $this->checkAjax($request);
  40. $this->checkAuthorize();
  41. }
  42.  
  43. /**
  44. * Возвращает bbCode для предпросмотра
  45. *
  46. * @param Request $request
  47. *
  48. * @return View
  49. */
  50. public function bbCode(Request $request): View
  51. {
  52. $message = (string) $request->input('data');
  53.  
  54. return view('app/_bbcode', compact('message'));
  55. }
  56.  
  57. /**
  58. * Отправляет жалобу на сообщение
  59. *
  60. * @param Request $request
  61. * @param Validator $validator
  62. *
  63. * @return JsonResponse
  64. */
  65. public function complaint(Request $request, Validator $validator): JsonResponse
  66. {
  67. $path = null;
  68. $model = false;
  69. $id = int($request->input('id'));
  70. $type = $request->input('type');
  71. $page = $request->input('page');
  72.  
  73. switch ($type) :
  74. case Guestbook::$morphName:
  75. $model = Guestbook::query()->find($id);
  76. $path = '/guestbook?page=' . $page;
  77. break;
  78.  
  79. case Post::$morphName:
  80. $model = Post::query()->find($id);
  81. $path = '/topics/' . $model->topic_id . '?page=' . $page;
  82. break;
  83.  
  84. case Message::$morphName:
  85. $model = Message::query()->find($id);
  86. break;
  87.  
  88. case Wall::$morphName:
  89. $model = Wall::query()->find($id);
  90. $path = '/walls/' . $model->user->login . '?page=' . $page;
  91. break;
  92.  
  93. case News::$morphName:
  94. case Article::$morphName:
  95. case Photo::$morphName:
  96. case Offer::$morphName:
  97. case Down::$morphName:
  98. $model = Comment::query()->find($id);
  99. $path = '/' . $model->relate_type . '/comments/' . $model->relate_id . '?page=' . $page;
  100. $type = 'comments';
  101. break;
  102. endswitch;
  103.  
  104. $spam = Spam::query()->where(['relate_type' => $type, 'relate_id' => $id])->first();
  105.  
  106. $validator
  107. ->equal($request->input('_token'), csrf_token(), __('validator.token'))
  108. ->true($model, __('main.message_not_found'))
  109. ->false($spam, __('ajax.complaint_already_sent'));
  110.  
  111. if ($validator->isValid()) {
  112. Spam::query()->create([
  113. 'relate_type' => $type,
  114. 'relate_id' => $model->id,
  115. 'user_id' => getUser('id'),
  116. 'path' => $path,
  117. 'created_at' => SITETIME,
  118. ]);
  119.  
  120. return response()->json(['success' => true]);
  121. }
  122.  
  123. return response()->json([
  124. 'success' => false,
  125. 'message' => current($validator->getErrors()),
  126. ]);
  127. }
  128.  
  129. /**
  130. * Удаляет комментарии
  131. *
  132. * @param Request $request
  133. * @param Validator $validator
  134. *
  135. * @return JsonResponse
  136. */
  137. public function delComment(Request $request, Validator $validator): JsonResponse
  138. {
  139. if (! isAdmin()) {
  140. return response()->json([
  141. 'success' => false,
  142. 'message' => __('main.not_authorized'),
  143. ]);
  144. }
  145.  
  146. $type = $request->input('type');
  147. $rid = int($request->input('rid'));
  148. $id = int($request->input('id'));
  149.  
  150. $validator->equal($request->input('_token'), csrf_token(), __('validator.token'));
  151.  
  152. if ($validator->isValid()) {
  153. $delComments = Comment::query()
  154. ->where('relate_type', $type)
  155. ->where('relate_id', $rid)
  156. ->where('id', $id)
  157. ->delete();
  158.  
  159. if ($delComments) {
  160. /** @var BaseModel $class */
  161. $class = Relation::getMorphedModel($type);
  162. $model = $class::query()->find($rid);
  163.  
  164. if ($model) {
  165. $model->decrement('count_comments');
  166. }
  167. }
  168.  
  169. return response()->json(['success' => true]);
  170. }
  171.  
  172. return response()->json([
  173. 'success' => 'false',
  174. 'message' => current($validator->getErrors()),
  175. ]);
  176. }
  177.  
  178. /**
  179. * Изменяет рейтинг
  180. *
  181. * @param Request $request
  182. *
  183. * @return JsonResponse
  184. * @throws Exception
  185. */
  186. public function rating(Request $request): JsonResponse
  187. {
  188. $types = [
  189. Post::$morphName,
  190. Article::$morphName,
  191. Photo::$morphName,
  192. Offer::$morphName,
  193. News::$morphName,
  194. Down::$morphName,
  195. ];
  196.  
  197. $id = int($request->input('id'));
  198. $type = $request->input('type');
  199. $vote = $request->input('vote');
  200.  
  201. if ($request->input('_token') !== csrf_token()) {
  202. return response()->json([
  203. 'success' => false,
  204. 'message' => 'Invalid token',
  205. ]);
  206. }
  207.  
  208. if (! in_array($vote, ['+', '-'], true)) {
  209. return response()->json([
  210. 'success' => false,
  211. 'message' => 'Invalid rating',
  212. ]);
  213. }
  214.  
  215. if (! in_array($type, $types, true)) {
  216. return response()->json([
  217. 'success' => false,
  218. 'message' => 'Type invalid',
  219. ]);
  220. }
  221.  
  222. /** @var BaseModel $model */
  223. $model = Relation::getMorphedModel($type);
  224.  
  225. $post = $model::query()
  226. ->where('id', $id)
  227. ->where('user_id', '<>', getUser('id'))
  228. ->first();
  229.  
  230. if (! $post) {
  231. return response()->json([
  232. 'success' => false,
  233. 'message' => 'Record not found',
  234. ]);
  235. }
  236.  
  237. $polling = $post->polling()->first();
  238. $cancel = false;
  239.  
  240. if ($polling) {
  241. if ($polling->vote === $vote) {
  242. return response()->json(['success' => false]);
  243. }
  244.  
  245. $polling->delete();
  246. $cancel = true;
  247. } else {
  248. $post->polling()->create([
  249. 'user_id' => getUser('id'),
  250. 'vote' => $vote,
  251. 'created_at' => SITETIME,
  252. ]);
  253. }
  254.  
  255. if ($vote === '+') {
  256. $post->increment('rating');
  257. } else {
  258. $post->decrement('rating');
  259. }
  260.  
  261. return response()->json([
  262. 'success' => true,
  263. 'cancel' => $cancel,
  264. 'rating' => formatNum($post['rating'])->toHtml(),
  265. ]);
  266. }
  267.  
  268. /**
  269. * Загружает изображение
  270. *
  271. * @param Request $request
  272. * @param Validator $validator
  273. *
  274. * @return JsonResponse
  275. */
  276. public function uploadFile(Request $request, Validator $validator): JsonResponse
  277. {
  278. $imageTypes = [
  279. Article::$morphName,
  280. Item::$morphName,
  281. Photo::$morphName,
  282. ];
  283.  
  284. $fileTypes = [
  285. Message::$morphName,
  286. ];
  287.  
  288. $id = int($request->input('id'));
  289. $file = $request->file('file');
  290. $type = $request->input('type');
  291.  
  292. if (! in_array($type, array_merge($imageTypes, $fileTypes), true)) {
  293. return response()->json([
  294. 'success' => false,
  295. 'message' => 'Type invalid',
  296. ]);
  297. }
  298.  
  299. /** @var BaseModel $class */
  300. $class = Relation::getMorphedModel($type);
  301. $isImageType = in_array($type, $imageTypes, true);
  302.  
  303. if ($id) {
  304. $model = $class::query()->find($id);
  305.  
  306. if (! $model) {
  307. return response()->json([
  308. 'success' => false,
  309. 'message' => 'Service not found',
  310. ]);
  311. }
  312. } else {
  313. $model = new $class();
  314. }
  315.  
  316. $countFiles = File::query()
  317. ->where('relate_type', $type)
  318. ->where('relate_id', $id)
  319. ->where('user_id', getUser('id'))
  320. ->count();
  321.  
  322. $validator
  323. ->equal($request->input('_token'), csrf_token(), __('validator.token'))
  324. ->lt($countFiles, setting('maxfiles'), __('validator.files_max', ['max' => setting('maxfiles')]));
  325.  
  326. if ($model->id) {
  327. $validator->true($model->user_id === getUser('id') || isAdmin(), __('ajax.record_not_author'));
  328. }
  329.  
  330. if ($validator->isValid()) {
  331. $rules = [
  332. 'minweight' => 100,
  333. 'maxsize' => setting('filesize'),
  334. 'extensions' => explode(',', setting('file_extensions')),
  335. ];
  336.  
  337. $validator->file($file, $rules, ['files' => __('validator.file_upload_failed')]);
  338. }
  339.  
  340. if ($validator->isValid()) {
  341. $fileData = $model->uploadFile($file);
  342.  
  343. if ($isImageType) {
  344. $imageData = resizeProcess($fileData['path'], ['size' => 100]);
  345. $data = [
  346. 'success' => true,
  347. 'id' => $fileData['id'],
  348. 'path' => $imageData['path'],
  349. 'source' => $imageData['source'],
  350. 'type' => $fileData['type'],
  351. ];
  352. } else {
  353. $data = [
  354. 'success' => true,
  355. 'id' => $fileData['id'],
  356. 'path' => $fileData['path'],
  357. 'name' => $fileData['name'],
  358. 'size' => $fileData['size'],
  359. 'type' => $fileData['type'],
  360. ];
  361. }
  362.  
  363. return response()->json($data);
  364. }
  365.  
  366. return response()->json([
  367. 'success' => false,
  368. 'message' => current($validator->getErrors()),
  369. ]);
  370. }
  371.  
  372. /**
  373. * Удаляет изображение
  374. *
  375. * @param Request $request
  376. * @param Validator $validator
  377. *
  378. * @return JsonResponse
  379. * @throws Exception
  380. */
  381. public function deleteFile(Request $request, Validator $validator): JsonResponse
  382. {
  383. $types = [
  384. Article::$morphName,
  385. Item::$morphName,
  386. Photo::$morphName,
  387. Message::$morphName,
  388. ];
  389.  
  390. $id = int($request->input('id'));
  391. $type = $request->input('type');
  392.  
  393. if (! in_array($type, $types, true)) {
  394. return response()->json([
  395. 'success' => false,
  396. 'message' => 'Type invalid',
  397. ]);
  398. }
  399.  
  400. /** @var File $file */
  401. $file = File::query()
  402. ->where('relate_type', $type)
  403. ->find($id);
  404.  
  405. if (! $file) {
  406. return response()->json([
  407. 'success' => false,
  408. 'message' => 'File not found'
  409. ]);
  410. }
  411.  
  412. $validator->equal($request->input('_token'), csrf_token(), __('validator.token'))
  413. ->true($file->user_id === getUser('id') || isAdmin(), __('ajax.record_not_author'));
  414.  
  415. if ($validator->isValid()) {
  416. $file->delete();
  417.  
  418. return response()->json([
  419. 'success' => true,
  420. 'path' => $file->hash,
  421. ]);
  422. }
  423.  
  424. return response()->json([
  425. 'success' => false,
  426. 'message' => current($validator->getErrors()),
  427. ]);
  428. }
  429.  
  430. /**
  431. * Вставляет стикер
  432. *
  433. * @return JsonResponse
  434. * @throws Exception
  435. */
  436. public function getStickers(): JsonResponse
  437. {
  438. $stickers = Sticker::query()
  439. //->where('category_id', $id)
  440. ->orderBy(DB::raw('CHAR_LENGTH(code)'))
  441. ->orderBy('name')
  442. ->get();
  443.  
  444. $view = view('pages/_stickers_modal', compact('stickers'))->render();
  445.  
  446. return response()->json([
  447. 'success' => true,
  448. 'stickers' => $view,
  449. ]);
  450. }
  451.  
  452. /**
  453. * Является ли запрос ajax
  454. *
  455. * @param Request $request
  456. *
  457. * @return JsonResponse|bool
  458. */
  459. private function checkAjax(Request $request)
  460. {
  461. if (! $request->ajax()) {
  462. return response()->json([
  463. 'success' => false,
  464. 'message' => __('validator.not_ajax'),
  465. ]);
  466. }
  467.  
  468. return true;
  469. }
  470.  
  471. /**
  472. * Возвращает авторизован ли пользователь
  473. *
  474. * @return JsonResponse|bool
  475. */
  476. private function checkAuthorize()
  477. {
  478. if (! getUser()) {
  479. return response()->json([
  480. 'success' => false,
  481. 'message' => __('main.not_authorized'),
  482. ]);
  483. }
  484.  
  485. return true;
  486. }
  487. }