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 (#1872)
by
unknown
17:31
created

ModuleHandler::ModuleHandler()   F

Complexity

Conditions 31
Paths 19458

Size

Total Lines 88
Code Lines 48

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 88
rs 2.1416
cc 31
eloc 48
nc 19458
nop 5

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
		if(__DEBUG__ == 1 && __DEBUG_OUTPUT__ == 0)
106
		{
107
			if(__DEBUG_PROTECT__ === 1 && __DEBUG_PROTECT_IP__ == $_SERVER['REMOTE_ADDR'])
108
			{
109
				set_error_handler(array($this, 'xeErrorLog'), E_WARNING);
110
			}
111
			else if(__DEBUG_PROTECT__ === 0)
112
			{
113
				set_error_handler(array($this, 'xeErrorLog'), E_WARNING);
114
			}
115
		}
116
117
		// execute addon (before module initialization)
118
		$called_position = 'before_module_init';
119
		$oAddonController = getController('addon');
120
		$addon_file = $oAddonController->getCacheFilePath(Mobile::isFromMobilePhone() ? 'mobile' : 'pc');
121
		if(file_exists($addon_file)) include($addon_file);
122
	}
123
124
	function xeErrorLog($errnumber, $errormassage, $errorfile, $errorline, $errorcontext)
0 ignored issues
show
Unused Code introduced by
The parameter $errorcontext is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
125
	{
126
		if($errnumber != E_WARNING)
127
		{
128
			return false;
129
		}
130
		else
131
		{
132
			$errorname = 'Warrning!';
133
		}
134
		$buff = "\n".$errorname . " : ";
135
		$buff .= $errormassage . "\n";
136
		$buff .= "file : " . $errorfile . " line : ";
137
		$buff .= $errorline . "\n";
138
		debugPrint($buff);
139
		restore_error_handler();
140
		return true;
141
	}
142
143
	/**
144
	 * Initialization. It finds the target module based on module, mid, document_srl, and prepares to execute an action
145
	 * @return boolean true: OK, false: redirected
146
	 * */
147
	function init()
148
	{
149
		$oModuleModel = getModel('module');
150
		$site_module_info = Context::get('site_module_info');
151
152
		// if success_return_url and error_return_url is incorrect
153
		$urls = array(Context::get('success_return_url'), Context::get('error_return_url'));
154
		foreach($urls as $url)
155
		{
156
			if(empty($url))
157
			{
158
				continue;
159
			}
160
		
161
			$urlInfo = parse_url($url);
162
			$host = $urlInfo['host'];
163
		
164
			$dbInfo = Context::getDBInfo();
165
			$defaultUrlInfo = parse_url($dbInfo->default_url);
166
			$defaultHost = $defaultUrlInfo['host'];
167
		
168
			if($host && ($host != $defaultHost && $host != $site_module_info->domain))
169
			{
170
				throw new Exception('msg_default_url_is_null');
171
			}
172
		}
173
		
174
		if(!$this->document_srl && $this->mid && $this->entry)
175
		{
176
			$oDocumentModel = getModel('document');
177
			$this->document_srl = $oDocumentModel->getDocumentSrlByAlias($this->mid, $this->entry);
178
			if($this->document_srl)
179
			{
180
				Context::set('document_srl', $this->document_srl);
181
			}
182
		}
183
184
		// Get module's information based on document_srl, if it's specified
185
		if($this->document_srl)
186
		{
187
			
188
			$module_info = $oModuleModel->getModuleInfoByDocumentSrl($this->document_srl);
189
			// If the document does not exist, remove document_srl
190
			if(!$module_info)
191
			{
192
				unset($this->document_srl);
193
			}
194
			else
195
			{
196
				// If it exists, compare mid based on the module information
197
				// if mids are not matching, set it as the document's mid
198
				if(!$this->mid || ($this->mid != $module_info->mid))
199
				{
200
					
201
					if(Context::getRequestMethod() == 'GET')
202
					{
203
						$this->mid = $module_info->mid;
204
						header('location:' . getNotEncodedSiteUrl($site_module_info->domain, 'mid', $this->mid, 'document_srl', $this->document_srl));
205
						return FALSE;
206
					}
207
					else
208
					{
209
						$this->mid = $module_info->mid;
210
						Context::set('mid', $this->mid);
211
					}
212
					
213
				}
214
				// if requested module is different from one of the document, remove the module information retrieved based on the document number
215
				if($this->module && $module_info->module != $this->module)
216
				{
217
					unset($module_info);
218
				}
219
			}
220
221
		}
222
223
		// If module_info is not set yet, and there exists mid information, get module information based on the mid
224
		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...
225
		{
226
			$module_info = $oModuleModel->getModuleInfoByMid($this->mid, $site_module_info->site_srl);
227
			//if($this->module && $module_info->module != $this->module) unset($module_info);
228
		}
229
230
		// redirect, if module_site_srl and site_srl are different
231
		if(!$this->module && !$module_info && $site_module_info->site_srl == 0 && $site_module_info->module_site_srl > 0)
232
		{
233
			$site_info = $oModuleModel->getSiteInfo($site_module_info->module_site_srl);
234
			header("location:" . getNotEncodedSiteUrl($site_info->domain, 'mid', $site_module_info->mid));
235
			return FALSE;
236
		}
237
238
		// If module_info is not set still, and $module does not exist, find the default module
239
		if(!$module_info && !$this->module && !$this->mid)
240
		{
241
			$module_info = $site_module_info;
242
		}
243
244
		if(!$module_info && !$this->module && $site_module_info->module_site_srl)
245
		{
246
			$module_info = $site_module_info;
247
		}
248
249
		// redirect, if site_srl of module_info is different from one of site's module_info
250
		if($module_info && $module_info->site_srl != $site_module_info->site_srl && !isCrawler())
251
		{
252
			// If the module is of virtual site
253
			if($module_info->site_srl)
254
			{
255
				$site_info = $oModuleModel->getSiteInfo($module_info->site_srl);
256
				$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'));
257
				// If it's called from a virtual site, though it's not a module of the virtual site
258
			}
259
			else
260
			{
261
				$db_info = Context::getDBInfo();
262
				if(!$db_info->default_url)
263
				{
264
					return Context::getLang('msg_default_url_is_not_defined');
265
				}
266
				else
267
				{
268
					$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'));
269
				}
270
			}
271
			header("location:" . $redirect_url);
272
			return FALSE;
273
		}
274
275
		// If module info was set, retrieve variables from the module information
276
		if($module_info)
277
		{
278
			$this->module = $module_info->module;
279
			$this->mid = $module_info->mid;
280
			$this->module_info = $module_info;
281
			Context::setBrowserTitle($module_info->browser_title);
282
283
			$viewType = (Mobile::isFromMobilePhone()) ? 'M' : 'P';
284
			$targetSrl = (Mobile::isFromMobilePhone()) ? 'mlayout_srl' : 'layout_srl';
285
286
			// use the site default layout.
287
			if($module_info->{$targetSrl} == -1)
288
			{
289
				$oLayoutAdminModel = getAdminModel('layout');
290
				$layoutSrl = $oLayoutAdminModel->getSiteDefaultLayout($viewType, $module_info->site_srl);
291
			}
292
			else
293
			{
294
				$layoutSrl = $module_info->{$targetSrl};
295
			}
296
297
			// reset a layout_srl in module_info.
298
			$module_info->{$targetSrl} = $layoutSrl;
299
300
			$part_config = $oModuleModel->getModulePartConfig('layout', $layoutSrl);
301
			Context::addHtmlHeader($part_config->header_script);
302
		}
303
304
		// Set module and mid into module_info
305
		if(!isset($this->module_info))
306
		{
307
			$this->module_info = new stdClass();
308
		}
309
		$this->module_info->module = $this->module;
310
		$this->module_info->mid = $this->mid;
311
312
		// Set site_srl add 2011 08 09
313
		$this->module_info->site_srl = $site_module_info->site_srl;
314
315
		// Still no module? it's an error
316
		if(!$this->module)
317
		{
318
			$this->error = 'msg_module_is_not_exists';
319
			$this->httpStatusCode = '404';
320
		}
321
322
		// If mid exists, set mid into context
323
		if($this->mid)
324
		{
325
			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...
326
		}
327
		
328
		// Call a trigger after moduleHandler init
329
		$output = ModuleHandler::triggerCall('moduleHandler.init', 'after', $this->module_info);
330
		if(!$output->toBool())
331
		{
332
			$this->error = $output->getMessage();
333
			return TRUE;
334
		}
335
336
		// Set current module info into context
337
		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...
338
339
		return TRUE;
340
	}
