Passed
Branch wip_sessions (2e0cc8)
by Nils
04:59
created

ItemController::inFoldersAction()   B

Complexity

Conditions 9
Paths 122

Size

Total Lines 81
Code Lines 48

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 48
nc 122
nop 1
dl 0
loc 81
rs 7.4323
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Teampass - a collaborative passwords manager.
4
 * ---
5
 * This library is distributed in the hope that it will be useful,
6
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
7
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
8
 * ---
9
 *
10
 * @project   Teampass
11
 * @version    API
12
 *
13
 * @file      ItemControler.php
14
 * ---
15
 *
16
 * @author    Nils Laumaillé ([email protected])
17
 *
18
 * @copyright 2009-2023 Teampass.net
19
 *
20
 * @license   https://spdx.org/licenses/GPL-3.0-only.html#licenseText GPL-3.0
21
 * ---
22
 *
23
 * @see       https://www.teampass.net
24
 */
25
26
use TeampassClasses\SuperGlobal\SuperGlobal;
27
28
class ItemController extends BaseController
29
{
30
31
32
    /**
33
     * Manage case inFolder - get items inside an array of folders
34
     *
35
     * @param array $userData
36
     */
37
    public function inFoldersAction(array $userData): void
38
    {
39
        $superGlobal = new SuperGlobal();
40
        $strErrorDesc = $responseData = $strErrorHeader = '';
41
        $requestMethod = $superGlobal->get('REQUEST_METHOD', 'SERVER');
42
43
        // get parameters
44
        $arrQueryStringParams = $this->getQueryStringParams();
45
46
        if (strtoupper($requestMethod) === 'GET') {
47
            // define WHERE clause
48
            $sqlExtra = '';
49
            if (empty($userData['folders_list']) === false) {
50
                $userData['folders_list'] = explode(',', $userData['folders_list']);
51
            } else {
52
                $userData['folders_list'] = [];
53
            }
54
55
            // SQL where clause with folders list
56
            if (isset($arrQueryStringParams['folders']) === true) {
57
                // convert the folders to an array
58
                $arrQueryStringParams['folders'] = explode(',', str_replace( array('[',']') , ''  , $arrQueryStringParams['folders']));
59
60
                // ensure to only use the intersection
61
                $foldersList = implode(',', array_intersect($arrQueryStringParams['folders'], $userData['folders_list']));
62
63
                // build sql where clause
64
                if (!empty($foldersList)) {
65
                    // build sql where clause
66
                    $sqlExtra = ' WHERE id_tree IN ('.$foldersList.')';
67
                } else {
68
                    // Send error
69
                    $this->sendOutput(
70
                        json_encode(['error' => 'Folders are mandatory']),
71
                        ['Content-Type: application/json', 'HTTP/1.1 401 Expected parameters not provided']
72
                    );
73
                }
74
            } else {
75
                // Send error
76
                $this->sendOutput(
77
                    json_encode(['error' => 'Folders are mandatory']),
78
                    ['Content-Type: application/json', 'HTTP/1.1 401 Expected parameters not provided']
79
                );
80
            }
81
82
            // SQL LIMIT
83
            $intLimit = 0;
84
            if (isset($arrQueryStringParams['limit']) === true) {
85
                $intLimit = $arrQueryStringParams['limit'];
86
            }
87
88
            // send query
89
            try {
90
                $itemModel = new ItemModel();
91
92
                $arrItems = $itemModel->getItems($sqlExtra, $intLimit, $userData['private_key'], $userData['id']);
93
                if (!empty($arrItems)) {
94
                    $responseData = json_encode($arrItems);
95
                } else {
96
                    $strErrorDesc = 'No content for this label';
97
                    $strErrorHeader = 'HTTP/1.1 204 No Content';
98
                }
99
            } catch (Error $e) {
100
                $strErrorDesc = $e->getMessage().'. Something went wrong! Please contact support.';
101
                $strErrorHeader = 'HTTP/1.1 500 Internal Server Error';
102
            }
103
        } else {
104
            $strErrorDesc = 'Method not supported';
105
            $strErrorHeader = 'HTTP/1.1 422 Unprocessable Entity';
106
        }
107
108
        // send output
109
        if (empty($strErrorDesc) === true) {
110
            $this->sendOutput(
111
                $responseData,
112
                ['Content-Type: application/json', 'HTTP/1.1 200 OK']
113
            );
114
        } else {
115
            $this->sendOutput(
116
                json_encode(['error' => $strErrorDesc]), 
117
                ['Content-Type: application/json', $strErrorHeader]
118
            );
119
        }
120
    }
121
    //end InFoldersAction()
122
123
    /**
124
     * Manage case Add
125
     *
126
     * @param array $userData
127
     */
128
    public function addAction(array $userData)
129
    {
130
        $superGlobal = new SuperGlobal();
131
        $strErrorDesc = $strErrorHeader = '';
132
        $requestMethod = $superGlobal->get('REQUEST_METHOD', 'SERVER');
133
134
        if (strtoupper($requestMethod) === 'POST') {
135
            if (empty($userData['folders_list']) === false) {
136
                $userData['folders_list'] = explode(',', $userData['folders_list']);
137
            } else {
138
                $userData['folders_list'] = [];
139
            }
140
141
            $data = json_decode(file_get_contents("php://input"));
142
143
            if (in_array($data->folderId, $userData['folders_list'])) {
144
                // send query
145
                try {
146
                    $itemModel = new ItemModel();
147
148
                    $itemModel->addItem($data->folderId, $data->userName, $data->hostname, $data->password);
149
                } catch (Error $e) {
150
                    $strErrorDesc = $e->getMessage().'. Something went wrong! Please contact support.';
151
                    $strErrorHeader = 'HTTP/1.1 500 Internal Server Error';
152
                }
153
            } else {
154
                $strErrorDesc = 'Folders are mandatory';
155
                $strErrorHeader = 'HTTP/1.1 401 Expected parameters not provided';
156
            }
157
        } else {
158
            $strErrorDesc = 'Method not supported';
159
            $strErrorHeader = 'HTTP/1.1 422 Unprocessable Entity';
160
        }
161
162
        // send output
163
        if (empty($strErrorDesc) === true) {
164
            $this->sendOutput(
165
                "",
166
                ['Content-Type: application/json', 'HTTP/1.1 201 Created']
167
            );
168
169
            //$this->sendOutput(['HTTP/1.1 201 Created']);
170
        } else {
171
            $this->sendOutput(
172
                json_encode(['error' => $strErrorDesc]),
173
                ['Content-Type: application/json', $strErrorHeader]
174
            );
175
        }
176
    }
177
    //end addAction()
178
179
180
    /**
181
     * Manage case get - get an item
182
     *
183
     * @param array $userData
184
     */
185
    public function getAction(array $userData): void
186
    {
187
        $superGlobal = new SuperGlobal();
188
        $strErrorDesc = '';
189
        $sqlExtra = '';
190
        $responseData = '';
191
        $strErrorHeader = '';
192
        $requestMethod = $superGlobal->get('REQUEST_METHOD', 'SERVER');
193
        $sql_constraint = ' AND (i.id_tree IN ('.$userData['folders_list'].') OR i.id IN ('.$userData['restricted_items_list'].'))';
194
195
        // get parameters
196
        $arrQueryStringParams = $this->getQueryStringParams();
197
198
        if (strtoupper($requestMethod) === 'GET') {
199
            // SQL where clause with item id
200
            if (isset($arrQueryStringParams['id']) === true) {
201
                // build sql where clause by ID
202
                $sqlExtra = ' WHERE i.id = '.$arrQueryStringParams['id'] . $sql_constraint;
203
            } else if (isset($arrQueryStringParams['label']) === true) {
204
                // build sql where clause by LABEL
205
                $sqlExtra = ' WHERE i.label '.(isset($arrQueryStringParams['like']) === true && (int) $arrQueryStringParams['like'] === 1 ? ' LIKE '.$arrQueryStringParams['label'] : ' = '.$arrQueryStringParams['label']) . $sql_constraint;
206
            } else if (isset($arrQueryStringParams['description']) === true) {
207
                // build sql where clause by LABEL
208
                $sqlExtra = ' WHERE i.description '.(isset($arrQueryStringParams['like']) === true && (int) $arrQueryStringParams['like'] === 1 ? ' LIKE '.$arrQueryStringParams['description'] : ' = '.$arrQueryStringParams['description']).$sql_constraint;
209
            } else {
210
                // Send error
211
                $this->sendOutput(
212
                    json_encode(['error' => 'Item id, label or description is mandatory']),
213
                    ['Content-Type: application/json', 'HTTP/1.1 401 Expected parameters not provided']
214
                );
215
            }
216
217
            // send query
218
            try {
219
                $itemModel = new ItemModel();
220
221
                $arrItems = $itemModel->getItems($sqlExtra, 0, $userData['private_key'], $userData['id']);
222
                $responseData = json_encode($arrItems);
223
            } catch (Error $e) {
224
                $strErrorDesc = $e->getMessage().'. Something went wrong! Please contact support.';
225
                $strErrorHeader = 'HTTP/1.1 500 Internal Server Error';
226
            }
227
        } else {
228
            $strErrorDesc = 'Method not supported';
229
            $strErrorHeader = 'HTTP/1.1 422 Unprocessable Entity';
230
        }
231
232
        // send output
233
        if (empty($strErrorDesc) === true) {
234
            $this->sendOutput(
235
                $responseData,
236
                ['Content-Type: application/json', 'HTTP/1.1 200 OK']
237
            );
238
        } else {
239
            $this->sendOutput(
240
                json_encode(['error' => $strErrorDesc]), 
241
                ['Content-Type: application/json', $strErrorHeader]
242
            );
243
        }
244
    }
245
    //end getAction() 
246
}