Completed
Push — master ( 4debaf...52a093 )
by Iurii
02:33
created

Credential::addSubmittedCredential()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 7
nc 2
nop 0
1
<?php
2
3
/**
4
 * @package Backup
5
 * @author Iurii Makukh <[email protected]>
6
 * @copyright Copyright (c) 2015, Iurii Makukh
7
 * @license https://www.gnu.org/licenses/gpl.html GNU/GPLv3
8
 */
9
10
namespace gplcart\modules\gapi\controllers;
11
12
use Exception;
13
use gplcart\core\models\FileTransfer as FileTransferModel;
14
use gplcart\modules\gapi\models\Credential as ModuleGapiCredentialModel;
15
use gplcart\core\controllers\backend\Controller as BackendController;
16
17
/**
18
 * Handles incoming requests and outputs data related to Google API credentials
19
 */
20
class Credential extends BackendController
21
{
22
23
    /**
24
     * Credential model class instance
25
     * @var \gplcart\modules\gapi\models\Credential $credential
26
     */
27
    protected $credential;
28
29
    /**
30
     * File transfer module instance
31
     * @var \gplcart\core\models\FileTransfer $file_transfer
32
     */
33
    protected $file_transfer;
34
35
    /**
36
     * Pager limit
37
     * @var array
38
     */
39
    protected $data_limit;
40
41
    /**
42
     * The current updating credential
43
     * @var array
44
     */
45
    protected $data_credential = array();
46
47
    /**
48
     * Credential type
49
     * @var string
50
     */
51
    protected $data_type;
52
53
    /**
54
     * @param ModuleGapiCredentialModel $credential
55
     * @param FileTransferModel $file_transfer
56
     */
57
    public function __construct(ModuleGapiCredentialModel $credential, FileTransferModel $file_transfer)
58
    {
59
        parent::__construct();
60
61
        $this->credential = $credential;
62
        $this->file_transfer = $file_transfer;
63
    }
64
65
    /**
66
     * Route page callback
67
     * Displays the add credential page
68
     * @param string $type
69
     */
70
    public function addCredential($type)
71
    {
72
        $this->data_type = $type;
73
74
        $this->setTitleEditCredential();
75
        $this->setBreadcrumbEditCredential();
76
77
        $this->credential->callHandler($type, 'edit');
78
    }
79
80
    /**
81
     * Handler callback
82
     * Edit "API key" credential page
83
     */
84
    public function editKeyCredential()
85
    {
86
        if ($this->validateKeyCredential()) {
87
            $this->saveCredential();
88
        }
89
90
        $this->output('gapi|credential/edit/key');
91
    }
92
93
    /**
94
     * Handler callback
95
     * Edit "OAuth" credential page
96
     */
97
    public function editOauthCredential()
98
    {
99
        if ($this->validateOauthCredential()) {
100
            $this->saveCredential();
101
        }
102
103
        $this->output('gapi|credential/edit/oauth');
104
    }
105
106
    /**
107
     * Handler callback
108
     * Edit "Service" credential page
109
     */
110
    public function editServiceCredential()
111
    {
112
        if ($this->validateServiceCredential()) {
113
            $this->saveCredential();
114
        }
115
116
        $this->output('gapi|credential/edit/service');
117
    }
118
119
    /**
120
     * Route page callback
121
     * Displays the edit credential page
122
     * @param int $credential_id
123
     */
124
    public function editCredential($credential_id)
125
    {
126
        $this->setCredential($credential_id);
127
128
        $this->setTitleEditCredential();
129
        $this->setBreadcrumbEditCredential();
130
131
        $this->setData('credential', $this->data_credential);
132
133
        $this->submitDeleteCredential();
134
        $this->credential->callHandler($this->data_credential['type'], 'edit');
135
    }
136
137
    /**
138
     * Sets the credential data
139
     * @param $credential_id
140
     */
141
    protected function setCredential($credential_id)
142
    {
143
        if (is_numeric($credential_id)) {
144
            $this->data_credential = $this->credential->get($credential_id);
145
            if (empty($this->data_credential)) {
146
                $this->outputHttpStatus(404);
147
            }
148
        }
149
    }
150
151
    /**
152
     * Set titles on the edit credential page
153
     */
154
    protected function setTitleEditCredential()
155
    {
156
        if (isset($this->data_credential['name'])) {
157
            $text = $this->text('Edit %name', array('%name' => $this->data_credential['name']));
158
        } else {
159
            $text = $this->text('Add credential');
160
        }
161
162
        $this->setTitle($text);
163
    }
164
165
    /**
166
     * Set breadcrumbs on the edit credential page
167
     */
168
    protected function setBreadcrumbEditCredential()
169
    {
170
        $breadcrumbs = array();
171
172
        $breadcrumbs[] = array(
173
            'url' => $this->url('admin'),
174
            'text' => $this->text('Dashboard')
175
        );
176
177
        $breadcrumbs[] = array(
178
            'text' => $this->text('Google API credentials'),
179
            'url' => $this->url('admin/report/gapi')
180
        );
181
182
        $this->setBreadcrumbs($breadcrumbs);
183
    }
184
185
    /**
186
     * Validates "API key" credential data
187
     * @return bool
188
     */
189
    protected function validateKeyCredential()
190
    {
191
        if (!$this->isPosted('save')) {
192
            return false;
193
        }
194
195
        $this->setSubmitted('credential');
196
        $this->validateElement(array('name' => $this->text('Name')), 'length', array(1, 255));
197
        $this->validateElement(array('data.key' => $this->text('Key')), 'length', array(1, 255));
198
199
        return !$this->hasErrors();
200
    }
201
202
    /**
203
     * Validates "OAuth" credential data
204
     * @return bool
205
     */
206
    protected function validateOauthCredential()
207
    {
208
        if (!$this->isPosted('save')) {
209
            return false;
210
        }
211
212
        $this->setSubmitted('credential');
213
        $this->validateElement(array('name' => $this->text('Name')), 'length', array(1, 255));
214
        $this->validateElement(array('data.id' => $this->text('Client ID')), 'length', array(1, 255));
215
        $this->validateElement(array('data.secret' => $this->text('Client secret')), 'length', array(1, 255));
216
217
        return !$this->hasErrors();
218
    }
219
220
    /**
221
     * Validates "Service" credential data
222
     * @return bool
223
     */
224
    protected function validateServiceCredential()
225
    {
226
        if (!$this->isPosted('save')) {
227
            return false;
228
        }
229
230
        $this->setSubmitted('credential');
231
        $this->validateElement(array('name' => $this->text('Name')), 'length', array(1, 255));
232
        $this->validateFileUploadCredential();
233
234
        return !$this->hasErrors();
235
    }
236
237
    /**
238
     * Validates JSON file upload
239
     * @return bool
240
     */
241
    protected function validateFileUploadCredential()
242
    {
243
        $upload = $this->request->file('file');
244
245
        if (empty($upload)) {
246
247
            if (!isset($this->data_credential['credential_id'])) {
248
                $this->setError('data.file', $this->text('File is required'));
249
                return false;
250
            }
251
252
            return null;
253
        }
254
255
        if ($this->isError()) {
256
            return null;
257
        }
258
259
        $result = $this->file_transfer->upload($upload, false, gplcart_file_private_module('gapi'));
260
261
        if ($result !== true) {
262
            $this->setError('data.file', $result);
263
            return false;
264
        }
265
266
        $file = $this->file_transfer->getTransferred();
267
        $decoded = json_decode(file_get_contents($file), true);
268
269
        if (empty($decoded['private_key'])) {
270
            unlink($file);
271
            $this->setError('data.file', $this->text('Failed to read JSON file'));
272
            return false;
273
        }
274
275
        if (isset($this->data_credential['data']['file'])) {
276
            $existing = gplcart_file_absolute($this->data_credential['data']['file']);
277
            if (file_exists($existing)) {
278
                unlink($existing);
279
            }
280
        }
281
282
        $this->setSubmitted('data.file', gplcart_file_relative($file));
283
        return true;
284
    }
285
286
    /**
287
     * Saves the submitted credential data
288
     */
289
    protected function saveCredential()
290
    {
291
        if (isset($this->data_credential['credential_id'])) {
292
            $this->updateSubmittedCredential();
293
        } else {
294
            $this->addSubmittedCredential();
295
        }
296
    }
297
298
    /**
299
     * Updates a submitted credential
300
     */
301
    protected function updateSubmittedCredential()
302
    {
303
        $this->controlAccess('module_gapi_credential_edit');
304
305
        if ($this->credential->update($this->data_credential['credential_id'], $this->getSubmitted())) {
306
            $this->redirect('admin/report/gapi', $this->text('Credential has been updated'), 'success');
307
        }
308
309
        $this->redirect('', $this->text('Credential has not been updated'), 'warning');
310
    }
311
312
    /**
313
     * Adds a submitted credential
314
     */
315
    protected function addSubmittedCredential()
316
    {
317
        $this->controlAccess('module_gapi_credential_add');
318
319
        $submitted = $this->getSubmitted();
320
        $submitted['type'] = $this->data_type;
321
322
        if ($this->credential->add($submitted)) {
323
            $this->redirect('admin/report/gapi', $this->text('Credential has been added'), 'success');
324
        }
325
326
        $this->redirect('', $this->text('Credential has not been added'), 'warning');
327
    }
328
329
    /**
330
     * Delete a submitted credential
331
     */
332
    protected function submitDeleteCredential()
333
    {
334
        if ($this->isPosted('delete') && isset($this->data_credential['credential_id'])) {
335
336
            $this->controlAccess('module_gapi_credential_delete');
337
338
            if ($this->credential->callHandler($this->data_credential['type'], 'delete', array(
339
                $this->data_credential['credential_id']))) {
340
                $this->redirect('admin/report/gapi', $this->text('Credential has been deleted'), 'success');
341
            }
342
343
            $this->redirect('', $this->text('Credential has not been deleted'), 'warning');
344
        }
345
    }
346
347
    /**
348
     * Route callback
349
     * Displays the credential overview page
350
     */
351
    public function listCredential()
352
    {
353
        $this->actionListCredential();
354
        $this->setTitleListCredential();
355
        $this->setBreadcrumbListCredential();
356
357
        $this->setFilterListCredential();
358
        $this->setPagerListCredential();
359
360
        $this->setData('credentials', $this->getListCredential());
361
        $this->setData('handlers', $this->credential->getHandlers());
362
        $this->outputListCredential();
363
    }
364
365
    /**
366
     * Applies an action to the selected credentials
367
     */
368
    protected function actionListCredential()
369
    {
370
        list($selected, $action) = $this->getPostedAction();
371
372
        $deleted = 0;
373
374
        foreach ($selected as $id) {
375
            if ($action === 'delete' && $this->access('module_gapi_credential_delete')) {
376
                $credential = $this->credential->get($id);
377
                $deleted += (int) $this->credential->callHandler($credential['type'], 'delete', array(
378
                    $credential['credential_id']));
379
            }
380
        }
381
382
        if ($deleted > 0) {
383
            $message = $this->text('Deleted %num item(s)', array('%num' => $deleted));
384
            $this->setMessage($message, 'success');
385
        }
386
    }
387
388
    /**
389
     * Sets filter parameters
390
     */
391
    protected function setFilterListCredential()
392
    {
393
        $this->setFilter(array('created', 'modified', 'name', 'credential_id', 'type'));
394
    }
395
396
    /**
397
     * Sets pager
398
     * @return array
399
     */
400
    protected function setPagerListCredential()
401
    {
402
        $options = $this->query_filter;
403
        $options['count'] = true;
404
405
        $pager = array(
406
            'query' => $this->query_filter,
407
            'total' => (int) $this->credential->getList($options)
408
        );
409
410
        return $this->data_limit = $this->setPager($pager);
411
    }
412
413
    /**
414
     * Returns an array of credentials
415
     * @return array
416
     */
417
    protected function getListCredential()
418
    {
419
        $options = $this->query_filter;
420
        $options['limit'] = $this->data_limit;
421
422
        return $this->credential->getList($options);
423
    }
424
425
    /**
426
     * Sets title on the credential overview page
427
     */
428
    protected function setTitleListCredential()
429
    {
430
        $this->setTitle($this->text('Google API credentials'));
431
    }
432
433
    /**
434
     * Sets breadcrumbs on the credential overview page
435
     */
436
    protected function setBreadcrumbListCredential()
437
    {
438
        $breadcrumb = array(
439
            'url' => $this->url('admin'),
440
            'text' => $this->text('Dashboard')
441
        );
442
443
        $this->setBreadcrumb($breadcrumb);
444
    }
445
446
    /**
447
     * Render and output the credential overview page
448
     */
449
    protected function outputListCredential()
450
    {
451
        $this->output('gapi|credential/list');
452
    }
453
454
}
455