Passed
Pull Request — master (#77)
by Daniel
36:15
created

SettingsController::createErrorResponse()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 7
c 1
b 0
f 0
dl 0
loc 12
ccs 0
cts 8
cp 0
rs 10
cc 2
nc 2
nop 2
crap 6
1
<?php
2
/**
3
 * CMS Pico - Create websites using Pico CMS for Nextcloud.
4
 *
5
 * @copyright Copyright (c) 2017, Maxence Lange (<[email protected]>)
6
 * @copyright Copyright (c) 2019, Daniel Rudolf (<[email protected]>)
7
 *
8
 * @license GNU AGPL version 3 or any later version
9
 *
10
 * This program is free software: you can redistribute it and/or modify
11
 * it under the terms of the GNU Affero General Public License as
12
 * published by the Free Software Foundation, either version 3 of the
13
 * License, or (at your option) any later version.
14
 *
15
 * This program is distributed in the hope that it will be useful,
16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
 * GNU Affero General Public License for more details.
19
 *
20
 * You should have received a copy of the GNU Affero General Public License
21
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22
 */
23
24
declare(strict_types=1);
25
26
namespace OCA\CMSPico\Controller;
27
28
use OCA\CMSPico\AppInfo\Application;
29
use OCA\CMSPico\Exceptions\PluginAlreadyExistsException;
30
use OCA\CMSPico\Exceptions\PluginNotFoundException;
31
use OCA\CMSPico\Exceptions\TemplateAlreadyExistsException;
32
use OCA\CMSPico\Exceptions\TemplateNotCompatibleException;
33
use OCA\CMSPico\Exceptions\TemplateNotFoundException;
34
use OCA\CMSPico\Exceptions\ThemeAlreadyExistsException;
35
use OCA\CMSPico\Exceptions\ThemeNotCompatibleException;
36
use OCA\CMSPico\Exceptions\ThemeNotFoundException;
37
use OCA\CMSPico\Exceptions\WebsiteExistsException;
38
use OCA\CMSPico\Exceptions\WebsiteForeignOwnerException;
39
use OCA\CMSPico\Exceptions\WebsiteInvalidDataException;
40
use OCA\CMSPico\Exceptions\WebsiteInvalidOwnerException;
41
use OCA\CMSPico\Exceptions\WebsiteNotFoundException;
42
use OCA\CMSPico\Model\Website;
43
use OCA\CMSPico\Service\ConfigService;
44
use OCA\CMSPico\Service\PluginsService;
45
use OCA\CMSPico\Service\TemplatesService;
46
use OCA\CMSPico\Service\ThemesService;
47
use OCA\CMSPico\Service\WebsitesService;
48
use OCP\AppFramework\Controller;
49
use OCP\AppFramework\Http;
50
use OCP\AppFramework\Http\DataResponse;
51
use OCP\IL10N;
52
use OCP\ILogger;
53
use OCP\IRequest;
54
55
class SettingsController extends Controller
56
{
57
	/** @var string */
58
	private $userId;
59
60
	/** @var IL10N */
61
	private $l10n;
62
63
	/** @var ILogger */
64
	private $logger;
65
66
	/** @var ConfigService */
67
	private $configService;
68
69
	/** @var TemplatesService */
70
	private $templatesService;
71
72
	/** @var ThemesService */
73
	private $themesService;
74
75
	/** @var PluginsService */
76
	private $pluginsService;
77
78
	/** @var WebsitesService */
79
	private $websitesService;
80
81
	/**
82
	 * SettingsController constructor.
83
	 *
84
	 * @param IRequest         $request
85
	 * @param string           $userId
86
	 * @param IL10N            $l10n
87
	 * @param ILogger          $logger
88
	 * @param ConfigService    $configService
89
	 * @param TemplatesService $templatesService
90
	 * @param ThemesService    $themesService
91
	 * @param PluginsService   $pluginsService
92
	 * @param WebsitesService  $websitesService
93
	 */
94 1
	public function __construct(
95
		IRequest $request,
96
		$userId,
97
		IL10N $l10n,
98
		ILogger $logger,
99
		ConfigService $configService,
100
		TemplatesService $templatesService,
101
		ThemesService $themesService,
102
		PluginsService $pluginsService,
103
		WebsitesService $websitesService
104
	) {
105 1
		parent::__construct(Application::APP_NAME, $request);
106
107 1
		$this->userId = $userId;
108 1
		$this->l10n = $l10n;
109 1
		$this->logger = $logger;
110 1
		$this->configService = $configService;
111 1
		$this->templatesService = $templatesService;
112 1
		$this->themesService = $themesService;
113 1
		$this->pluginsService = $pluginsService;
114 1
		$this->websitesService = $websitesService;
115 1
	}
116
117
	/**
118
	 * @NoAdminRequired
119
	 *
120
	 * @return DataResponse
121
	 */
122
	public function getPersonalWebsites(): DataResponse
123
	{
124
		$data = [ 'websites' => $this->websitesService->getWebsitesFromUser($this->userId) ];
125
		return new DataResponse($data, Http::STATUS_OK);
126
	}
127
128
	/**
129
	 * @NoAdminRequired
130
	 *
131
	 * @param array<string,string> $data
132
	 *
133
	 * @return DataResponse
134
	 */
135
	public function createPersonalWebsite(array $data): DataResponse
136
	{
137
		try {
138
			$website = (new Website())
139
				->setName($data['name'])
140
				->setUserId($this->userId)
141
				->setSite($data['site'])
142
				->setTheme($data['theme'])
143
				->setPath($data['path'])
144
				->setTemplateSource($data['template']);
145
146
			$this->websitesService->createWebsite($website);
147
148
			return $this->getPersonalWebsites();
149
		} catch (\Exception $e) {
150
			$error = [];
151
			if ($e instanceof WebsiteExistsException) {
152
				$error['error'] = [ 'field' => 'site', 'message' => $this->l10n->t('Website exists.') ];
153
			} elseif ($e instanceof WebsiteInvalidOwnerException) {
154
				$error['error'] = [ 'field' => 'user', 'message' => $this->l10n->t('No permission.') ];
155
			} elseif (($e instanceof WebsiteInvalidDataException) && $e->getField()) {
156
				$error['error'] = [ 'field' => $e->getField(), 'message' => $e->getMessage() ];
157
			} elseif ($e instanceof ThemeNotFoundException) {
158
				$error['error'] = [ 'field' => 'theme', 'message' => $this->l10n->t('Theme not found.') ];
159
			} elseif ($e instanceof ThemeNotCompatibleException) {
160
				$error['error'] = [ 'field' => 'theme', 'message' => $this->l10n->t($e->getReason()) ];
161
			} elseif ($e instanceof TemplateNotFoundException) {
162
				$error['error'] = [ 'field' => 'template', 'message' => $this->l10n->t('Template not found.') ];
163
			} elseif ($e instanceof TemplateNotCompatibleException) {
164
				$error['error'] = [ 'field' => 'template', 'message' => $this->l10n->t($e->getReason()) ];
165
			}
166
167
			return $this->createErrorResponse($e, $error);
168
		}
169
	}
170
171
	/**
172
	 * @NoAdminRequired
173
	 *
174
	 * @param int     $siteId
175
	 * @param mixed[] $data
176
	 *
177
	 * @return DataResponse
178
	 */
179
	public function updatePersonalWebsite(int $siteId, array $data): DataResponse
180
	{
181
		try {
182
			$website = $this->websitesService->getWebsiteFromId($siteId);
183
184
			$website->assertOwnedBy($this->userId);
185
186
			foreach ($data as $key => $value) {
187
				switch ($key) {
188
					case 'type':
189
						$website->setType((int) $value);
190
						break;
191
192
					case 'theme':
193
						$website->setTheme($value);
194
						break;
195
196
					default:
197
						throw new WebsiteInvalidDataException();
198
				}
199
			}
200
201
			$this->websitesService->updateWebsite($website);
202
203
			return $this->getPersonalWebsites();
204
		} catch (\Exception $e) {
205
			$error = [];
206
			if (($e instanceof WebsiteNotFoundException) || ($e instanceof WebsiteForeignOwnerException)) {
207
				$error['error'] = [ 'field' => 'identifier', 'message' => $this->l10n->t('Website not found.') ];
208
			} elseif ($e instanceof WebsiteInvalidDataException) {
209
				$error['error'] = [ 'field' => $e->getField(), 'message' => $e->getMessage() ];
210
			} elseif ($e instanceof ThemeNotFoundException) {
211
				$error['error'] = [ 'field' => 'theme', 'message' => $this->l10n->t('Theme not found.') ];
212
			} elseif ($e instanceof ThemeNotCompatibleException) {
213
				$error['error'] = [ 'field' => 'theme', 'message' => $this->l10n->t($e->getReason()) ];
214
			} elseif ($e instanceof TemplateNotFoundException) {
215
				$error['error'] = [ 'field' => 'template', 'message' => $this->l10n->t('Template not found.') ];
216
			} elseif ($e instanceof TemplateNotCompatibleException) {
217
				$error['error'] = [ 'field' => 'template', 'message' => $this->l10n->t($e->getReason()) ];
218
			}
219
220
			return $this->createErrorResponse($e, $error);
221
		}
222
	}
223
224
	/**
225
	 * @NoAdminRequired
226
	 *
227
	 * @param int $siteId
228
	 *
229
	 * @return DataResponse
230
	 */
231
	public function removePersonalWebsite(int $siteId): DataResponse
232
	{
233
		try {
234
			$website = $this->websitesService->getWebsiteFromId($siteId);
235
236
			$website->assertOwnedBy($this->userId);
237
238
			$this->websitesService->deleteWebsite($website);
239
240
			return $this->getPersonalWebsites();
241
		} catch (WebsiteNotFoundException $e) {
242
			return $this->createErrorResponse($e, [ 'error' => $this->l10n->t('Website not found.') ]);
243
		} catch (WebsiteForeignOwnerException $e) {
244
			return $this->createErrorResponse($e, [ 'error' => $this->l10n->t('Website not found.') ]);
245
		} catch (\Exception $e) {
246
			return $this->createErrorResponse($e);
247
		}
248
	}
249
250
	/**
251
	 * @return DataResponse
252
	 */
253 1
	public function getTemplates(): DataResponse
254
	{
255
		$data = [
256 1
			'systemItems' => $this->templatesService->getSystemTemplates(),
257 1
			'customItems' => $this->templatesService->getCustomTemplates(),
258 1
			'newItems' => $this->templatesService->getNewCustomTemplates(),
259
		];
260
261 1
		return new DataResponse($data, Http::STATUS_OK);
262
	}
263
264
	/**
265
	 * @param string $item
266
	 *
267
	 * @return DataResponse
268
	 */
269 1
	public function addCustomTemplate(string $item): DataResponse
270
	{
271
		try {
272 1
			$this->templatesService->registerCustomTemplate($item);
273
274 1
			return $this->getTemplates();
275
		} catch (TemplateNotFoundException $e) {
276
			return $this->createErrorResponse($e, [ 'error' => $this->l10n->t('Template not found.') ]);
277
		} catch (TemplateAlreadyExistsException $e) {
278
			return $this->createErrorResponse($e, [ 'error' => $this->l10n->t('Template exists already.') ]);
279
		} catch (\Exception $e) {
280
			return $this->createErrorResponse($e);
281
		}
282
	}
283
284
	/**
285
	 * @param string $item
286
	 *
287
	 * @return DataResponse
288
	 */
289 1
	public function removeCustomTemplate(string $item): DataResponse
290
	{
291
		try {
292 1
			$this->templatesService->removeCustomTemplate($item);
293
294 1
			return $this->getTemplates();
295
		} catch (TemplateNotFoundException $e) {
296
			return $this->createErrorResponse($e, [ 'error' => $this->l10n->t('Template not found.') ]);
297
		} catch (\Exception $e) {
298
			return $this->createErrorResponse($e);
299
		}
300
	}
301
302
	/**
303
	 * @param string $item
304
	 * @param string $name
305
	 *
306
	 * @return DataResponse
307
	 */
308
	public function copyTemplate(string $item, string $name): DataResponse
309
	{
310
		try {
311
			$this->templatesService->copyTemplate($item, $name);
312
313
			return $this->getTemplates();
314
		} catch (TemplateNotFoundException $e) {
315
			return $this->createErrorResponse($e, [ 'error' => $this->l10n->t('Template not found.') ]);
316
		} catch (TemplateAlreadyExistsException $e) {
317
			return $this->createErrorResponse($e, [ 'error' => $this->l10n->t('Template exists already.') ]);
318
		} catch (\Exception $e) {
319
			return $this->createErrorResponse($e);
320
		}
321
	}
322
323
	/**
324
	 * @return DataResponse
325
	 */
326 1
	public function getThemes(): DataResponse
327
	{
328
		$data = [
329 1
			'systemItems' => $this->themesService->getSystemThemes(),
330 1
			'customItems' => $this->themesService->getCustomThemes(),
331 1
			'newItems' => $this->themesService->getNewCustomThemes(),
332
		];
333
334 1
		return new DataResponse($data, Http::STATUS_OK);
335
	}
336
337
	/**
338
	 * @param string $item
339
	 *
340
	 * @return DataResponse
341
	 */
342 1
	public function addCustomTheme(string $item): DataResponse
343
	{
344
		try {
345 1
			$this->themesService->publishCustomTheme($item);
346
347 1
			return $this->getThemes();
348
		} catch (ThemeNotFoundException $e) {
349
			return $this->createErrorResponse($e, [ 'error' => $this->l10n->t('Theme not found.') ]);
350
		} catch (ThemeAlreadyExistsException $e) {
351
			return $this->createErrorResponse($e, [ 'error' => $this->l10n->t('Theme exists already.') ]);
352
		} catch (\Exception $e) {
353
			return $this->createErrorResponse($e);
354
		}
355
	}
356
357
	/**
358
	 * @param string $item
359
	 *
360
	 * @return DataResponse
361
	 */
362
	public function updateCustomTheme(string $item): DataResponse
363
	{
364
		try {
365
			$this->themesService->depublishCustomTheme($item);
366
			$this->themesService->publishCustomTheme($item);
367
368
			return $this->getThemes();
369
		} catch (ThemeNotFoundException $e) {
370
			return $this->createErrorResponse($e, [ 'error' => $this->l10n->t('Theme not found.') ]);
371
		} catch (\Exception $e) {
372
			return $this->createErrorResponse($e);
373
		}
374
	}
375
376
	/**
377
	 * @param string $item
378
	 *
379
	 * @return DataResponse
380
	 */
381 1
	public function removeCustomTheme(string $item): DataResponse
382
	{
383
		try {
384 1
			$this->themesService->depublishCustomTheme($item);
385
386 1
			return $this->getThemes();
387
		} catch (ThemeNotFoundException $e) {
388
			return $this->createErrorResponse($e, [ 'error' => $this->l10n->t('Theme not found.') ]);
389
		} catch (\Exception $e) {
390
			return $this->createErrorResponse($e);
391
		}
392
	}
393
394
	/**
395
	 * @param string $item
396
	 * @param string $name
397
	 *
398
	 * @return DataResponse
399
	 */
400
	public function copyTheme(string $item, string $name): DataResponse
401
	{
402
		try {
403
			$this->themesService->copyTheme($item, $name);
404
405
			return $this->getThemes();
406
		} catch (ThemeNotFoundException $e) {
407
			return $this->createErrorResponse($e, [ 'error' => $this->l10n->t('Theme not found.') ]);
408
		} catch (ThemeAlreadyExistsException $e) {
409
			return $this->createErrorResponse($e, [ 'error' => $this->l10n->t('Theme exists already.') ]);
410
		} catch (\Exception $e) {
411
			return $this->createErrorResponse($e);
412
		}
413
	}
414
415
	/**
416
	 * @return DataResponse
417
	 */
418
	public function getPlugins(): DataResponse
419
	{
420
		$data = [
421
			'systemItems' => $this->pluginsService->getSystemPlugins(),
422
			'customItems' => $this->pluginsService->getCustomPlugins(),
423
			'newItems' => $this->pluginsService->getNewCustomPlugins(),
424
		];
425
426
		return new DataResponse($data, Http::STATUS_OK);
427
	}
428
429
	/**
430
	 * @param string $item
431
	 *
432
	 * @return DataResponse
433
	 */
434
	public function addCustomPlugin(string $item): DataResponse
435
	{
436
		try {
437
			$this->pluginsService->publishCustomPlugin($item);
438
439
			return $this->getPlugins();
440
		} catch (PluginNotFoundException $e) {
441
			return $this->createErrorResponse($e, [ 'error' => $this->l10n->t('Plugin not found.') ]);
442
		} catch (PluginAlreadyExistsException $e) {
443
			return $this->createErrorResponse($e, [ 'error' => $this->l10n->t('Plugin exists already.') ]);
444
		} catch (\Exception $e) {
445
			return $this->createErrorResponse($e);
446
		}
447
	}
448
449
	/**
450
	 * @param string $item
451
	 *
452
	 * @return DataResponse
453
	 */
454
	public function updateCustomPlugin(string $item): DataResponse
455
	{
456
		try {
457
			$this->pluginsService->depublishCustomPlugin($item);
458
			$this->pluginsService->publishCustomPlugin($item);
459
460
			return $this->getPlugins();
461
		} catch (PluginNotFoundException $e) {
462
			return $this->createErrorResponse($e, [ 'error' => $this->l10n->t('Plugin not found.') ]);
463
		} catch (\Exception $e) {
464
			return $this->createErrorResponse($e);
465
		}
466
	}
467
468
	/**
469
	 * @param string $item
470
	 *
471
	 * @return DataResponse
472
	 */
473
	public function removeCustomPlugin(string $item): DataResponse
474
	{
475
		try {
476
			$this->pluginsService->depublishCustomPlugin($item);
477
478
			return $this->getPlugins();
479
		} catch (PluginNotFoundException $e) {
480
			return $this->createErrorResponse($e, [ 'error' => $this->l10n->t('Plugin not found.') ]);
481
		} catch (\Exception $e) {
482
			return $this->createErrorResponse($e);
483
		}
484
	}
485
486
	/**
487
	 * @param array $data
488
	 *
489
	 * @return DataResponse
490
	 */
491
	public function setLimitGroups(array $data): DataResponse
492
	{
493
		try {
494
			if (!isset($data['limit_groups'])) {
495
				throw new \UnexpectedValueException();
496
			}
497
498
			$limitGroups = $data['limit_groups'] ? explode('|', $data['limit_groups']) : [];
499
			$this->websitesService->setLimitGroups($limitGroups);
500
501
			return new DataResponse();
502
		} catch (\Exception $e) {
503
			return $this->createErrorResponse($e);
504
		}
505
	}
506
507
	/**
508
	 * @param array $data
509
	 *
510
	 * @return DataResponse
511
	 */
512
	public function setLinkMode(array $data): DataResponse
513
	{
514
		try {
515
			if (!isset($data['link_mode'])) {
516
				throw new \UnexpectedValueException();
517
			}
518
519
			$this->websitesService->setLinkMode((int) $data['link_mode']);
520
521
			return new DataResponse();
522
		} catch (\Exception $e) {
523
			return $this->createErrorResponse($e);
524
		}
525
	}
526
527
	/**
528
	 * @param \Exception $exception
529
	 * @param array      $data
530
	 *
531
	 * @return DataResponse
532
	 */
533
	private function createErrorResponse(\Exception $exception, array $data = []): DataResponse
534
	{
535
		$this->logger->logException($exception, [ 'app' => Application::APP_NAME, 'level' => 2 ]);
536
537
		$data['status'] = 0;
538
		if (\OC::$server->getSystemConfig()->getValue('debug', false)) {
539
			$data['exception'] = get_class($exception);
540
			$data['exceptionMessage'] = $exception->getMessage();
541
			$data['exceptionCode'] = $exception->getCode();
542
		}
543
544
		return new DataResponse($data, Http::STATUS_INTERNAL_SERVER_ERROR);
545
	}
546
}
547