Passed
Pull Request — master (#77)
by Daniel
24:04
created

SettingsController::getTemplates()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 5
c 0
b 0
f 0
dl 0
loc 9
ccs 5
cts 5
cp 1
rs 10
cc 1
nc 1
nop 0
crap 1
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\TemplateNotFoundException;
30
use OCA\CMSPico\Exceptions\ThemeNotCompatibleException;
31
use OCA\CMSPico\Exceptions\ThemeNotFoundException;
32
use OCA\CMSPico\Exceptions\WebsiteExistsException;
33
use OCA\CMSPico\Exceptions\WebsiteForeignOwnerException;
34
use OCA\CMSPico\Exceptions\WebsiteInvalidDataException;
35
use OCA\CMSPico\Exceptions\WebsiteInvalidOwnerException;
36
use OCA\CMSPico\Exceptions\WebsiteNotFoundException;
37
use OCA\CMSPico\Model\Website;
38
use OCA\CMSPico\Service\ConfigService;
39
use OCA\CMSPico\Service\PluginsService;
40
use OCA\CMSPico\Service\TemplatesService;
41
use OCA\CMSPico\Service\ThemesService;
42
use OCA\CMSPico\Service\WebsitesService;
43
use OCP\AppFramework\Controller;
44
use OCP\AppFramework\Http;
45
use OCP\AppFramework\Http\DataResponse;
46
use OCP\IL10N;
47
use OCP\ILogger;
48
use OCP\IRequest;
49
50
class SettingsController extends Controller
51
{
52
	/** @var string */
53
	private $userId;
54
55
	/** @var IL10N */
56
	private $l10n;
57
58
	/** @var ILogger */
59
	private $logger;
60
61
	/** @var ConfigService */
62
	private $configService;
63
64
	/** @var TemplatesService */
65
	private $templatesService;
66
67
	/** @var ThemesService */
68
	private $themesService;
69
70
	/** @var PluginsService */
71
	private $pluginsService;
72
73
	/** @var WebsitesService */
74
	private $websitesService;
75
76
	/**
77
	 * SettingsController constructor.
78
	 *
79
	 * @param IRequest         $request
80
	 * @param string           $userId
81
	 * @param IL10N            $l10n
82
	 * @param ILogger          $logger
83
	 * @param ConfigService    $configService
84
	 * @param TemplatesService $templatesService
85
	 * @param ThemesService    $themesService
86
	 * @param PluginsService   $pluginsService
87
	 * @param WebsitesService  $websitesService
88
	 */
89 1
	public function __construct(
90
		IRequest $request,
91
		$userId,
92
		IL10N $l10n,
93
		ILogger $logger,
94
		ConfigService $configService,
95
		TemplatesService $templatesService,
96
		ThemesService $themesService,
97
		PluginsService $pluginsService,
98
		WebsitesService $websitesService
99
	) {
100 1
		parent::__construct(Application::APP_NAME, $request);
101
102 1
		$this->userId = $userId;
103 1
		$this->l10n = $l10n;
104 1
		$this->logger = $logger;
105 1
		$this->configService = $configService;
106 1
		$this->templatesService = $templatesService;
107 1
		$this->themesService = $themesService;
108 1
		$this->pluginsService = $pluginsService;
109 1
		$this->websitesService = $websitesService;
110 1
	}
111
112
	/**
113
	 * @NoAdminRequired
114
	 *
115
	 * @return DataResponse
116
	 */
117
	public function getPersonalWebsites(): DataResponse
118
	{
119
		$data = [ 'websites' => $this->websitesService->getWebsitesFromUser($this->userId) ];
120
		return new DataResponse($data, Http::STATUS_OK);
121
	}
122
123
	/**
124
	 * @NoAdminRequired
125
	 *
126
	 * @param array<string,string> $data
127
	 *
128
	 * @return DataResponse
129
	 */
130
	public function createPersonalWebsite(array $data): DataResponse
131
	{
132
		try {
133
			$website = (new Website())
134
				->setName($data['name'])
135
				->setUserId($this->userId)
136
				->setSite($data['site'])
137
				->setTheme($data['theme'])
138
				->setPath($data['path'])
139
				->setTemplateSource($data['template']);
140
141
			$this->websitesService->createWebsite($website);
142
143
			return $this->getPersonalWebsites();
144
		} catch (\Exception $e) {
145
			$data = [];
146
			if ($e instanceof WebsiteExistsException) {
147
				$data['form_error'] = [ 'field' => 'site', 'message' => $this->l10n->t('Website exists.') ];
148
			} elseif ($e instanceof WebsiteInvalidOwnerException) {
149
				$data['form_error'] = [ 'field' => 'user', 'message' => $this->l10n->t('No permission.') ];
150
			} elseif (($e instanceof WebsiteInvalidDataException) && $e->getField()) {
151
				$data['form_error'] = [ 'field' => $e->getField(), 'message' => $e->getMessage() ];
152
			} elseif ($e instanceof ThemeNotFoundException) {
153
				$data['form_error'] = [ 'field' => 'theme', 'message' => $this->l10n->t('Theme not found.') ];
154
			} elseif ($e instanceof ThemeNotCompatibleException) {
155
				$data['form_error'] = [ 'field' => 'theme', 'message' => $this->l10n->t($e->getReason()) ];
156
			} elseif ($e instanceof TemplateNotFoundException) {
157
				$data['form_error'] = [ 'field' => 'template', 'message' => $this->l10n->t('Template not found.') ];
158
			}
159
160
			return $this->createErrorResponse($e, $data);
161
		}
162
	}
163
164
	/**
165
	 * @NoAdminRequired
166
	 *
167
	 * @param int     $siteId
168
	 * @param mixed[] $data
169
	 *
170
	 * @return DataResponse
171
	 */
172
	public function updatePersonalWebsite(int $siteId, array $data): DataResponse
173
	{
174
		try {
175
			$website = $this->websitesService->getWebsiteFromId($siteId);
176
177
			$website->assertOwnedBy($this->userId);
178
179
			foreach ($data as $key => $value) {
180
				switch ($key) {
181
					case 'type':
182
						$website->setType((int) $value);
183
						break;
184
185
					case 'theme':
186
						$website->setTheme($value);
187
						break;
188
189
					default:
190
						throw new WebsiteInvalidDataException();
191
				}
192
			}
193
194
			$this->websitesService->updateWebsite($website);
195
196
			return $this->getPersonalWebsites();
197
		} catch (\Exception $e) {
198
			$data = [];
199
			if (($e instanceof WebsiteNotFoundException) || ($e instanceof WebsiteForeignOwnerException)) {
200
				$data['form_error'] = [ 'field' => 'identifier', 'message' => $this->l10n->t('Website not found.') ];
201
			} elseif ($e instanceof WebsiteInvalidDataException) {
202
				$data['form_error'] = [ 'field' => $e->getField(), 'message' => $e->getMessage() ];
203
			} elseif ($e instanceof ThemeNotFoundException) {
204
				$data['form_error'] = [ 'field' => 'theme', 'message' => $this->l10n->t('Theme not found.') ];
205
			} elseif ($e instanceof ThemeNotCompatibleException) {
206
				$data['form_error'] = [ 'field' => 'theme', 'message' => $this->l10n->t($e->getReason()) ];
207
			} elseif ($e instanceof TemplateNotFoundException) {
208
				$data['form_error'] = [ 'field' => 'template', 'message' => $this->l10n->t('Template not found.') ];
209
			}
210
211
			return $this->createErrorResponse($e, $data);
212
		}
213
	}
214
215
	/**
216
	 * @NoAdminRequired
217
	 *
218
	 * @param int $siteId
219
	 *
220
	 * @return DataResponse
221
	 */
222
	public function removePersonalWebsite(int $siteId): DataResponse
223
	{
224
		try {
225
			$website = $this->websitesService->getWebsiteFromId($siteId);
226
227
			$website->assertOwnedBy($this->userId);
228
229
			$this->websitesService->deleteWebsite($website);
230
231
			return $this->getPersonalWebsites();
232
		} catch (\Exception $e) {
233
			return $this->createErrorResponse($e);
234
		}
235
	}
236
237
	/**
238
	 * @return DataResponse
239
	 */
240 1
	public function getTemplates(): DataResponse
241
	{
242
		$data = [
243 1
			'systemItems' => $this->templatesService->getSystemTemplates(),
244 1
			'customItems' => $this->templatesService->getCustomTemplates(),
245 1
			'newItems' => $this->templatesService->getNewCustomTemplates(),
246
		];
247
248 1
		return new DataResponse($data, Http::STATUS_OK);
249
	}
250
251
	/**
252
	 * @param string $item
253
	 *
254
	 * @return DataResponse
255
	 */
256 1
	public function addCustomTemplate(string $item): DataResponse
257
	{
258
		try {
259 1
			$customTemplates = $this->templatesService->getCustomTemplates();
260 1
			$customTemplates[] = $item;
261
262 1
			$this->configService->setAppValue(ConfigService::CUSTOM_TEMPLATES, json_encode($customTemplates));
263
264 1
			return $this->getTemplates();
265
		} catch (\Exception $e) {
266
			return $this->createErrorResponse($e);
267
		}
268
	}
269
270
	/**
271
	 * @param string $item
272
	 *
273
	 * @return DataResponse
274
	 */
275 1
	public function removeCustomTemplate(string $item): DataResponse
276
	{
277
		try {
278 1
			$customTemplates = $this->templatesService->getCustomTemplates();
279
280 1
			$newCustomTemplates = [];
281 1
			foreach ($customTemplates as $customTemplate) {
282 1
				if ($customTemplate === $item) {
283 1
					continue;
284
				}
285
286
				$newCustomTemplates[] = $customTemplate;
287
			}
288
289 1
			$this->configService->setAppValue(ConfigService::CUSTOM_TEMPLATES, json_encode($newCustomTemplates));
290
291 1
			return $this->getTemplates();
292
		} catch (\Exception $e) {
293
			return $this->createErrorResponse($e);
294
		}
295
	}
296
297
	/**
298
	 * @return DataResponse
299
	 */
300 1
	public function getThemes(): DataResponse
301
	{
302
		$data = [
303 1
			'systemItems' => $this->themesService->getSystemThemes(),
304 1
			'customItems' => $this->themesService->getCustomThemes(),
305 1
			'newItems' => $this->themesService->getNewCustomThemes(),
306
		];
307
308 1
		return new DataResponse($data, Http::STATUS_OK);
309
	}
310
311
	/**
312
	 * @param string $item
313
	 *
314
	 * @return DataResponse
315
	 */
316 1
	public function addCustomTheme(string $item): DataResponse
317
	{
318
		try {
319 1
			$this->themesService->publishCustomTheme($item);
320
321 1
			return $this->getThemes();
322
		} catch (\Exception $e) {
323
			return $this->createErrorResponse($e);
324
		}
325
	}
326
327
	/**
328
	 * @param string $item
329
	 *
330
	 * @return DataResponse
331
	 */
332
	public function updateCustomTheme(string $item): DataResponse
333
	{
334
		try {
335
			$this->themesService->depublishCustomTheme($item);
336
			$this->themesService->publishCustomTheme($item);
337
338
			return $this->getThemes();
339
		} catch (\Exception $e) {
340
			return $this->createErrorResponse($e);
341
		}
342
	}
343
344
	/**
345
	 * @param string $item
346
	 *
347
	 * @return DataResponse
348
	 */
349 1
	public function removeCustomTheme(string $item): DataResponse
350
	{
351
		try {
352 1
			$this->themesService->depublishCustomTheme($item);
353
354 1
			return $this->getThemes();
355
		} catch (\Exception $e) {
356
			return $this->createErrorResponse($e);
357
		}
358
	}
359
360
	/**
361
	 * @return DataResponse
362
	 */
363
	public function getPlugins(): DataResponse
364
	{
365
		$data = [
366
			'systemItems' => $this->pluginsService->getSystemPlugins(),
367
			'customItems' => $this->pluginsService->getCustomPlugins(),
368
			'newItems' => $this->pluginsService->getNewCustomPlugins(),
369
		];
370
371
		return new DataResponse($data, Http::STATUS_OK);
372
	}
373
374
	/**
375
	 * @param string $item
376
	 *
377
	 * @return DataResponse
378
	 */
379
	public function addCustomPlugin(string $item): DataResponse
380
	{
381
		try {
382
			$this->pluginsService->publishCustomPlugin($item);
383
384
			return $this->getPlugins();
385
		} catch (\Exception $e) {
386
			return $this->createErrorResponse($e);
387
		}
388
	}
389
390
	/**
391
	 * @param string $item
392
	 *
393
	 * @return DataResponse
394
	 */
395
	public function updateCustomPlugin(string $item): DataResponse
396
	{
397
		try {
398
			$this->pluginsService->depublishCustomPlugin($item);
399
			$this->pluginsService->publishCustomPlugin($item);
400
401
			return $this->getPlugins();
402
		} catch (\Exception $e) {
403
			return $this->createErrorResponse($e);
404
		}
405
	}
406
407
	/**
408
	 * @param string $item
409
	 *
410
	 * @return DataResponse
411
	 */
412
	public function removeCustomPlugin(string $item): DataResponse
413
	{
414
		try {
415
			$this->pluginsService->depublishCustomPlugin($item);
416
417
			return $this->getPlugins();
418
		} catch (\Exception $e) {
419
			return $this->createErrorResponse($e);
420
		}
421
	}
422
423
	/**
424
	 * @param array $data
425
	 *
426
	 * @return DataResponse
427
	 */
428
	public function setLimitGroups(array $data): DataResponse
429
	{
430
		try {
431
			if (!isset($data['limit_groups'])) {
432
				throw new \UnexpectedValueException();
433
			}
434
435
			$limitGroups = $data['limit_groups'] ? explode('|', $data['limit_groups']) : [];
436
			$this->websitesService->setLimitGroups($limitGroups);
437
438
			return new DataResponse();
439
		} catch (\Exception $e) {
440
			return $this->createErrorResponse($e);
441
		}
442
	}
443
444
	/**
445
	 * @param array $data
446
	 *
447
	 * @return DataResponse
448
	 */
449
	public function setLinkMode(array $data): DataResponse
450
	{
451
		try {
452
			if (!isset($data['link_mode'])) {
453
				throw new \UnexpectedValueException();
454
			}
455
456
			$this->websitesService->setLinkMode((int) $data['link_mode']);
457
458
			return new DataResponse();
459
		} catch (\Exception $e) {
460
			return $this->createErrorResponse($e);
461
		}
462
	}
463
464
	/**
465
	 * @param \Exception $exception
466
	 * @param array      $data
467
	 *
468
	 * @return DataResponse
469
	 */
470
	private function createErrorResponse(\Exception $exception, array $data = []): DataResponse
471
	{
472
		$this->logger->logException($exception, [ 'app' => Application::APP_NAME, 'level' => 2 ]);
473
474
		$data['status'] = 0;
475
		if (\OC::$server->getSystemConfig()->getValue('debug', false)) {
476
			$data['exception'] = get_class($exception);
477
			$data['error'] = $exception->getMessage();
478
			$data['code'] = $exception->getCode();
479
		}
480
481
		return new DataResponse($data, Http::STATUS_INTERNAL_SERVER_ERROR);
482
	}
483
}
484