Passed
Push — developer ( ac75b2...f4c496 )
by Mariusz
30:53
created

View::validateRequest()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
/**
3
 * Controller class for views.
4
 *
5
 * @package App
6
 *
7
 * @copyright YetiForce Sp. z o.o.
8
 * @license   YetiForce Public License 3.0 (licenses/LicenseEN.txt or yetiforce.com)
9
 * @author    Tomasz Kur <[email protected]>
10
 * @author    Mariusz Krzaczkowski <[email protected]>
11
 */
12
13
namespace App\Controller;
14
15
/**
16
 * Controller class for views.
17
 */
18
abstract class View extends Base
0 ignored issues
show
Coding Style introduced by
View does not seem to conform to the naming convention (^Abstract|Factory$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
19
{
20
	/** @var \App\Viewer Viewer object. */
21
	protected $viewer;
22
23
	/** {@inheritdoc} */
24
	public function __construct(\App\Request $request)
25
	{
26
		parent::__construct($request);
27
		$this->loadJsConfig($request);
28
		$this->viewer = new \App\Viewer();
29
		$this->viewer->assign('MODULE_NAME', $this->getModuleNameFromRequest($this->request));
0 ignored issues
show
Unused Code introduced by
The call to View::getModuleNameFromRequest() has too many arguments starting with $this->request.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
30
		$this->viewer->assign('VIEW', $this->request->getByType('view', \App\Purifier::ALNUM));
31
		$this->viewer->assign('LANGUAGE', \App\Language::getLanguage());
32
		$this->viewer->assign('LANG', \App\Language::getShortLanguageName());
33
		$this->viewer->assign('USER', \App\User::getUser());
34
		$this->viewer->assign('ACTION_NAME', $this->request->getAction());
35
	}
36
37
	/**
38
	 * Check permission.
39
	 *
40
	 * @throws \App\Exceptions\NoPermitted
41
	 *
42
	 * @return void
43
	 */
44
	public function checkPermission(): void
45
	{
46
		$this->getModuleNameFromRequest($this->request);
0 ignored issues
show
Unused Code introduced by
The call to View::getModuleNameFromRequest() has too many arguments starting with $this->request.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
47
		if (!\App\User::getUser()->isPermitted($this->moduleName)) {
48
			throw new \App\Exceptions\AppException('ERR_MODULE_PERMISSION_DENIED');
49
		}
50
	}
51
52
	/** {@inheritdoc} */
53
	public function preProcess($display = true): void
54
	{
55
		if ($this->loginRequired()) {
56
			$this->viewer->assign('MENU', \YF\Modules\Base\Model\Menu::getInstance($this->viewer->getTemplateVars('MODULE_NAME'))->getMenu());
57
		}
58
		$this->viewer->assign('PAGE_TITLE', (\Conf\Config::$siteName ?: \App\Language::translate('LBL_CUSTOMER_PORTAL')) . ' ' . $this->getPageTitle());
59
		$this->viewer->assign('CSS_FILE', $this->getHeaderCss());
60
		$this->viewer->assign('USER_QUICK_MENU', $this->getUserQuickMenuLinks());
61
		if ($display) {
62
			$this->preProcessDisplay();
63
		}
64
	}
65
66
	/**
67
	 * Get page title.
68
	 *
69
	 * @return string
70
	 */
71
	public function getPageTitle(): string
72
	{
73
		$title = \App\Language::translateModule($this->moduleName);
74
		$pageTitle = $this->getBreadcrumbTitle();
75
		if (isset($this->pageTitle)) {
76
			$pageTitle = \App\Language::translate($this->pageTitle);
0 ignored issues
show
Bug introduced by
The property pageTitle does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
77
		}
78
		if ($pageTitle) {
79
			$title .= ' - ' . $pageTitle;
80
		}
81
		return $title;
82
	}
83
84
	/**
85
	 * Get breadcrumb title.
86
	 *
87
	 * @return string
88
	 */
89
	public function getBreadcrumbTitle(): string
90
	{
91
		if (!empty($this->pageTitle)) {
92
			return $this->pageTitle;
93
		}
94
		return '';
95
	}
96
97
	/**
98
	 * Convert scripts path.
99
	 *
100
	 * @param array  $files
101
	 * @param string $fileExtension
102
	 *
103
	 * @return array
104
	 */
105
	public function convertScripts(array $files, string $fileExtension): array
106
	{
107
		$scriptsInstances = [];
108
		foreach ($files as $file) {
109
			[$fileName, $isOptional] = array_pad($file, 2, false);
0 ignored issues
show
Bug introduced by
The variable $fileName does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $isOptional does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
110
			$path = ROOT_DIRECTORY . "/public_html/$fileName";
111
			$script = new \App\Script();
112
			$script->set('type', $fileExtension);
113
			$minFilePath = str_replace('.' . $fileExtension, '.min.' . $fileExtension, $fileName);
114
			if (\App\Config::$minScripts && file_exists(ROOT_DIRECTORY . "/public_html/$minFilePath")) {
115
				$scriptsInstances[] = $script->set('src', PUBLIC_DIRECTORY . $minFilePath . self::getTime($path));
116
			} elseif (file_exists($path)) {
117
				$scriptsInstances[] = $script->set('src', PUBLIC_DIRECTORY . $fileName . self::getTime($path));
118
			} elseif ($isOptional) {
119
				\App\Log::info('File not found: ' . $path);
120
			} else {
121
				\App\Log::warning('File not found: ' . $path);
122
			}
123
		}
124
		return $scriptsInstances;
125
	}
126
127
	/**
128
	 * Gets file modification time.
129
	 *
130
	 * @param string $path
131
	 *
132
	 * @return string
133
	 */
134
	public static function getTime(string $path): string
135
	{
136
		$url = '';
137
		if ($fs = filemtime($path)) {
138
			$url = '?s=' . $fs;
139
		}
140
		return $url;
141
	}
142
143
	/**
144
	 * Retrieves css styles that need to loaded in the page.
145
	 *
146
	 * @return \App\Script[]
147
	 */
148
	public function getHeaderCss(): array
149
	{
150
		return $this->convertScripts([
151
			['libraries/@fortawesome/fontawesome-free/css/all.css'],
152
			['libraries/@mdi/font/css/materialdesignicons.css'],
153
			['libraries/bootstrap/dist/css/bootstrap.css'],
154
			['libraries/chosen-js/chosen.css'],
155
			['libraries/bootstrap-chosen/bootstrap-chosen.css'],
156
			['libraries/jQuery-Validation-Engine/css/validationEngine.jquery.css'],
157
			['libraries/select2/dist/css/select2.css'],
158
			['libraries/select2-theme-bootstrap4/dist/select2-bootstrap.css'],
159
			['libraries/datatables.net-bs4/css/dataTables.bootstrap4.css'],
160
			['libraries/datatables.net-responsive-bs4/css/responsive.bootstrap4.css'],
161
			['libraries/bootstrap-datepicker/dist/css/bootstrap-datepicker3.css'],
162
			['libraries/bootstrap-daterangepicker/daterangepicker.css'],
163
			['libraries/clockpicker/dist/bootstrap4-clockpicker.css'],
164
			['libraries/jstree-bootstrap-theme/dist/themes/proton/style.css'],
165
			['libraries/jstree/dist/themes/default/style.css'],
166
			['libraries/@pnotify/core/dist/PNotify.css'],
167
			['libraries/@pnotify/confirm/dist/PNotifyConfirm.css'],
168
			['libraries/@pnotify/bootstrap4/dist/PNotifyBootstrap4.css'],
169
			['libraries/@pnotify/mobile/dist/PNotifyMobile.css'],
170
			['libraries/@pnotify/desktop/dist/PNotifyDesktop.css'],
171
			['layouts/resources/icons/additionalIcons.css'],
172
			['layouts/resources/icons/yfm.css'],
173
			['layouts/resources/icons/yfi.css'],
174
			['layouts/' . \App\Viewer::getLayoutName() . '/skins/basic/Main.css'],
175
		], 'css');
176
	}
177
178
	/**
179
	 * Pre process display.
180
	 *
181
	 * @return void
182
	 */
183
	protected function preProcessDisplay(): void
184
	{
185
		if (\App\Session::has('systemError')) {
186
			$this->viewer->assign('ERRORS', \App\Session::get('systemError'));
187
			\App\Session::unset('systemError');
188
		}
189
		$this->viewer->view($this->preProcessTplName(), $this->moduleName);
190
	}
191
192
	/**
193
	 * Get preprocess tpl name.
194
	 *
195
	 * @return string
196
	 */
197
	protected function preProcessTplName(): string
198
	{
199
		return 'Header.tpl';
200
	}
201
202
	/**
203
	 * Get process tpl name.
204
	 *
205
	 * @return string
206
	 */
207
	protected function processTplName(): string
208
	{
209
		return $this->request->getAction() . '/Index.tpl';
210
	}
211
212
	/** {@inheritdoc}  */
213
	protected function postProcessTplName(): string
214
	{
215
		return 'Footer.tpl';
216
	}
217
218
	/** {@inheritdoc} */
219
	public function postProcess(): void
220
	{
221
		if (null === $this->viewer->getTemplateVars('SHOW_FOOTER_BAR')) {
222
			$this->viewer->assign('SHOW_FOOTER_BAR', true);
223
		}
224
		$this->viewer->assign('JS_FILE', $this->getFooterScripts());
225
		if (\App\Config::$debugApi && \App\Session::has('debugApi') && \App\Session::get('debugApi')) {
226
			$this->viewer->assign('DEBUG_API', \App\Session::get('debugApi'));
227
			$this->viewer->view('DebugApi.tpl', $this->moduleName);
228
			\App\Session::set('debugApi', false);
229
		}
230
		$this->viewer->view($this->postProcessTplName(), $this->moduleName);
231
	}
232
233
	/**
234
	 * Scripts.
235
	 *
236
	 * @return \App\Script[]
237
	 */
238
	public function getFooterScripts(): array
239
	{
240
		$moduleName = $this->getModuleNameFromRequest();
241
		$action = $this->request->getAction();
242
		$languageHandlerShortName = \App\Language::getShortLanguageName();
243
		$fileName = ["libraries/jQuery-Validation-Engine/js/languages/jquery.validationEngine-$languageHandlerShortName.js"];
244
		if (!file_exists(PUBLIC_DIRECTORY . $fileName[0])) {
245
			$fileName = ['libraries/jQuery-Validation-Engine/js/languages/jquery.validationEngine-en.js'];
246
		}
247
		return $this->convertScripts([
248
			['libraries/jquery/dist/jquery.js'],
249
			['libraries/jquery.class.js/jquery.class.js'],
250
			['libraries/block-ui/jquery.blockUI.js'],
251
			['libraries/@pnotify/core/dist/PNotify.js'],
252
			['libraries/@pnotify/mobile/dist/PNotifyMobile.js'],
253
			['libraries/@pnotify/desktop/dist/PNotifyDesktop.js'],
254
			['libraries/@pnotify/confirm/dist/PNotifyConfirm.js'],
255
			['libraries/@pnotify/bootstrap4/dist/PNotifyBootstrap4.js'],
256
			['libraries/@pnotify/font-awesome5/dist/PNotifyFontAwesome5.js'],
257
			['libraries/popper.js/dist/umd/popper.js'],
258
			['vendor/ckeditor/ckeditor/ckeditor.js'],
259
			['vendor/ckeditor/ckeditor/adapters/jquery.js'],
260
			['libraries/bootstrap/dist/js/bootstrap.js'],
261
			['libraries/bootstrap-datepicker/dist/js/bootstrap-datepicker.js'],
262
			['libraries/bootstrap-daterangepicker/daterangepicker.js'],
263
			['libraries/bootbox/dist/bootbox.min.js'],
264
			['libraries/chosen-js/chosen.jquery.js'],
265
			['libraries/select2/dist/js/select2.full.js'],
266
			['libraries/moment/min/moment.min.js'],
267
			['libraries/inputmask/dist/jquery.inputmask.js'],
268
			['libraries/datatables.net/js/jquery.dataTables.js'],
269
			['libraries/datatables.net-bs4/js/dataTables.bootstrap4.js'],
270
			['libraries/datatables.net-responsive/js/dataTables.responsive.js'],
271
			['libraries/datatables.net-responsive-bs4/js/responsive.bootstrap4.js'],
272
			['libraries/jQuery-Validation-Engine/js/jquery.validationEngine.js'],
273
			$fileName,
274
			['libraries/jstree/dist/jstree.js'],
275
			['libraries/clockpicker/dist/bootstrap4-clockpicker.js'],
276
			['layouts/resources/validator/BaseValidator.js'],
277
			['layouts/resources/validator/FieldValidator.js'],
278
			['layouts/resources/helper.js'],
279
			['layouts/resources/Field.js'],
280
			['layouts/resources/Connector.js'],
281
			['layouts/resources/app.js'],
282
			['layouts/resources/Fields.js'],
283
			['layouts/resources/ProgressIndicator.js'],
284
			['layouts/' . \App\Viewer::getLayoutName() . '/modules/Base/resources/Header.js'],
285
			['layouts/' . \App\Viewer::getLayoutName() . "/modules/Base/resources/{$action}.js"],
286
			['layouts/' . \App\Viewer::getLayoutName() . "/modules/{$moduleName}/resources/{$action}.js", true],
287
		], 'js');
288
	}
289
290
	/** {@inheritdoc} */
291
	public function validateRequest()
292
	{
293
		$this->request->validateReadAccess();
294
	}
295
296
	/** {@inheritdoc} */
297
	public function postProcessAjax()
298
	{
299
	}
300
301
	/** {@inheritdoc} */
302
	public function preProcessAjax()
303
	{
304
	}
305
306
	/**
307
	 * Get module name from request.
308
	 *
309
	 * @return string
310
	 */
311
	private function getModuleNameFromRequest(): string
312
	{
313
		if (empty($this->moduleName)) {
314
			$this->moduleName = $this->request->getModule();
315
		}
316
		return $this->moduleName;
317
	}
318
319
	/**
320
	 * Load js config.
321
	 *
322
	 * @param \App\Request $request
323
	 */
324
	public function loadJsConfig(\App\Request $request): void
325
	{
326
		$jsEnv = [
327
			'siteUrl' => \App\Utils::getPublicUrl('', true),
328
			'langPrefix' => \App\Language::getLanguage(),
329
			'langKey' => \App\Language::getShortLanguageName(),
330
			'parentModule' => $request->getByType('parent', 2),
331
		];
332
		foreach ($jsEnv as $key => $value) {
333
			\App\Config::setJsEnv($key, $value);
334
		}
335
	}
336
337
	/**
338
	 * Get the list of user quick menu links.
339
	 *
340
	 * @return array
341
	 */
342
	protected function getUserQuickMenuLinks(): array
343
	{
344
		$user = \App\User::getUser();
345
		$links = [
346
			[
347
				'label' => 'LBL_CHANGE_PASSWORD',
348
				'moduleName' => 'Users',
349
				'data' => ['url' => 'index.php?module=Users&view=PasswordChangeModal'],
350
				'icon' => 'yfi yfi-change-passowrd',
351
				'class' => 'text-decoration-none u-fs-sm text-secondary js-show-modal d-block',
352
				'btnClass' => ' ',
353
				'href' => '#',
354
				'showLabel' => true,
355
			],
356
			[
357
				'label' => 'BTN_YOUR_ACCOUNT_ACCESS_HISTORY',
358
				'moduleName' => 'Users',
359
				'data' => ['url' => 'index.php?module=Users&view=AccessActivityHistoryModal'],
360
				'icon' => 'yfi yfi-login-history',
361
				'class' => 'text-decoration-none u-fs-sm text-secondary js-show-modal d-block',
362
				'btnClass' => ' ',
363
				'href' => '#',
364
				'showLabel' => true,
365
			],
366
		];
367
		if ('PLL_PASSWORD_2FA' === $user->get('login_method') && !$user->isEmpty('authy_methods')) {
368
			$links[] = [
369
				'label' => 'BTN_2FA_TOTP_QR_CODE',
370
				'moduleName' => 'Users',
371
				'data' => ['url' => 'index.php?module=Users&view=TwoFactorAuthenticationModal'],
372
				'icon' => 'fas fa-key',
373
				'class' => 'text-decoration-none u-fs-sm text-secondary js-show-modal d-block',
374
				'btnClass' => ' ',
375
				'href' => '#',
376
				'showLabel' => true,
377
			];
378
		}
379
		return $links;
380
	}
381
}
382