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
Push — develop ( 135708...2b55b1 )
by gyeong-won
07:51
created

Context::checkSSO()   D

Complexity

Conditions 19
Paths 27

Size

Total Lines 89
Code Lines 46

Duplication

Lines 10
Ratio 11.24 %

Importance

Changes 0
Metric Value
cc 19
eloc 46
nc 27
nop 0
dl 10
loc 89
rs 4.764
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
define('FOLLOW_REQUEST_SSL', 0);
5
define('ENFORCE_SSL', 1);
6
define('RELEASE_SSL', 2);
7
8
/**
9
 * Manages Context such as request arguments/environment variables
10
 * It has dual method structure, easy-to use methods which can be called as self::methodname(),and methods called with static object.
11
 *
12
 * @author NAVER ([email protected])
13
 */
14
class Context
15
{
16
17
	/**
18
	 * Allow rewrite
19
	 * @var bool TRUE: using rewrite mod, FALSE: otherwise
20
	 */
21
	public $allow_rewrite = FALSE;
22
23
	/**
24
	 * Request method
25
	 * @var string GET|POST|XMLRPC
26
	 */
27
	public $request_method = 'GET';
28
29
	/**
30
	 * js callback function name.
31
	 * @var string
32
	 */
33
	public $js_callback_func = '';
34
35
	/**
36
	 * Response method.If it's not set, it follows request method.
37
	 * @var string HTML|XMLRPC
38
	 */
39
	public $response_method = '';
40
41
	/**
42
	 * Conatins request parameters and environment variables
43
	 * @var object
44
	 */
45
	public $context = NULL;
46
47
	/**
48
	 * DB info
49
	 * @var object
50
	 */
51
	public $db_info = NULL;
52
53
	/**
54
	 * FTP info
55
	 * @var object
56
	 */
57
	public $ftp_info = NULL;
58
59
	/**
60
	 * ssl action cache file
61
	 * @var array
62
	 */
63
	public $sslActionCacheFile = './files/cache/sslCacheFile.php';
64
65
	/**
66
	 * List of actions to be sent via ssl (it is used by javascript xml handler for ajax)
67
	 * @var array
68
	 */
69
	public $ssl_actions = array();
70
71
	/**
72
	 * obejct oFrontEndFileHandler()
73
	 * @var object
74
	 */
75
	public $oFrontEndFileHandler;
76
77
	/**
78
	 * script codes in <head>..</head>
79
	 * @var string
80
	 */
81
	public $html_header = NULL;
82
83
	/**
84
	 * class names of <body>
85
	 * @var array
86
	 */
87
	public $body_class = array();
88
89
	/**
90
	 * codes after <body>
91
	 * @var string
92
	 */
93
	public $body_header = NULL;
94
95
	/**
96
	 * class names before </body>
97
	 * @var string
98
	 */
99
	public $html_footer = NULL;
100
101
	/**
102
	 * path of Xpress Engine
103
	 * @var string
104
	 */
105
	public $path = '';
106
	// language information - it is changed by HTTP_USER_AGENT or user's cookie
107
	/**
108
	 * language type
109
	 * @var string
110
	 */
111
	public $lang_type = '';
112
113
	/**
114
	 * contains language-specific data
115
	 * @var object
116
	 */
117
	public $lang = NULL;
118
119
	/**
120
	 * list of loaded languages (to avoid re-loading them)
121
	 * @var array
122
	 */
123
	public $loaded_lang_files = array();
124
125
	/**
126
	 * site's browser title
127
	 * @var string
128
	 */
129
	public $site_title = '';
130
131
	/**
132
	 * variables from GET or form submit
133
	 * @var mixed
134
	 */
135
	public $get_vars = NULL;
136
137
	/**
138
	 * Checks uploaded
139
	 * @var bool TRUE if attached file exists
140
	 */
141
	public $is_uploaded = FALSE;
142
	/**
143
	 * Pattern for request vars check
144
	 * @var array
145
	 */
146
	public $patterns = array(
147
			'/<\?/iUsm',
148
			'/<\%/iUsm',
149
			'/<script\s*?language\s*?=\s*?("|\')?\s*?php\s*("|\')?/iUsm'
150
			);
151
	/**
152
	 * Check init
153
	 * @var bool FALSE if init fail
154
	 */
155
	public $isSuccessInit = TRUE;
156
157
	/**
158
	 * returns static context object (Singleton). It's to use Context without declaration of an object
159
	 *
160
	 * @return object Instance
161
	 */
162
	function &getInstance()
163
	{
164
		static $theInstance = null;
165
		if(!$theInstance)
166
		{
167
			$theInstance = new Context();
168
		}
169
170
		return $theInstance;
171
	}
172
173
	/**
174
	 * Cunstructor
175
	 *
176
	 * @return void
177
	 */
178
	function Context()
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...
179
	{
180
		$this->oFrontEndFileHandler = new FrontEndFileHandler();
181
		$this->get_vars = new stdClass();
182
183
		// include ssl action cache file
184
		$this->sslActionCacheFile = FileHandler::getRealPath($this->sslActionCacheFile);
0 ignored issues
show
Documentation introduced by
$this->sslActionCacheFile is of type array, 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...
Documentation Bug introduced by
It seems like \FileHandler::getRealPat...is->sslActionCacheFile) of type string is incompatible with the declared type array of property $sslActionCacheFile.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
185
		if(is_readable($this->sslActionCacheFile))
186
		{
187
			require($this->sslActionCacheFile);
188
			if(isset($sslActions))
0 ignored issues
show
Bug introduced by
The variable $sslActions seems to never exist, and therefore isset should always return false. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
189
			{
190
				$this->ssl_actions = $sslActions;
191
			}
192
		}
193
	}
194
195
	/**
196
	 * Initialization, it sets DB information, request arguments and so on.
197
	 *
198
	 * @see This function should be called only once
199
	 * @return void
200
	 */
201
	function init()
