PlgSystemRedcore   F
last analyzed

Complexity

Total Complexity 83

Size/Duplication

Total Lines 454
Duplicated Lines 0 %

Importance

Changes 4
Bugs 2 Features 0
Metric Value
wmc 83
eloc 183
c 4
b 2
f 0
dl 0
loc 454
rs 2

12 Methods

Rating   Name   Duplication   Size   Complexity  
A isRedcoreExtension() 0 12 3
A isInstaller() 0 8 4
A isRedcoreComponent() 0 3 1
A onBeforeRender() 0 5 2
F onAfterInitialise() 0 102 13
B isApiEnabled() 0 8 8
A onContentPrepareForm() 0 9 4
A __construct() 0 13 3
A disableMootools() 0 12 2
A onAfterRender() 0 21 3
A onAfterRoute() 0 14 5
F onBeforeCompileHead() 0 135 35

How to fix   Complexity   

Complex Class

Complex classes like PlgSystemRedcore often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use PlgSystemRedcore, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * @package     Joomla.Plugin
4
 * @subpackage  System.Redcore
5
 *
6
 * @copyright   Copyright (C) 2008 - 2021 redWEB.dk. All rights reserved.
7
 * @license     GNU General Public License version 2 or later, see LICENSE.
8
 */
9
10
defined('JPATH_BASE') or die;
11
12
/**
13
 * System plugin for redCORE
14
 *
15
 * @package     Joomla.Plugin
16
 * @subpackage  System
17
 * @since       1.0
18
 */
