Passed
Pull Request — develop (#888)
by Lu Nguyen
12:17
created

PlgSystemRedcore::onBeforeCompileHead()   F

Complexity

Conditions 35
Paths 6485

Size

Total Lines 140
Code Lines 72

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 2 Features 1
Metric Value
eloc 72
c 6
b 2
f 1
dl 0
loc 140
rs 0
cc 35
nc 6485
nop 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * @package     Joomla.Plugin
4
 * @subpackage  System.Redcore
5
 *
6
 * @copyright   Copyright (C) 2008 - 2020 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
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');
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
Deprecated Code introduced by
The function JError::setErrorHandling() has been deprecated: 1.7 ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

70
						/** @scrutinizer ignore-deprecated */ JError::setErrorHandling(E_ERROR, 'message');

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

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')) ?
0 ignored issues
show
Deprecated Code introduced by
The function JApplicationCms::isAdmin() has been deprecated: Use isClient('administrator') instead. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

95
								/** @scrutinizer ignore-deprecated */ JFactory::getApplication()->isAdmin() : JFactory::getApplication()->isClient('administrator')) ?

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
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
Deprecated Code introduced by
The function JResponse::getBody() has been deprecated: 3.2 Use JApplicationWeb::getBody() instead ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

200
		$body = /** @scrutinizer ignore-deprecated */ JResponse::getBody();

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

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);
0 ignored issues
show
Deprecated Code introduced by
The function JResponse::setBody() has been deprecated: 3.2 Use JApplicationWeb::setBody() instead ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

210
		/** @scrutinizer ignore-deprecated */ JResponse::setBody($body);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
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'));
0 ignored issues
show
Deprecated Code introduced by
The function JApplicationCms::isAdmin() has been deprecated: Use isClient('administrator') instead. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

253
			/** @scrutinizer ignore-deprecated */ JFactory::getApplication()->isAdmin() : JFactory::getApplication()->isClient('administrator'));

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
254
255
		if (!$isAdmin || $isRedcoreExtension)
256
		{
257
			RHtmlMedia::loadFrameworkJs();
258
		}
259
260
		if ($doc->_scripts)
0 ignored issues
show
Bug Best Practice introduced by
The expression $doc->_scripts of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
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']);
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)
0 ignored issues
show
Bug Best Practice introduced by
The expression $doc->_styleSheets of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
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']))
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
		RTranslationHelper::addAlternateLinks();
381
	}
382
383
	/**
384
	 * This event is triggered immediately before pushing the document buffers into the template placeholders,
385
	 * retrieving data from the document and pushing it into the into the JResponse buffer.
386
	 * http://docs.joomla.org/Plugin/Events/System
387
	 *
388
	 * @return  void
389
	 */
390
	public function onBeforeRender()
391
	{
392
		if (!$this->isRedcoreComponent())
393
		{
394
			return;
395
		}
396
	}
397
398
	/**
399
	 * Called before a JForm is rendered. It can be used to modify the JForm object in memory before rendering.
400
	 * https://docs.joomla.org/Plugin/Events/Content
401
	 *
402
	 * @return  void
403
	 */
404
	public function onContentPrepareForm()
405
	{
406
		// 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
407
		if (RBootstrap::getConfig('enable_translations', 0) == 1 && RBootstrap::getConfig('show_edit_button_on_all_forms', 0) == 1)
408
		{
409
			$isAdmin = (version_compare(JVERSION, '3.7', '<') ?
410
				JFactory::getApplication()->isAdmin() : JFactory::getApplication()->isClient('administrator'));
0 ignored issues
show
Deprecated Code introduced by
The function JApplicationCms::isAdmin() has been deprecated: Use isClient('administrator') instead. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

410
				/** @scrutinizer ignore-deprecated */ JFactory::getApplication()->isAdmin() : JFactory::getApplication()->isClient('administrator'));

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
411
412
			RTranslationHelper::isTranslatableForm($isAdmin);
413
		}
414
	}
415
416
	/**
417
	 * Check is is a redCORE view
418
	 *
419
	 * @return  boolean
420
	 */
421
	private function isRedcoreComponent()
422
	{
423
		return defined('REDCORE_BOOTSTRAPPED');
424
	}
425
426
	/**
427
	 * Check is is a redCORE view
428
	 *
429
	 * @return  boolean
430
	 */
431
	private function isInstaller()
432
	{
433
		$app     = JFactory::getApplication();
434
		$input   = $app->input;
435
		$isAdmin = version_compare(JVERSION, '3.7', '<') ? $app->isAdmin() : $app->isClient('administrator');
0 ignored issues
show
Deprecated Code introduced by
The function JApplicationCms::isAdmin() has been deprecated: Use isClient('administrator') instead. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

435
		$isAdmin = version_compare(JVERSION, '3.7', '<') ? /** @scrutinizer ignore-deprecated */ $app->isAdmin() : $app->isClient('administrator');

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
436
437
		return $isAdmin && $input->getString('option') == 'com_installer'
438
			&& $input->get('task') == 'install.install';
439
	}
440
441
	/**
442
	 * Check if the view asked to disable mootools
443
	 *
444
	 * @return  boolean
445
	 */
446
	private function disableMootools()
447
	{
448
		$app = JFactory::getApplication();
449
450
		$disable = $app->input->get('disable_mootools', false);
451
452
		if (!$disable)
453
		{
454
			$disable = RHtmlMedia::isMootoolsDisabled();
455
		}
456
457
		return $disable;
458
	}
459
460
	/**
461
	 * Checks if given api name is currently install and enabled on this server
462
	 *
463
	 * @param   string  $apiName  Api name
464
	 *
465
	 * @return boolean
466
	 */
467
	private function isApiEnabled($apiName)
468
	{
469
		$apiName = strtolower($apiName);
470
471
		return (RBootstrap::getConfig('enable_webservices', 0) == 1 && $apiName == 'hal')
472
		|| (RBootstrap::getConfig('enable_oauth2_server', 0) == 1 && $apiName == 'oauth2')
473
		|| (RBootstrap::getConfig('enable_soap', 0) == 1 && $apiName == 'soap')
474
		|| (RBootstrap::getConfig('enable_payment', 1) == 1 && $apiName == 'payment');
475
	}
476
}
477