Completed
Push — develop ( a19d95...ea9703 )
by Schlaefer
07:57
created

UploadsController::add()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 43
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 5
eloc 31
nc 5
nop 0
dl 0
loc 43
rs 9.1128
c 1
b 0
f 1
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
        $userId = (int)$this->getRequest()->getData('userId');
81
        /** @var User */
82
        $user = $this->Users->get($userId);
83
        $permission = $this->CurrentUser->permission(
84
            'saito.plugin.uploader.add',
85
            (new ResourceAI())->onRole($user->getRole())->onOwner($user->getId())
86
        );
87
        if (!$permission) {
88
            throw new SaitoForbiddenException(
89
                sprintf('Attempt to add uploads for "%s".', $userId),
90
                ['CurrentUser' => $this->CurrentUser]
91
            );
92
        }
93
94
        $submitted = $this->request->getData('upload.0.file');
95
        if (!is_array($submitted)) {
96
            throw new GenericApiException(__d('image_uploader', 'add.failure'));
97
        }
98
        $parts = explode('.', $submitted['name']);
99
        $ext = array_pop($parts);
100
        $name = $this->CurrentUser->getId() .
101
                '_' .
102
                substr(Security::hash($submitted['name'], 'sha256'), 32) .
103
                '.' .
104
                $ext;
105
        $data = [
106
            'document' => $submitted,
107
            'name' => $name,
108
            'title' => $submitted['name'],
109
            'size' => $submitted['size'],
110
            'user_id' => $userId,
111
        ];
112
        $document = $this->Uploads->newEntity($data);
113
114
        if (!$this->Uploads->save($document)) {
115
            $errors = $document->getErrors();
116
            $msg = $errors ? current(current($errors)) : null;
117
            throw new GenericApiException($msg);
118
        }
119
120
        $this->set('image', $document);
121
    }
122
123
    /**
124
     * Deletes an upload
125
     *
126
     * @param int $imageId the ID of the image to delete
127
     * @return void
128
     */
129
    public function delete($imageId)
130
    {
131
        /** @var Upload */
132
        $upload = $this->Uploads->get($imageId, ['contain' => ['Users']]);
133
        $permission = $this->CurrentUser->permission(
134
            'saito.plugin.uploader.delete',
135
            (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...
136
        );
137
        if (!$permission) {
138
            throw new SaitoForbiddenException(
139
                sprintf('Attempt to delete upload "%s".', $imageId),
140
                ['CurrentUser' => $this->CurrentUser]
141
            );
142
        }
143
144
        if (!$this->Uploads->delete($upload)) {
145
            $msg = __d('image_uploader', 'delete.failure');
146
            throw new GenericApiException($msg);
147
        }
148
149
        Cache::delete((string)$imageId, 'uploadsThumbnails');
150
151
        $this->autoRender = false;
152
        $this->response = $this->response->withStatus(204);
153
    }
154
}
155