202
	{
203
		// fix missing HTTP_RAW_POST_DATA in PHP 5.6 and above
204
		if(!isset($GLOBALS['HTTP_RAW_POST_DATA']) && version_compare(PHP_VERSION, '5.6.0', '>=') === TRUE)
205
		{
206
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents("php://input");
207
			
208
			// If content is not XML JSON, unset
209
			if(!preg_match('/^[\<\{\[]/', $GLOBALS['HTTP_RAW_POST_DATA']) && strpos($_SERVER['CONTENT_TYPE'], 'json') === FALSE && strpos($_SERVER['HTTP_CONTENT_TYPE'], 'json') === FALSE)
210
			{
211
				unset($GLOBALS['HTTP_RAW_POST_DATA']);
212
			}
213
		}
214
215
		// set context variables in $GLOBALS (to use in display handler)
216
		$this->context = &$GLOBALS['__Context__'];
217
		$this->context->lang = &$GLOBALS['lang'];
218
		$this->context->_COOKIE = $_COOKIE;
219
220
		// 20140429 editor/image_link
221
		$this->_checkGlobalVars();
222
223
		$this->setRequestMethod('');
224
225
		$this->_setXmlRpcArgument();
226
		$this->_setJSONRequestArgument();
227
		$this->_setRequestArgument();
228
		$this->_setUploadedArgument();
229
230
		$this->loadDBInfo();
231
		if($this->db_info->use_sitelock == 'Y')
232
		{
233
			if(is_array($this->db_info->sitelock_whitelist)) $whitelist = $this->db_info->sitelock_whitelist;
234
235
			if(!IpFilter::filter($whitelist))
0 ignored issues
show
Bug introduced by
The variable $whitelist 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...
236
			{
237
				$title = ($this->db_info->sitelock_title) ? $this->db_info->sitelock_title : 'Maintenance in progress...';
238
				$message = $this->db_info->sitelock_message;
239
240
				define('_XE_SITELOCK_', TRUE);
241
				define('_XE_SITELOCK_TITLE_', $title);
242
				define('_XE_SITELOCK_MESSAGE_', $message);
243
244
				header("HTTP/1.1 403 Forbidden");
245
				if(FileHandler::exists(_XE_PATH_ . 'common/tpl/sitelock.user.html'))
0 ignored issues
show
Bug Best Practice introduced by
The expression \FileHandler::exists(_XE...pl/sitelock.user.html') 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...
246
				{
247
					include _XE_PATH_ . 'common/tpl/sitelock.user.html';
248
				}
249
				else
250
				{
251
					include _XE_PATH_ . 'common/tpl/sitelock.html';
252
				}
253
				exit;
254
			}
255
		}
256
257
		// If XE is installed, get virtual site information
258
		if(self::isInstalled())
259
		{
260
			$oModuleModel = getModel('module');
261
			$site_module_info = $oModuleModel->getDefaultMid();
262
263
			if(!isset($site_module_info))
264
			{
265
				$site_module_info = new stdClass();
266
			}
267
268
			// if site_srl of site_module_info is 0 (default site), compare the domain to default_url of db_config
269
			if($site_module_info->site_srl == 0 && $site_module_info->domain != $this->db_info->default_url)
270
			{
271
				$site_module_info->domain = $this->db_info->default_url;
272
			}
273
274
			$this->set('site_module_info', $site_module_info);
275
			if($site_module_info->site_srl && isSiteID($site_module_info->domain))
276
			{
277
				$this->set('vid', $site_module_info->domain, 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...
278
			}
279
280
			if(!isset($this->db_info))
281
			{
282
				$this->db_info = new stdClass();
283
			}
284
285
			$this->db_info->lang_type = $site_module_info->default_language;
286
			if(!$this->db_info->lang_type)
287
			{
288
				$this->db_info->lang_type = 'en';
289
			}
290
			if(!$this->db_info->use_db_session)
291
			{
292
				$this->db_info->use_db_session = 'N';
293
			}
294
		}
295
296
		// Load Language File
297
		$lang_supported = $this->loadLangSelected();
298
299
		// Retrieve language type set in user's cookie
300
		if($this->lang_type = $this->get('l'))
301
		{
302
			if($_COOKIE['lang_type'] != $this->lang_type)
303
			{
304
				setcookie('lang_type', $this->lang_type, $_SERVER['REQUEST_TIME'] + 3600 * 24 * 1000);
305
			}
306
		}
307
		elseif($_COOKIE['lang_type'])
308
		{
309
			$this->lang_type = $_COOKIE['lang_type'];
310
		}
311
312
		// If it's not exists, follow default language type set in db_info
313
		if(!$this->lang_type)
314
		{
315
			$this->lang_type = $this->db_info->lang_type;
316
		}
317
318
		// if still lang_type has not been set or has not-supported type , set as English.
319
		if(!$this->lang_type)
320
		{
321
			$this->lang_type = 'en';
322
		}
323
		if(is_array($lang_supported) && !isset($lang_supported[$this->lang_type]))
324
		{
325
			$this->lang_type = 'en';
326
		}
327
328
		$this->set('lang_supported', $lang_supported);
0 ignored issues
show
Documentation introduced by
$lang_supported is of type null|array, 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...
329
		$this->setLangType($this->lang_type);
330
331
		// load module module's language file according to language setting
332
		$this->loadLang(_XE_PATH_ . 'modules/module/lang');
333
334
		// set session handler
335
		if(self::isInstalled() && $this->db_info->use_db_session == 'Y')
336
		{
337
			$oSessionModel = getModel('session');
338
			$oSessionController = getController('session');
339
			session_set_save_handler(
340
					array(&$oSessionController, 'open'), array(&$oSessionController, 'close'), array(&$oSessionModel, 'read'), array(&$oSessionController, 'write'), array(&$oSessionController, 'destroy'), array(&$oSessionController, 'gc')
341
			);
342
		}
343
344
		if($sess = $_POST[session_name()]) session_id($sess);
345
		session_start();
346
347
		// set authentication information in Context and session
348
		if(self::isInstalled())
349
		{
350
			$oModuleModel = getModel('module');
351
			$oModuleModel->loadModuleExtends();
352
353
			$oMemberModel = getModel('member');
354
			$oMemberController = getController('member');
355
356
			if($oMemberController && $oMemberModel)
357
			{
358
				// if signed in, validate it.
359
				if($oMemberModel->isLogged())
360
				{
361
					$oMemberController->setSessionInfo();
362
				}
363
				// check auto sign-in
364
				elseif($_COOKIE['xeak'])
365
				{
366
					$oMemberController->doAutologin();
367
				}
368
369
				$this->set('is_logged', $oMemberModel->isLogged());
370
				$this->set('logged_info', $oMemberModel->getLoggedInfo());
371
			}
372
		}
373
374
		// load common language file
375
		$this->lang = &$GLOBALS['lang'];
376
		$this->loadLang(_XE_PATH_ . 'common/lang/');
377
378
		// check if using rewrite module
379
		$this->allow_rewrite = ($this->db_info->use_rewrite == 'Y' ? TRUE : FALSE);
380
381
		// set locations for javascript use
382
		$url = array();
0 ignored issues
show
Unused Code introduced by
$url 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...
383
		$current_url = self::getRequestUri();
0 ignored issues
show
Unused Code introduced by
$current_url 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...
384
		if($_SERVER['REQUEST_METHOD'] == 'GET')
385
		{
386
			if($this->get_vars)
387
			{
388
				$url = array();
389 View Code Duplication
				foreach($this->get_vars as $key => $val)
390
				{
391
					if(is_array($val) && count($val) > 0)
392
					{
393
						foreach($val as $k => $v)
394
						{
395
							$url[] = $key . '[' . $k . ']=' . urlencode($v);
396
						}
397
					}
398
					elseif($val)
399
					{
400
						$url[] = $key . '=' . urlencode($val);
401
					}
402
				}
403
404
				$current_url = self::getRequestUri();
405
				if($url) $current_url .= '?' . join('&', $url);
0 ignored issues
show
Bug Best Practice introduced by
The expression $url of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

Loading history...
406
			}
407
			else
408
			{
409
				$current_url = $this->getUrl();
410
			}
411
		}
412
		else
413
		{
414
			$current_url = self::getRequestUri();
415
		}
416
417
		$this->set('current_url', $current_url);
418
		$this->set('request_uri', self::getRequestUri());
419
420
		if(strpos($current_url, 'xn--') !== FALSE)
421
		{
422
			$this->set('current_url', self::decodeIdna($current_url));
423
		}
424
425
		if(strpos(self::getRequestUri(), 'xn--') !== FALSE)
426
		{
427
			$this->set('request_uri', self::decodeIdna(self::getRequestUri()));
428
		}
429
	}
430
431
	/**
432
	 * Finalize using resources, such as DB connection
433
	 *
434
	 * @return void
435
	 */
436
	function close()
437
	{
438
		session_write_close();
439
	}
440
441
	/**
442
	 * Load the database information
443
	 *
444
	 * @return void
445
	 */
446
	function loadDBInfo()
447
	{
448
		$self = self::getInstance();
449
450
		if(!$self->isInstalled())
451
		{
452
			return;
453
		}
454
455
		include($self::getConfigFile());
456
457
		// If master_db information does not exist, the config file needs to be updated
458
		if(!isset($db_info->master_db))
459
		{
460
			$db_info->master_db = array();
0 ignored issues
show
Bug introduced by
The variable $db_info 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...
461
			$db_info->master_db["db_type"] = $db_info->db_type;
462
			unset($db_info->db_type);
463
			$db_info->master_db["db_port"] = $db_info->db_port;
464
			unset($db_info->db_port);
465
			$db_info->master_db["db_hostname"] = $db_info->db_hostname;
466
			unset($db_info->db_hostname);
467
			$db_info->master_db["db_password"] = $db_info->db_password;
468
			unset($db_info->db_password);
469
			$db_info->master_db["db_database"] = $db_info->db_database;
470
			unset($db_info->db_database);
471
			$db_info->master_db["db_userid"] = $db_info->db_userid;
472
			unset($db_info->db_userid);
473
			$db_info->master_db["db_table_prefix"] = $db_info->db_table_prefix;
474
			unset($db_info->db_table_prefix);
475
476
			if(isset($db_info->master_db["db_table_prefix"]) && substr_compare($db_info->master_db["db_table_prefix"], '_', -1) !== 0)
477
			{
478
				$db_info->master_db["db_table_prefix"] .= '_';
479
			}
480
481
			$db_info->slave_db = array($db_info->master_db);
482
			$self->setDBInfo($db_info);
483
484
			$oInstallController = getController('install');
485
			$oInstallController->makeConfigFile();
486
		}
487
488
		if(!$db_info->use_prepared_statements)
489
		{
490
			$db_info->use_prepared_statements = 'Y';
491
		}
492
493
		if(!$db_info->time_zone)
494
			$db_info->time_zone = date('O');
495
		$GLOBALS['_time_zone'] = $db_info->time_zone;
496
497
		if($db_info->qmail_compatibility != 'Y')
498
			$db_info->qmail_compatibility = 'N';
499
		$GLOBALS['_qmail_compatibility'] = $db_info->qmail_compatibility;
500
501
		if(!$db_info->use_db_session)
502
			$db_info->use_db_session = 'N';
503
		if(!$db_info->use_ssl)
504
			$db_info->use_ssl = 'none';
505
		$this->set('_use_ssl', $db_info->use_ssl);
506
507
		$self->set('_http_port', ($db_info->http_port) ? $db_info->http_port : NULL);
508
		$self->set('_https_port', ($db_info->https_port) ? $db_info->https_port : NULL);
509
510
		if(!$db_info->sitelock_whitelist) {
511
			$db_info->sitelock_whitelist = '127.0.0.1';
512
		}
513
514
		if(is_string($db_info->sitelock_whitelist)) {
515
			$db_info->sitelock_whitelist = explode(',', $db_info->sitelock_whitelist);
516
		}
517
518
		$self->setDBInfo($db_info);
519
	}
520
521
	/**
522
	 * Get DB's db_type
523
	 *
524
	 * @return string DB's db_type
525
	 */
526
	function getDBType()
527
	{
528
		$self = self::getInstance();
529
		return $self->db_info->master_db["db_type"];
530
	}
531
532
	/**
533
	 * Set DB information
534
	 *
535
	 * @param object $db_info DB information
536
	 * @return void
537
	 */
538
	function setDBInfo($db_info)
539
	{
540
		$self = self::getInstance();
541
		$self->db_info = $db_info;
542
	}
543
544
	/**
545
	 * Get DB information
546
	 *
547
	 * @return object DB information
548
	 */
549
	function getDBInfo()
550
	{
551
		$self = self::getInstance();
552
		return $self->db_info;
553
	}
554
555
	/**
556
	 * Return ssl status
557
	 *
558
	 * @return object SSL status (Optional - none|always|optional)
559
	 */
560
	function getSslStatus()
561
	{
562
		$dbInfo = self::getDBInfo();
563
		return $dbInfo->use_ssl;
564
	}
565
566
	/**
567
	 * Return default URL
568
	 *
569
	 * @return string Default URL
570
	 */
571
	function getDefaultUrl()
572
	{
573
		$db_info = self::getDBInfo();
574
		return $db_info->default_url;
575
	}
576
577
	/**
578
	 * Find supported languages
579
	 *
580
	 * @return array Supported languages
581
	 */
582
	function loadLangSupported()
583
	{
584
		static $lang_supported = null;
585 View Code Duplication
		if(!$lang_supported)
586
		{
587
			$langs = file(_XE_PATH_ . 'common/lang/lang.info');
588
			foreach($langs as $val)
589
			{
590
				list($lang_prefix, $lang_text) = explode(',', $val);
591
				$lang_text = trim($lang_text);
592
				$lang_supported[$lang_prefix] = $lang_text;
593
			}
594
		}
595
		return $lang_supported;
596
	}
597
598
	/**
599
	 * Find selected languages to serve in the site
600
	 *
601
	 * @return array Selected languages
602
	 */
603
	function loadLangSelected()
604
	{
605
		static $lang_selected = null;
606
		if(!$lang_selected)
607
		{
608
			$orig_lang_file = _XE_PATH_ . 'common/lang/lang.info';
609
			$selected_lang_file = _XE_PATH_ . 'files/config/lang_selected.info';
610
			if(!FileHandler::hasContent($selected_lang_file))
611
			{
612
				$old_selected_lang_file = _XE_PATH_ . 'files/cache/lang_selected.info';
613
				FileHandler::moveFile($old_selected_lang_file, $selected_lang_file);
614
			}
615
616
			if(!FileHandler::hasContent($selected_lang_file))
617
			{
618
				$buff = FileHandler::readFile($orig_lang_file);
619
				FileHandler::writeFile($selected_lang_file, $buff);
620
				$lang_selected = self::loadLangSupported();
621
			}
622 View Code Duplication
			else
623
			{
624
				$langs = file($selected_lang_file);
625
				foreach($langs as $val)
626
				{
627
					list($lang_prefix, $lang_text) = explode(',', $val);
628
					$lang_text = trim($lang_text);
629
					$lang_selected[$lang_prefix] = $lang_text;
630
				}
631
			}
632
		}
633
		return $lang_selected;
634
	}
635
636
	/**
637
	 * Single Sign On (SSO)
638
	 *
639
	 * @return bool True : Module handling is necessary in the control path of current request , False : Otherwise
640
	 */
641
	function checkSSO()
642
	{
643
		// pass if it's not GET request or XE is not yet installed
644
		if($this->db_info->use_sso != 'Y' || isCrawler())
645
		{
646
			return TRUE;
647
		}
648
		$checkActList = array('rss' => 1, 'atom' => 1);
649
		if(self::getRequestMethod() != 'GET' || !self::isInstalled() || isset($checkActList[self::get('act')]))
650
		{
651
			return TRUE;
652
		}
653
654
		// pass if default URL is not set
655
		$default_url = trim($this->db_info->default_url);
656
		if(!$default_url)
657
		{
658
			return TRUE;
659
		}
660
661
		if(substr_compare($default_url, '/', -1) !== 0)
662
		{
663
			$default_url .= '/';
664
		}
665
666
		// for sites recieving SSO valdiation
667
		if($default_url == self::getRequestUri())
668
		{
669
			if(self::get('url'))
670
			{
671
				$url = base64_decode(self::get('url'));
672
				$url_info = parse_url($url);
673 View Code Duplication
				if(!Password::checkSignature($url, self::get('sig')))
674
				{
675
					echo self::get('lang')->msg_invalid_request;
676
					return false;
677
				}
678
679
				$oModuleModel = getModel('module');
680
				$domain = $url_info['host'] . $url_info['path'];
681
				if(substr_compare($domain, '/', -1) === 0) $domain = substr($domain, 0, -1);
682
				$site_info = $oModuleModel->getSiteInfoByDomain($domain);
683
684
				if($site_info->site_srl)
685
				{
686
				$url_info['query'].= ($url_info['query'] ? '&' : '') . 'SSOID=' . urlencode(session_id()) . '&sig=' . urlencode(Password::createSignature(session_id()));
687
				$redirect_url = sprintf('%s://%s%s%s?%s', $url_info['scheme'], $url_info['host'], $url_info['port'] ? ':' . $url_info['port'] : '', $url_info['path'], $url_info['query']);
688
				}
689
				else
690
				{
691
					$redirect_url = $url;
692
				}
693
				header('location:' . $redirect_url);
694
695
				return FALSE;
696
			}
697
			// for sites requesting SSO validation
698
		}
699
		else
700
		{
701
			// result handling : set session_name()
702
			if($session_name = self::get('SSOID'))
703
			{
704 View Code Duplication
				if(!Password::checkSignature($session_name, self::get('sig')))
705
				{
706
					echo self::get('lang')->msg_invalid_request;
707
					return false;
708
				}
709
				
710
				setcookie(session_name(), $session_name);
711
712
				$url = preg_replace('/[\?\&]SSOID=.+$/', '', self::getRequestUrl());
713
				header('location:' . $url);
714
				return FALSE;
715
				// send SSO request
716
			}
717
			else if(!self::get('SSOID') && $_COOKIE['sso'] != md5(self::getRequestUri()))
718
			{
719
				setcookie('sso', md5(self::getRequestUri()));
720
				$origin_url = self::getRequestUrl();
721
				$origin_sig = Password::createSignature($origin_url);
722
				$url = sprintf("%s?url=%s&sig=%s", $default_url, urlencode(base64_encode($origin_url)), urlencode($origin_sig));
723
				header('location:' . $url);
724
				return FALSE;
725
			}
726
		}
727
728
		return TRUE;
729
	}
730
731
	/**
732
	 * Check if FTP info is registered
733
	 *
734
	 * @return bool True: FTP information is registered, False: otherwise
735
	 */
736
	function isFTPRegisted()
737
	{
738
		return file_exists(self::getFTPConfigFile());
739
	}
740
741
	/**
742
	 * Get FTP information
743
	 *
744
	 * @return object FTP information
745
	 */
746
	function getFTPInfo()
747
	{
748
		$self = self::getInstance();
749
750
		if(!$self->isFTPRegisted())
751
		{
752
			return null;
753
		}
754
755
		include($self->getFTPConfigFile());
756
757
		return $ftp_info;
0 ignored issues
show
Bug introduced by
The variable $ftp_info 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...
758
	}
759
760
	/**
761
	 * Add string to browser title
762
	 *
763
	 * @param string $site_title Browser title to be added
764
	 * @return void
765
	 */
766
	function addBrowserTitle($site_title)
767
	{
768
		if(!$site_title)
769
		{
770
			return;
771
		}
772
		$self = self::getInstance();
773
774
		if($self->site_title)
775
		{
776
			$self->site_title .= ' - ' . $site_title;
777
		}
778
		else
779
		{
780
			$self->site_title = $site_title;
781
		}
782
	}
783
784
	/**
785
	 * Set string to browser title
786
	 *
787
	 * @param string $site_title Browser title  to be set
788
	 * @return void
789
	 */
790
	function setBrowserTitle($site_title)
791
	{
792
		if(!$site_title)
793
		{
794
			return;
795
		}
796
		$self = self::getInstance();
797
		$self->site_title = $site_title;
798
	}
799
800
	/**
801
	 * Get browser title
802
	 *
803
	 * @return string Browser title(htmlspecialchars applied)
804
	 */
805
	function getBrowserTitle()
806
	{
807
		$self = self::getInstance();
808
809
		$oModuleController = getController('module');
810
		$oModuleController->replaceDefinedLangCode($self->site_title);
811
812
		return htmlspecialchars($self->site_title, ENT_COMPAT | ENT_HTML401, 'UTF-8', FALSE);
813
	}
814
815
	/**
816
	 * Return layout's title
817
	 * @return string layout's title
818
	 */
819
	public function getSiteTitle()
820
	{
821
		$oModuleModel = getModel('module');
822
		$moduleConfig = $oModuleModel->getModuleConfig('module');
823
824
		if(isset($moduleConfig->siteTitle))
825
		{
826
			return $moduleConfig->siteTitle;
827
		}
828
		return '';
829
	}
830
831
	/**
832
	 * Get browser title
833
	 * @deprecated
834
	 */
835
	function _getBrowserTitle()
836
	{
837
		return $this->getBrowserTitle();
838
	}
839
840
	/**
841
	 * Load language file according to language type
842
	 *
843
	 * @param string $path Path of the language file
844
	 * @return void
845
	 */
846
	function loadLang($path)
847
	{
848
		global $lang;
849
850
		$self = self::getInstance();
851
		if(!$self->lang_type)
852
		{
853
			return;
854
		}
855
		if(!is_object($lang))
856
		{
857
			$lang = new stdClass;
858
		}
859
860
		if(!($filename = $self->_loadXmlLang($path)))
861
		{
862
			$filename = $self->_loadPhpLang($path);
863
		}
864
865
		if(!is_array($self->loaded_lang_files))
866
		{
867
			$self->loaded_lang_files = array();
868
		}
869
		if(in_array($filename, $self->loaded_lang_files))
870
		{
871
			return;
872
		}
873
874
		if($filename && is_readable($filename))
875
		{
876
			$self->loaded_lang_files[] = $filename;
877
			include($filename);
878
		}
879
		else
880
		{
881
			$self->_evalxmlLang($path);
882
		}
883
	}
884
885
	/**
886
	 * Evaluation of xml language file
887
	 *
888
	 * @param string Path of the language file
889
	 * @return void
890
	 */
891
	function _evalxmlLang($path)
892
	{
893
		global $lang;
894
895
		if(!$path) return;
896
897
		$_path = 'eval://' . $path;
898
899
		if(in_array($_path, $this->loaded_lang_files))
900
		{
901
			return;
902
		}
903
904
		if(substr_compare($path, '/', -1) !== 0)
905
		{
906
			$path .= '/';
907
		}
908
909
		$oXmlLangParser = new XmlLangParser($path . 'lang.xml', $this->lang_type);
910
		$content = $oXmlLangParser->getCompileContent();
911
912
		if($content)
0 ignored issues
show
Bug Best Practice introduced by
The expression $content of type false|string 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...
913
		{
914
			$this->loaded_lang_files[] = $_path;
915
			eval($content);
0 ignored issues
show
Coding Style introduced by
It is generally not recommended to use eval unless absolutely required.

On one hand, eval might be exploited by malicious users if they somehow manage to inject dynamic content. On the other hand, with the emergence of faster PHP runtimes like the HHVM, eval prevents some optimization that they perform.

Loading history...
916
		}
917
	}
918
919
	/**
920
	 * Load language file of xml type
921
	 *
922
	 * @param string $path Path of the language file
923
	 * @return string file name
924
	 */
925
	function _loadXmlLang($path)
926
	{
927
		if(!$path) return;
928
929
		$oXmlLangParser = new XmlLangParser($path . ((substr_compare($path, '/', -1) !== 0) ? '/' : '') . 'lang.xml', $this->lang_type);
930
		return $oXmlLangParser->compile();
931
	}
932
933
	/**
934
	 * Load language file of php type
935
	 *
936
	 * @param string $path Path of the language file
937
	 * @return string file name
938
	 */
939
	function _loadPhpLang($path)
940
	{
941
		if(!$path) return;
942
943
		if(substr_compare($path, '/', -1) !== 0)
944
		{
945
			$path .= '/';
946
		}
947
		$path_tpl = $path . '%s.lang.php';
948
		$file = sprintf($path_tpl, $this->lang_type);
949
950
		$langs = array('ko', 'en'); // this will be configurable.
951
		while(!is_readable($file) && $langs[0])
952
		{
953
			$file = sprintf($path_tpl, array_shift($langs));
954
		}
955
956
		if(!is_readable($file))
957
		{
958
			return FALSE;
959
		}
960
		return $file;
961
	}
962
963
	/**
964
	 * Set lang_type
965
	 *
966
	 * @param string $lang_type Language type.
967
	 * @return void
968
	 */
969
	function setLangType($lang_type = 'ko')
970
	{
971
		$self = self::getInstance();
972
973
		$self->lang_type = $lang_type;
974
		$self->set('lang_type', $lang_type);
975
976
		$_SESSION['lang_type'] = $lang_type;
977
	}
978
979
	/**
980
	 * Get lang_type
981
	 *
982
	 * @return string Language type
983
	 */
984
	function getLangType()
985
	{
986
		$self = self::getInstance();
987
		return $self->lang_type;
988
	}
989
990
	/**
991
	 * Return string accoring to the inputed code
992
	 *
993
	 * @param string $code Language variable name
994
	 * @return string If string for the code exists returns it, otherwise returns original code
995
	 */
996
	function getLang($code)
997
	{
998
		if(!$code)
999
		{
1000
			return;
1001
		}
1002
		if($GLOBALS['lang']->{$code})
1003
		{
1004
			return $GLOBALS['lang']->{$code};
1005
		}
1006
		return $code;
1007
	}
1008
1009
	/**
1010
	 * Set data to lang variable
1011
	 *
1012
	 * @param string $code Language variable name
1013
	 * @param string $val `$code`s value
1014
	 * @return void
1015
	 */
1016
	function setLang($code, $val)
1017
	{
1018
		if(!isset($GLOBALS['lang']))
1019
		{
1020
			$GLOBALS['lang'] = new stdClass();
1021
		}
1022
		$GLOBALS['lang']->{$code} = $val;
1023
	}
1024
1025
	/**
1026
	 * Convert strings of variables in $source_object into UTF-8
1027
	 *
1028
	 * @param object $source_obj Conatins strings to convert
1029
	 * @return object converted object
1030
	 */
1031
	function convertEncoding($source_obj)
1032
	{
1033
		$charset_list = array(
1034
			'UTF-8', 'EUC-KR', 'CP949', 'ISO8859-1', 'EUC-JP', 'SHIFT_JIS', 'CP932',
1035
			'EUC-CN', 'HZ', 'GBK', 'GB18030', 'EUC-TW', 'BIG5', 'CP950', 'BIG5-HKSCS',
1036
			'ISO2022-CN', 'ISO2022-CN-EXT', 'ISO2022-JP', 'ISO2022-JP-2', 'ISO2022-JP-1',
1037
			'ISO8859-6', 'ISO8859-8', 'JOHAB', 'ISO2022-KR', 'CP1255', 'CP1256', 'CP862',
1038
			'ASCII', 'ISO8859-1', 'ISO8850-2', 'ISO8850-3', 'ISO8850-4', 'ISO8850-5',
1039
			'ISO8850-7', 'ISO8850-9', 'ISO8850-10', 'ISO8850-13', 'ISO8850-14',
1040
			'ISO8850-15', 'ISO8850-16', 'CP1250', 'CP1251', 'CP1252', 'CP1253', 'CP1254',
1041
			'CP1257', 'CP850', 'CP866',
1042
		);
1043
1044
		$obj = clone $source_obj;
1045
1046
		foreach($charset_list as $charset)
1047
		{
1048
			array_walk($obj,'Context::checkConvertFlag',$charset);
1049
			$flag = self::checkConvertFlag($flag = TRUE);
0 ignored issues
show
Bug introduced by
$flag = TRUE cannot be passed to checkconvertflag() as the parameter $val expects a reference.
Loading history...
1050
			if($flag)
1051
			{
1052
				if($charset == 'UTF-8')
1053
				{
1054
					return $obj;
1055
				}
1056
				array_walk($obj,'Context::doConvertEncoding',$charset);
1057
				return $obj;
1058
			}
1059
		}
1060
		return $obj;
1061
	}
1062
1063
	/**
1064
	 * Check flag
1065
	 *
1066
	 * @param mixed $val
1067
	 * @param string $key
1068
	 * @param mixed $charset charset
1069
	 * @see arrayConvWalkCallback will replaced array_walk_recursive in >=PHP5
1070
	 * @return void
1071
	 */
1072
	function checkConvertFlag(&$val, $key = null, $charset = null)
0 ignored issues
show
Unused Code introduced by
The parameter $key 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...
1073
	{
1074
		static $flag = TRUE;
1075
		if($charset)
1076
		{
1077
			if(is_array($val))
1078
				array_walk($val,'Context::checkConvertFlag',$charset);
1079
			else if($val && iconv($charset,$charset,$val)!=$val) $flag = FALSE;
1080
			else $flag = FALSE;
1081
		}
1082
		else
1083
		{
1084
			$return = $flag;
1085
			$flag = TRUE;
1086
			return $return;
1087
		}
1088
	}
1089
1090
	/**
1091
	 * Convert array type variables into UTF-8
1092
	 *
1093
	 * @param mixed $val
1094
	 * @param string $key
1095
	 * @param string $charset character set
1096
	 * @see arrayConvWalkCallback will replaced array_walk_recursive in >=PHP5
1097
	 * @return object converted object
1098
	 */
1099
	function doConvertEncoding(&$val, $key = null, $charset)
0 ignored issues
show
Unused Code introduced by
The parameter $key 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...
1100
	{
1101
		if (is_array($val))
1102
		{
1103
			array_walk($val,'Context::doConvertEncoding',$charset);
1104
		}
1105
		else $val = iconv($charset,'UTF-8',$val);
1106
	}
1107
1108
	/**
1109
	 * Convert strings into UTF-8
1110
	 *
1111
	 * @param string $str String to convert
1112
	 * @return string converted string
1113
	 */
1114
	function convertEncodingStr($str)
1115
	{
1116
        if(!$str) return null;
1117
		$obj = new stdClass();
1118
		$obj->str = $str;
1119
		$obj = self::convertEncoding($obj);
1120
		return $obj->str;
1121
	}
1122
1123
	function decodeIdna($domain)
1124
	{
1125
		if(strpos($domain, 'xn--') !== FALSE)
1126
		{
1127
			require_once(_XE_PATH_ . 'libs/idna_convert/idna_convert.class.php');
1128
			$IDN = new idna_convert(array('idn_version' => 2008));
1129
			$domain = $IDN->decode($domain);
1130
		}
1131
1132
		return $domain;
1133
	}
1134
1135
	/**
1136
	 * Force to set response method
1137
	 *
1138
	 * @param string $method Response method. [HTML|XMLRPC|JSON]
1139
	 * @return void
1140
	 */
1141
	function setResponseMethod($method = 'HTML')
1142
	{
1143
		$self = self::getInstance();
1144
1145
		$methods = array('HTML' => 1, 'XMLRPC' => 1, 'JSON' => 1, 'JS_CALLBACK' => 1);
1146
		$self->response_method = isset($methods[$method]) ? $method : 'HTML';
1147
	}
1148
1149
	/**
1150
	 * Get reponse method
1151
	 *
1152
	 * @return string Response method. If it's not set, returns request method.
1153
	 */
1154
	function getResponseMethod()
1155
	{
1156
		$self = self::getInstance();
1157
1158
		if($self->response_method)
1159
		{
1160
			return $self->response_method;
1161
		}
1162
1163
		$method = $self->getRequestMethod();
1164
		$methods = array('HTML' => 1, 'XMLRPC' => 1, 'JSON' => 1, 'JS_CALLBACK' => 1);
1165
1166
		return isset($methods[$method]) ? $method : 'HTML';
1167
	}
1168
1169
	/**
1170
	 * Determine request method
1171
	 *
1172
	 * @param string $type Request method. (Optional - GET|POST|XMLRPC|JSON)
1173
	 * @return void
1174
	 */
1175
	function setRequestMethod($type = '')
1176
	{
1177
		$self = self::getInstance();
1178
1179
		$self->js_callback_func = $self->getJSCallbackFunc();
1180
1181
		($type && $self->request_method = $type) or
1182
				((strpos($_SERVER['CONTENT_TYPE'], 'json') || strpos($_SERVER['HTTP_CONTENT_TYPE'], 'json')) && $self->request_method = 'JSON') or
1183
				($GLOBALS['HTTP_RAW_POST_DATA'] && $self->request_method = 'XMLRPC') or
1184
				($self->js_callback_func && $self->request_method = 'JS_CALLBACK') or
1185
				($self->request_method = $_SERVER['REQUEST_METHOD']);
1186
	}
1187
1188
	/**
1189
	 * handle global arguments
1190
	 *
1191
	 * @return void
1192
	 */
1193
	function _checkGlobalVars()
1194
	{
1195
		$this->_recursiveCheckVar($_SERVER['HTTP_HOST']);
1196
1197
		$pattern = "/[\,\"\'\{\}\[\]\(\);$]/";
1198
		if(preg_match($pattern, $_SERVER['HTTP_HOST']))
1199
		{
1200
			$this->isSuccessInit = FALSE;
1201
		}
1202
	}
1203
1204
	/**
1205
	 * handle request arguments for GET/POST
1206
	 *
1207
	 * @return void
1208
	 */
1209
	function _setRequestArgument()
1210
	{
1211
		if(!count($_REQUEST))
1212
		{
1213
			return;
1214
		}
1215
1216
		$requestMethod = $this->getRequestMethod();
1217
		foreach($_REQUEST as $key => $val)
1218
		{
1219
			if($val === '' || self::get($key))
1220
			{
1221
				continue;
1222
			}
1223
			$key = htmlentities($key);
1224
			$val = $this->_filterRequestVar($key, $val);
1225
1226
			if($requestMethod == 'GET' && isset($_GET[$key]))
1227
			{
1228
				$set_to_vars = TRUE;
1229
			}
1230
			elseif($requestMethod == 'POST' && isset($_POST[$key]))
1231
			{
1232
				$set_to_vars = TRUE;
1233
			}
1234
			elseif($requestMethod == 'JS_CALLBACK' && (isset($_GET[$key]) || isset($_POST[$key])))
1235
			{
1236
				$set_to_vars = TRUE;
1237
			}
1238
			else
1239
			{
1240
				$set_to_vars = FALSE;
1241
			}
1242
1243
			if($set_to_vars)
1244
			{
1245
				$this->_recursiveCheckVar($val);
1246
			}
1247
1248
			$this->set($key, $val, $set_to_vars);
0 ignored issues
show
Documentation introduced by
$set_to_vars 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...
1249
		}
1250
	}
1251
1252
	function _recursiveCheckVar($val)
1253
	{
1254
		if(is_string($val))
1255
		{
1256
			foreach($this->patterns as $pattern)
1257
			{
1258
				if(preg_match($pattern, $val))
1259
				{
1260
					$this->isSuccessInit = FALSE;
1261
					return;
1262
				}
1263
			}
1264
		}
1265
		else if(is_array($val))
1266
		{
1267
			foreach($val as $val2)
1268
			{
1269
				$this->_recursiveCheckVar($val2);
1270
			}
1271
		}
1272
	}
1273
1274
	/**
1275
	 * Handle request arguments for JSON
1276
	 *
1277
	 * @return void
1278
	 */
1279
	function _setJSONRequestArgument()
1280
	{
1281
		if($this->getRequestMethod() != 'JSON')
1282
		{
1283
			return;
1284
		}
1285
1286
		$params = array();
1287
		parse_str($GLOBALS['HTTP_RAW_POST_DATA'], $params);
1288
1289
		foreach($params as $key => $val)
0 ignored issues
show
Bug introduced by
The expression $params of type null|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
1290
		{
1291
			$this->set($key, $this->_filterRequestVar($key, $val, 1), 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...
1292
		}
1293
	}
1294
1295
	/**
1296
	 * Handle request arguments for XML RPC
1297
	 *
1298
	 * @return void
1299
	 */
1300
	function _setXmlRpcArgument()
1301
	{
1302
		if($this->getRequestMethod() != 'XMLRPC')
1303
		{
1304
			return;
1305
		}
1306
1307
		$xml = $GLOBALS['HTTP_RAW_POST_DATA'];
1308
		if(Security::detectingXEE($xml))
1309
		{
1310
			header("HTTP/1.0 400 Bad Request");
1311
			exit;
1312
		}
1313
1314
		$oXml = new XmlParser();
1315
		$xml_obj = $oXml->parse($xml);
1316
1317
		$params = $xml_obj->methodcall->params;
1318
		unset($params->node_name, $params->attrs, $params->body);
1319
1320
		if(!count(get_object_vars($params)))
1321
		{
1322
			return;
1323
		}
1324
1325
		foreach($params as $key => $val)
1326
		{
1327
			$this->set($key, $this->_filterXmlVars($key, $val), 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...
1328
		}
1329
	}
1330
1331
	/**
1332
	 * Filter xml variables
1333
	 *
1334
	 * @param string $key Variable key
1335
	 * @param object $val Variable value
1336
	 * @return mixed filtered value
1337
	 */
1338
	function _filterXmlVars($key, $val)
1339
	{
1340
		if(is_array($val))
1341
		{
1342
			$stack = array();
1343
			foreach($val as $k => $v)
1344
			{
1345
				$stack[$k] = $this->_filterXmlVars($k, $v);
1346
			}
1347
1348
			return $stack;
1349
		}
1350
1351
		$body = $val->body;
1352
		unset($val->node_name, $val->attrs, $val->body);
1353
		if(!count(get_object_vars($val)))
1354
		{
1355
			return $this->_filterRequestVar($key, $body, 0);
1356
		}
1357
1358
		$stack = new stdClass();
1359
		foreach($val as $k => $v)
1360
		{
1361
			$output = $this->_filterXmlVars($k, $v);
1362
			if(is_object($v) && $v->attrs->type == 'array')
1363
			{
1364
				$output = array($output);
1365
			}
1366
			if($k == 'value' && (is_array($v) || $v->attrs->type == 'array'))
1367
			{
1368
				return $output;
1369
			}
1370
1371
			$stack->{$k} = $output;
1372
		}
1373
1374
		if(!count(get_object_vars($stack)))
1375
		{
1376
			return NULL;
1377
		}
1378
1379
		return $stack;
1380
	}
1381
1382
	/**
1383
	 * Filter request variable
1384
	 *
1385
	 * @see Cast variables, such as _srl, page, and cpage, into interger
1386
	 * @param string $key Variable key
1387
	 * @param string $val Variable value
1388
	 * @param string $do_stripslashes Whether to strip slashes
1389
	 * @return mixed filtered value. Type are string or array
1390
	 */
1391
	function _filterRequestVar($key, $val, $do_stripslashes = 1)
1392
	{
1393
		if(!($isArray = is_array($val)))
1394
		{
1395
			$val = array($val);
1396
		}
1397
1398
		$result = array();
1399
		foreach($val as $k => $v)
1400
		{
1401
			$k = htmlentities($k);
1402
			if($key === 'page' || $key === 'cpage' || substr_compare($key, 'srl', -3) === 0)
1403
			{
1404
				$result[$k] = !preg_match('/^[0-9,]+$/', $v) ? (int) $v : $v;
1405
			}
1406 View Code Duplication
			elseif($key === 'mid' || $key === 'search_keyword')
1407
			{
1408
				$result[$k] = htmlspecialchars($v, ENT_COMPAT | ENT_HTML401, 'UTF-8', FALSE);
1409
			}
1410
			elseif($key === 'vid')
1411
			{
1412
				$result[$k] = urlencode($v);
1413
			}
1414 View Code Duplication
			elseif($key === 'xe_validator_id')
1415
			{
1416
				$result[$k] = htmlspecialchars($v, ENT_COMPAT | ENT_HTML401, 'UTF-8', FALSE);
1417
			}
1418
			elseif(stripos($key, 'XE_VALIDATOR', 0) === 0)
1419
			{
1420
				unset($result[$k]);
1421
			}
1422
			else
1423
			{
1424
				$result[$k] = $v;
1425
1426
				if($do_stripslashes && version_compare(PHP_VERSION, '5.4.0', '<') && get_magic_quotes_gpc())
1427
				{
1428 View Code Duplication
					if (is_array($result[$k]))
1429
					{
1430
						array_walk_recursive($result[$k], function(&$val) { $val = stripslashes($val); });
1431
					}
1432
					else
1433
					{
1434
						$result[$k] = stripslashes($result[$k]);
1435
					}
1436
				}
1437
1438 View Code Duplication
				if(is_array($result[$k]))
1439
				{
1440
					array_walk_recursive($result[$k], function(&$val) { $val = trim($val); });
1441
				}
1442
				else
1443
				{
1444
					$result[$k] = trim($result[$k]);
1445
				}
1446
			}
1447
		}
1448
1449
		return $isArray ? $result : $result[0];
1450
	}
1451
1452
	/**
1453
	 * Check if there exists uploaded file
1454
	 *
1455
	 * @return bool True: exists, False: otherwise
1456
	 */
1457
	function isUploaded()
1458
	{
1459
		$self = self::getInstance();
1460
		return $self->is_uploaded;
1461
	}
1462
1463
	/**
1464
	 * Handle uploaded file
1465
	 *
1466
	 * @return void
1467
	 */
1468
	function _setUploadedArgument()
1469
	{
1470
		if($_SERVER['REQUEST_METHOD'] != 'POST' || !$_FILES || (stripos($_SERVER['CONTENT_TYPE'], 'multipart/form-data') === FALSE && stripos($_SERVER['HTTP_CONTENT_TYPE'], 'multipart/form-data') === FALSE))
1471
		{
1472
			return;
1473
		}
1474
1475
		foreach($_FILES as $key => $val)
1476
		{
1477
			$tmp_name = $val['tmp_name'];
1478
			if(!is_array($tmp_name))
1479
			{
1480
				if(!$tmp_name || !is_uploaded_file($tmp_name))
1481
				{
1482
					continue;
1483
				}
1484
				$val['name'] = htmlspecialchars($val['name'], ENT_COMPAT | ENT_HTML401, 'UTF-8', FALSE);
1485
				$this->set($key, $val, TRUE);
0 ignored issues
show
Documentation introduced by
$val is of type array<string,string,{"name":"string"}>, 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...
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...
1486
				$this->is_uploaded = TRUE;
1487
			}
1488
			else
1489
			{
1490
				for($i = 0, $c = count($tmp_name); $i < $c; $i++)
1491
				{
1492
					if($val['size'][$i] > 0)
1493
					{
1494
						$file['name'] = $val['name'][$i];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$file was never initialized. Although not strictly required by PHP, it is generally a good practice to add $file = 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...
1495
						$file['type'] = $val['type'][$i];
0 ignored issues
show
Bug introduced by
The variable $file 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...
1496
						$file['tmp_name'] = $val['tmp_name'][$i];
1497
						$file['error'] = $val['error'][$i];
1498
						$file['size'] = $val['size'][$i];
1499
						$files[] = $file;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$files was never initialized. Although not strictly required by PHP, it is generally a good practice to add $files = 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...
1500
					}
1501
				}
1502
				$this->set($key, $files, TRUE);
0 ignored issues
show
Bug introduced by
The variable $files 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...
Documentation introduced by
$files is of type array<integer,array<string,?,{"size":"?"}>>, 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...
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...
1503
			}
1504
		}
1505
	}
1506
1507
	/**
1508
	 * Return request method
1509
	 * @return string Request method type. (Optional - GET|POST|XMLRPC|JSON)
1510
	 */
1511
	function getRequestMethod()
1512
	{
1513
		$self = self::getInstance();
1514
		return $self->request_method;
1515
	}
1516
1517
	/**
1518
	 * Return request URL
1519
	 * @return string request URL
1520
	 */
1521
	function getRequestUrl()
1522
	{
1523
		static $url = null;
1524
		if(is_null($url))
1525
		{
1526
			$url = self::getRequestUri();
1527
			if(count($_GET) > 0)
1528
			{
1529
				foreach($_GET as $key => $val)
1530
				{
1531
					$vars[] = $key . '=' . ($val ? urlencode(self::convertEncodingStr($val)) : '');
0 ignored issues
show
Coding Style Comprehensibility introduced by
$vars was never initialized. Although not strictly required by PHP, it is generally a good practice to add $vars = 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...
1532
				}
1533
				$url .= '?' . join('&', $vars);
0 ignored issues
show
Bug introduced by
The variable $vars 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...
1534
			}
1535
		}
1536
		return $url;
1537
	}
1538
1539
	/**
1540
	 * Return js callback func.
1541
	 * @return string callback func.
1542
	 */
1543
	function getJSCallbackFunc()
1544
	{
1545
		$self = self::getInstance();
0 ignored issues
show
Unused Code introduced by
$self 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...
1546
		$js_callback_func = isset($_GET['xe_js_callback']) ? $_GET['xe_js_callback'] : $_POST['xe_js_callback'];
1547
1548
		if(!preg_match('/^[a-z0-9\.]+$/i', $js_callback_func))
1549
		{
1550
			unset($js_callback_func);
1551
			unset($_GET['xe_js_callback']);
1552
			unset($_POST['xe_js_callback']);
1553
		}
1554
1555
		return $js_callback_func;
1556
	}
1557
1558
	/**
1559
	 * Make URL with args_list upon request URL
1560
	 *
1561
	 * @param int $num_args Arguments nums
1562
	 * @param array $args_list Argument list for set url
1563
	 * @param string $domain Domain
1564
	 * @param bool $encode If TRUE, use url encode.
1565
	 * @param bool $autoEncode If TRUE, url encode automatically, detailed. Use this option, $encode value should be TRUE
1566
	 * @return string URL
1567
	 */
1568
	function getUrl($num_args = 0, $args_list = array(), $domain = null, $encode = TRUE, $autoEncode = FALSE)
0 ignored issues
show
Unused Code introduced by
The parameter $num_args 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...
1569
	{
1570
		static $site_module_info = null;
1571
		static $current_info = null;
1572
1573
		$self = self::getInstance();
1574
1575
		// retrieve virtual site information
1576
		if(is_null($site_module_info))
1577
		{
1578
			$site_module_info = self::get('site_module_info');
1579
		}
1580
1581
		// If $domain is set, handle it (if $domain is vid type, remove $domain and handle with $vid)
1582
		if($domain && isSiteID($domain))
0 ignored issues
show
Bug Best Practice introduced by
The expression $domain of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null 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...
1583
		{
1584
			$vid = $domain;
1585
			$domain = '';
1586
		}
1587
1588
		// If $domain, $vid are not set, use current site information
1589
		if(!$domain && !$vid)
0 ignored issues
show
Bug introduced by
The variable $vid 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...
Bug Best Practice introduced by
The expression $domain of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null 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...
1590
		{
1591
			if($site_module_info->domain && isSiteID($site_module_info->domain))
1592
			{
1593
				$vid = $site_module_info->domain;
1594
			}
1595
			else
1596
			{
1597
				$domain = $site_module_info->domain;
1598
			}
1599
		}
1600
1601
		// if $domain is set, compare current URL. If they are same, remove the domain, otherwise link to the domain.
1602
		if($domain)
1603
		{
1604
			$domain_info = parse_url($domain);
1605
			if(is_null($current_info))
1606
			{
1607
				$current_info = parse_url(($_SERVER['HTTPS'] == 'on' ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . getScriptPath());
1608
			}
1609
			if($domain_info['host'] . $domain_info['path'] == $current_info['host'] . $current_info['path'])
1610
			{
1611
				unset($domain);
1612
			}
1613
			else
1614
			{
1615
				$domain = preg_replace('/^(http|https):\/\//i', '', trim($domain));
1616
				if(substr_compare($domain, '/', -1) !== 0)
1617
				{
1618
					$domain .= '/';
1619
				}
1620
			}
1621
		}
1622
1623
		$get_vars = array();
1624
1625
		// If there is no GET variables or first argument is '' to reset variables
1626
		if(!$self->get_vars || $args_list[0] == '')
1627
		{
1628
			// rearrange args_list
1629
			if(is_array($args_list) && $args_list[0] == '')
1630
			{
1631
				array_shift($args_list);
1632
			}
1633
		}
1634
		else
1635
		{
1636
			// Otherwise, make GET variables into array
1637
			$get_vars = get_object_vars($self->get_vars);
1638
		}
1639
1640
		// arrange args_list
1641
		for($i = 0, $c = count($args_list); $i < $c; $i += 2)
1642
		{
1643
			$key = $args_list[$i];
1644
			$val = trim($args_list[$i + 1]);
1645
1646
			// If value is not set, remove the key
1647
			if(!isset($val) || !strlen($val))
1648
			{
1649
				unset($get_vars[$key]);
1650
				continue;
1651
			}
1652
			// set new variables
1653
			$get_vars[$key] = $val;
1654
		}
1655
1656
		// remove vid, rnd
1657
		unset($get_vars['rnd']);
1658
		if($vid)
1659
		{
1660
			$get_vars['vid'] = $vid;
1661
		}
1662
		else
1663
		{
1664
			unset($get_vars['vid']);
1665
		}
1666
1667
		// for compatibility to lower versions
1668
		$act = $get_vars['act'];
1669
		$act_alias = array(
1670
			'dispMemberFriend' => 'dispCommunicationFriend',
1671
			'dispMemberMessages' => 'dispCommunicationMessages',
1672
			'dispDocumentAdminManageDocument' => 'dispDocumentManageDocument',
1673
			'dispModuleAdminSelectList' => 'dispModuleSelectList'
1674
		);
1675
		if($act_alias[$act])
1676
		{
1677
			$get_vars['act'] = $act_alias[$act];
1678
		}
1679
1680
		// organize URL
1681
		$query = '';
1682
		if(count($get_vars) > 0)
1683
		{
1684
			// if using rewrite mod
1685
			if($self->allow_rewrite)
1686
			{
1687
				$var_keys = array_keys($get_vars);
1688
				sort($var_keys);
1689
1690
				$target = join('.', $var_keys);
1691
1692
				$act = $get_vars['act'];
1693
				$vid = $get_vars['vid'];
1694
				$mid = $get_vars['mid'];
1695
				$key = $get_vars['key'];
1696
				$srl = $get_vars['document_srl'];
1697
1698
				$tmpArray = array('rss' => 1, 'atom' => 1, 'api' => 1);
1699
				$is_feed = isset($tmpArray[$act]);
1700
1701
				$target_map = array(
1702
					'vid' => $vid,
1703
					'mid' => $mid,
1704
					'mid.vid' => "$vid/$mid",
1705
					'entry.mid' => "$mid/entry/" . $get_vars['entry'],
1706
					'entry.mid.vid' => "$vid/$mid/entry/" . $get_vars['entry'],
1707
					'document_srl' => $srl,
1708
					'document_srl.mid' => "$mid/$srl",
1709
					'document_srl.vid' => "$vid/$srl",
1710
					'document_srl.mid.vid' => "$vid/$mid/$srl",
1711
					'act' => ($is_feed && $act !== 'api') ? $act : '',
1712
					'act.mid' => $is_feed ? "$mid/$act" : '',
1713
					'act.mid.vid' => $is_feed ? "$vid/$mid/$act" : '',
1714
					'act.document_srl.key' => ($act == 'trackback') ? "$srl/$key/$act" : '',
1715
					'act.document_srl.key.mid' => ($act == 'trackback') ? "$mid/$srl/$key/$act" : '',
1716
					'act.document_srl.key.vid' => ($act == 'trackback') ? "$vid/$srl/$key/$act" : '',
1717
					'act.document_srl.key.mid.vid' => ($act == 'trackback') ? "$vid/$mid/$srl/$key/$act" : ''
1718
				);
1719
1720
				$query = $target_map[$target];
1721
			}
1722
1723
			if(!$query)
1724
			{
1725
				$queries = array();
1726 View Code Duplication
				foreach($get_vars as $key => $val)
1727
				{
1728
					if(is_array($val) && count($val) > 0)
1729
					{
1730
						foreach($val as $k => $v)
1731
						{
1732
							$queries[] = $key . '[' . $k . ']=' . urlencode($v);
1733
						}
1734
					}
1735
					elseif(!is_array($val))
1736
					{
1737
						$queries[] = $key . '=' . urlencode($val);
1738
					}
1739
				}
1740
				if(count($queries) > 0)
1741
				{
1742
					$query = 'index.php?' . join('&', $queries);
1743
				}
1744
			}
1745
		}
1746
1747
		// If using SSL always
1748
		$_use_ssl = $self->get('_use_ssl');
1749
		if($_use_ssl == 'always')
1750
		{
1751
			$query = $self->getRequestUri(ENFORCE_SSL, $domain) . $query;
1752
			// optional SSL use
1753
		}
1754
		elseif($_use_ssl == 'optional')
1755
		{
1756
			$ssl_mode = (($self->get('module') === 'admin') || ($get_vars['module'] === 'admin') || (isset($get_vars['act']) && $self->isExistsSSLAction($get_vars['act']))) ? ENFORCE_SSL : RELEASE_SSL;
1757
			$query = $self->getRequestUri($ssl_mode, $domain) . $query;
1758
			// no SSL
1759
		}
1760
		else
1761
		{
1762
			// currently on SSL but target is not based on SSL
1763
			if($_SERVER['HTTPS'] == 'on')
1764
			{
1765
				$query = $self->getRequestUri(ENFORCE_SSL, $domain) . $query;
1766
			}
1767
			else if($domain) // if $domain is set
1768
			{
1769
				$query = $self->getRequestUri(FOLLOW_REQUEST_SSL, $domain) . $query;
1770
			}
1771
			else
1772
			{
1773
				$query = getScriptPath() . $query;
1774
			}
1775
		}
1776
1777
		if(!$encode)
1778
		{
1779
			return $query;
1780
		}
1781
1782
		if(!$autoEncode)
1783
		{
1784
			return htmlspecialchars($query, ENT_COMPAT | ENT_HTML401, 'UTF-8', FALSE);
1785
		}
1786
1787
		$output = array();
1788
		$encode_queries = array();
1789
		$parsedUrl = parse_url($query);
1790
		parse_str($parsedUrl['query'], $output);
1791
		foreach($output as $key => $value)
0 ignored issues
show
Bug introduced by
The expression $output of type null|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
1792
		{
1793
			if(preg_match('/&([a-z]{2,}|#\d+);/', urldecode($value)))
1794
			{
1795
				$value = urlencode(htmlspecialchars_decode(urldecode($value)));
1796
			}
1797
			$encode_queries[] = $key . '=' . $value;
1798
		}
1799
1800
		return htmlspecialchars($parsedUrl['path'] . '?' . join('&', $encode_queries), ENT_COMPAT | ENT_HTML401, 'UTF-8', FALSE);
1801
	}
1802
1803
	/**
1804
	 * Return after removing an argument on the requested URL
1805
	 *
1806
	 * @param string $ssl_mode SSL mode
1807
	 * @param string $domain Domain
1808
	 * @retrun string converted URL
1809
	 */
1810
	function getRequestUri($ssl_mode = FOLLOW_REQUEST_SSL, $domain = null)
1811
	{
1812
		static $url = array();
1813
1814
		// Check HTTP Request
1815
		if(!isset($_SERVER['SERVER_PROTOCOL']))
1816
		{
1817
			return;
1818
		}
1819
1820
		if(self::get('_use_ssl') == 'always')
1821
		{
1822
			$ssl_mode = ENFORCE_SSL;
1823
		}
1824
1825
		if($domain)
0 ignored issues
show
Bug Best Practice introduced by
The expression $domain of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null 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...
1826
		{
1827
			$domain_key = md5($domain);
1828
		}
1829
		else
1830
		{
1831
			$domain_key = 'default';
1832
		}
1833
1834
		if(isset($url[$ssl_mode][$domain_key]))
1835
		{
1836
			return $url[$ssl_mode][$domain_key];
1837
		}
1838
1839
		$current_use_ssl = ($_SERVER['HTTPS'] == 'on');
1840
1841
		switch($ssl_mode)
1842
		{
1843
			case FOLLOW_REQUEST_SSL: $use_ssl = $current_use_ssl;
1844
				break;
1845
			case ENFORCE_SSL: $use_ssl = TRUE;
1846
				break;
1847
			case RELEASE_SSL: $use_ssl = FALSE;
1848
				break;
1849
		}
1850
1851
		if($domain)
0 ignored issues
show
Bug Best Practice introduced by
The expression $domain of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null 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...
1852
		{
1853
			$target_url = trim($domain);
1854
			if(substr_compare($target_url, '/', -1) !== 0)
1855
			{
1856
				$target_url.= '/';
1857
			}
1858
		}
1859
		else
1860
		{
1861
			$target_url = $_SERVER['HTTP_HOST'] . getScriptPath();
1862
		}
1863
1864
		$url_info = parse_url('http://' . $target_url);
1865
1866
		if($current_use_ssl != $use_ssl)
0 ignored issues
show
Bug introduced by
The variable $use_ssl 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...
1867
		{
1868
			unset($url_info['port']);
1869
		}
1870
1871
		if($use_ssl)
1872
		{
1873
			$port = self::get('_https_port');
1874 View Code Duplication
			if($port && $port != 443)
1875
			{
1876
				$url_info['port'] = $port;
1877
			}
1878
			elseif($url_info['port'] == 443)
1879
			{
1880
				unset($url_info['port']);
1881
			}
1882
		}
1883 View Code Duplication
		else
1884
		{
1885
			$port = self::get('_http_port');
1886
			if($port && $port != 80)
1887
			{
1888
				$url_info['port'] = $port;
1889
			}
1890
			elseif($url_info['port'] == 80)
1891
			{
1892
				unset($url_info['port']);
1893
			}
1894
		}
1895
1896
		$url[$ssl_mode][$domain_key] = sprintf('%s://%s%s%s', $use_ssl ? 'https' : $url_info['scheme'], $url_info['host'], $url_info['port'] && $url_info['port'] != 80 ? ':' . $url_info['port'] : '', $url_info['path']);
1897
1898
		return $url[$ssl_mode][$domain_key];
1899
	}
1900
1901
	/**
1902
	 * Set a context value with a key
1903
	 *
1904
	 * @param string $key Key
1905
	 * @param string $val Value
1906
	 * @param mixed $set_to_get_vars If not FALSE, Set to get vars.
1907
	 * @return void
1908
	 */
1909
	function set($key, $val, $set_to_get_vars = 0)
1910
	{
1911
		$self = self::getInstance();
1912
		$self->context->{$key} = $val;
1913
		if($set_to_get_vars === FALSE)
1914
		{
1915
			return;
1916
		}
1917
		if($val === NULL || $val === '')
1918
		{
1919
			unset($self->get_vars->{$key});
1920
			return;
1921
		}
1922
		if($set_to_get_vars || $self->get_vars->{$key})
1923
		{
1924
			$self->get_vars->{$key} = $val;
1925
		}
1926
	}
1927
1928
	/**
1929
	 * Return key's value
1930
	 *
1931
	 * @param string $key Key
1932
	 * @return string Key
1933
	 */
1934
	function get($key)
1935
	{
1936
		$self = self::getInstance();
1937
1938
		if(!isset($self->context->{$key}))
1939
		{
1940
			return null;
1941
		}
1942
		return $self->context->{$key};
1943
	}
1944
1945
	/**
1946
	 * Get one more vars in object vars with given arguments(key1, key2, key3,...)
1947
	 *
1948
	 * @return object
1949
	 */
1950
	function gets()
1951
	{
1952
		$num_args = func_num_args();
1953
		if($num_args < 1)
1954
		{
1955
			return;
1956
		}
1957
		$self = self::getInstance();
1958
1959
		$args_list = func_get_args();
1960
		$output = new stdClass();
1961
		foreach($args_list as $v)
1962
		{
1963
			$output->{$v} = $self->get($v);
1964
		}
1965
		return $output;
1966
	}
1967
1968
	/**
1969
	 * Return all data
1970
	 *
1971
	 * @return object All data
1972
	 */
1973
	function getAll()
1974
	{
1975
		$self = self::getInstance();
1976
		return $self->context;
1977
	}
1978
1979
	/**
1980
	 * Return values from the GET/POST/XMLRPC
1981
	 *
1982
	 * @return Object Request variables.
1983
	 */
1984
	function getRequestVars()
1985
	{
1986
		$self = self::getInstance();
1987
		if($self->get_vars)
1988
		{
1989
			return clone($self->get_vars);
1990
		}
1991
		return new stdClass;
1992
	}
1993
1994
	/**
1995
	 * Register if an action is to be encrypted by SSL. Those actions are sent to https in common/js/xml_handler.js
1996
	 *
1997
	 * @param string $action act name
1998
	 * @return void
1999
	 */
2000
	function addSSLAction($action)
2001
	{
2002
		$self = self::getInstance();
2003
2004
		if(!is_readable($self->sslActionCacheFile))
2005
		{
2006
			$buff = '<?php if(!defined("__XE__"))exit;';
2007
			FileHandler::writeFile($self->sslActionCacheFile, $buff);
0 ignored issues
show
Documentation introduced by
$self->sslActionCacheFile is of type array, 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...
2008
		}
2009
2010 View Code Duplication
		if(!isset($self->ssl_actions[$action]))
2011
		{
2012
			$self->ssl_actions[$action] = 1;
2013
			$sslActionCacheString = sprintf('$sslActions[\'%s\'] = 1;', $action);
2014
			FileHandler::writeFile($self->sslActionCacheFile, $sslActionCacheString, 'a');
0 ignored issues
show
Documentation introduced by
$self->sslActionCacheFile is of type array, 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...
2015
		}
2016
	}
2017
2018
	/**
2019
	 * Register if actions are to be encrypted by SSL. Those actions are sent to https in common/js/xml_handler.js
2020
	 *
2021
	 * @param string $action act name
0 ignored issues
show
Documentation introduced by
There is no parameter named $action. Did you maybe mean $action_array?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
2022
	 * @return void
2023
	 */
2024
	function addSSLActions($action_array)
2025
	{
2026
		$self = self::getInstance();
2027
2028
		if(!is_readable($self->sslActionCacheFile))
2029
		{
2030
			unset($self->ssl_actions);
2031
			$buff = '<?php if(!defined("__XE__"))exit;';
2032
			FileHandler::writeFile($self->sslActionCacheFile, $buff);
0 ignored issues
show
Documentation introduced by
$self->sslActionCacheFile is of type array, 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...
2033
		}
2034
2035
		foreach($action_array as $action)
2036
		{
2037 View Code Duplication
			if(!isset($self->ssl_actions[$action]))
2038
			{
2039
				$self->ssl_actions[$action] = 1;
2040
				$sslActionCacheString = sprintf('$sslActions[\'%s\'] = 1;', $action);
2041
				FileHandler::writeFile($self->sslActionCacheFile, $sslActionCacheString, 'a');
0 ignored issues
show
Documentation introduced by
$self->sslActionCacheFile is of type array, 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...
2042
			}
2043
		}
2044
	}
2045
2046
	/**
2047
	 * Delete if action is registerd to be encrypted by SSL.
2048
	 *
2049
	 * @param string $action act name
2050
	 * @return void
2051
	 */
2052
	function subtractSSLAction($action)
2053
	{
2054
		$self = self::getInstance();
2055
2056
		if($self->isExistsSSLAction($action))
2057
		{
2058
			$sslActionCacheString = sprintf('$sslActions[\'%s\'] = 1;', $action);
2059
			$buff = FileHandler::readFile($self->sslActionCacheFile);
0 ignored issues
show
Documentation introduced by
$self->sslActionCacheFile is of type array, 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...
2060
			$buff = str_replace($sslActionCacheString, '', $buff);
2061
			FileHandler::writeFile($self->sslActionCacheFile, $buff);
0 ignored issues
show
Documentation introduced by
$self->sslActionCacheFile is of type array, 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...
2062
		}
2063
	}
2064
2065
	/**
2066
	 * Get SSL Action
2067
	 *
2068
	 * @return string acts in array
2069
	 */
2070
	function getSSLActions()
2071
	{
2072
		$self = self::getInstance();
2073
		if($self->getSslStatus() == 'optional')
2074
		{
2075
			return $self->ssl_actions;
2076
		}
2077
	}
2078
2079
	/**
2080
	 * Check SSL action are existed
2081
	 *
2082
	 * @param string $action act name
2083
	 * @return bool If SSL exists, return TRUE.
2084
	 */
2085
	function isExistsSSLAction($action)
2086
	{
2087
		$self = self::getInstance();
2088
		return isset($self->ssl_actions[$action]);
2089
	}
2090
2091
	/**
2092
	 * Normalize file path
2093
	 *
2094
	 * @deprecated
2095
	 * @param string $file file path
2096
	 * @return string normalized file path
2097
	 */
2098
	function normalizeFilePath($file)
2099
	{
2100
		if($file{0} != '/' && $file{0} != '.' && strpos($file, '://') === FALSE)
2101
		{
2102
			$file = './' . $file;
2103
		}
2104
		$file = preg_replace('@/\./|(?<!:)\/\/@', '/', $file);
2105
		while(strpos($file, '/../') !== FALSE)
2106
		{
2107
			$file = preg_replace('/\/([^\/]+)\/\.\.\//s', '/', $file, 1);
2108
		}
2109
2110
		return $file;
2111
	}
2112
2113
	/**
2114
	 * Get abstract file url
2115
	 *
2116
	 * @deprecated
2117
	 * @param string $file file path
2118
	 * @return string Converted file path
2119
	 */
2120
	function getAbsFileUrl($file)
2121
	{
2122
		$file = self::normalizeFilePath($file);
0 ignored issues
show
Deprecated Code introduced by
The method Context::normalizeFilePath() has been deprecated.

This method has been deprecated.

Loading history...
2123
		$script_path = getScriptPath();
2124
		if(strpos($file, './') === 0)
2125
		{
2126
			$file = $script_path . substr($file, 2);
2127
		}
2128
		elseif(strpos($file, '../') === 0)
2129
		{
2130
			$file = self::normalizeFilePath($script_path . $file);
0 ignored issues
show
Deprecated Code introduced by
The method Context::normalizeFilePath() has been deprecated.

This method has been deprecated.

Loading history...
2131
		}
2132
2133
		return $file;
2134
	}
2135
2136
	/**
2137
	 * Load front end file
2138
	 *
2139
	 * @param array $args array
2140
	 * case js :
2141
	 * 		$args[0]: file name,
2142
	 * 		$args[1]: type (head | body),
2143
	 * 		$args[2]: target IE,
2144
	 * 		$args[3]: index
2145
	 * case css :
2146
	 * 		$args[0]: file name,
2147
	 * 		$args[1]: media,
2148
	 * 		$args[2]: target IE,
2149
	 * 		$args[3]: index
2150
	 *
2151
	 */
2152
	function loadFile($args)
2153
	{
2154
		$self = self::getInstance();
2155
2156
		$self->oFrontEndFileHandler->loadFile($args);
2157
	}
2158
2159
	/**
2160
	 * Unload front end file
2161
	 *
2162
	 * @param string $file File name with path
2163
	 * @param string $targetIe Target IE
2164
	 * @param string $media Media query
2165
	 * @return void
2166
	 */
2167
	function unloadFile($file, $targetIe = '', $media = 'all')
2168
	{
2169
		$self = self::getInstance();
2170
		$self->oFrontEndFileHandler->unloadFile($file, $targetIe, $media);
2171
	}
2172
2173
	/**
2174
	 * Unload front end file all
2175
	 *
2176
	 * @param string $type Unload target (optional - all|css|js)
2177
	 * @return void
2178
	 */
2179
	function unloadAllFiles($type = 'all')
2180
	{
2181
		$self = self::getInstance();
2182
		$self->oFrontEndFileHandler->unloadAllFiles($type);
2183
	}
2184
2185
	/**
2186
	 * Add the js file
2187
	 *
2188
	 * @deprecated
2189
	 * @param string $file File name with path
2190
	 * @param string $optimized optimized (That seems to not use)
2191
	 * @param string $targetie target IE
2192
	 * @param string $index index
2193
	 * @param string $type Added position. (head:<head>..</head>, body:<body>..</body>)
2194
	 * @param bool $isRuleset Use ruleset
2195
	 * @param string $autoPath If path not readed, set the path automatically.
2196
	 * @return void
2197
	 */
2198
	function addJsFile($file, $optimized = FALSE, $targetie = '', $index = 0, $type = 'head', $isRuleset = FALSE, $autoPath = null)
0 ignored issues
show
Unused Code introduced by
The parameter $optimized 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...
2199
	{
2200
		if($isRuleset)
2201
		{
2202
			if(strpos($file, '#') !== FALSE)
2203
			{
2204
				$file = str_replace('#', '', $file);
2205
				if(!is_readable($file))
2206
				{
2207
					$file = $autoPath;
2208
				}
2209
			}
2210
			$validator = new Validator($file);
2211
			$validator->setCacheDir('files/cache');
2212
			$file = $validator->getJsPath();
2213
		}
2214
2215
		$self = self::getInstance();
2216
		$self->oFrontEndFileHandler->loadFile(array($file, $type, $targetie, $index));
2217
	}
2218
2219
	/**
2220
	 * Remove the js file
2221
	 *
2222
	 * @deprecated
2223
	 * @param string $file File name with path
2224
	 * @param string $optimized optimized (That seems to not use)
2225
	 * @param string $targetie target IE
2226
	 * @return void
2227
	 */
2228
	function unloadJsFile($file, $optimized = FALSE, $targetie = '')
0 ignored issues
show
Unused Code introduced by
The parameter $optimized 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...
2229
	{
2230
		$self = self::getInstance();
2231
		$self->oFrontEndFileHandler->unloadFile($file, $targetie);
2232
	}
2233
2234
	/**
2235
	 * Unload all javascript files
2236
	 *
2237
	 * @return void
2238
	 */
2239
	function unloadAllJsFiles()
2240
	{
2241
		$self = self::getInstance();
2242
		$self->oFrontEndFileHandler->unloadAllFiles('js');
2243
	}
2244
2245
	/**
2246
	 * Add javascript filter
2247
	 *
2248
	 * @param string $path File path
2249
	 * @param string $filename File name
2250
	 * @return void
2251
	 */
2252
	function addJsFilter($path, $filename)
2253
	{
2254
		$oXmlFilter = new XmlJSFilter($path, $filename);
2255
		$oXmlFilter->compile();
2256
	}
2257
2258
	/**
2259
	 * Same as array_unique but works only for file subscript
2260
	 *
2261
	 * @deprecated
2262
	 * @param array $files File list
2263
	 * @return array File list
2264
	 */
2265
	function _getUniqueFileList($files)
2266
	{
2267
		ksort($files);
2268
		$files = array_values($files);
2269
		$filenames = array();
2270
		for($i = 0, $c = count($files); $i < $c; ++$i)
2271
		{
2272
			if(in_array($files[$i]['file'], $filenames))
2273
			{
2274
				unset($files[$i]);
2275
			}
2276
			$filenames[] = $files[$i]['file'];
2277
		}
2278
2279
		return $files;
2280
	}
2281
2282
	/**
2283
	 * Returns the list of javascripts that matches the given type.
2284
	 *
2285
	 * @param string $type Added position. (head:<head>..</head>, body:<body>..</body>)
2286
	 * @return array Returns javascript file list. Array contains file, targetie.
2287
	 */
2288
	function getJsFile($type = 'head')
2289
	{
2290
		$self = self::getInstance();
2291
		return $self->oFrontEndFileHandler->getJsFileList($type);
2292
	}
2293
2294
	/**
2295
	 * Add CSS file
2296
	 *
2297
	 * @deprecated
2298
	 * @param string $file File name with path
2299
	 * @param string $optimized optimized (That seems to not use)
2300
	 * @param string $media Media query
2301
	 * @param string $targetie target IE
2302
	 * @param string $index index
2303
	 * @return void
2304
	 *
2305
	 */
2306
	function addCSSFile($file, $optimized = FALSE, $media = 'all', $targetie = '', $index = 0)
0 ignored issues
show
Unused Code introduced by
The parameter $optimized 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...
2307
	{
2308
		$self = self::getInstance();
2309
		$self->oFrontEndFileHandler->loadFile(array($file, $media, $targetie, $index));
2310
	}
2311
2312
	/**
2313
	 * Remove css file
2314
	 *
2315
	 * @deprecated
2316
	 * @param string $file File name with path
2317
	 * @param string $optimized optimized (That seems to not use)
2318
	 * @param string $media Media query
2319
	 * @param string $targetie target IE
2320
	 * @return void
2321
	 */
2322
	function unloadCSSFile($file, $optimized = FALSE, $media = 'all', $targetie = '')
0 ignored issues
show
Unused Code introduced by
The parameter $optimized 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...
2323
	{
2324
		$self = self::getInstance();
2325
		$self->oFrontEndFileHandler->unloadFile($file, $targetie, $media);
2326
	}
2327
2328
	/**
2329
	 * Unload all css files
2330
	 *
2331
	 * @return void
2332
	 */
2333
	function unloadAllCSSFiles()
2334
	{
2335
		$self = self::getInstance();
2336
		$self->oFrontEndFileHandler->unloadAllFiles('css');
2337
	}
2338
2339
	/**
2340
	 * Return a list of css files
2341
	 *
2342
	 * @return array Returns css file list. Array contains file, media, targetie.
2343
	 */
2344
	function getCSSFile()
2345
	{
2346
		$self = self::getInstance();
2347
		return $self->oFrontEndFileHandler->getCssFileList();
2348
	}
2349
2350
	/**
2351
	 * Returns javascript plugin file info
2352
	 * @param string $pluginName
2353
	 * @return stdClass
2354
	 */
2355
	function getJavascriptPluginInfo($pluginName)
2356
	{
2357
		if($plugin_name == 'ui.datepicker')
0 ignored issues
show
Bug introduced by
The variable $plugin_name seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
2358
		{
2359
			$plugin_name = 'ui';
0 ignored issues
show
Unused Code introduced by
$plugin_name 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...
2360
		}
2361
2362
		$plugin_path = './common/js/plugins/' . $pluginName . '/';
2363
		$info_file = $plugin_path . 'plugin.load';
2364
		if(!is_readable($info_file))
2365
		{
2366
			return;
2367
		}
2368
2369
		$list = file($info_file);
2370
		$result = new stdClass();
2371
		$result->jsList = array();
2372
		$result->cssList = array();
2373
2374
		foreach($list as $filename)
2375
		{
2376
			$filename = trim($filename);
2377
			if(!$filename)
2378
			{
2379
				continue;
2380
			}
2381
2382
			if(strncasecmp('./', $filename, 2) === 0)
2383
			{
2384
				$filename = substr($filename, 2);
2385
			}
2386
2387
			if(substr_compare($filename, '.js', -3) === 0)
2388
			{
2389
				$result->jsList[] = $plugin_path . $filename;
2390
			}
2391
			elseif(substr_compare($filename, '.css', -4) === 0)
2392
			{
2393
				$result->cssList[] = $plugin_path . $filename;
2394
			}
2395
		}
2396
2397
		if(is_dir($plugin_path . 'lang'))
2398
		{
2399
			$result->langPath = $plugin_path . 'lang';
2400
		}
2401
2402
		return $result;
2403
	}
2404
	/**
2405
	 * Load javascript plugin
2406
	 *
2407
	 * @param string $plugin_name plugin name
2408
	 * @return void
2409
	 */
2410
	function loadJavascriptPlugin($plugin_name)
2411
	{
2412
		static $loaded_plugins = array();
2413
2414
		$self = self::getInstance();
2415
		if($plugin_name == 'ui.datepicker')
2416
		{
2417
			$plugin_name = 'ui';
2418
		}
2419
2420
		if($loaded_plugins[$plugin_name])
2421
		{
2422
			return;
2423
		}
2424
		$loaded_plugins[$plugin_name] = TRUE;
2425
2426
		$plugin_path = './common/js/plugins/' . $plugin_name . '/';
2427
		$info_file = $plugin_path . 'plugin.load';
2428
		if(!is_readable($info_file))
2429
		{
2430
			return;
2431
		}
2432
2433
		$list = file($info_file);
2434
		foreach($list as $filename)
2435
		{
2436
			$filename = trim($filename);
2437
			if(!$filename)
2438
			{
2439
				continue;
2440
			}
2441
2442
			if(strncasecmp('./', $filename, 2) === 0)
2443
			{
2444
				$filename = substr($filename, 2);
2445
			}
2446 View Code Duplication
			if(substr_compare($filename, '.js', -3) === 0)
2447
			{
2448
				$self->loadFile(array($plugin_path . $filename, 'body', '', 0), TRUE);
0 ignored issues
show
Unused Code introduced by
The call to Context::loadFile() has too many arguments starting with TRUE.

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

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

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

Loading history...
2449
			}
2450 View Code Duplication
			if(substr_compare($filename, '.css', -4) === 0)
2451
			{
2452
				$self->loadFile(array($plugin_path . $filename, 'all', '', 0), TRUE);
0 ignored issues
show
Unused Code introduced by
The call to Context::loadFile() has too many arguments starting with TRUE.

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

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

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

Loading history...
2453
			}
2454
		}
2455
2456
		if(is_dir($plugin_path . 'lang'))
2457
		{
2458
			$self->loadLang($plugin_path . 'lang');
2459
		}
2460
	}
2461
2462
	/**
2463
	 * Add html code before </head>
2464
	 *
2465
	 * @param string $header add html code before </head>.
2466
	 * @return void
2467
	 */
2468
	function addHtmlHeader($header)
2469
	{
2470
		$self = self::getInstance();
2471
		$self->html_header .= "\n" . $header;
2472
	}
2473
2474
	function clearHtmlHeader()
2475
	{
2476
		$self = self::getInstance();
2477
		$self->html_header = '';
2478
	}
2479
2480
	/**
2481
	 * Returns added html code by addHtmlHeader()
2482
	 *
2483
	 * @return string Added html code before </head>
2484
	 */
2485
	function getHtmlHeader()
2486
	{
2487
		$self = self::getInstance();
2488
		return $self->html_header;
2489
	}
2490
2491
	/**
2492
	 * Add css class to Html Body
2493
	 *
2494
	 * @param string $class_name class name
2495
	 */
2496
	function addBodyClass($class_name)
2497
	{
2498
		$self = self::getInstance();
2499
		$self->body_class[] = $class_name;
2500
	}
2501
2502
	/**
2503
	 * Return css class to Html Body
2504
	 *
2505
	 * @return string Return class to html body
2506
	 */
2507
	function getBodyClass()
2508
	{
2509
		$self = self::getInstance();
2510
		$self->body_class = array_unique($self->body_class);
2511
2512
		return (count($self->body_class) > 0) ? sprintf(' class="%s"', join(' ', $self->body_class)) : '';
2513
	}
2514
2515
	/**
2516
	 * Add html code after <body>
2517
	 *
2518
	 * @param string $header Add html code after <body>
2519
	 */
2520
	function addBodyHeader($header)
2521
	{
2522
		$self = self::getInstance();
2523
		$self->body_header .= "\n" . $header;
2524
	}
2525
2526
	/**
2527
	 * Returns added html code by addBodyHeader()
2528
	 *
2529
	 * @return string Added html code after <body>
2530
	 */
2531
	function getBodyHeader()
2532
	{
2533
		$self = self::getInstance();
2534
		return $self->body_header;
2535
	}
2536
2537
	/**
2538
	 * Add html code before </body>
2539
	 *
2540
	 * @param string $footer Add html code before </body>
2541
	 */
2542
	function addHtmlFooter($footer)
2543
	{
2544
		$self = self::getInstance();
2545
		$self->html_footer .= ($self->Htmlfooter ? "\n" : '') . $footer;
0 ignored issues
show
Bug introduced by
The property Htmlfooter 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...
2546
	}
2547
2548
	/**
2549
	 * Returns added html code by addHtmlHeader()
2550
	 *
2551
	 * @return string Added html code before </body>
2552
	 */
2553
	function getHtmlFooter()
2554
	{
2555
		$self = self::getInstance();
2556
		return $self->html_footer;
2557
	}
2558
2559
	/**
2560
	 * Get config file
2561
	 *
2562
	 * @retrun string The path of the config file that contains database settings
2563
	 */
2564
	function getConfigFile()
2565
	{
2566
		return _XE_PATH_ . 'files/config/db.config.php';
2567
	}
2568
2569
	/**
2570
	 * Get FTP config file
2571
	 *
2572
	 * @return string The path of the config file that contains FTP settings
2573
	 */
2574
	function getFTPConfigFile()
2575
	{
2576
		return _XE_PATH_ . 'files/config/ftp.config.php';
2577
	}
2578
2579
	/**
2580
	 * Checks whether XE is installed
2581
	 *
2582
	 * @return bool True if the config file exists, otherwise FALSE.
2583
	 */
2584
	function isInstalled()
2585
	{
2586
		return FileHandler::hasContent(self::getConfigFile());
2587
	}
2588
2589
	/**
2590
	 * Transforms codes about widget or other features into the actual code, deprecatred
2591
	 *
2592
	 * @param string Transforms codes
2593
	 * @return string Transforms codes
2594
	 */
2595
	function transContent($content)
2596
	{
2597
		return $content;
2598
	}
2599
2600
	/**
2601
	 * Check whether it is allowed to use rewrite mod
2602
	 *
2603
	 * @return bool True if it is allowed to use rewrite mod, otherwise FALSE
2604
	 */
2605
	function isAllowRewrite()
2606
	{
2607
		$oContext = self::getInstance();
2608
		return $oContext->allow_rewrite;
2609
	}
2610
2611
	/**
2612
	 * Converts a local path into an URL
2613
	 *
2614
	 * @param string $path URL path
2615
	 * @return string Converted path
2616
	 */
2617
	function pathToUrl($path)
2618
	{
2619
		$xe = _XE_PATH_;
2620
		$path = strtr($path, "\\", "/");
2621
2622
		$base_url = preg_replace('@^https?://[^/]+/?@', '', self::getRequestUri());
2623
2624
		$_xe = explode('/', $xe);
2625
		$_path = explode('/', $path);
2626
		$_base = explode('/', $base_url);
2627
2628
		if(!$_base[count($_base) - 1])
2629
		{
2630
			array_pop($_base);
2631
		}
2632
2633
		foreach($_xe as $idx => $dir)
2634
		{
2635
			if($_path[0] != $dir)
2636
			{
2637
				break;
2638
			}
2639
			array_shift($_path);
2640
		}
2641
2642
		$idx = count($_xe) - $idx - 1;
0 ignored issues
show
Bug introduced by
The variable $idx 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...
2643
		while($idx--)
2644
		{
2645
			if(count($_base) > 0)
2646
			{
2647
				array_shift($_base);
2648
			}
2649
			else
2650
			{
2651
				array_unshift($_base, '..');
2652
			}
2653
		}
2654
2655
		if(count($_base) > 0)
2656
		{
2657
			array_unshift($_path, join('/', $_base));
2658
		}
2659
2660
		$path = '/' . join('/', $_path);
2661
		if(substr_compare($path, '/', -1) !== 0)
2662
		{
2663
			$path .= '/';
2664
		}
2665
		return $path;
2666
	}
2667
2668
	/**
2669
	 * Get meta tag
2670
	 * @return array The list of meta tags
2671
	 */
2672
	function getMetaTag()
2673
	{
2674
		$self = self::getInstance();
2675
2676
		if(!is_array($self->meta_tags))
2677
		{
2678
			$self->meta_tags = array();
0 ignored issues
show
Bug introduced by
The property meta_tags 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...
2679
		}
2680
2681
		$ret = array();
2682
		foreach($self->meta_tags as $key => $val)
2683
		{
2684
			list($name, $is_http_equiv) = explode("\t", $key);
2685
			$ret[] = array('name' => $name, 'is_http_equiv' => $is_http_equiv, 'content' => $val);
2686
		}
2687
2688
		return $ret;
2689
	}
2690
2691
	/**
2692
	 * Add the meta tag
2693
	 *
2694
	 * @param string $name name of meta tag
2695
	 * @param string $content content of meta tag
2696
	 * @param mixed $is_http_equiv value of http_equiv
2697
	 * @return void
2698
	 */
2699
	function addMetaTag($name, $content, $is_http_equiv = FALSE)
2700
	{
2701
		$self = self::getInstance();
2702
		$self->meta_tags[$name . "\t" . ($is_http_equiv ? '1' : '0')] = $content;
2703
	}
2704
2705
}
2706
/* End of file Context.class.php */
2707
/* Location: ./classes/context/Context.class.php */
2708