341
342
	/**
343
	 * get a module instance and execute an action
344
	 * @return ModuleObject executed module instance
345
	 * */
346
	function procModule()
347
	{
348
		$oModuleModel = getModel('module');
349
		$display_mode = Mobile::isFromMobilePhone() ? 'mobile' : 'view';
350
351
		// If error occurred while preparation, return a message instance
352
		if($this->error)
353
		{
354
			$this->_setInputErrorToContext();
355
			$oMessageObject = ModuleHandler::getModuleInstance('message', $display_mode);
356
			$oMessageObject->setError(-1);
357
			$oMessageObject->setMessage($this->error);
358
			$oMessageObject->dispMessage();
359
			if($this->httpStatusCode)
360
			{
361
				$oMessageObject->setHttpStatusCode($this->httpStatusCode);
362
			}
363
			return $oMessageObject;
364
		}
365
366
		// Get action information with conf/module.xml
367
		$xml_info = $oModuleModel->getModuleActionXml($this->module);
368
369
		// If not installed yet, modify act
370
		if($this->module == "install")
371
		{
372
			if(!$this->act || !$xml_info->action->{$this->act})
373
			{
374
				$this->act = $xml_info->default_index_act;
375
			}
376
		}
377
378
		// if act exists, find type of the action, if not use default index act
379
		if(!$this->act)
380
		{
381
			$this->act = $xml_info->default_index_act;
382
		}
383
384
		// still no act means error
385
		if(!$this->act)
386
		{
387
			$this->error = 'msg_module_is_not_exists';
388
			$this->httpStatusCode = '404';
389
390
			$this->_setInputErrorToContext();
391
			$oMessageObject = ModuleHandler::getModuleInstance('message', $display_mode);
392
			$oMessageObject->setError(-1);
393
			$oMessageObject->setMessage($this->error);
394
			$oMessageObject->dispMessage();
395
			if($this->httpStatusCode)
396
			{
397
				$oMessageObject->setHttpStatusCode($this->httpStatusCode);
398
			}
399
			return $oMessageObject;
400
		}
401
402
		// get type, kind
403
		$type = $xml_info->action->{$this->act}->type;
404
		$ruleset = $xml_info->action->{$this->act}->ruleset;
405
		$kind = stripos($this->act, 'admin') !== FALSE ? 'admin' : '';
406
		if(!$kind && $this->module == 'admin')
407
		{
408
			$kind = 'admin';
409
		}
410
411
		// check REQUEST_METHOD in controller
412 View Code Duplication
		if($type == 'controller')
413
		{
414
			$allowedMethod = $xml_info->action->{$this->act}->method;
415
416
			if(!$allowedMethod)
417
			{
418
				$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...
419
			}
420
			else
421
			{
422
				$allowedMethodList = explode('|', strtoupper($allowedMethod));
423
			}
424
425
			if(!in_array(strtoupper($_SERVER['REQUEST_METHOD']), $allowedMethodList))
426
			{
427
				$this->error = "msg_invalid_request";
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
436
		if($this->module_info->use_mobile != "Y")
437
		{
438
			Mobile::setMobile(FALSE);
439
		}
440
441
		$logged_info = Context::get('logged_info');
442
443
		// check CSRF for POST actions
444
		if(Context::getRequestMethod() === 'POST' && Context::isInstalled() && $this->act !== 'procFileUpload' && !checkCSRF()) {
445
			$this->error = 'msg_invalid_request';
446
			$oMessageObject = ModuleHandler::getModuleInstance('message', $display_mode);
447
			$oMessageObject->setError(-1);
448
			$oMessageObject->setMessage($this->error);
449
			$oMessageObject->dispMessage();
450
			return $oMessageObject;
451
		}
452
453
		// Admin ip
454
		if($kind == 'admin' && $_SESSION['denied_admin'] == 'Y')
455
		{
456
			$this->_setInputErrorToContext();
457
			$this->error = "msg_not_permitted_act";
458
			$oMessageObject = ModuleHandler::getModuleInstance('message', $display_mode);
459
			$oMessageObject->setError(-1);
460
			$oMessageObject->setMessage($this->error);
461
			$oMessageObject->dispMessage();
462
			return $oMessageObject;
463
		}
464
465
		// if(type == view, and case for using mobilephone)
466
		if($type == "view" && Mobile::isFromMobilePhone() && Context::isInstalled())
467
		{
468
			$orig_type = "view";
469
			$type = "mobile";
470
			// create a module instance
471
			$oModule = $this->getModuleInstance($this->module, $type, $kind);
472 View Code Duplication
			if(!is_object($oModule) || !method_exists($oModule, $this->act))
473
			{
474
				$type = $orig_type;
475
				Mobile::setMobile(FALSE);
476
				$oModule = $this->getModuleInstance($this->module, $type, $kind);
477
			}
478
		}
479
		else
480
		{
481
			// create a module instance
482
			$oModule = $this->getModuleInstance($this->module, $type, $kind);
483
		}
484
485 View Code Duplication
		if(!is_object($oModule))
486
		{
487
			$this->_setInputErrorToContext();
488
			$oMessageObject = ModuleHandler::getModuleInstance('message', $display_mode);
489
			$oMessageObject->setError(-1);
490
			$oMessageObject->setMessage($this->error);
491
			$oMessageObject->dispMessage();
492
			if($this->httpStatusCode)
493
			{
494
				$oMessageObject->setHttpStatusCode($this->httpStatusCode);
495
			}
496
			return $oMessageObject;
497
		}
498
499
		// If there is no such action in the module object
500
		if(!isset($xml_info->action->{$this->act}) || !method_exists($oModule, $this->act))
501
		{
502
503 View Code Duplication
			if(!Context::isInstalled())
504
			{
505
				$this->_setInputErrorToContext();
506
				$this->error = 'msg_invalid_request';
507
				$oMessageObject = ModuleHandler::getModuleInstance('message', $display_mode);
508
				$oMessageObject->setError(-1);
509
				$oMessageObject->setMessage($this->error);
510
				$oMessageObject->dispMessage();
511
				if($this->httpStatusCode)
512
				{
513
					$oMessageObject->setHttpStatusCode($this->httpStatusCode);
514
				}
515
				return $oMessageObject;
516
			}
517
518
			$forward = NULL;
519
			// 1. Look for the module with action name
520
			if(preg_match('/^([a-z]+)([A-Z])([a-z0-9\_]+)(.*)$/', $this->act, $matches))
521
			{
522
				$module = strtolower($matches[2] . $matches[3]);
523
				$xml_info = $oModuleModel->getModuleActionXml($module);
524
525
				if($xml_info->action->{$this->act} && ((stripos($this->act, 'admin') !== FALSE) || $xml_info->action->{$this->act}->standalone != 'false'))
526
				{
527
					$forward = new stdClass();
528
					$forward->module = $module;
529
					$forward->type = $xml_info->action->{$this->act}->type;
530
					$forward->ruleset = $xml_info->action->{$this->act}->ruleset;
531
					$forward->act = $this->act;
532
				}
533 View Code Duplication
				else
534
				{
535
					$this->error = 'msg_invalid_request';
536
					$oMessageObject = ModuleHandler::getModuleInstance('message', $display_mode);
537
					$oMessageObject->setError(-1);
538
					$oMessageObject->setMessage($this->error);
539
					$oMessageObject->dispMessage();
540
541
					return $oMessageObject;
542
				}
543
			}
544
545
			if(!$forward)
546
			{
547
				$forward = $oModuleModel->getActionForward($this->act);
548
			}
549
550
			if($forward->module && $forward->type && $forward->act && $forward->act == $this->act)
551
			{
552
				$kind = stripos($forward->act, 'admin') !== FALSE ? 'admin' : '';
553
				$type = $forward->type;
554
				$ruleset = $forward->ruleset;
555
				$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...
556
				$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...
557
558
				$xml_info = $oModuleModel->getModuleActionXml($forward->module);
559
560
				// SECISSUE also check foward act method
561
				// check REQUEST_METHOD in controller
562 View Code Duplication
				if($type == 'controller')
563
				{
564
					$allowedMethod = $xml_info->action->{$forward->act}->method;
565
566
					if(!$allowedMethod)
567
					{
568
						$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...
569
					}
570
					else
571
					{
572
						$allowedMethodList = explode('|', strtoupper($allowedMethod));
573
					}
574
575
					if(!in_array(strtoupper($_SERVER['REQUEST_METHOD']), $allowedMethodList))
576
					{
577
						$this->error = "msg_invalid_request";
578
						$oMessageObject = ModuleHandler::getModuleInstance('message', $display_mode);
579
						$oMessageObject->setError(-1);
580
						$oMessageObject->setMessage($this->error);
581
						$oMessageObject->dispMessage();
582
						return $oMessageObject;
583
					}
584
				}
585
586
				if($type == "view" && Mobile::isFromMobilePhone())
587
				{
588
					$orig_type = "view";
589
					$type = "mobile";
590
					// create a module instance
591
					$oModule = $this->getModuleInstance($forward->module, $type, $kind);
592 View Code Duplication
					if(!is_object($oModule) || !method_exists($oModule, $this->act))
593
					{
594
						$type = $orig_type;
595
						Mobile::setMobile(FALSE);
596
						$oModule = $this->getModuleInstance($forward->module, $type, $kind);
597
					}
598
				}
599
				else
600
				{
601
					$oModule = $this->getModuleInstance($forward->module, $type, $kind);
602
				}
603
604 View Code Duplication
				if(!is_object($oModule))
605
				{
606
					$this->_setInputErrorToContext();
607
					$oMessageObject = ModuleHandler::getModuleInstance('message', $display_mode);
608
					$oMessageObject->setError(-1);
609
					$oMessageObject->setMessage('msg_module_is_not_exists');
610
					$oMessageObject->dispMessage();
611
					if($this->httpStatusCode)
612
					{
613
						$oMessageObject->setHttpStatusCode($this->httpStatusCode);
614
					}
615
					return $oMessageObject;
616
				}
617
618
				if($this->module == "admin" && $type == "view")
619
				{
620
					if($logged_info->is_admin == 'Y')
621
					{
622
						if($this->act != 'dispLayoutAdminLayoutModify')
623
						{
624
							$oAdminView = getAdminView('admin');
625
							$oAdminView->makeGnbUrl($forward->module);
626
							$oModule->setLayoutPath("./modules/admin/tpl");
627
							$oModule->setLayoutFile("layout.html");
628
						}
629
					}
630 View Code Duplication
					else
631
					{
632
						$this->_setInputErrorToContext();
633
634
						$this->error = 'msg_is_not_administrator';
635
						$oMessageObject = ModuleHandler::getModuleInstance('message', $display_mode);
636
						$oMessageObject->setError(-1);
637
						$oMessageObject->setMessage($this->error);
638
						$oMessageObject->dispMessage();
639
						return $oMessageObject;
640
					}
641
				}
642
				if($kind == 'admin')
643
				{
644
					$grant = $oModuleModel->getGrant($this->module_info, $logged_info);
645
					if(!$grant->manager)
646
					{
647
						$this->_setInputErrorToContext();
648
						$this->error = 'msg_is_not_manager';
649
						$oMessageObject = ModuleHandler::getModuleInstance('message', $display_mode);
650
						$oMessageObject->setError(-1);
651
						$oMessageObject->setMessage($this->error);
652
						$oMessageObject->dispMessage();
653
						return $oMessageObject;
654
					}
655
					else
656
					{
657
						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...
658
						{
659
							$this->_setInputErrorToContext();
660
							$this->error = 'msg_is_not_administrator';
661
							$oMessageObject = ModuleHandler::getModuleInstance('message', $display_mode);
662
							$oMessageObject->setError(-1);
663
							$oMessageObject->setMessage($this->error);
664
							$oMessageObject->dispMessage();
665
							return $oMessageObject;
666
						}
667
					}
668
				}
669
			}
670
			else if($xml_info->default_index_act && method_exists($oModule, $xml_info->default_index_act))
671
			{
672
				$this->act = $xml_info->default_index_act;
673
			}
674
			else
675
			{
676
				$this->error = 'msg_invalid_request';
677
				$oModule->setError(-1);
678
				$oModule->setMessage($this->error);
679
				return $oModule;
680
			}
681
		}
682
683
		// ruleset check...
684
		if(!empty($ruleset))
685
		{
686
			$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...
687
			$rulesetFile = $oModuleModel->getValidatorFilePath($rulesetModule, $ruleset, $this->mid);
688
			if(!empty($rulesetFile))
689
			{
690
				if($_SESSION['XE_VALIDATOR_ERROR_LANG'])
691
				{
692
					$errorLang = $_SESSION['XE_VALIDATOR_ERROR_LANG'];
693
					foreach($errorLang as $key => $val)
694
					{
695
						Context::setLang($key, $val);
696
					}
697
					unset($_SESSION['XE_VALIDATOR_ERROR_LANG']);
698
				}
699
700
				$Validator = new Validator($rulesetFile);
701
				$result = $Validator->validate();
702
				if(!$result)
703
				{
704
					$lastError = $Validator->getLastError();
705
					$returnUrl = Context::get('error_return_url');
706
					$errorMsg = $lastError['msg'] ? $lastError['msg'] : 'validation error';
707
708
					//for xml response
709
					$oModule->setError(-1);
710
					$oModule->setMessage($errorMsg);
711
					//for html redirect
712
					$this->error = $errorMsg;
713
					$_SESSION['XE_VALIDATOR_ERROR'] = -1;
714
					$_SESSION['XE_VALIDATOR_MESSAGE'] = $this->error;
715
					$_SESSION['XE_VALIDATOR_MESSAGE_TYPE'] = 'error';
716
					$_SESSION['XE_VALIDATOR_RETURN_URL'] = $returnUrl;
717
					$_SESSION['XE_VALIDATOR_ID'] = Context::get('xe_validator_id');
718
					$this->_setInputValueToSession();
719
					return $oModule;
720
				}
721
			}
722
		}
723
724
		$oModule->setAct($this->act);
725
726
		$this->module_info->module_type = $type;
727
		$oModule->setModuleInfo($this->module_info, $xml_info);
728
729
		$skipAct = array(
730
				'dispEditorConfigPreview' => 1,
731
				'dispLayoutPreviewWithModule' => 1
732
		);
733
		$db_use_mobile = Mobile::isMobileEnabled();
734
		if($type == "view" && $this->module_info->use_mobile == "Y" && Mobile::isMobileCheckByAgent() && !isset($skipAct[Context::get('act')]) && $db_use_mobile === true)
735
		{
736
			global $lang;
737
			$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>';
738
			$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>';
739
			Context::addHtmlHeader($header);
740
			Context::addHtmlFooter($footer);
741
		}
742
743
		if($type == "view" && $kind != 'admin')
744
		{
745
			$module_config = $oModuleModel->getModuleConfig('module');
746
			if($module_config->htmlFooter)
747
			{
748
				Context::addHtmlFooter($module_config->htmlFooter);
749
			}
750
			if($module_config->siteTitle)
751
			{
752
				$siteTitle = Context::getBrowserTitle();
753
				if(!$siteTitle)
754
				{
755
					Context::setBrowserTitle($module_config->siteTitle);
756
				}
757
			}
758
		}
759
760
		// if failed message exists in session, set context
761
		$this->_setInputErrorToContext();
762
763
		$procResult = $oModule->proc();
764
765
		$methodList = array('XMLRPC' => 1, 'JSON' => 1, 'JS_CALLBACK' => 1);
766
		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...
767
		{
768
			$error = $oModule->getError();
769
			$message = $oModule->getMessage();
770
			$messageType = $oModule->getMessageType();
771
			$redirectUrl = $oModule->getRedirectUrl();
772
			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...
773
774
			if(!$procResult)
775
			{
776
				$this->error = $message;
777
				if(!$redirectUrl && Context::get('error_return_url'))
778
				{
779
					$redirectUrl = Context::get('error_return_url');
780
				}
781
				$this->_setInputValueToSession();
782
			}
783
			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...
784
			{
785
786
			}
787
788
			$_SESSION['XE_VALIDATOR_ERROR'] = $error;
789
			$_SESSION['XE_VALIDATOR_ID'] = Context::get('xe_validator_id');
790
			if($message != 'success')
791
			{
792
				$_SESSION['XE_VALIDATOR_MESSAGE'] = $message;
793
			}
794
			$_SESSION['XE_VALIDATOR_MESSAGE_TYPE'] = $messageType;
795
796
			if(Context::get('xeVirtualRequestMethod') != 'xml')
797
			{
798
				$_SESSION['XE_VALIDATOR_RETURN_URL'] = $redirectUrl;
799
			}
800
		}
801
802
		unset($logged_info);
803
		return $oModule;
804
	}
805
806
	/**
807
	 * set error message to Session.
808
	 * @return void
809
	 * */
810
	function _setInputErrorToContext()
811
	{
812
		if($_SESSION['XE_VALIDATOR_ERROR'] && !Context::get('XE_VALIDATOR_ERROR'))
813
		{
814
			Context::set('XE_VALIDATOR_ERROR', $_SESSION['XE_VALIDATOR_ERROR']);
815
		}
816
		if($_SESSION['XE_VALIDATOR_MESSAGE'] && !Context::get('XE_VALIDATOR_MESSAGE'))
817
		{
818
			Context::set('XE_VALIDATOR_MESSAGE', $_SESSION['XE_VALIDATOR_MESSAGE']);
819
		}
820
		if($_SESSION['XE_VALIDATOR_MESSAGE_TYPE'] && !Context::get('XE_VALIDATOR_MESSAGE_TYPE'))
821
		{
822
			Context::set('XE_VALIDATOR_MESSAGE_TYPE', $_SESSION['XE_VALIDATOR_MESSAGE_TYPE']);
823
		}
824
		if($_SESSION['XE_VALIDATOR_RETURN_URL'] && !Context::get('XE_VALIDATOR_RETURN_URL'))
825
		{
826
			Context::set('XE_VALIDATOR_RETURN_URL', $_SESSION['XE_VALIDATOR_RETURN_URL']);
827
		}
828
		if($_SESSION['XE_VALIDATOR_ID'] && !Context::get('XE_VALIDATOR_ID'))
829
		{
830
			Context::set('XE_VALIDATOR_ID', $_SESSION['XE_VALIDATOR_ID']);
831
		}
832
		if(count($_SESSION['INPUT_ERROR']))
833
		{
834
			Context::set('INPUT_ERROR', $_SESSION['INPUT_ERROR']);
835
		}
836
837
		$this->_clearErrorSession();
838
	}
839
840
	/**
841
	 * clear error message to Session.
842
	 * @return void
843
	 * */
844
	function _clearErrorSession()
845
	{
846
		$_SESSION['XE_VALIDATOR_ERROR'] = '';
847
		$_SESSION['XE_VALIDATOR_MESSAGE'] = '';
848
		$_SESSION['XE_VALIDATOR_MESSAGE_TYPE'] = '';
849
		$_SESSION['XE_VALIDATOR_RETURN_URL'] = '';
850
		$_SESSION['XE_VALIDATOR_ID'] = '';
851
		$_SESSION['INPUT_ERROR'] = '';
852
	}
853
854
	/**
855
	 * occured error when, set input values to session.
856
	 * @return void
857
	 * */
858
	function _setInputValueToSession()
859
	{
860
		$requestVars = Context::getRequestVars();
861
		unset($requestVars->act, $requestVars->mid, $requestVars->vid, $requestVars->success_return_url, $requestVars->error_return_url);
862
		foreach($requestVars AS $key => $value)
863
		{
864
			$_SESSION['INPUT_ERROR'][$key] = $value;
865
		}
866
	}
867
868
	/**
869
	 * display contents from executed module
870
	 * @param ModuleObject $oModule module instance
871
	 * @return void
872
	 * */
873
	function displayContent($oModule = NULL)
874
	{
875
		// If the module is not set or not an object, set error
876
		if(!$oModule || !is_object($oModule))
877
		{
878
			$this->error = 'msg_module_is_not_exists';
879
			$this->httpStatusCode = '404';
880
		}
881
882
		// If connection to DB has a problem even though it's not install module, set error
883
		if($this->module != 'install' && isset($GLOBALS['__DB__']) && $GLOBALS['__DB__'][Context::getDBType()]->isConnected() == FALSE)
884
		{
885
			$this->error = 'msg_dbconnect_failed';
886
		}
887
888
		// Call trigger after moduleHandler proc
889
		$output = ModuleHandler::triggerCall('moduleHandler.proc', 'after', $oModule);
0 ignored issues
show
Bug introduced by
It seems like $oModule defined by parameter $oModule on line 873 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...
890
		if(!$output->toBool())
891
		{
892
			$this->error = $output->getMessage();
893
		}
894
895
		// Use message view object, if HTML call
896
		$methodList = array('XMLRPC' => 1, 'JSON' => 1, 'JS_CALLBACK' => 1);
897
		if(!isset($methodList[Context::getRequestMethod()]))
898
		{
899
900
			if($_SESSION['XE_VALIDATOR_RETURN_URL'])
901
			{
902
				$display_handler = new DisplayHandler();
903
				$display_handler->_debugOutput();
904
905
				header('location:' . $_SESSION['XE_VALIDATOR_RETURN_URL']);
906
				return;
907
			}
908
909
			// If error occurred, handle it
910
			if($this->error)
911
			{
912
				// display content with message module instance
913
				$type = Mobile::isFromMobilePhone() ? 'mobile' : 'view';
914
				$oMessageObject = ModuleHandler::getModuleInstance('message', $type);
915
				$oMessageObject->setError(-1);
916
				$oMessageObject->setMessage($this->error);
917
				$oMessageObject->dispMessage();
918
919
				if($oMessageObject->getHttpStatusCode() && $oMessageObject->getHttpStatusCode() != '200')
920
				{
921
					$this->_setHttpStatusMessage($oMessageObject->getHttpStatusCode());
922
					$oMessageObject->setTemplateFile('http_status_code');
923
				}
924
925
				// If module was called normally, change the templates of the module into ones of the message view module
926
				if($oModule)
927
				{
928
					$oModule->setTemplatePath($oMessageObject->getTemplatePath());
929
					$oModule->setTemplateFile($oMessageObject->getTemplateFile());
930
					// Otherwise, set message instance as the target module
931
				}
932
				else
933
				{
934
					$oModule = $oMessageObject;
935
				}
936
937
				$this->_clearErrorSession();
938
			}
939
940
			// Check if layout_srl exists for the module
941
			if(Mobile::isFromMobilePhone())
942
			{
943
				$layout_srl = $oModule->module_info->mlayout_srl;
944
			}
945
			else
946
			{
947
				$layout_srl = $oModule->module_info->layout_srl;
948
			}
949
950
			// if layout_srl is rollback by module, set default layout
951
			if($layout_srl == -1)
952
			{
953
				$viewType = (Mobile::isFromMobilePhone()) ? 'M' : 'P';
954
				$oLayoutAdminModel = getAdminModel('layout');
955
				$layout_srl = $oLayoutAdminModel->getSiteDefaultLayout($viewType, $oModule->module_info->site_srl);
956
			}
957
958
			if($layout_srl && !$oModule->getLayoutFile())
959
			{
960
961
				// If layout_srl exists, get information of the layout, and set the location of layout_path/ layout_file
962
				$oLayoutModel = getModel('layout');
963
				$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...
964
				if($layout_info)
965
				{
966
967
					// Input extra_vars into $layout_info
968 View Code Duplication
					if($layout_info->extra_var_count)
969
					{
970
971
						foreach($layout_info->extra_var as $var_id => $val)
972
						{
973
							if($val->type == 'image')
974
							{
975
								if(strncmp('./files/attach/images/', $val->value, 22) === 0)
976
								{
977
									$val->value = Context::getRequestUri() . substr($val->value, 2);
978
								}
979
							}
980
							$layout_info->{$var_id} = $val->value;
981
						}
982
					}
983
					// Set menus into context
984
					if($layout_info->menu_count)
985
					{
986
						foreach($layout_info->menu as $menu_id => $menu)
987
						{
988
							// set default menu set(included home menu)
989 View Code Duplication
							if(!$menu->menu_srl || $menu->menu_srl == -1)
990
							{
991
								$oMenuAdminController = getAdminController('menu');
992
								$homeMenuCacheFile = $oMenuAdminController->getHomeMenuCacheFile();
993
994
								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...
995
								{
996
									include($homeMenuCacheFile);
997
								}
998
999
								if(!$menu->menu_srl)
1000
								{
1001
									$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...
1002
									$menu->php_file = str_replace('.php', $homeMenuSrl . '.php', $menu->php_file);
1003
									$layout_info->menu->{$menu_id}->menu_srl = $homeMenuSrl;
1004
								}
1005
								else
1006
								{
1007
									$menu->xml_file = str_replace($menu->menu_srl, $homeMenuSrl, $menu->xml_file);
1008
									$menu->php_file = str_replace($menu->menu_srl, $homeMenuSrl, $menu->php_file);
1009
								}
1010
							}
1011
1012
							$php_file = FileHandler::exists($menu->php_file);
1013
							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...
1014
							{
1015
								include($php_file);
1016
							}
1017
							Context::set($menu_id, $menu);
1018
						}
1019
					}
1020
1021
					// Set layout information into context
1022
					Context::set('layout_info', $layout_info);
1023
1024
					$oModule->setLayoutPath($layout_info->path);
1025
					$oModule->setLayoutFile('layout');
1026
1027
					// If layout was modified, use the modified version
1028
					$edited_layout = $oLayoutModel->getUserLayoutHtml($layout_info->layout_srl);
1029
					if(file_exists($edited_layout))
1030
					{
1031
						$oModule->setEditedLayoutFile($edited_layout);
1032
					}
1033
				}
1034
			}
1035
			$isLayoutDrop = Context::get('isLayoutDrop');
1036
			if($isLayoutDrop)
1037
			{
1038
				$kind = stripos($this->act, 'admin') !== FALSE ? 'admin' : '';
1039
				if($kind == 'admin')
1040
				{
1041
					$oModule->setLayoutFile('popup_layout');
1042
				}
1043
				else
1044
				{
1045
					$oModule->setLayoutPath('common/tpl');
1046
					$oModule->setLayoutFile('default_layout');
1047
				}
1048
			}
1049
		}
1050
1051
		// Display contents
1052
		$oDisplayHandler = new DisplayHandler();
1053
		$oDisplayHandler->printContent($oModule);
1054
	}
1055
1056
	/**
1057
	 * returns module's path
1058
	 * @param string $module module name
1059
	 * @return string path of the module
1060
	 * */
1061
	function getModulePath($module)
1062
	{
1063
		return sprintf('./modules/%s/', $module);
1064
	}
1065
1066
	/**
1067
	 * It creates a module instance
1068
	 * @param string $module module name
1069
	 * @param string $type instance type, (e.g., view, controller, model)
1070
	 * @param string $kind admin or svc
1071
	 * @return ModuleObject module instance (if failed it returns null)
1072
	 * @remarks if there exists a module instance created before, returns it.
1073
	 * */
1074
	function &getModuleInstance($module, $type = 'view', $kind = '')
1075
	{
1076
1077
		if(__DEBUG__ == 3)
1078
		{
1079
			$start_time = getMicroTime();
1080
		}
1081
1082
		$parent_module = $module;
1083
		$kind = strtolower($kind);
1084
		$type = strtolower($type);
1085
1086
		$kinds = array('svc' => 1, 'admin' => 1);
1087
		if(!isset($kinds[$kind]))
1088
		{
1089
			$kind = 'svc';
1090
		}
1091
1092
		$key = $module . '.' . ($kind != 'admin' ? '' : 'admin') . '.' . $type;
1093
1094
		if(is_array($GLOBALS['__MODULE_EXTEND__']) && array_key_exists($key, $GLOBALS['__MODULE_EXTEND__']))
1095
		{
1096
			$module = $extend_module = $GLOBALS['__MODULE_EXTEND__'][$key];
1097
		}
1098
1099
		// if there is no instance of the module in global variable, create a new one
1100
		if(!isset($GLOBALS['_loaded_module'][$module][$type][$kind]))
1101
		{
1102
			ModuleHandler::_getModuleFilePath($module, $type, $kind, $class_path, $high_class_file, $class_file, $instance_name);
1103
1104
			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...
1105
			{
1106
				$module = $parent_module;
1107
				ModuleHandler::_getModuleFilePath($module, $type, $kind, $class_path, $high_class_file, $class_file, $instance_name);
1108
			}
1109
1110
			// Check if the base class and instance class exist
1111
			if(!class_exists($module, true))
1112
			{
1113
				return NULL;
1114
			}
1115
			if(!class_exists($instance_name, true))
1116
			{
1117
				return NULL;
1118
			}
1119
1120
			// Create an instance
1121
			$oModule = new $instance_name();
1122
			if(!is_object($oModule))
1123
			{
1124
				return NULL;
1125
			}
1126
1127
			// Load language files for the class
1128
			Context::loadLang($class_path . 'lang');
1129
			if($extend_module)
1130
			{
1131
				Context::loadLang(ModuleHandler::getModulePath($parent_module) . 'lang');
1132
			}
1133
1134
			// Set variables to the instance
1135
			$oModule->setModule($module);
1136
			$oModule->setModulePath($class_path);
1137
1138
			// If the module has a constructor, run it.
1139
			if(!isset($GLOBALS['_called_constructor'][$instance_name]))
1140
			{
1141
				$GLOBALS['_called_constructor'][$instance_name] = TRUE;
1142
				if(@method_exists($oModule, $instance_name))
1143
				{
1144
					$oModule->{$instance_name}();
1145
				}
1146
			}
1147
1148
			// Store the created instance into GLOBALS variable
1149
			$GLOBALS['_loaded_module'][$module][$type][$kind] = $oModule;
1150
		}
1151
1152
		if(__DEBUG__ == 3)
1153
		{
1154
			$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...
1155
		}
1156
1157
		// return the instance
1158
		return $GLOBALS['_loaded_module'][$module][$type][$kind];
1159
	}
1160
1161
	function _getModuleFilePath($module, $type, $kind, &$classPath, &$highClassFile, &$classFile, &$instanceName)
1162
	{
1163
		$classPath = ModuleHandler::getModulePath($module);
1164
1165
		$highClassFile = sprintf('%s%s%s.class.php', _XE_PATH_, $classPath, $module);
1166
		$highClassFile = FileHandler::getRealPath($highClassFile);
1167
1168
		$types = array('view','controller','model','api','wap','mobile','class');
1169
		if(!in_array($type, $types))
1170
		{
1171
			$type = $types[0];
1172
		}
1173
		if($type == 'class')
1174
		{
1175
			$instanceName = '%s';
1176
			$classFile = '%s%s.%s.php';
1177
		}
1178
		elseif($kind == 'admin' && array_search($type, $types) < 3)
1179
		{
1180
			$instanceName = '%sAdmin%s';
1181
			$classFile = '%s%s.admin.%s.php';
1182
		}
1183
		else
1184
		{
1185
			$instanceName = '%s%s';
1186
			$classFile = '%s%s.%s.php';
1187
		}
1188
1189
		$instanceName = sprintf($instanceName, $module, ucfirst($type));
1190
		$classFile = FileHandler::getRealPath(sprintf($classFile, $classPath, $module, $type));
1191
	}
1192
1193
	/**
1194
	 * call a trigger
1195
	 * @param string $trigger_name trigger's name to call
1196
	 * @param string $called_position called position
1197
	 * @param object $obj an object as a parameter to trigger
1198
	 * @return Object
1199
	 * */
1200
	function triggerCall($trigger_name, $called_position, &$obj)
1201
	{
1202
		// skip if not installed
1203
		if(!Context::isInstalled())
1204
		{
1205
			return new Object();
1206
		}
1207
1208
		$oModuleModel = getModel('module');
1209
		$triggers = $oModuleModel->getTriggers($trigger_name, $called_position);
1210
		if(!$triggers || count($triggers) < 1)
1211
		{
1212
			return new Object();
1213
		}
1214
		
1215
		//store before trigger call time
1216
		$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...
1217
		if(__LOG_SLOW_TRIGGER__> 0)
1218
		{
1219
			$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...
1220
		}
1221
1222
		foreach($triggers as $item)
1223
		{
1224
			$module = $item->module;
1225
			$type = $item->type;
1226
			$called_method = $item->called_method;
1227
1228
			// todo why don't we call a normal class object ?
1229
			$oModule = getModule($module, $type);
1230
			if(!$oModule || !method_exists($oModule, $called_method))
1231
			{
1232
				continue;
1233
			}
1234
1235
			$before_each_trigger_time = microtime(true);
1236
1237
			$output = $oModule->{$called_method}($obj);
1238
1239
			$after_each_trigger_time = microtime(true);
1240
			$elapsed_time_trigger = $after_each_trigger_time - $before_each_trigger_time;
1241
1242
			$slowlog = new stdClass;
1243
			$slowlog->caller = $trigger_name . '.' . $called_position;
1244
			$slowlog->called = $module . '.' . $called_method;
1245
			$slowlog->called_extension = $module;
1246
			if($trigger_name != 'XE.writeSlowlog') writeSlowlog('trigger', $elapsed_time_trigger, $slowlog);
1247
1248
			if(is_object($output) && method_exists($output, 'toBool') && !$output->toBool())
1249
			{
1250
				return $output;
1251
			}
1252
			unset($oModule);
1253
		}
1254
1255
		return new Object();
1256
	}
1257
1258
	/**
1259
	 * get http status message by http status code
1260
	 * @param string $code
1261
	 * @return string
1262
	 * */
1263
	function _setHttpStatusMessage($code)
1264
	{
1265
		$statusMessageList = array(
1266
			'100' => 'Continue',
1267
			'101' => 'Switching Protocols',
1268
			'201' => 'OK', // todo check array key '201'
1269
			'201' => 'Created',
1270
			'202' => 'Accepted',
1271
			'203' => 'Non-Authoritative Information',
1272
			'204' => 'No Content',
1273
			'205' => 'Reset Content',
1274
			'206' => 'Partial Content',
1275
			'300' => 'Multiple Choices',
1276
			'301' => 'Moved Permanently',
1277
			'302' => 'Found',
1278
			'303' => 'See Other',
1279
			'304' => 'Not Modified',
1280
			'305' => 'Use Proxy',
1281
			'307' => 'Temporary Redirect',
1282
			'400' => 'Bad Request',
1283
			'401' => 'Unauthorized',
1284
			'402' => 'Payment Required',
1285
			'403' => 'Forbidden',
1286
			'404' => 'Not Found',
1287
			'405' => 'Method Not Allowed',
1288
			'406' => 'Not Acceptable',
1289
			'407' => 'Proxy Authentication Required',
1290
			'408' => 'Request Timeout',
1291
			'409' => 'Conflict',
1292
			'410' => 'Gone',
1293
			'411' => 'Length Required',
1294
			'412' => 'Precondition Failed',
1295
			'413' => 'Request Entity Too Large',
1296
			'414' => 'Request-URI Too Long',
1297
			'415' => 'Unsupported Media Type',
1298
			'416' => 'Requested Range Not Satisfiable',
1299
			'417' => 'Expectation Failed',
1300
			'500' => 'Internal Server Error',
1301
			'501' => 'Not Implemented',
1302
			'502' => 'Bad Gateway',
1303
			'503' => 'Service Unavailable',
1304
			'504' => 'Gateway Timeout',
1305
			'505' => 'HTTP Version Not Supported',
1306
		);
1307
		$statusMessage = $statusMessageList[$code];
1308
		if(!$statusMessage)
1309
		{
1310
			$statusMessage = 'OK';
1311
		}
1312
1313
		Context::set('http_status_code', $code);
1314
		Context::set('http_status_message', $statusMessage);
1315
	}
1316
1317
}
1318
/* End of file ModuleHandler.class.php */
1319
/* Location: ./classes/module/ModuleHandler.class.php */
1320