Completed
Push — master ( e849bf...44b152 )
by Schlaefer
11:58 queued 03:40
created

UploadsController::initialize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * Saito - The Threaded Web Forum
7
 *
8
 * @copyright Copyright (c) the Saito Project Developers
9
 * @link https://github.com/Schlaefer/Saito
10
 * @license http://opensource.org/licenses/MIT
11
 */
12
13
namespace ImageUploader\Controller;
14
15
use Api\Controller\ApiAppController;
16
use Api\Error\Exception\GenericApiException;
17
use App\Model\Entity\User;
18
use Cake\Cache\Cache;
19
use Cake\Utility\Security;
20
use ImageUploader\Model\Entity\Upload;
21
use ImageUploader\Model\Table\UploadsTable;
22
use Saito\Exception\SaitoForbiddenException;
23
use Saito\User\CurrentUser\CurrentUserInterface;
24
use Saito\User\Permission\ResourceAI;
25
26
/**
27
 * Upload Controller
28
 *
29
 * @property CurrentUserInterface $CurrentUser
30
 * @property UploadsTable $Uploads
31
 */
32
class UploadsController extends ApiAppController
33
{
34
    public $helpers = ['ImageUploader.ImageUploader'];
35
36
    /**
37
     * {@inheritDoc}
38
     */
39
    public function initialize()
40
    {
41
        parent::initialize();
42
        $this->loadModel('Users');
43
    }
44
45
    /**
46
     * View uploads
47
     *
48
     * @return void
49
     */
50
    public function index()
51
    {
52
        $userId = (int)$this->getRequest()->getQuery('id');
53
        /** @var User */
54
        $user = $this->Users->get($userId);
55
        $permission = $this->CurrentUser->permission(
56
            'saito.plugin.uploader.view',
57
            (new ResourceAI())->onRole($user->getRole())->onOwner($user->getId())
0 ignored issues
show
Bug introduced by
The method getRole() does not exist on Cake\Datasource\EntityInterface. It seems like you code against a sub-type of Cake\Datasource\EntityInterface such as App\Model\Entity\User. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

57
            (new ResourceAI())->onRole($user->/** @scrutinizer ignore-call */ getRole())->onOwner($user->getId())
Loading history...
Bug introduced by
The method getId() does not exist on Cake\Datasource\EntityInterface. Did you maybe mean get()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

57
            (new ResourceAI())->onRole($user->getRole())->onOwner($user->/** @scrutinizer ignore-call */ getId())

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
58
        );
59
        if (!$permission) {
60
            throw new SaitoForbiddenException(
61
                sprintf('Attempt to index uploads of "%s".', $userId),
62
                ['CurrentUser' => $this->CurrentUser]
63
            );
64
        }
65
66
        $images = $this->Uploads->find()
67
            ->where(['user_id' => $userId])
68
            ->order(['id' => 'DESC'])
69
            ->all();
70
        $this->set('images', $images);
71
    }
72
73
    /**
74
     * Adds a new upload
75
     *
76
     * @return void
77
     */
78
    public function add()
79
    {
80
        $submitted = $this->request->getData('upload.0.file');
81
        if (!is_array($submitted)) {
82
            throw new GenericApiException(__d('image_uploader', 'add.failure'));
83
        }
84
85
        $userId = (int)$this->getRequest()->getData('userId');
86
        /** @var User */
87
        $user = $this->Users->get($userId);
88
        $permission = $this->CurrentUser->permission(
89
            'saito.plugin.uploader.add',
90
            (new ResourceAI())->onRole($user->getRole())->onOwner($user->getId())
91
        );
92
        if (!$permission) {
93
            throw new SaitoForbiddenException(
94
                sprintf('Attempt to add uploads for "%s".', $userId),
95
                ['CurrentUser' => $this->CurrentUser]
96
            );
97
        }
98
99
        $parts = explode('.', $submitted['name']);
100
        $ext = array_pop($parts);
101
        $name = $this->CurrentUser->getId() .
102
                '_' .
103
                substr(Security::hash($submitted['name'], 'sha256'), 32) .
104
                '.' .
105
                $ext;
106
        $data = [
107
            'document' => $submitted,
108
            'name' => $name,
109
            'title' => $submitted['name'],
110
            'size' => $submitted['size'],
111
            'user_id' => $userId,
112
        ];
113
        $document = $this->Uploads->newEntity($data);
114
115
        if (!$this->Uploads->save($document)) {
116
            $errors = $document->getErrors();
117
            $msg = $errors ? current(current($errors)) : null;
118
            throw new GenericApiException($msg);
119
        }
120
121
        $this->set('image', $document);
122
    }
123
124
    /**
125
     * Deletes an upload
126
     *
127
     * @param int $imageId the ID of the image to delete
128
     * @return void
129
     */
130
    public function delete($imageId)
131
    {
132
        /** @var Upload */
133
        $upload = $this->Uploads->get($imageId, ['contain' => ['Users']]);
134
        $permission = $this->CurrentUser->permission(
135
            'saito.plugin.uploader.delete',
136
            (new ResourceAI())->onRole($upload->user->getRole())->onOwner($upload->user->getId())
0 ignored issues
show
Bug introduced by
Accessing user on the interface Cake\Datasource\EntityInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
137
        );
138
        if (!$permission) {
139
            throw new SaitoForbiddenException(
140
                sprintf('Attempt to delete upload "%s".', $imageId),
141
                ['CurrentUser' => $this->CurrentUser]
142
            );
143
        }
144
145
        if (!$this->Uploads->delete($upload)) {
146
            $msg = __d('image_uploader', 'delete.failure');
147
            throw new GenericApiException($msg);
148
        }
149
150
        Cache::delete((string)$imageId, 'uploadsThumbnails');
151
152
        $this->autoRender = false;
153
        $this->response = $this->response->withStatus(204);
154
    }
155
}
156