19
class PlgSystemRedcore extends JPlugin
0 ignored issues
show
Bug introduced by
The type JPlugin was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
20
{
21
	/**
22
	 * Constructor
23
	 *
24
	 * @param   object  &$subject  The object to observe
25
	 * @param   array   $config    An optional associative array of configuration settings.
26
	 *                             Recognized key values include 'name', 'group', 'params', 'language'
27
	 *                             (this list is not meant to be comprehensive).
28
	 *
29
	 * @since   1.5
30
	 */
31
	public function __construct(&$subject, $config = array())
32
	{
33
		parent::__construct($subject, $config);
34
35
		$redcoreLoader = JPATH_LIBRARIES . '/redcore/bootstrap.php';
36
37
		if (file_exists($redcoreLoader))
38
		{
39
			require_once $redcoreLoader;
40
41
			if (!$this->isInstaller())
42
			{
43
				RBootstrap::bootstrap(false);
44
			}
45
		}
46
	}
47
48
	/**
49
	 * Method to register custom library.
50
	 *
51
	 * @return  void
52
	 */
53
	public function onAfterInitialise()
54
	{
55
		if (defined('REDCORE_LIBRARY_LOADED'))
56
		{
57
			$apiName = JFactory::getApplication()->input->getString('api');
0 ignored issues
show
Bug introduced by
The type JFactory was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
58
59
			if ($this->isApiEnabled($apiName))
60
			{
61
				$input = JFactory::getApplication()->input;
62
63
				if (!empty($apiName))
64
				{
65
					try
66
					{
67
						// We will disable all error messaging from PHP from the output
68
						error_reporting(0);
69
						ini_set('display_errors', 0);
70
						JError::setErrorHandling(E_ERROR, 'message');
0 ignored issues
show
Bug introduced by
The type JError was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
71
						RApi::clearHeaders();
72
						$webserviceClient = $input->get->getString('webserviceClient', '');
73
						$optionName       = $input->get->getString('option', '');
74
						$optionName       = strpos($optionName, 'com_') === 0 ? substr($optionName, 4) : $optionName;
75
						$viewName         = $input->getString('view', '');
76
						$version          = $input->getString('webserviceVersion', '');
77
						$token            = $input->getString(RBootstrap::getConfig('oauth2_token_param_name', 'access_token'), '');
78
						$apiName          = ucfirst($apiName);
79
						$method           = strtoupper($input->getMethod());
80
						$task             = RApiHalHelper::getTask();
81
						$data             = RApi::getPostedData();
82
83
						if (version_compare(JVERSION, '3') >= 0)
84
						{
85
							$dataGet = $input->get->getArray();
86
						}
87
						else
88
						{
89
							$dataGet = $input->get->getArray($_GET);
90
						}
91
92
						if (empty($webserviceClient))
93
						{
94
							$webserviceClient = (version_compare(JVERSION, '3.7', '<') ?
95
								JFactory::getApplication()->isAdmin() : JFactory::getApplication()->isClient('administrator')) ?
96
								'administrator' : 'site';
97
						}
98
99
						$options = array(
100
							'api'               => $apiName,
101
							'optionName'        => $optionName,
102
							'viewName'          => $viewName,
103
							'webserviceVersion' => $version,
104
							'webserviceClient'  => $webserviceClient,
105
							'method'            => $method,
106
							'task'              => $task,
107
							'data'              => $data,
108
							'dataGet'           => $dataGet,
109
							'accessToken'       => $token,
110
							'format'            => $input->getString('format', RBootstrap::getConfig('webservices_default_format', 'json')),
111
							'id'                => $input->getString('id', ''),
112
							'absoluteHrefs'     => $input->get->getBool('absoluteHrefs', true),
113
							'webservice_stateful' => RBootstrap::getConfig('webservice_stateful', 0)
114
						);
115
116
						// Create instance of Api and fill all required options
117
						$api = RApi::getInstance($options);
118
119
						// Run the api task
120
						$api->execute();
121
122
						// Display output
123
						$api->render();
124
					}
125
					catch (Exception $e)
126
					{
127
						$code = $e->getCode() > 0 ? $e->getCode() : 500;
128
129
						if (strtolower($apiName) == 'soap')
130
						{
131
							// We must have status of 200 for SOAP communication even if it is fault
132
							$message = RApiSoapHelper::createSoapFaultResponse($e->getMessage());
133
							header("Content-Type: soap+xml");
134
							header("Content-length: " . strlen($message));
135
							header("Status: 200");
136
							echo $message;
137
						}
138
						else
139
						{
140
							// Set the server response code.
141
							header('Status: ' . $code, true, $code);
142
143
							// Check for defined constants
144
							if (!defined('JSON_UNESCAPED_SLASHES'))
145
							{
146
								define('JSON_UNESCAPED_SLASHES', 64);
147
							}
148
149
							// An exception has been caught, echo the message and exit.
150
							echo json_encode(array('message' => $e->getMessage(), 'code' => $e->getCode(), 'type' => get_class($e)), JSON_UNESCAPED_SLASHES);
151
						}
152
					}
153
154
					JFactory::getApplication()->close();
155
				}
156
			}
157
		}
158
	}
159
160
	/**
161
	 * After route.
162
	 *
163
	 * @return  void
164
	 *
165
	 * @since   3.4
166
	 */
167
	public function onAfterRoute()
168
	{
169
		if (defined('REDCORE_LIBRARY_LOADED'))
170
		{
171
			$app     = JFactory::getApplication();
172
			$oldLang = $app->getUserState('redcore.old_lang', null);
173
174
			if (RTranslationHelper::getSiteLanguage() != JFactory::getLanguage()->getTag()
175
				|| (!empty($oldLang) && JFactory::getLanguage()->getTag() != $oldLang))
176
			{
177
				$app->setUserState('redcore.old_lang', JFactory::getLanguage()->getTag());
178
179
				// Reset menus because they are loaded before any other module
180
				RMenu::resetJoomlaMenuItems();
181
			}
182
		}
183
	}
184
185
	/**
186
	 * This event is triggered after pushing the document buffers into the template placeholders,
187
	 * retrieving data from the document and pushing it into the into the JResponse buffer.
188
	 * http://docs.joomla.org/Plugin/Events/System
189
	 *
190
	 * @return boolean
191
	 */
192
	public function onAfterRender()
193
	{
194
		if (!$this->isRedcoreComponent() || !$this->disableMootools())
195
		{
196
			return true;
197
		}
198
199
		// Get the generated content
200
		$body = JResponse::getBody();
0 ignored issues
show
Bug introduced by
The type JResponse was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
201
202
		// Remove JCaption JS calls
203
		$pattern     = "/(new JCaption\()(.*)(\);)/isU";
204
		$replacement = '';
205
		$body        = preg_replace($pattern, $replacement, $body);
206
207
		// Null window.addEvent( calls
208
		$pattern = "/(window.addEvent\()(.*)(,)/isU";
209
		$body    = preg_replace($pattern, 'do_nothing(', $body);
210
		JResponse::setBody($body);
211
212
		return true;
213
	}
214
215
	/**
216
	 * Checks if this is a redCORE supported extension
217
	 *
218
	 * @return boolean
219
	 */
220
	private function isRedcoreExtension()
221
	{
222
		$redcoreExtensions   = RComponentHelper::getRedcoreComponents();
223
		$redcoreExtensions[] = 'com_redcore';
224
		$option              = JFactory::getApplication()->input->getCmd('option');
225
226
		if (!empty($option) && in_array($option, $redcoreExtensions))
227
		{
228
			return true;
229
		}
230
231
		return false;
232
	}
233
234
	/**
235
	 * This event is triggered before the framework creates the Head section of the Document.
236
	 *
237
	 * @return  void
238
	 *
239
	 * @todo    Find a cleaner way to prioritise assets
240
	 */
241
	public function onBeforeCompileHead()
242
	{
243
		if (!$this->isRedcoreComponent())
244
		{
245
			return;
246
		}
247
248
		// Only set media settings for Extensions that are redCORE supported Extension in administration
249
		$isRedcoreExtension = $this->isRedcoreExtension();
250
251
		$doc     = JFactory::getDocument();
252
		$isAdmin = (version_compare(JVERSION, '3.7', '<') ?
253
			JFactory::getApplication()->isAdmin() : JFactory::getApplication()->isClient('administrator'));
254
255
		if (!$isAdmin || $isRedcoreExtension)
256
		{
257
			RHtmlMedia::loadFrameworkJs();
258
		}
259
260
		if ($doc->_scripts)
261
		{
262
			$template = JFactory::getApplication()->getTemplate();
263
264
			// Remove Mootools if asked by view, or if it's a site view and it has been asked via plugin parameters
265
			if ($this->disableMootools() || (!$isAdmin && RBootstrap::$disableFrontendMootools))
266
			{
267
				$doc->addScriptDeclaration("function do_nothing() { return; }");
268
				unset($doc->_scripts[JURI::root(true) . '/media/system/js/mootools-core.js']);
0 ignored issues
show
Bug introduced by
The type JURI was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
269
				unset($doc->_scripts[JURI::root(true) . '/media/system/js/mootools-more.js']);
270
				unset($doc->_scripts[JURI::root(true) . '/media/system/js/caption.js']);
271
				unset($doc->_scripts[JURI::root(true) . '/media/system/js/modal.js']);
272
				unset($doc->_scripts[JURI::root(true) . '/media/system/js/mootools.js']);
273
				unset($doc->_scripts[JURI::root(true) . '/plugins/system/mtupgrade/mootools.js']);
274
				unset($doc->_scripts[JURI::root(true) . '/media/system/js/mootools-core-uncompressed.js']);
275
				unset($doc->_scripts[JURI::root(true) . '/media/system/js/caption-uncompressed.js']);
276
				unset($doc->_scripts[JURI::root(true) . '/media/system/js/modal-uncompressed.js']);
277
				unset($doc->_scripts[JURI::root(true) . '/media/system/js/mootools-more-uncompressed.js']);
278
279
				if ($doc->_styleSheets)
280
				{
281
					unset($doc->_styleSheets[JURI::root(true) . '/media/system/css/modal.css']);
282
				}
283
284
				if (!$isAdmin && version_compare(JVERSION, '3.4', '<'))
285
				{
286
					unset($doc->_scripts[JURI::root(true) . '/media/system/js/core.js']);
287
					unset($doc->_scripts[JURI::root(true) . '/media/system/js/core-uncompressed.js']);
288
				}
289
			}
290
291
			// Remove jQuery in administration, or if it's frontend site and it has been asked via plugin parameters
292
			if (($isAdmin && $isRedcoreExtension) || (!$isAdmin && RBootstrap::$loadFrontendjQuery))
293
			{
294
				unset($doc->_scripts[JURI::root(true) . '/media/jui/js/jquery.min.js']);
295
				unset($doc->_scripts[JURI::root(true) . '/media/jui/js/jquery.js']);
296
				unset($doc->_scripts[JURI::root(true) . '/media/jui/js/jquery-noconflict.js']);
297
298
				$jQueryChosen = false;
299
300
				if (isset($doc->_scripts[JURI::root(true) . '/media/jui/js/chosen.jquery.js'])
301
					|| isset($doc->_scripts[JURI::root(true) . '/media/jui/js/chosen.jquery.min.js']))
302
				{
303
					$jQueryChosen = true;
304
					unset($doc->_scripts[JURI::root(true) . '/media/jui/js/chosen.jquery.js']);
305
					unset($doc->_scripts[JURI::root(true) . '/media/jui/js/chosen.jquery.min.js']);
306
					unset($doc->_styleSheets[JURI::root(true) . '/media/jui/css/chosen.css']);
307
					unset($doc->_styleSheets[JURI::root(true) . '/media/jui/css/chosen.min.css']);
308
				}
309
310
				// Template specific overrides for jQuery files (valid in Joomla 3.x)
311
				unset($doc->_scripts[JURI::root(true) . '/templates/' . $template . '/js/jui/jquery.min.js']);
312
				unset($doc->_scripts[JURI::root(true) . '/templates/' . $template . '/js/jui/jquery.js']);
313
				unset($doc->_scripts[JURI::root(true) . '/templates/' . $template . '/js/jui/jquery-noconflict.js']);
314
315
				if (isset($doc->_scripts[JURI::root(true) . '/templates/' . $template . '/js/jui/chosen.jquery.js'])
316
					|| isset($doc->_scripts[JURI::root(true) . '/templates/' . $template . '/js/jui/chosen.jquery.min.js']))
317
				{
318
					$jQueryChosen = true;
319
					unset($doc->_scripts[JURI::root(true) . '/templates/' . $template . '/js/jui/chosen.jquery.js']);
320
					unset($doc->_scripts[JURI::root(true) . '/templates/' . $template . '/js/jui/chosen.jquery.min.js']);
321
					unset($doc->_styleSheets[JURI::root(true) . '/templates/' . $template . '/css/jui/chosen.css']);
322
					unset($doc->_styleSheets[JURI::root(true) . '/templates/' . $template . '/css/jui/chosen.min.css']);
323
				}
324
325
				// Enables chosen when it was removed
326
				if ($jQueryChosen)
327
				{
328
					RHtml::_('rjquery.chosen', 'select');
329
				}
330
			}
331
332
			// Remove jQuery Migrate in administration, or if it's frontend site and it has been asked via plugin parameters
333
			if (($isAdmin && $isRedcoreExtension) || (!$isAdmin && RBootstrap::$loadFrontendjQueryMigrate))
334
			{
335
				unset($doc->_scripts[JURI::root(true) . '/media/jui/js/jquery-migrate.min.js']);
336
				unset($doc->_scripts[JURI::root(true) . '/media/jui/js/jquery-migrate.js']);
337
338
				// Template specific overrides for jQuery files (valid in Joomla 3.x)
339
				unset($doc->_scripts[JURI::root(true) . '/templates/' . $template . '/js/jui/jquery-migrate.min.js']);
340
				unset($doc->_scripts[JURI::root(true) . '/templates/' . $template . '/js/jui/jquery-migrate.js']);
341
			}
342
343
			// Remove Bootstrap in administration, or if it's frontend site and it has been asked via plugin parameters
344
			if (($isAdmin && $isRedcoreExtension) || (!$isAdmin && RBootstrap::$loadFrontendCSS))
345
			{
346
				unset($doc->_scripts[JURI::root(true) . '/media/jui/js/bootstrap.js']);
347
				unset($doc->_scripts[JURI::root(true) . '/media/jui/js/bootstrap.min.js']);
348
349
				// Template specific overrides for jQuery files (valid in Joomla 3.x)
350
				unset($doc->_scripts[JURI::root(true) . '/templates/' . $template . '/js/jui/bootstrap.js']);
351
				unset($doc->_scripts[JURI::root(true) . '/templates/' . $template . '/js/jui/bootstrap.min.js']);
352
			}
353
354
			// Remove permission.js. Specially for Joomla 3.6 and make sure run only on redCORE's base extensions
355
			if ($isAdmin && version_compare(JVERSION, '3.6.0', '>=') && $isRedcoreExtension)
356
			{
357
				$usePermission = false;
358
359
				if (isset($doc->_scripts[JUri::root(true) . '/media/system/js/permissions.js']))
0 ignored issues
show
Bug introduced by
The type JUri was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
360
				{
361
					unset($doc->_scripts[JUri::root(true) . '/media/system/js/permissions.js']);
362
363
					$usePermission = true;
364
				}
365
366
				if (isset($doc->_scripts[JUri::root(true) . '/media/system/js/permissions-uncompressed.js']))
367
				{
368
					unset($doc->_scripts[JUri::root(true) . '/media/system/js/permissions-uncompressed.js']);
369
370
					$usePermission = true;
371
				}
372
373
				if ($usePermission)
374
				{
375
					RHelperAsset::load('permission.min.js', 'redcore');
376
				}
377
			}
378
		}
379
	}
380
381
	/**
382
	 * This event is triggered immediately before pushing the document buffers into the template placeholders,
383
	 * retrieving data from the document and pushing it into the into the JResponse buffer.
384
	 * http://docs.joomla.org/Plugin/Events/System
385
	 *
386
	 * @return  void
387
	 */
388
	public function onBeforeRender()
389
	{
390
		if (!$this->isRedcoreComponent())
391
		{
392
			return;
393
		}
394
	}
395
396
	/**
397
	 * Called before a JForm is rendered. It can be used to modify the JForm object in memory before rendering.
398
	 * https://docs.joomla.org/Plugin/Events/Content
399
	 *
400
	 * @return  void
401
	 */
402
	public function onContentPrepareForm()
403
	{
404
		// If the options to do so are turned on, create a button for opening a modal window to edit translations directly from a translatable form
405
		if (RBootstrap::getConfig('enable_translations', 0) == 1 && RBootstrap::getConfig('show_edit_button_on_all_forms', 0) == 1)
406
		{
407
			$isAdmin = (version_compare(JVERSION, '3.7', '<') ?
408
				JFactory::getApplication()->isAdmin() : JFactory::getApplication()->isClient('administrator'));
409
410
			RTranslationHelper::isTranslatableForm($isAdmin);
411
		}
412
	}
413
414
	/**
415
	 * Check is is a redCORE view
416
	 *
417
	 * @return  boolean
418
	 */
419
	private function isRedcoreComponent()
420
	{
421
		return defined('REDCORE_BOOTSTRAPPED');
422
	}
423
424
	/**
425
	 * Check is is a redCORE view
426
	 *
427
	 * @return  boolean
428
	 */
429
	private function isInstaller()
430
	{
431
		$app     = JFactory::getApplication();
432
		$input   = $app->input;
433
		$isAdmin = version_compare(JVERSION, '3.7', '<') ? $app->isAdmin() : $app->isClient('administrator');
434
435
		return $isAdmin && $input->getString('option') == 'com_installer'
436
			&& $input->get('task') == 'install.install';
437
	}
438
439
	/**
440
	 * Check if the view asked to disable mootools
441
	 *
442
	 * @return  boolean
443
	 */
444
	private function disableMootools()
445
	{
446
		$app = JFactory::getApplication();
447
448
		$disable = $app->input->get('disable_mootools', false);
449
450
		if (!$disable)
451
		{
452
			$disable = RHtmlMedia::isMootoolsDisabled();
453
		}
454
455
		return $disable;
456
	}
457
458
	/**
459
	 * Checks if given api name is currently install and enabled on this server
460
	 *
461
	 * @param   string  $apiName  Api name
462
	 *
463
	 * @return boolean
464
	 */
465
	private function isApiEnabled($apiName)
466
	{
467
		$apiName = strtolower($apiName);
468
469
		return (RBootstrap::getConfig('enable_webservices', 0) == 1 && $apiName == 'hal')
470
		|| (RBootstrap::getConfig('enable_oauth2_server', 0) == 1 && $apiName == 'oauth2')
471
		|| (RBootstrap::getConfig('enable_soap', 0) == 1 && $apiName == 'soap')
472
		|| (RBootstrap::getConfig('enable_payment', 1) == 1 && $apiName == 'payment');
473
	}
474
}
475