GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Pull Request — develop (#1930)
by
unknown
13:51
created

ModuleHandler::triggerCall()   C

Complexity

Conditions 12
Paths 14

Size

Total Lines 57
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
eloc 30
nc 14
nop 3
dl 0
loc 57
rs 6.62
c 0
b 0
f 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
/* Copyright (C) NAVER <http://www.navercorp.com> */
3
4
/**
5
 * @class ModuleHandler
6
 * @author NAVER ([email protected])
7
 * Handling modules
8
 *
9
 * @remarks This class is to excute actions of modules.
10
 *          Constructing an instance without any parameterconstructor, it finds the target module based on Context.
11
 *          If there is no act on the found module, excute an action referencing action_forward.
12
 * */
13
class ModuleHandler extends Handler
14
{
15
16
	var $module = NULL; ///< Module
17
	var $act = NULL; ///< action
18
	var $mid = NULL; ///< Module ID
19
	var $document_srl = NULL; ///< Document Number
20
	var $module_srl = NULL; ///< Module Number
21
	var $module_info = NULL; ///< Module Info. Object
22
	var $error = NULL; ///< an error code.
23
	var $httpStatusCode = NULL; ///< http status code.
24
25
	/**
26
	 * prepares variables to use in moduleHandler
27
	 * @param string $module name of module
28
	 * @param string $act name of action
29
	 * @param int $mid
30
	 * @param int $document_srl
31
	 * @param int $module_srl
32
	 * @return void
33
	 * */
34
35
	function ModuleHandler($module = '', $act = '', $mid = '', $document_srl = '', $module_srl = '')
0 ignored issues
show
Coding Style Best Practice introduced by
Please use __construct() instead of a PHP4-style constructor that is named after the class.
Loading history...
36
	{
37
		// If XE has not installed yet, set module as install
38
		if(!Context::isInstalled())
39
		{
40
			$this->module = 'install';
41
			$this->act = Context::get('act');
42
			return;
43
		}
44
45
		$oContext = Context::getInstance();
46
		if($oContext->isSuccessInit == FALSE)
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
47
		{
48
			$logged_info = Context::get('logged_info');
49
			if($logged_info->is_admin != "Y")
50
			{
51
				$this->error = 'msg_invalid_request';
52
				return;
53
			}
54
		}
55
56
		// Set variables from request arguments
57
		$this->module = $module ? $module : Context::get('module');
58
		$this->act = $act ? $act : Context::get('act');
59
		$this->mid = $mid ? $mid : Context::get('mid');
60
		$this->document_srl = $document_srl ? (int) $document_srl : (int) Context::get('document_srl');
61
		$this->module_srl = $module_srl ? (int) $module_srl : (int) Context::get('module_srl');
62
        if($entry = Context::get('entry'))
63
        {
64
            $this->entry = Context::convertEncodingStr($entry);
0 ignored issues
show
Bug introduced by
The property entry 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...
65
        }
66
67
		// Validate variables to prevent XSS
68
		$isInvalid = NULL;
69
		if($this->module && !preg_match("/^([a-z0-9\_\-]+)$/i", $this->module))
70
		{
71
			$isInvalid = TRUE;
72
		}
73
		if($this->mid && !preg_match("/^([a-z0-9\_\-]+)$/i", $this->mid))
74
		{
75
			$isInvalid = TRUE;
76
		}
77
		if($this->act && !preg_match("/^([a-z0-9\_\-]+)$/i", $this->act))
78
		{
79
			$isInvalid = TRUE;
80
		}
81
		if($isInvalid)
82
		{
83
			htmlHeader();
84
			echo Context::getLang("msg_invalid_request");
85
			htmlFooter();
86
			Context::close();
87
			exit;
88
		}
89
90
		if(isset($this->act) && (strlen($this->act) >= 4 && substr_compare($this->act, 'disp', 0, 4) === 0))
91
		{
92
			if(Context::get('_use_ssl') == 'optional' && Context::isExistsSSLAction($this->act) && $_SERVER['HTTPS'] != 'on')
93
			{
94
				if(Context::get('_https_port')!=null) {
95
					header('location:https://' . $_SERVER['HTTP_HOST'] . ':' . Context::get('_https_port') . $_SERVER['REQUEST_URI']);
96
				} else {
97
					header('location:https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
98
				}
99
				return;
100
			}
101
		}
102
103
		// call a trigger before moduleHandler init
104
		ModuleHandler::triggerCall('moduleHandler.init', 'before', $this);
105
106
		// execute addon (before module initialization)
107
		$called_position = 'before_module_init';
108
		$oAddonController = getController('addon');
109
		$addon_file = $oAddonController->getCacheFilePath(Mobile::isFromMobilePhone() ? 'mobile' : 'pc');
110
		if(file_exists($addon_file)) include($addon_file);
111
	}
112
113
	/**
114
	 * Initialization. It finds the target module based on module, mid, document_srl, and prepares to execute an action
115
	 * @return boolean true: OK, false: redirected
116
	 * */
117
	function init()
118
	{
119
		$oModuleModel = getModel('module');
120
		$site_module_info = Context::get('site_module_info');
121
122
		// if success_return_url and error_return_url is incorrect
123
		$urls = array(Context::get('success_return_url'), Context::get('error_return_url'));
124
		foreach($urls as $url)
125
		{
126
			if(empty($url))
127
			{
128
				continue;
129
			}
130
		
131
			$urlInfo = parse_url($url);
132
			$host = $urlInfo['host'];
133
		
134
			$dbInfo = Context::getDBInfo();
135
			$defaultUrlInfo = parse_url($dbInfo->default_url);
136
			$defaultHost = $defaultUrlInfo['host'];
137
		
138
			if($host && ($host != $defaultHost && $host != $site_module_info->domain))
139
			{
140
				throw new Exception('msg_default_url_is_null');
141
			}
142
		}
143
		
144
		if(!$this->document_srl && $this->mid && $this->entry)
145
		{
146
			$oDocumentModel = getModel('document');
147
			$this->document_srl = $oDocumentModel->getDocumentSrlByAlias($this->mid, $this->entry);
148
			if($this->document_srl)
149
			{
150
				Context::set('document_srl', $this->document_srl);
151
			}
152
		}
153
154
		// Get module's information based on document_srl, if it's specified
155
		if($this->document_srl)
156
		{
157
			
158
			$module_info = $oModuleModel->getModuleInfoByDocumentSrl($this->document_srl);
159
			// If the document does not exist, remove document_srl
160
			if(!$module_info)
161
			{
162
				unset($this->document_srl);
163
			}
164
			else
165
			{
166
				// If it exists, compare mid based on the module information
167
				// if mids are not matching, set it as the document's mid
168
				if(!$this->mid || ($this->mid != $module_info->mid))
169
				{
170
					
171
					if(Context::getRequestMethod() == 'GET')
172
					{
173
						$this->mid = $module_info->mid;
174
						header('location:' . getNotEncodedSiteUrl($site_module_info->domain, 'mid', $this->mid, 'document_srl', $this->document_srl));
175
						return FALSE;
176
					}
177
					else
178
					{
179
						$this->mid = $module_info->mid;
180
						Context::set('mid', $this->mid);
181
					}
182
					
183
				}
184
				// if requested module is different from one of the document, remove the module information retrieved based on the document number
185
				if($this->module && $module_info->module != $this->module)
186
				{
187
					unset($module_info);
188
				}
189
			}
190
191
		}
192
193
		// If module_info is not set yet, and there exists mid information, get module information based on the mid
194
		if(!$module_info && $this->mid)
0 ignored issues
show
Bug introduced by
The variable $module_info does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
195
		{
196
			$module_info = $oModuleModel->getModuleInfoByMid($this->mid, $site_module_info->site_srl);
197
			//if($this->module && $module_info->module != $this->module) unset($module_info);
198
		}
199
200
		// redirect, if module_site_srl and site_srl are different
201
		if(!$this->module && !$module_info && $site_module_info->site_srl == 0 && $site_module_info->module_site_srl > 0)
202
		{
203
			$site_info = $oModuleModel->getSiteInfo($site_module_info->module_site_srl);
204
			header("location:" . getNotEncodedSiteUrl($site_info->domain, 'mid', $site_module_info->mid));
205
			return FALSE;
206
		}
207
208
		// If module_info is not set still, and $module does not exist, find the default module
209
		if(!$module_info && !$this->module && !$this->mid)
210
		{
211
			$module_info = $site_module_info;
212
		}
213
214
		if(!$module_info && !$this->module && $site_module_info->module_site_srl)
215
		{
216
			$module_info = $site_module_info;
217
		}
218
219
		// redirect, if site_srl of module_info is different from one of site's module_info
220
		if($module_info && $module_info->site_srl != $site_module_info->site_srl && !isCrawler())
221
		{
222
			// If the module is of virtual site
223
			if($module_info->site_srl)
224
			{
225
				$site_info = $oModuleModel->getSiteInfo($module_info->site_srl);
226
				$redirect_url = getNotEncodedSiteUrl($site_info->domain, 'mid', Context::get('mid'), 'document_srl', Context::get('document_srl'), 'module_srl', Context::get('module_srl'), 'entry', Context::get('entry'));
227
				// If it's called from a virtual site, though it's not a module of the virtual site
228
			}
229
			else
230
			{
231
				$db_info = Context::getDBInfo();
232
				if(!$db_info->default_url)
233
				{
234
					return Context::getLang('msg_default_url_is_not_defined');
235
				}
236
				else
237
				{
238
					$redirect_url = getNotEncodedSiteUrl($db_info->default_url, 'mid', Context::get('mid'), 'document_srl', Context::get('document_srl'), 'module_srl', Context::get('module_srl'), 'entry', Context::get('entry'));
239
				}
240
			}
241
			header("location:" . $redirect_url);
242
			return FALSE;
243
		}
244
245
		// If module info was set, retrieve variables from the module information
246
		if($module_info)
247
		{
248
			$this->module = $module_info->module;
249
			$this->mid = $module_info->mid;
250
			$this->module_info = $module_info;
251
			Context::setBrowserTitle($module_info->browser_title);
252
253
			$viewType = (Mobile::isFromMobilePhone()) ? 'M' : 'P';
254
			$targetSrl = (Mobile::isFromMobilePhone()) ? 'mlayout_srl' : 'layout_srl';
255
256
			// use the site default layout.
257
			if($module_info->{$targetSrl} == -1)
258
			{
259
				$oLayoutAdminModel = getAdminModel('layout');
260
				$layoutSrl = $oLayoutAdminModel->getSiteDefaultLayout($viewType, $module_info->site_srl);
261
			}
262
			else
263
			{
264
				$layoutSrl = $module_info->{$targetSrl};
265
			}
266
267
			// reset a layout_srl in module_info.
268
			$module_info->{$targetSrl} = $layoutSrl;
269
270
			$part_config = $oModuleModel->getModulePartConfig('layout', $layoutSrl);
271
			Context::addHtmlHeader($part_config->header_script);
272
		}
273
274
		// Set module and mid into module_info
275
		if(!isset($this->module_info))
276
		{
277
			$this->module_info = new stdClass();
278
		}
279
		$this->module_info->module = $this->module;
280
		$this->module_info->mid = $this->mid;
281
282
		// Set site_srl add 2011 08 09
283
		$this->module_info->site_srl = $site_module_info->site_srl;
284
285
		// Still no module? it's an error
286
		if(!$this->module)
287
		{
288
			$this->error = 'msg_module_is_not_exists';
289
			$this->httpStatusCode = '404';
290
		}
291
292
		// If mid exists, set mid into context
293
		if($this->mid)
294
		{
295
			Context::set('mid', $this->mid, TRUE);
0 ignored issues
show
Documentation introduced by
TRUE is of type boolean, but the function expects a integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
296
		}
297
		
298
		// Call a trigger after moduleHandler init
299
		$output = ModuleHandler::triggerCall('moduleHandler.init', 'after', $this->module_info);
300
		if(!$output->toBool())
301
		{
302
			$this->error = $output->getMessage();
303
			return TRUE;
304
		}
305
306
		// Set current module info into context
307
		Context::set('current_module_info', $this->module_info);
0 ignored issues
show
Documentation introduced by
$this->module_info is of type object, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
308
309
		return TRUE;
310
	}
311
312
	/**
313
	 * get a module instance and execute an action
314
	 * @return ModuleObject executed module instance
315
	 * */
316
	function procModule()
317
	{
318
		$oModuleModel = getModel('module');
319
		$display_mode = Mobile::isFromMobilePhone() ? 'mobile' : 'view';
320
321
		// If error occurred while preparation, return a message instance
322
		if($this->error)
323
		{
324
			$this->_setInputErrorToContext();
325
			$oMessageObject = ModuleHandler::getModuleInstance('message', $display_mode);
326
			$oMessageObject->setError(-1);
327
			$oMessageObject->setMessage($this->error);
328
			$oMessageObject->dispMessage();
329
			if($this->httpStatusCode)
330
			{
331
				$oMessageObject->setHttpStatusCode($this->httpStatusCode);
332
			}
333
			return $oMessageObject;
334
		}
335
336
		// Get action information with conf/module.xml
337
		$xml_info = $oModuleModel->getModuleActionXml($this->module);
338
339
		// If not installed yet, modify act
340
		if($this->module == "install")
341
		{
342
			if(!$this->act || !$xml_info->action->{$this->act})
343
			{
344
				$this->act = $xml_info->default_index_act;
345
			}
346
		}
347
348
		// if act exists, find type of the action, if not use default index act
349
		if(!$this->act)
350
		{
351
			$this->act = $xml_info->default_index_act;
352
		}
353
354
		// still no act means error
355
		if(!$this->act)
356
		{
357
			$this->error = 'msg_module_is_not_exists';
358
			$this->httpStatusCode = '404';
359
360
			$this->_setInputErrorToContext();
361
			$oMessageObject = ModuleHandler::getModuleInstance('message', $display_mode);
362
			$oMessageObject->setError(-1);
363
			$oMessageObject->setMessage($this->error);
364
			$oMessageObject->dispMessage();
365
			if($this->httpStatusCode)
366
			{
367
				$oMessageObject->setHttpStatusCode($this->httpStatusCode);
368
			}
369
			return $oMessageObject;
370
		}
371
372
		// get type, kind
373
		$type = $xml_info->action->{$this->act}->type;
374
		$ruleset = $xml_info->action->{$this->act}->ruleset;
375
		$kind = stripos($this->act, 'admin') !== FALSE ? 'admin' : '';
376
		if(!$kind && $this->module == 'admin')
377
		{
378
			$kind = 'admin';
379
		}
380
381
		// check REQUEST_METHOD in controller
382 View Code Duplication
		if($type == 'controller')
383
		{
384
			$allowedMethod = $xml_info->action->{$this->act}->method;
385
386
			if(!$allowedMethod)
387
			{
388
				$allowedMethodList[0] = 'POST';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$allowedMethodList was never initialized. Although not strictly required by PHP, it is generally a good practice to add $allowedMethodList = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
389
			}
390
			else
391
			{
392
				$allowedMethodList = explode('|', strtoupper($allowedMethod));
393
			}
394
395
			if(!in_array(strtoupper($_SERVER['REQUEST_METHOD']), $allowedMethodList))
396
			{
397
				$this->error = "msg_invalid_request";
398
				$oMessageObject = ModuleHandler::getModuleInstance('message', $display_mode);
399
				$oMessageObject->setError(-1);
400
				$oMessageObject->setMessage($this->error);
401
				$oMessageObject->dispMessage();
402
				return $oMessageObject;
403
			}
404
		}
405
406
		if($this->module_info->use_mobile != "Y")
407
		{
408
			Mobile::setMobile(FALSE);
409
		}
410
411
		$logged_info = Context::get('logged_info');
412
413
		// check CSRF for POST actions
414
		if(Context::getRequestMethod() === 'POST' && Context::isInstalled() && $this->act !== 'procFileUpload' && !checkCSRF()) {
415
			$this->error = 'msg_invalid_request';
416
			$oMessageObject = ModuleHandler::getModuleInstance('message', $display_mode);
417
			$oMessageObject->setError(-1);
418
			$oMessageObject->setMessage($this->error);
419
			$oMessageObject->dispMessage();
420
			return $oMessageObject;
421
		}
422
423
		// Admin ip
424
		if($kind == 'admin' && $_SESSION['denied_admin'] == 'Y')
425
		{
426
			$this->_setInputErrorToContext();
427
			$this->error = "msg_not_permitted_act";
428
			$oMessageObject = ModuleHandler::getModuleInstance('message', $display_mode);
429
			$oMessageObject->setError(-1);
430
			$oMessageObject->setMessage($this->error);
431
			$oMessageObject->dispMessage();
432
			return $oMessageObject;
433
		}
434
435
		// if(type == view, and case for using mobilephone)
436
		if($type == "view" && Mobile::isFromMobilePhone() && Context::isInstalled())
437
		{
438
			$orig_type = "view";
439
			$type = "mobile";
440
			// create a module instance
441
			$oModule = $this->getModuleInstance($this->module, $type, $kind);
442 View Code Duplication
			if(!is_object($oModule) || !method_exists($oModule, $this->act))
443
			{
444
				$type = $orig_type;
445
				Mobile::setMobile(FALSE);
446
				$oModule = $this->getModuleInstance($this->module, $type, $kind);
447
			}
448
		}
449
		else
450
		{
451
			// create a module instance
452
			$oModule = $this->getModuleInstance($this->module, $type, $kind);
453
		}
454
455 View Code Duplication
		if(!is_object($oModule))
456
		{
457
			$this->_setInputErrorToContext();
458
			$oMessageObject = ModuleHandler::getModuleInstance('message', $display_mode);
459
			$oMessageObject->setError(-1);
460
			$oMessageObject->setMessage($this->error);
461
			$oMessageObject->dispMessage();
462
			if($this->httpStatusCode)
463
			{
464
				$oMessageObject->setHttpStatusCode($this->httpStatusCode);
465
			}
466
			return $oMessageObject;
467
		}
468
469
		// If there is no such action in the module object
470
		if(!isset($xml_info->action->{$this->act}) || !method_exists($oModule, $this->act))
471
		{
472
473 View Code Duplication
			if(!Context::isInstalled())
474
			{
475
				$this->_setInputErrorToContext();
476
				$this->error = 'msg_invalid_request';
477
				$oMessageObject = ModuleHandler::getModuleInstance('message', $display_mode);
478
				$oMessageObject->setError(-1);
479
				$oMessageObject->setMessage($this->error);
480
				$oMessageObject->dispMessage();
481
				if($this->httpStatusCode)
482
				{
483
					$oMessageObject->setHttpStatusCode($this->httpStatusCode);
484
				}
485
				return $oMessageObject;
486
			}
487
488
			$forward = NULL;
489
			// 1. Look for the module with action name
490
			if(preg_match('/^([a-z]+)([A-Z])([a-z0-9\_]+)(.*)$/', $this->act, $matches))
491
			{
492
				$module = strtolower($matches[2] . $matches[3]);
493
				$xml_info = $oModuleModel->getModuleActionXml($module);
494
495
				if($xml_info->action->{$this->act} && ((stripos($this->act, 'admin') !== FALSE) || $xml_info->action->{$this->act}->standalone != 'false'))
496
				{
497
					$forward = new stdClass();
498
					$forward->module = $module;
499
					$forward->type = $xml_info->action->{$this->act}->type;
500
					$forward->ruleset = $xml_info->action->{$this->act}->ruleset;
501
					$forward->act = $this->act;
502
				}
503 View Code Duplication
				else
504
				{
505
					$this->error = 'msg_invalid_request';
506
					$oMessageObject = ModuleHandler::getModuleInstance('message', $display_mode);
507
					$oMessageObject->setError(-1);
508
					$oMessageObject->setMessage($this->error);
509
					$oMessageObject->dispMessage();
510
511
					return $oMessageObject;
512
				}
513
			}
514
515
			if(!$forward)
516
			{
517
				$forward = $oModuleModel->getActionForward($this->act);
518
			}
519
520
			if($forward->module && $forward->type && $forward->act && $forward->act == $this->act)
521
			{
522
				$kind = stripos($forward->act, 'admin') !== FALSE ? 'admin' : '';
523
				$type = $forward->type;
524
				$ruleset = $forward->ruleset;
525
				$tpl_path = $oModule->getTemplatePath();
0 ignored issues
show
Unused Code introduced by
$tpl_path is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
526
				$orig_module = $oModule;
0 ignored issues
show
Unused Code introduced by
$orig_module is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
527
528
				$xml_info = $oModuleModel->getModuleActionXml($forward->module);
529
530
				// SECISSUE also check foward act method
531
				// check REQUEST_METHOD in controller
532 View Code Duplication
				if($type == 'controller')
533
				{
534
					$allowedMethod = $xml_info->action->{$forward->act}->method;
535
536
					if(!$allowedMethod)
537
					{
538
						$allowedMethodList[0] = 'POST';
0 ignored issues
show
Bug introduced by
The variable $allowedMethodList does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
539
					}
540
					else
541
					{
542
						$allowedMethodList = explode('|', strtoupper($allowedMethod));
543
					}
544
545
					if(!in_array(strtoupper($_SERVER['REQUEST_METHOD']), $allowedMethodList))
546
					{
547
						$this->error = "msg_invalid_request";
548
						$oMessageObject = ModuleHandler::getModuleInstance('message', $display_mode);
549
						$oMessageObject->setError(-1);
550
						$oMessageObject->setMessage($this->error);
551
						$oMessageObject->dispMessage();
552
						return $oMessageObject;
553
					}
554
				}
555
556
				if($type == "view" && Mobile::isFromMobilePhone())
557
				{
558
					$orig_type = "view";
559
					$type = "mobile";
560
					// create a module instance
561
					$oModule = $this->getModuleInstance($forward->module, $type, $kind);
562 View Code Duplication
					if(!is_object($oModule) || !method_exists($oModule, $this->act))
563
					{
564
						$type = $orig_type;
565
						Mobile::setMobile(FALSE);
566
						$oModule = $this->getModuleInstance($forward->module, $type, $kind);
567
					}
568
				}
569
				else
570
				{
571
					$oModule = $this->getModuleInstance($forward->module, $type, $kind);
572
				}
573
574 View Code Duplication
				if(!is_object($oModule))
575
				{
576
					$this->_setInputErrorToContext();
577
					$oMessageObject = ModuleHandler::getModuleInstance('message', $display_mode);
578
					$oMessageObject->setError(-1);
579
					$oMessageObject->setMessage('msg_module_is_not_exists');
580
					$oMessageObject->dispMessage();
581
					if($this->httpStatusCode)
582
					{
583
						$oMessageObject->setHttpStatusCode($this->httpStatusCode);
584
					}
585
					return $oMessageObject;
586
				}
587
588
				if($this->module == "admin" && $type == "view")
589
				{
590
					if($logged_info->is_admin == 'Y')
591
					{
592
						if($this->act != 'dispLayoutAdminLayoutModify')
593
						{
594
							$oAdminView = getAdminView('admin');
595
							$oAdminView->makeGnbUrl($forward->module);
596
							$oModule->setLayoutPath("./modules/admin/tpl");
597
							$oModule->setLayoutFile("layout.html");
598
						}
599
					}
600 View Code Duplication
					else
601
					{
602
						$this->_setInputErrorToContext();
603
604
						$this->error = 'msg_is_not_administrator';
605
						$oMessageObject = ModuleHandler::getModuleInstance('message', $display_mode);
606
						$oMessageObject->setError(-1);
607
						$oMessageObject->setMessage($this->error);
608
						$oMessageObject->dispMessage();
609
						return $oMessageObject;
610
					}
611
				}
612
				if($kind == 'admin')
613
				{
614
					$grant = $oModuleModel->getGrant($this->module_info, $logged_info);
615
					if(!$grant->manager)
616
					{
617
						$this->_setInputErrorToContext();
618
						$this->error = 'msg_is_not_manager';
619
						$oMessageObject = ModuleHandler::getModuleInstance('message', $display_mode);
620
						$oMessageObject->setError(-1);
621
						$oMessageObject->setMessage($this->error);
622
						$oMessageObject->dispMessage();
623
						return $oMessageObject;
624
					}
625
					else
626
					{
627
						if(!$grant->is_admin && $this->module != $this->orig_module->module && $xml_info->permission->{$this->act} != 'manager')
0 ignored issues
show
Bug introduced by
The property orig_module does not seem to exist. Did you mean module?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
628
						{
629
							$this->_setInputErrorToContext();
630
							$this->error = 'msg_is_not_administrator';
631
							$oMessageObject = ModuleHandler::getModuleInstance('message', $display_mode);
632
							$oMessageObject->setError(-1);
633
							$oMessageObject->setMessage($this->error);
634
							$oMessageObject->dispMessage();
635
							return $oMessageObject;
636
						}
637
					}
638
				}
639
			}
640
			else if($xml_info->default_index_act && method_exists($oModule, $xml_info->default_index_act))
641
			{
642
				$this->act = $xml_info->default_index_act;
643
			}
644
			else
645
			{
646
				$this->error = 'msg_invalid_request';
647
				$oModule->setError(-1);
648
				$oModule->setMessage($this->error);
649
				return $oModule;
650
			}
651
		}
652
653
		// ruleset check...
654
		if(!empty($ruleset))
655
		{
656
			$rulesetModule = $forward->module ? $forward->module : $this->module;
0 ignored issues
show
Bug introduced by
The variable $forward does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
657
			$rulesetFile = $oModuleModel->getValidatorFilePath($rulesetModule, $ruleset, $this->mid);
658
			if(!empty($rulesetFile))
659
			{
660
				if($_SESSION['XE_VALIDATOR_ERROR_LANG'])
661
				{
662
					$errorLang = $_SESSION['XE_VALIDATOR_ERROR_LANG'];
663
					foreach($errorLang as $key => $val)
664
					{
665
						Context::setLang($key, $val);
666
					}
667
					unset($_SESSION['XE_VALIDATOR_ERROR_LANG']);
668
				}
669
670
				$Validator = new Validator($rulesetFile);
671
				$result = $Validator->validate();
672
				if(!$result)
673
				{
674
					$lastError = $Validator->getLastError();
675
					$returnUrl = Context::get('error_return_url');
676
					$errorMsg = $lastError['msg'] ? $lastError['msg'] : 'validation error';
677
678
					//for xml response
679
					$oModule->setError(-1);
680
					$oModule->setMessage($errorMsg);
681
					//for html redirect
682
					$this->error = $errorMsg;
683
					$_SESSION['XE_VALIDATOR_ERROR'] = -1;
684
					$_SESSION['XE_VALIDATOR_MESSAGE'] = $this->error;
685
					$_SESSION['XE_VALIDATOR_MESSAGE_TYPE'] = 'error';
686
					$_SESSION['XE_VALIDATOR_RETURN_URL'] = $returnUrl;
687
					$_SESSION['XE_VALIDATOR_ID'] = Context::get('xe_validator_id');
688
					$this->_setInputValueToSession();
689
					return $oModule;
690
				}
691
			}
692
		}
693
694
		$oModule->setAct($this->act);
695
696
		$this->module_info->module_type = $type;
697
		$oModule->setModuleInfo($this->module_info, $xml_info);
698
699
		$skipAct = array(
700
				'dispEditorConfigPreview' => 1,
701
				'dispLayoutPreviewWithModule' => 1
702
		);
703
		$db_use_mobile = Mobile::isMobileEnabled();
704
		if($type == "view" && $this->module_info->use_mobile == "Y" && Mobile::isMobileCheckByAgent() && !isset($skipAct[Context::get('act')]) && $db_use_mobile === true)
705
		{
706
			global $lang;
707
			$header = '<style>div.xe_mobile{opacity:0.7;margin:1em 0;padding:.5em;background:#333;border:1px solid #666;border-left:0;border-right:0}p.xe_mobile{text-align:center;margin:1em 0}a.xe_mobile{color:#ff0;font-weight:bold;font-size:24px}@media only screen and (min-width:500px){a.xe_mobile{font-size:15px}}</style>';
708
			$footer = '<div class="xe_mobile"><p class="xe_mobile"><a class="xe_mobile" href="' . getUrl('m', '1') . '">' . $lang->msg_pc_to_mobile . '</a></p></div>';
709
			Context::addHtmlHeader($header);
710
			Context::addHtmlFooter($footer);
711
		}
712
713
		if($type == "view" && $kind != 'admin')
714
		{
715
			$module_config = $oModuleModel->getModuleConfig('module');
716
			if($module_config->htmlFooter)
717
			{
718
				Context::addHtmlFooter($module_config->htmlFooter);
719
			}
720
			if($module_config->siteTitle)
721
			{
722
				$siteTitle = Context::getBrowserTitle();
723
				if(!$siteTitle)
724
				{
725
					Context::setBrowserTitle($module_config->siteTitle);
726
				}
727
			}
728
		}
729
730
		// if failed message exists in session, set context
731
		$this->_setInputErrorToContext();
732
733
		$procResult = $oModule->proc();
734
735
		$methodList = array('XMLRPC' => 1, 'JSON' => 1, 'JS_CALLBACK' => 1);
736
		if(!$oModule->stop_proc && !isset($methodList[Context::getRequestMethod()]))
0 ignored issues
show
Bug introduced by
The property stop_proc cannot be accessed from this context as it is declared private in class ModuleObject.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
737
		{
738
			$error = $oModule->getError();
739
			$message = $oModule->getMessage();
740
			$messageType = $oModule->getMessageType();
741
			$redirectUrl = $oModule->getRedirectUrl();
742
			if($messageType == 'error') debugPrint($message, 'ERROR');
0 ignored issues
show
Documentation introduced by
'ERROR' is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
743
744
			if(!$procResult)
745
			{
746
				$this->error = $message;
747
				if(!$redirectUrl && Context::get('error_return_url'))
748
				{
749
					$redirectUrl = Context::get('error_return_url');
750
				}
751
				$this->_setInputValueToSession();
752
			}
753
			else
0 ignored issues
show
Unused Code introduced by
This else statement is empty and can be removed.

This check looks for the else branches of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These else branches can be removed.

if (rand(1, 6) > 3) {
print "Check failed";
} else {
    //print "Check succeeded";
}

could be turned into

if (rand(1, 6) > 3) {
    print "Check failed";
}

This is much more concise to read.

Loading history...
754
			{
755
756
			}
757
758
			$_SESSION['XE_VALIDATOR_ERROR'] = $error;
759
			$_SESSION['XE_VALIDATOR_ID'] = Context::get('xe_validator_id');
760
			if($message != 'success')
761
			{
762
				$_SESSION['XE_VALIDATOR_MESSAGE'] = $message;
763
			}
764
			$_SESSION['XE_VALIDATOR_MESSAGE_TYPE'] = $messageType;
765
766
			if(Context::get('xeVirtualRequestMethod') != 'xml')
767
			{
768
				$_SESSION['XE_VALIDATOR_RETURN_URL'] = $redirectUrl;
769
			}
770
		}
771
772
		unset($logged_info);
773
		return $oModule;
774
	}
775
776
	/**
777
	 * set error message to Session.
778
	 * @return void
779
	 * */
780
	function _setInputErrorToContext()
781
	{
782
		if($_SESSION['XE_VALIDATOR_ERROR'] && !Context::get('XE_VALIDATOR_ERROR'))
783
		{
784
			Context::set('XE_VALIDATOR_ERROR', $_SESSION['XE_VALIDATOR_ERROR']);
785
		}
786
		if($_SESSION['XE_VALIDATOR_MESSAGE'] && !Context::get('XE_VALIDATOR_MESSAGE'))
787
		{
788
			Context::set('XE_VALIDATOR_MESSAGE', $_SESSION['XE_VALIDATOR_MESSAGE']);
789
		}
790
		if($_SESSION['XE_VALIDATOR_MESSAGE_TYPE'] && !Context::get('XE_VALIDATOR_MESSAGE_TYPE'))
791
		{
792
			Context::set('XE_VALIDATOR_MESSAGE_TYPE', $_SESSION['XE_VALIDATOR_MESSAGE_TYPE']);
793
		}
794
		if($_SESSION['XE_VALIDATOR_RETURN_URL'] && !Context::get('XE_VALIDATOR_RETURN_URL'))
795
		{
796
			Context::set('XE_VALIDATOR_RETURN_URL', $_SESSION['XE_VALIDATOR_RETURN_URL']);
797
		}
798
		if($_SESSION['XE_VALIDATOR_ID'] && !Context::get('XE_VALIDATOR_ID'))
799
		{
800
			Context::set('XE_VALIDATOR_ID', $_SESSION['XE_VALIDATOR_ID']);
801
		}
802
		if(count($_SESSION['INPUT_ERROR']))
803
		{
804
			Context::set('INPUT_ERROR', $_SESSION['INPUT_ERROR']);
805
		}
806
807
		$this->_clearErrorSession();
808
	}
809
810
	/**
811
	 * clear error message to Session.
812
	 * @return void
813
	 * */
814
	function _clearErrorSession()
815
	{
816
		$_SESSION['XE_VALIDATOR_ERROR'] = '';
817
		$_SESSION['XE_VALIDATOR_MESSAGE'] = '';
818
		$_SESSION['XE_VALIDATOR_MESSAGE_TYPE'] = '';
819
		$_SESSION['XE_VALIDATOR_RETURN_URL'] = '';
820
		$_SESSION['XE_VALIDATOR_ID'] = '';
821
		$_SESSION['INPUT_ERROR'] = '';
822
	}
823
824
	/**
825
	 * occured error when, set input values to session.
826
	 * @return void
827
	 * */
828
	function _setInputValueToSession()
829
	{
830
		$requestVars = Context::getRequestVars();
831
		unset($requestVars->act, $requestVars->mid, $requestVars->vid, $requestVars->success_return_url, $requestVars->error_return_url);
832
		foreach($requestVars AS $key => $value)
833
		{
834
			$_SESSION['INPUT_ERROR'][$key] = $value;
835
		}
836
	}
837
838
	/**
839
	 * display contents from executed module
840
	 * @param ModuleObject $oModule module instance
841
	 * @return void
842
	 * */
843
	function displayContent($oModule = NULL)
844
	{
845
		// If the module is not set or not an object, set error
846
		if(!$oModule || !is_object($oModule))
847
		{
848
			$this->error = 'msg_module_is_not_exists';
849
			$this->httpStatusCode = '404';
850
		}
851
852
		// If connection to DB has a problem even though it's not install module, set error
853
		if($this->module != 'install' && isset($GLOBALS['__DB__']) && $GLOBALS['__DB__'][Context::getDBType()]->isConnected() == FALSE)
854
		{
855
			$this->error = 'msg_dbconnect_failed';
856
		}
857
858
		// Call trigger after moduleHandler proc
859
		$output = ModuleHandler::triggerCall('moduleHandler.proc', 'after', $oModule);
0 ignored issues
show
Bug introduced by
It seems like $oModule defined by parameter $oModule on line 843 can be null; however, ModuleHandler::triggerCall() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
860
		if(!$output->toBool())
861
		{
862
			$this->error = $output->getMessage();
863
		}
864
865
		// Use message view object, if HTML call
866
		$methodList = array('XMLRPC' => 1, 'JSON' => 1, 'JS_CALLBACK' => 1);
867
		if(!isset($methodList[Context::getRequestMethod()]))
868
		{
869
870
			if($_SESSION['XE_VALIDATOR_RETURN_URL'])
871
			{
872
				$display_handler = new DisplayHandler();
873
				$display_handler->_debugOutput();
874
875
				header('location:' . $_SESSION['XE_VALIDATOR_RETURN_URL']);
876
				return;
877
			}
878
879
			// If error occurred, handle it
880
			if($this->error)
881
			{
882
				// display content with message module instance
883
				$type = Mobile::isFromMobilePhone() ? 'mobile' : 'view';
884
				$oMessageObject = ModuleHandler::getModuleInstance('message', $type);
885
				$oMessageObject->setError(-1);
886
				$oMessageObject->setMessage($this->error);
887
				$oMessageObject->dispMessage();
888
889
				if($oMessageObject->getHttpStatusCode() && $oMessageObject->getHttpStatusCode() != '200')
890
				{
891
					$this->_setHttpStatusMessage($oMessageObject->getHttpStatusCode());
892
					$oMessageObject->setTemplateFile('http_status_code');
893
				}
894
895
				// If module was called normally, change the templates of the module into ones of the message view module
896
				if($oModule)
897
				{
898
					$oModule->setTemplatePath($oMessageObject->getTemplatePath());
899
					$oModule->setTemplateFile($oMessageObject->getTemplateFile());
900
					// Otherwise, set message instance as the target module
901
				}
902
				else
903
				{
904
					$oModule = $oMessageObject;
905
				}
906
907
				$this->_clearErrorSession();
908
			}
909
910
			// Check if layout_srl exists for the module
911
			if(Mobile::isFromMobilePhone())
912
			{
913
				$layout_srl = $oModule->module_info->mlayout_srl;
914
			}
915
			else
916
			{
917
				$layout_srl = $oModule->module_info->layout_srl;
918
			}
919
920
			// if layout_srl is rollback by module, set default layout
921
			if($layout_srl == -1)
922
			{
923
				$viewType = (Mobile::isFromMobilePhone()) ? 'M' : 'P';
924
				$oLayoutAdminModel = getAdminModel('layout');
925
				$layout_srl = $oLayoutAdminModel->getSiteDefaultLayout($viewType, $oModule->module_info->site_srl);
926
			}
927
928
			if($layout_srl && !$oModule->getLayoutFile())
929
			{
930
931
				// If layout_srl exists, get information of the layout, and set the location of layout_path/ layout_file
932
				$oLayoutModel = getModel('layout');
933
				$layout_info = $oLayoutModel->getLayout($layout_srl);
0 ignored issues
show
Bug introduced by
The method getLayout() does not exist on ModuleObject. Did you maybe mean getLayoutFile()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
934
				if($layout_info)
935
				{
936
937
					// Input extra_vars into $layout_info
938 View Code Duplication
					if($layout_info->extra_var_count)
939
					{
940
941
						foreach($layout_info->extra_var as $var_id => $val)
942
						{
943
							if($val->type == 'image')
944
							{
945
								if(strncmp('./files/attach/images/', $val->value, 22) === 0)
946
								{
947
									$val->value = Context::getRequestUri() . substr($val->value, 2);
948
								}
949
							}
950
							$layout_info->{$var_id} = $val->value;
951
						}
952
					}
953
					// Set menus into context
954
					if($layout_info->menu_count)
955
					{
956
						foreach($layout_info->menu as $menu_id => $menu)
957
						{
958
							// set default menu set(included home menu)
959 View Code Duplication
							if(!$menu->menu_srl || $menu->menu_srl == -1)
960
							{
961
								$oMenuAdminController = getAdminController('menu');
962
								$homeMenuCacheFile = $oMenuAdminController->getHomeMenuCacheFile();
963
964
								if(FileHandler::exists($homeMenuCacheFile))
0 ignored issues
show
Bug Best Practice introduced by
The expression \FileHandler::exists($homeMenuCacheFile) of type string|false is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
965
								{
966
									include($homeMenuCacheFile);
967
								}
968
969
								if(!$menu->menu_srl)
970
								{
971
									$menu->xml_file = str_replace('.xml.php', $homeMenuSrl . '.xml.php', $menu->xml_file);
0 ignored issues
show
Bug introduced by
The variable $homeMenuSrl 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...
972
									$menu->php_file = str_replace('.php', $homeMenuSrl . '.php', $menu->php_file);
973
									$layout_info->menu->{$menu_id}->menu_srl = $homeMenuSrl;
974
								}
975
								else
976
								{
977
									$menu->xml_file = str_replace($menu->menu_srl, $homeMenuSrl, $menu->xml_file);
978
									$menu->php_file = str_replace($menu->menu_srl, $homeMenuSrl, $menu->php_file);
979
								}
980
							}
981
982
							$php_file = FileHandler::exists($menu->php_file);
983
							if($php_file)
0 ignored issues
show
Bug Best Practice introduced by
The expression $php_file of type string|false is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
984
							{
985
								include($php_file);
986
							}
987
							Context::set($menu_id, $menu);
988
						}
989
					}
990
991
					// Set layout information into context
992
					Context::set('layout_info', $layout_info);
993
994
					$oModule->setLayoutPath($layout_info->path);
995
					$oModule->setLayoutFile('layout');
996
997
					// If layout was modified, use the modified version
998
					$edited_layout = $oLayoutModel->getUserLayoutHtml($layout_info->layout_srl);
999
					if(file_exists($edited_layout))
1000
					{
1001
						$oModule->setEditedLayoutFile($edited_layout);
1002
					}
1003
				}
1004
			}
1005
			$isLayoutDrop = Context::get('isLayoutDrop');
1006
			if($isLayoutDrop)
1007
			{
1008
				$kind = stripos($this->act, 'admin') !== FALSE ? 'admin' : '';
1009
				if($kind == 'admin')
1010
				{
1011
					$oModule->setLayoutFile('popup_layout');
1012
				}
1013
				else
1014
				{
1015
					$oModule->setLayoutPath('common/tpl');
1016
					$oModule->setLayoutFile('default_layout');
1017
				}
1018
			}
1019
		}
1020
1021
		// Display contents
1022
		$oDisplayHandler = new DisplayHandler();
1023
		$oDisplayHandler->printContent($oModule);
1024
	}
1025
1026
	/**
1027
	 * returns module's path
1028
	 * @param string $module module name
1029
	 * @return string path of the module
1030
	 * */
1031
	function getModulePath($module)
1032
	{
1033
		return sprintf('./modules/%s/', $module);
1034
	}
1035
1036
	/**
1037
	 * It creates a module instance
1038
	 * @param string $module module name
1039
	 * @param string $type instance type, (e.g., view, controller, model)
1040
	 * @param string $kind admin or svc
1041
	 * @return ModuleObject module instance (if failed it returns null)
1042
	 * @remarks if there exists a module instance created before, returns it.
1043
	 * */
1044
	function &getModuleInstance($module, $type = 'view', $kind = '')
1045
	{
1046
1047
		if(__DEBUG__ == 3)
1048
		{
1049
			$start_time = getMicroTime();
1050
		}
1051
1052
		$parent_module = $module;
1053
		$kind = strtolower($kind);
1054
		$type = strtolower($type);
1055
1056
		$kinds = array('svc' => 1, 'admin' => 1);
1057
		if(!isset($kinds[$kind]))
1058
		{
1059
			$kind = 'svc';
1060
		}
1061
1062
		$key = $module . '.' . ($kind != 'admin' ? '' : 'admin') . '.' . $type;
1063
1064
		if(is_array($GLOBALS['__MODULE_EXTEND__']) && array_key_exists($key, $GLOBALS['__MODULE_EXTEND__']))
1065
		{
1066
			$module = $extend_module = $GLOBALS['__MODULE_EXTEND__'][$key];
1067
		}
1068
1069
		// if there is no instance of the module in global variable, create a new one
1070
		if(!isset($GLOBALS['_loaded_module'][$module][$type][$kind]))
1071
		{
1072
			ModuleHandler::_getModuleFilePath($module, $type, $kind, $class_path, $high_class_file, $class_file, $instance_name);
1073
1074
			if($extend_module && (!is_readable($high_class_file) || !is_readable($class_file)))
0 ignored issues
show
Bug introduced by
The variable $extend_module does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
1075
			{
1076
				$module = $parent_module;
1077
				ModuleHandler::_getModuleFilePath($module, $type, $kind, $class_path, $high_class_file, $class_file, $instance_name);
1078
			}
1079
1080
			// Check if the base class and instance class exist
1081
			if(!class_exists($module, true))
1082
			{
1083
				return NULL;
1084
			}
1085
			if(!class_exists($instance_name, true))
1086
			{
1087
				return NULL;
1088
			}
1089
1090
			// Create an instance
1091
			$oModule = new $instance_name();
1092
			if(!is_object($oModule))
1093
			{
1094
				return NULL;
1095
			}
1096
1097
			// Load language files for the class
1098
			Context::loadLang($class_path . 'lang');
1099
			if($extend_module)
1100
			{
1101
				Context::loadLang(ModuleHandler::getModulePath($parent_module) . 'lang');
1102
			}
1103
1104
			// Set variables to the instance
1105
			$oModule->setModule($module);
1106
			$oModule->setModulePath($class_path);
1107
1108
			// If the module has a constructor, run it.
1109
			if(!isset($GLOBALS['_called_constructor'][$instance_name]))
1110
			{
1111
				$GLOBALS['_called_constructor'][$instance_name] = TRUE;
1112
				if(@method_exists($oModule, $instance_name))
1113
				{
1114
					$oModule->{$instance_name}();
1115
				}
1116
			}
1117
1118
			// Store the created instance into GLOBALS variable
1119
			$GLOBALS['_loaded_module'][$module][$type][$kind] = $oModule;
1120
		}
1121
1122
		if(__DEBUG__ == 3)
1123
		{
1124
			$GLOBALS['__elapsed_class_load__'] += getMicroTime() - $start_time;
0 ignored issues
show
Bug introduced by
The variable $start_time does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
1125
		}
1126
1127
		// return the instance
1128
		return $GLOBALS['_loaded_module'][$module][$type][$kind];
1129
	}
1130
1131
	function _getModuleFilePath($module, $type, $kind, &$classPath, &$highClassFile, &$classFile, &$instanceName)
1132
	{
1133
		$classPath = ModuleHandler::getModulePath($module);
1134
1135
		$highClassFile = sprintf('%s%s%s.class.php', _XE_PATH_, $classPath, $module);
1136
		$highClassFile = FileHandler::getRealPath($highClassFile);
1137
1138
		$types = array('view','controller','model','api','wap','mobile','class');
1139
		if(!in_array($type, $types))
1140
		{
1141
			$type = $types[0];
1142
		}
1143
		if($type == 'class')
1144
		{
1145
			$instanceName = '%s';
1146
			$classFile = '%s%s.%s.php';
1147
		}
1148
		elseif($kind == 'admin' && array_search($type, $types) < 3)
1149
		{
1150
			$instanceName = '%sAdmin%s';
1151
			$classFile = '%s%s.admin.%s.php';
1152
		}
1153
		else
1154
		{
1155
			$instanceName = '%s%s';
1156
			$classFile = '%s%s.%s.php';
1157
		}
1158
1159
		$instanceName = sprintf($instanceName, $module, ucfirst($type));
1160
		$classFile = FileHandler::getRealPath(sprintf($classFile, $classPath, $module, $type));
1161
	}
1162
1163
	/**
1164
	 * call a trigger
1165
	 * @param string $trigger_name trigger's name to call
1166
	 * @param string $called_position called position
1167
	 * @param object $obj an object as a parameter to trigger
1168
	 * @return Object
1169
	 * */
1170
	function triggerCall($trigger_name, $called_position, &$obj)
1171
	{
1172
		// skip if not installed
1173
		if(!Context::isInstalled())
1174
		{
1175
			return new Object();
1176
		}
1177
1178
		$oModuleModel = getModel('module');
1179
		$triggers = $oModuleModel->getTriggers($trigger_name, $called_position);
1180
		if(!$triggers || count($triggers) < 1)
1181
		{
1182
			return new Object();
1183
		}
1184
		
1185
		//store before trigger call time
1186
		$before_trigger_time = NULL;
0 ignored issues
show
Unused Code introduced by
$before_trigger_time is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
1187
		if(__LOG_SLOW_TRIGGER__> 0)
1188
		{
1189
			$before_trigger_time = microtime(true);
0 ignored issues
show
Unused Code introduced by
$before_trigger_time is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
1190
		}
1191
1192
		foreach($triggers as $item)
1193
		{
1194
			$module = $item->module;
1195
			$type = $item->type;
1196
			$called_method = $item->called_method;
1197
1198
			// todo why don't we call a normal class object ?
1199
			$oModule = getModule($module, $type);
1200
			if(!$oModule || !method_exists($oModule, $called_method))
1201
			{
1202
				continue;
1203
			}
1204
1205
			$before_each_trigger_time = microtime(true);
1206
1207
			$output = $oModule->{$called_method}($obj);
1208
1209
			$after_each_trigger_time = microtime(true);
1210
			$elapsed_time_trigger = $after_each_trigger_time - $before_each_trigger_time;
1211
1212
			$slowlog = new stdClass;
1213
			$slowlog->caller = $trigger_name . '.' . $called_position;
1214
			$slowlog->called = $module . '.' . $called_method;
1215
			$slowlog->called_extension = $module;
1216
			if($trigger_name != 'XE.writeSlowlog') writeSlowlog('trigger', $elapsed_time_trigger, $slowlog);
1217
1218
			if(is_object($output) && method_exists($output, 'toBool') && !$output->toBool())
1219
			{
1220
				return $output;
1221
			}
1222
			unset($oModule);
1223
		}
1224
1225
		return new Object();
1226
	}
1227
1228
	/**
1229
	 * get http status message by http status code
1230
	 * @param string $code
1231
	 * @return string
1232
	 * */
1233
	function _setHttpStatusMessage($code)
1234
	{
1235
		$statusMessageList = array(
1236
			'100' => 'Continue',
1237
			'101' => 'Switching Protocols',
1238
			'201' => 'OK', // todo check array key '201'
1239
			'201' => 'Created',
1240
			'202' => 'Accepted',
1241
			'203' => 'Non-Authoritative Information',
1242
			'204' => 'No Content',
1243
			'205' => 'Reset Content',
1244
			'206' => 'Partial Content',
1245
			'300' => 'Multiple Choices',
1246
			'301' => 'Moved Permanently',
1247
			'302' => 'Found',
1248
			'303' => 'See Other',
1249
			'304' => 'Not Modified',
1250
			'305' => 'Use Proxy',
1251
			'307' => 'Temporary Redirect',
1252
			'400' => 'Bad Request',
1253
			'401' => 'Unauthorized',
1254
			'402' => 'Payment Required',
1255
			'403' => 'Forbidden',
1256
			'404' => 'Not Found',
1257
			'405' => 'Method Not Allowed',
1258
			'406' => 'Not Acceptable',
1259
			'407' => 'Proxy Authentication Required',
1260
			'408' => 'Request Timeout',
1261
			'409' => 'Conflict',
1262
			'410' => 'Gone',
1263
			'411' => 'Length Required',
1264
			'412' => 'Precondition Failed',
1265
			'413' => 'Request Entity Too Large',
1266
			'414' => 'Request-URI Too Long',
1267
			'415' => 'Unsupported Media Type',
1268
			'416' => 'Requested Range Not Satisfiable',
1269
			'417' => 'Expectation Failed',
1270
			'500' => 'Internal Server Error',
1271
			'501' => 'Not Implemented',
1272
			'502' => 'Bad Gateway',
1273
			'503' => 'Service Unavailable',
1274
			'504' => 'Gateway Timeout',
1275
			'505' => 'HTTP Version Not Supported',
1276
		);
1277
		$statusMessage = $statusMessageList[$code];
1278
		if(!$statusMessage)
1279
		{
1280
			$statusMessage = 'OK';
1281
		}
1282
1283
		Context::set('http_status_code', $code);
1284
		Context::set('http_status_message', $statusMessage);
1285
	}
1286
1287
}
1288
/* End of file ModuleHandler.class.php */
1289
/* Location: ./classes/module/ModuleHandler.class.php */
1290