1<?php
2
3// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
4// See the LICENCE file in the repository root for full licence text.
5
6namespace App\Http\Controllers\Forum;
7
8use App\Exceptions\ImageProcessorException;
9use App\Models\Forum\Forum;
10use App\Models\Forum\ForumCover;
11use App\Transformers\Forum\ForumCoverTransformer;
12use Auth;
13use Request;
14
15class ForumCoversController extends Controller
16{
17 public function __construct()
18 {
19 parent::__construct();
20
21 $this->middleware('auth', ['only' => [
22 'destroy',
23 'store',
24 'update',
25 ]]);
26
27 $this->middleware(function ($request, $next) {
28 if (Auth::check() && !Auth::user()->isAdmin()) {
29 abort(403);
30 }
31
32 return $next($request);
33 });
34 }
35
36 public function store()
37 {
38 if (Request::hasFile('cover_file') !== true) {
39 abort(422);
40 }
41
42 $forum = Forum::findOrFail(Request::input('forum_id'));
43
44 if ($forum->cover !== null) {
45 abort(422);
46 }
47
48 try {
49 $cover = ForumCover::upload(
50 Request::file('cover_file')->getRealPath(),
51 Auth::user(),
52 $forum
53 );
54 } catch (ImageProcessorException $e) {
55 return error_popup($e->getMessage());
56 }
57
58 return json_item($cover, new ForumCoverTransformer());
59 }
60
61 public function destroy($id)
62 {
63 $cover = ForumCover::find($id);
64
65 if ($cover !== null) {
66 $cover->deleteWithFile();
67 }
68
69 return json_item($cover, new ForumCoverTransformer());
70 }
71
72 public function update($id)
73 {
74 $cover = ForumCover::findOrFail($id);
75
76 if (Request::hasFile('cover_file') === true) {
77 try {
78 $cover = $cover->updateFile(
79 Request::file('cover_file')->getRealPath(),
80 Auth::user()
81 );
82 } catch (ImageProcessorException $e) {
83 return error_popup($e->getMessage());
84 }
85 }
86
87 return json_item($cover, new ForumCoverTransformer());
88 }
89}