GitHub Access Token became invalid

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

Context::addJsFile()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 11
nc 4
nop 7
dl 0
loc 20
rs 9.2
c 0
b 0
f 0
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
		$config_file = $self->getConfigFile();
456
		if(is_readable($config_file))
457
		{
458
			include($config_file);
459
		}
460
461
		// If master_db information does not exist, the config file needs to be updated
462
		if(!isset($db_info->master_db))
463
		{
464
			$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...
465
			$db_info->master_db["db_type"] = $db_info->db_type;
466
			unset($db_info->db_type);
467
			$db_info->master_db["db_port"] = $db_info->db_port;
468
			unset($db_info->db_port);
469
			$db_info->master_db["db_hostname"] = $db_info->db_hostname;
470
			unset($db_info->db_hostname);
471
			$db_info->master_db["db_password"] = $db_info->db_password;
472
			unset($db_info->db_password);
473
			$db_info->master_db["db_database"] = $db_info->db_database;
474
			unset($db_info->db_database);
475
			$db_info->master_db["db_userid"] = $db_info->db_userid;
476
			unset($db_info->db_userid);
477
			$db_info->master_db["db_table_prefix"] = $db_info->db_table_prefix;
478
			unset($db_info->db_table_prefix);
479
480
			if(isset($db_info->master_db["db_table_prefix"]) && substr_compare($db_info->master_db["db_table_prefix"], '_', -1) !== 0)
481
			{
482
				$db_info->master_db["db_table_prefix"] .= '_';
483
			}
484
485
			$db_info->slave_db = array($db_info->master_db);
486
			$self->setDBInfo($db_info);
487
488
			$oInstallController = getController('install');
489
			$oInstallController->makeConfigFile();
490
		}
491
492
		if(!$db_info->use_prepared_statements)
493
		{
494
			$db_info->use_prepared_statements = 'Y';
495
		}
496
497
		if(!$db_info->time_zone)
498
			$db_info->time_zone = date('O');
499
		$GLOBALS['_time_zone'] = $db_info->time_zone;
500
501
		if($db_info->qmail_compatibility != 'Y')
502
			$db_info->qmail_compatibility = 'N';
503
		$GLOBALS['_qmail_compatibility'] = $db_info->qmail_compatibility;
504
505
		if(!$db_info->use_db_session)
506
			$db_info->use_db_session = 'N';
507
		if(!$db_info->use_ssl)
508
			$db_info->use_ssl = 'none';
509
		$this->set('_use_ssl', $db_info->use_ssl);
510
511
		$self->set('_http_port', ($db_info->http_port) ? $db_info->http_port : NULL);
512
		$self->set('_https_port', ($db_info->https_port) ? $db_info->https_port : NULL);
513
514
		if(!$db_info->sitelock_whitelist) {
515
			$db_info->sitelock_whitelist = '127.0.0.1';
516
		}
517
518
		if(is_string($db_info->sitelock_whitelist)) {
519
			$db_info->sitelock_whitelist = explode(',', $db_info->sitelock_whitelist);
520
		}
521
522
		$self->setDBInfo($db_info);
523
	}
524
525
	/**
526
	 * Get DB's db_type
527
	 *
528
	 * @return string DB's db_type
529
	 */
530
	function getDBType()
531
	{
532
		$self = self::getInstance();
533
		return $self->db_info->master_db["db_type"];
534
	}
535
536
	/**
537
	 * Set DB information
538
	 *
539
	 * @param object $db_info DB information
540
	 * @return void
541
	 */
542
	function setDBInfo($db_info)
543
	{
544
		$self = self::getInstance();
545
		$self->db_info = $db_info;
546
	}
547
548
	/**
549
	 * Get DB information
550
	 *
551
	 * @return object DB information
552
	 */
553
	function getDBInfo()
554
	{
555
		$self = self::getInstance();
556
		return $self->db_info;
557
	}
558
559
	/**
560
	 * Return ssl status
561
	 *
562
	 * @return object SSL status (Optional - none|always|optional)
563
	 */
564
	function getSslStatus()
565
	{
566
		$dbInfo = self::getDBInfo();
567
		return $dbInfo->use_ssl;
568
	}
569
570
	/**
571
	 * Return default URL
572
	 *
573
	 * @return string Default URL
574
	 */
575
	function getDefaultUrl()
576
	{
577
		$db_info = self::getDBInfo();
578
		return $db_info->default_url;
579
	}
580
581
	/**
582
	 * Find supported languages
583
	 *
584
	 * @return array Supported languages
585
	 */
586
	function loadLangSupported()
587
	{
588
		static $lang_supported = null;
589 View Code Duplication
		if(!$lang_supported)
590
		{
591
			$langs = file(_XE_PATH_ . 'common/lang/lang.info');
592
			foreach($langs as $val)
593
			{
594
				list($lang_prefix, $lang_text) = explode(',', $val);
595
				$lang_text = trim($lang_text);
596
				$lang_supported[$lang_prefix] = $lang_text;
597
			}
598
		}
599
		return $lang_supported;
600
	}
601
602
	/**
603
	 * Find selected languages to serve in the site
604
	 *
605
	 * @return array Selected languages
606
	 */
607
	function loadLangSelected()
608
	{
609
		static $lang_selected = null;
610
		if(!$lang_selected)
611
		{
612
			$orig_lang_file = _XE_PATH_ . 'common/lang/lang.info';
613
			$selected_lang_file = _XE_PATH_ . 'files/config/lang_selected.info';
614
			if(!FileHandler::hasContent($selected_lang_file))
615
			{
616
				$old_selected_lang_file = _XE_PATH_ . 'files/cache/lang_selected.info';
617
				FileHandler::moveFile($old_selected_lang_file, $selected_lang_file);
618
			}
619
620
			if(!FileHandler::hasContent($selected_lang_file))
621
			{
622
				$buff = FileHandler::readFile($orig_lang_file);
623
				FileHandler::writeFile($selected_lang_file, $buff);
624
				$lang_selected = self::loadLangSupported();
625
			}
626 View Code Duplication
			else
627
			{
628
				$langs = file($selected_lang_file);
629
				foreach($langs as $val)
630
				{
631
					list($lang_prefix, $lang_text) = explode(',', $val);
632
					$lang_text = trim($lang_text);
633
					$lang_selected[$lang_prefix] = $lang_text;
634
				}
635
			}
636
		}
637
		return $lang_selected;
638
	}
639
640
	/**
641
	 * Single Sign On (SSO)
642
	 *
643
	 * @return bool True : Module handling is necessary in the control path of current request , False : Otherwise
644
	 */
645
	function checkSSO()
646
	{
647
		// pass if it's not GET request or XE is not yet installed
648
		if($this->db_info->use_sso != 'Y' || isCrawler())
649
		{
650
			return TRUE;
651
		}
652
		$checkActList = array('rss' => 1, 'atom' => 1);
653
		if(self::getRequestMethod() != 'GET' || !self::isInstalled() || isset($checkActList[self::get('act')]))
654
		{
655
			return TRUE;
656
		}
657
658
		// pass if default URL is not set
659
		$default_url = trim($this->db_info->default_url);
660
		if(!$default_url)
661
		{
662
			return TRUE;
663
		}
664
665
		if(substr_compare($default_url, '/', -1) !== 0)
666
		{
667
			$default_url .= '/';
668
		}
669
670
		// for sites recieving SSO valdiation
671
		if($default_url == self::getRequestUri())
672
		{
673
			if(self::get('url'))
674
			{
675
				$url = base64_decode(self::get('url'));
676
				$url_info = parse_url($url);
677 View Code Duplication
				if(!Password::checkSignature($url, self::get('sig')))
678
				{
679
					echo self::get('lang')->msg_invalid_request;
680
					return false;
681
				}
682
683
				$url_info['query'].= ($url_info['query'] ? '&' : '') . 'SSOID=' . urlencode(session_id()) . '&sig=' . urlencode(Password::createSignature(session_id()));
684
				$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']);
685
				header('location:' . $redirect_url);
686
687
				return FALSE;
688
			}
689
			// for sites requesting SSO validation
690
		}
691
		else
692
		{
693
			// result handling : set session_name()
694
			if($session_name = self::get('SSOID'))
695
			{
696 View Code Duplication
				if(!Password::checkSignature($session_name, self::get('sig')))
697
				{
698
					echo self::get('lang')->msg_invalid_request;
699
					return false;
700
				}
701
				
702
				setcookie(session_name(), $session_name);
703
704
				$url = preg_replace('/[\?\&]SSOID=.+$/', '', self::getRequestUrl());
705
				header('location:' . $url);
706
				return FALSE;
707
				// send SSO request
708
			}
709
			else if(!self::get('SSOID') && $_COOKIE['sso'] != md5(self::getRequestUri()))
710
			{
711
				setcookie('sso', md5(self::getRequestUri()), 0, '/');
712
				$origin_url = self::getRequestUrl();
713
				$origin_sig = Password::createSignature($origin_url);
714
				$url = sprintf("%s?url=%s&sig=%s", $default_url, urlencode(base64_encode($origin_url)), urlencode($origin_sig));
715
				header('location:' . $url);
716
				return FALSE;
717
			}
718
		}
719
720
		return TRUE;
721
	}
722
723
	/**
724
	 * Check if FTP info is registered
725
	 *
726
	 * @return bool True: FTP information is registered, False: otherwise
727
	 */
728
	function isFTPRegisted()
729
	{
730
		return file_exists(self::getFTPConfigFile());
731
	}
732
733
	/**
734
	 * Get FTP information
735
	 *
736
	 * @return object FTP information
737
	 */
738
	function getFTPInfo()
739
	{
740
		$self = self::getInstance();
741
742
		if(!$self->isFTPRegisted())
743
		{
744
			return null;
745
		}
746
747
		include($self->getFTPConfigFile());
748
749
		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...
750
	}
751
752
	/**
753
	 * Add string to browser title
754
	 *
755
	 * @param string $site_title Browser title to be added
756
	 * @return void
757
	 */
758
	function addBrowserTitle($site_title)
759
	{
760
		if(!$site_title)
761
		{
762
			return;
763
		}
764
		$self = self::getInstance();
765
766
		if($self->site_title)
767
		{
768
			$self->site_title .= ' - ' . $site_title;
769
		}
770
		else
771
		{
772
			$self->site_title = $site_title;
773
		}
774
	}
775
776
	/**
777
	 * Set string to browser title
778
	 *
779
	 * @param string $site_title Browser title  to be set
780
	 * @return void
781
	 */
782
	function setBrowserTitle($site_title)
783
	{
784
		if(!$site_title)
785
		{
786
			return;
787
		}
788
		$self = self::getInstance();
789
		$self->site_title = $site_title;
790
	}
791
792
	/**
793
	 * Get browser title
794
	 *
795
	 * @return string Browser title(htmlspecialchars applied)
796
	 */
797
	function getBrowserTitle()
798
	{
799
		$self = self::getInstance();
800
801
		$oModuleController = getController('module');
802
		$oModuleController->replaceDefinedLangCode($self->site_title);
803
804
		return htmlspecialchars($self->site_title, ENT_COMPAT | ENT_HTML401, 'UTF-8', FALSE);
805
	}
806
807
	/**
808
	 * Return layout's title
809
	 * @return string layout's title
810
	 */
811
	public function getSiteTitle()
812
	{
813
		$oModuleModel = getModel('module');
814
		$moduleConfig = $oModuleModel->getModuleConfig('module');
815
816
		if(isset($moduleConfig->siteTitle))
817
		{
818
			return $moduleConfig->siteTitle;
819
		}
820
		return '';
821
	}
822
823
	/**
824
	 * Get browser title
825
	 * @deprecated
826
	 */
827
	function _getBrowserTitle()
828
	{
829
		return $this->getBrowserTitle();
830
	}
831
832
	/**
833
	 * Load language file according to language type
834
	 *
835
	 * @param string $path Path of the language file
836
	 * @return void
837
	 */
838
	function loadLang($path)
839
	{
840
		global $lang;
841
842
		$self = self::getInstance();
843
		if(!$self->lang_type)
844
		{
845
			return;
846
		}
847
		if(!is_object($lang))
848
		{
849
			$lang = new stdClass;
850
		}
851
852
		if(!($filename = $self->_loadXmlLang($path)))
853
		{
854
			$filename = $self->_loadPhpLang($path);
855
		}
856
857
		if(!is_array($self->loaded_lang_files))
858
		{
859
			$self->loaded_lang_files = array();
860
		}
861
		if(in_array($filename, $self->loaded_lang_files))
862
		{
863
			return;
864
		}
865
866
		if($filename && is_readable($filename))
867
		{
868
			$self->loaded_lang_files[] = $filename;
869
			include($filename);
870
		}
871
		else
872
		{
873
			$self->_evalxmlLang($path);
874
		}
875
	}
876
877
	/**
878
	 * Evaluation of xml language file
879
	 *
880
	 * @param string Path of the language file
881
	 * @return void
882
	 */
883
	function _evalxmlLang($path)
884
	{
885
		global $lang;
886
887
		if(!$path) return;
888
889
		$_path = 'eval://' . $path;
890
891
		if(in_array($_path, $this->loaded_lang_files))
892
		{
893
			return;
894
		}
895
896
		if(substr_compare($path, '/', -1) !== 0)
897
		{
898
			$path .= '/';
899
		}
900
901
		$oXmlLangParser = new XmlLangParser($path . 'lang.xml', $this->lang_type);
902
		$content = $oXmlLangParser->getCompileContent();
903
904
		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...
905
		{
906
			$this->loaded_lang_files[] = $_path;
907
			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...
908
		}
909
	}
910
911
	/**
912
	 * Load language file of xml type
913
	 *
914
	 * @param string $path Path of the language file
915
	 * @return string file name
916
	 */
917
	function _loadXmlLang($path)
918
	{
919
		if(!$path) return;
920
921
		$oXmlLangParser = new XmlLangParser($path . ((substr_compare($path, '/', -1) !== 0) ? '/' : '') . 'lang.xml', $this->lang_type);
922
		return $oXmlLangParser->compile();
923
	}
924
925
	/**
926
	 * Load language file of php type
927
	 *
928
	 * @param string $path Path of the language file
929
	 * @return string file name
930
	 */
931
	function _loadPhpLang($path)
932
	{
933
		if(!$path) return;
934
935
		if(substr_compare($path, '/', -1) !== 0)
936
		{
937
			$path .= '/';
938
		}
939
		$path_tpl = $path . '%s.lang.php';
940
		$file = sprintf($path_tpl, $this->lang_type);
941
942
		$langs = array('ko', 'en'); // this will be configurable.
943
		while(!is_readable($file) && $langs[0])
944
		{
945
			$file = sprintf($path_tpl, array_shift($langs));
946
		}
947
948
		if(!is_readable($file))
949
		{
950
			return FALSE;
951
		}
952
		return $file;
953
	}
954
955
	/**
956
	 * Set lang_type
957
	 *
958
	 * @param string $lang_type Language type.
959
	 * @return void
960
	 */
961
	function setLangType($lang_type = 'ko')
962
	{
963
		$self = self::getInstance();
964
965
		$self->lang_type = $lang_type;
966
		$self->set('lang_type', $lang_type);
967
968
		$_SESSION['lang_type'] = $lang_type;
969
	}
970
971
	/**
972
	 * Get lang_type
973
	 *
974
	 * @return string Language type
975
	 */
976
	function getLangType()
977
	{
978
		$self = self::getInstance();
979
		return $self->lang_type;
980
	}
981
982
	/**
983
	 * Return string accoring to the inputed code
984
	 *
985
	 * @param string $code Language variable name
986
	 * @return string If string for the code exists returns it, otherwise returns original code
987
	 */
988
	function getLang($code)
989
	{
990
		if(!$code)
991
		{
992
			return;
993
		}
994
		if($GLOBALS['lang']->{$code})
995
		{
996
			return $GLOBALS['lang']->{$code};
997
		}
998
		return $code;
999
	}
1000
1001
	/**
1002
	 * Set data to lang variable
1003
	 *
1004
	 * @param string $code Language variable name
1005
	 * @param string $val `$code`s value
1006
	 * @return void
1007
	 */
1008
	function setLang($code, $val)
1009
	{
1010
		if(!isset($GLOBALS['lang']))
1011
		{
1012
			$GLOBALS['lang'] = new stdClass();
1013
		}
1014
		$GLOBALS['lang']->{$code} = $val;
1015
	}
1016
1017
	/**
1018
	 * Convert strings of variables in $source_object into UTF-8
1019
	 *
1020
	 * @param object $source_obj Conatins strings to convert
1021
	 * @return object converted object
1022
	 */
1023
	function convertEncoding($source_obj)
1024
	{
1025
		$charset_list = array(
1026
			'UTF-8', 'EUC-KR', 'CP949', 'ISO8859-1', 'EUC-JP', 'SHIFT_JIS', 'CP932',
1027
			'EUC-CN', 'HZ', 'GBK', 'GB18030', 'EUC-TW', 'BIG5', 'CP950', 'BIG5-HKSCS',
1028
			'ISO2022-CN', 'ISO2022-CN-EXT', 'ISO2022-JP', 'ISO2022-JP-2', 'ISO2022-JP-1',
1029
			'ISO8859-6', 'ISO8859-8', 'JOHAB', 'ISO2022-KR', 'CP1255', 'CP1256', 'CP862',
1030
			'ASCII', 'ISO8859-1', 'ISO8850-2', 'ISO8850-3', 'ISO8850-4', 'ISO8850-5',
1031
			'ISO8850-7', 'ISO8850-9', 'ISO8850-10', 'ISO8850-13', 'ISO8850-14',
1032
			'ISO8850-15', 'ISO8850-16', 'CP1250', 'CP1251', 'CP1252', 'CP1253', 'CP1254',
1033
			'CP1257', 'CP850', 'CP866',
1034
		);
1035
1036
		$obj = clone $source_obj;
1037
1038
		foreach($charset_list as $charset)
1039
		{
1040
			array_walk($obj,'Context::checkConvertFlag',$charset);
1041
			$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...
1042
			if($flag)
1043
			{
1044
				if($charset == 'UTF-8')
1045
				{
1046
					return $obj;
1047
				}
1048
				array_walk($obj,'Context::doConvertEncoding',$charset);
1049
				return $obj;
1050
			}
1051
		}
1052
		return $obj;
1053
	}
1054
1055
	/**
1056
	 * Check flag
1057
	 *
1058
	 * @param mixed $val
1059
	 * @param string $key
1060
	 * @param mixed $charset charset
1061
	 * @see arrayConvWalkCallback will replaced array_walk_recursive in >=PHP5
1062
	 * @return void
1063
	 */
1064
	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...
1065
	{
1066
		static $flag = TRUE;
1067
		if($charset)
1068
		{
1069
			if(is_array($val))
1070
				array_walk($val,'Context::checkConvertFlag',$charset);
1071
			else if($val && iconv($charset,$charset,$val)!=$val) $flag = FALSE;
1072
			else $flag = FALSE;
1073
		}
1074
		else
1075
		{
1076
			$return = $flag;
1077
			$flag = TRUE;
1078
			return $return;
1079
		}
1080
	}
1081
1082
	/**
1083
	 * Convert array type variables into UTF-8
1084
	 *
1085
	 * @param mixed $val
1086
	 * @param string $key
1087
	 * @param string $charset character set
1088
	 * @see arrayConvWalkCallback will replaced array_walk_recursive in >=PHP5
1089
	 * @return object converted object
1090
	 */
1091
	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...
1092
	{
1093
		if (is_array($val))
1094
		{
1095
			array_walk($val,'Context::doConvertEncoding',$charset);
1096
		}
1097
		else $val = iconv($charset,'UTF-8',$val);
1098
	}
1099
1100
	/**
1101
	 * Convert strings into UTF-8
1102
	 *
1103
	 * @param string $str String to convert
1104
	 * @return string converted string
1105
	 */
1106
	function convertEncodingStr($str)
1107
	{
1108
        if(!$str) return null;
1109
		$obj = new stdClass();
1110
		$obj->str = $str;
1111
		$obj = self::convertEncoding($obj);
1112
		return $obj->str;
1113
	}
1114
1115
	function decodeIdna($domain)
1116
	{
1117
		if(strpos($domain, 'xn--') !== FALSE)
1118
		{
1119
			require_once(_XE_PATH_ . 'libs/idna_convert/idna_convert.class.php');
1120
			$IDN = new idna_convert(array('idn_version' => 2008));
1121
			$domain = $IDN->decode($domain);
1122
		}
1123
1124
		return $domain;
1125
	}
1126
1127
	/**
1128
	 * Force to set response method
1129
	 *
1130
	 * @param string $method Response method. [HTML|XMLRPC|JSON]
1131
	 * @return void
1132
	 */
1133
	function setResponseMethod($method = 'HTML')
1134
	{
1135
		$self = self::getInstance();
1136
1137
		$methods = array('HTML' => 1, 'XMLRPC' => 1, 'JSON' => 1, 'JS_CALLBACK' => 1);
1138
		$self->response_method = isset($methods[$method]) ? $method : 'HTML';
1139
	}
1140
1141
	/**
1142
	 * Get reponse method
1143
	 *
1144
	 * @return string Response method. If it's not set, returns request method.
1145
	 */
1146
	function getResponseMethod()
1147
	{
1148
		$self = self::getInstance();
1149
1150
		if($self->response_method)
1151
		{
1152
			return $self->response_method;
1153
		}
1154
1155
		$method = $self->getRequestMethod();
1156
		$methods = array('HTML' => 1, 'XMLRPC' => 1, 'JSON' => 1, 'JS_CALLBACK' => 1);
1157
1158
		return isset($methods[$method]) ? $method : 'HTML';
1159
	}
1160
1161
	/**
1162
	 * Determine request method
1163
	 *
1164
	 * @param string $type Request method. (Optional - GET|POST|XMLRPC|JSON)
1165
	 * @return void
1166
	 */
1167
	function setRequestMethod($type = '')
1168
	{
1169
		$self = self::getInstance();
1170
1171
		$self->js_callback_func = $self->getJSCallbackFunc();
1172
1173
		($type && $self->request_method = $type) or
1174
				((strpos($_SERVER['CONTENT_TYPE'], 'json') || strpos($_SERVER['HTTP_CONTENT_TYPE'], 'json')) && $self->request_method = 'JSON') or
1175
				($GLOBALS['HTTP_RAW_POST_DATA'] && $self->request_method = 'XMLRPC') or
1176
				($self->js_callback_func && $self->request_method = 'JS_CALLBACK') or
1177
				($self->request_method = $_SERVER['REQUEST_METHOD']);
1178
	}
1179
1180
	/**
1181
	 * handle global arguments
1182
	 *
1183
	 * @return void
1184
	 */
1185
	function _checkGlobalVars()
1186
	{
1187
		$this->_recursiveCheckVar($_SERVER['HTTP_HOST']);
1188
1189
		$pattern = "/[\,\"\'\{\}\[\]\(\);$]/";
1190
		if(preg_match($pattern, $_SERVER['HTTP_HOST']))
1191
		{
1192
			$this->isSuccessInit = FALSE;
1193
		}
1194
	}
1195
1196
	/**
1197
	 * handle request arguments for GET/POST
1198
	 *
1199
	 * @return void
1200
	 */
1201
	function _setRequestArgument()
1202
	{
1203
		if(!count($_REQUEST))
1204
		{
1205
			return;
1206
		}
1207
1208
		$requestMethod = $this->getRequestMethod();
1209
		foreach($_REQUEST as $key => $val)
1210
		{
1211
			if($val === '' || self::get($key))
1212
			{
1213
				continue;
1214
			}
1215
			$key = htmlentities($key);
1216
			$val = $this->_filterRequestVar($key, $val);
1217
1218
			if($requestMethod == 'GET' && isset($_GET[$key]))
1219
			{
1220
				$set_to_vars = TRUE;
1221
			}
1222
			elseif($requestMethod == 'POST' && isset($_POST[$key]))
1223
			{
1224
				$set_to_vars = TRUE;
1225
			}
1226
			elseif($requestMethod == 'JS_CALLBACK' && (isset($_GET[$key]) || isset($_POST[$key])))
1227
			{
1228
				$set_to_vars = TRUE;
1229
			}
1230
			else
1231
			{
1232
				$set_to_vars = FALSE;
1233
			}
1234
1235
			if($set_to_vars)
1236
			{
1237
				$this->_recursiveCheckVar($val);
1238
			}
1239
1240
			$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...
1241
		}
1242
	}
1243
1244
	function _recursiveCheckVar($val)
1245
	{
1246
		if(is_string($val))
1247
		{
1248
			foreach($this->patterns as $pattern)
1249
			{
1250
				if(preg_match($pattern, $val))
1251
				{
1252
					$this->isSuccessInit = FALSE;
1253
					return;
1254
				}
1255
			}
1256
		}
1257
		else if(is_array($val))
1258
		{
1259
			foreach($val as $val2)
1260
			{
1261
				$this->_recursiveCheckVar($val2);
1262
			}
1263
		}
1264
	}
1265
1266
	/**
1267
	 * Handle request arguments for JSON
1268
	 *
1269
	 * @return void
1270
	 */
1271
	function _setJSONRequestArgument()
1272
	{
1273
		if($this->getRequestMethod() != 'JSON')
1274
		{
1275
			return;
1276
		}
1277
1278
		$params = array();
1279
		parse_str($GLOBALS['HTTP_RAW_POST_DATA'], $params);
1280
1281
		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...
1282
		{
1283
			$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...
1284
		}
1285
	}
1286
1287
	/**
1288
	 * Handle request arguments for XML RPC
1289
	 *
1290
	 * @return void
1291
	 */
1292
	function _setXmlRpcArgument()
1293
	{
1294
		if($this->getRequestMethod() != 'XMLRPC')
1295
		{
1296
			return;
1297
		}
1298
1299
		$xml = $GLOBALS['HTTP_RAW_POST_DATA'];
1300
		if(Security::detectingXEE($xml))
1301
		{
1302
			header("HTTP/1.0 400 Bad Request");
1303
			exit;
1304
		}
1305
1306
		$oXml = new XmlParser();
1307
		$xml_obj = $oXml->parse($xml);
1308
1309
		$params = $xml_obj->methodcall->params;
1310
		unset($params->node_name, $params->attrs, $params->body);
1311
1312
		if(!count(get_object_vars($params)))
1313
		{
1314
			return;
1315
		}
1316
1317
		foreach($params as $key => $val)
1318
		{
1319
			$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...
1320
		}
1321
	}
1322
1323
	/**
1324
	 * Filter xml variables
1325
	 *
1326
	 * @param string $key Variable key
1327
	 * @param object $val Variable value
1328
	 * @return mixed filtered value
1329
	 */
1330
	function _filterXmlVars($key, $val)
1331
	{
1332
		if(is_array($val))
1333
		{
1334
			$stack = array();
1335
			foreach($val as $k => $v)
1336
			{
1337
				$stack[$k] = $this->_filterXmlVars($k, $v);
1338
			}
1339
1340
			return $stack;
1341
		}
1342
1343
		$body = $val->body;
1344
		unset($val->node_name, $val->attrs, $val->body);
1345
		if(!count(get_object_vars($val)))
1346
		{
1347
			return $this->_filterRequestVar($key, $body, 0);
1348
		}
1349
1350
		$stack = new stdClass();
1351
		foreach($val as $k => $v)
1352
		{
1353
			$output = $this->_filterXmlVars($k, $v);
1354
			if(is_object($v) && $v->attrs->type == 'array')
1355
			{
1356
				$output = array($output);
1357
			}
1358
			if($k == 'value' && (is_array($v) || $v->attrs->type == 'array'))
1359
			{
1360
				return $output;
1361
			}
1362
1363
			$stack->{$k} = $output;
1364
		}
1365
1366
		if(!count(get_object_vars($stack)))
1367
		{
1368
			return NULL;
1369
		}
1370
1371
		return $stack;
1372
	}
1373
1374
	/**
1375
	 * Filter request variable
1376
	 *
1377
	 * @see Cast variables, such as _srl, page, and cpage, into interger
1378
	 * @param string $key Variable key
1379
	 * @param string $val Variable value
1380
	 * @param string $do_stripslashes Whether to strip slashes
1381
	 * @return mixed filtered value. Type are string or array
1382
	 */
1383
	function _filterRequestVar($key, $val, $do_stripslashes = 1)
1384
	{
1385
		if(!($isArray = is_array($val)))
1386
		{
1387
			$val = array($val);
1388
		}
1389
1390
		$result = array();
1391
		foreach($val as $k => $v)
1392
		{
1393
			$k = htmlentities($k);
1394
			if($key === 'page' || $key === 'cpage' || substr_compare($key, 'srl', -3) === 0)
1395
			{
1396
				$result[$k] = !preg_match('/^[0-9,]+$/', $v) ? (int) $v : $v;
1397
			}
1398
			elseif($key === 'mid' || $key === 'search_keyword')
1399
			{
1400
				$result[$k] = htmlspecialchars($v, ENT_COMPAT | ENT_HTML401, 'UTF-8', FALSE);
1401
			}
1402
			elseif($key === 'vid')
1403
			{
1404
				$result[$k] = urlencode($v);
1405
			}
1406
			else
1407
			{
1408
				$result[$k] = $v;
1409
1410
				if($do_stripslashes && version_compare(PHP_VERSION, '5.4.0', '<') && get_magic_quotes_gpc())
1411
				{
1412
					$result[$k] = stripslashes($result[$k]);
1413
				}
1414
1415
				if(!is_array($result[$k]))
1416
				{
1417
					$result[$k] = trim($result[$k]);
1418
				}
1419
			}
1420
		}
1421
1422
		return $isArray ? $result : $result[0];
1423
	}
1424
1425
	/**
1426
	 * Check if there exists uploaded file
1427
	 *
1428
	 * @return bool True: exists, False: otherwise
1429
	 */
1430
	function isUploaded()
1431
	{
1432
		$self = self::getInstance();
1433
		return $self->is_uploaded;
1434
	}
1435
1436
	/**
1437
	 * Handle uploaded file
1438
	 *
1439
	 * @return void
1440
	 */
1441
	function _setUploadedArgument()
1442
	{
1443
		if($_SERVER['REQUEST_METHOD'] != 'POST' || !$_FILES || (stripos($_SERVER['CONTENT_TYPE'], 'multipart/form-data') === FALSE && stripos($_SERVER['HTTP_CONTENT_TYPE'], 'multipart/form-data') === FALSE))
1444
		{
1445
			return;
1446
		}
1447
1448
		foreach($_FILES as $key => $val)
1449
		{
1450
			$tmp_name = $val['tmp_name'];
1451
			if(!is_array($tmp_name))
1452
			{
1453
				if(!$tmp_name || !is_uploaded_file($tmp_name))
1454
				{
1455
					continue;
1456
				}
1457
				$val['name'] = htmlspecialchars($val['name'], ENT_COMPAT | ENT_HTML401, 'UTF-8', FALSE);
1458
				$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...
1459
				$this->is_uploaded = TRUE;
1460
			}
1461
			else
1462
			{
1463
				for($i = 0, $c = count($tmp_name); $i < $c; $i++)
1464
				{
1465
					if($val['size'][$i] > 0)
1466
					{
1467
						$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...
1468
						$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...
1469
						$file['tmp_name'] = $val['tmp_name'][$i];
1470
						$file['error'] = $val['error'][$i];
1471
						$file['size'] = $val['size'][$i];
1472
						$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...
1473
					}
1474
				}
1475
				$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...
1476
			}
1477
		}
1478
	}
1479
1480
	/**
1481
	 * Return request method
1482
	 * @return string Request method type. (Optional - GET|POST|XMLRPC|JSON)
1483
	 */
1484
	function getRequestMethod()
1485
	{
1486
		$self = self::getInstance();
1487
		return $self->request_method;
1488
	}
1489
1490
	/**
1491
	 * Return request URL
1492
	 * @return string request URL
1493
	 */
1494
	function getRequestUrl()
1495
	{
1496
		static $url = null;
1497
		if(is_null($url))
1498
		{
1499
			$url = self::getRequestUri();
1500
			if(count($_GET) > 0)
1501
			{
1502
				foreach($_GET as $key => $val)
1503
				{
1504
					$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...
1505
				}
1506
				$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...
1507
			}
1508
		}
1509
		return $url;
1510
	}
1511
1512
	/**
1513
	 * Return js callback func.
1514
	 * @return string callback func.
1515
	 */
1516
	function getJSCallbackFunc()
1517
	{
1518
		$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...
1519
		$js_callback_func = isset($_GET['xe_js_callback']) ? $_GET['xe_js_callback'] : $_POST['xe_js_callback'];
1520
1521
		if(!preg_match('/^[a-z0-9\.]+$/i', $js_callback_func))
1522
		{
1523
			unset($js_callback_func);
1524
			unset($_GET['xe_js_callback']);
1525
			unset($_POST['xe_js_callback']);
1526
		}
1527
1528
		return $js_callback_func;
1529
	}
1530
1531
	/**
1532
	 * Make URL with args_list upon request URL
1533
	 *
1534
	 * @param int $num_args Arguments nums
1535
	 * @param array $args_list Argument list for set url
1536
	 * @param string $domain Domain
1537
	 * @param bool $encode If TRUE, use url encode.
1538
	 * @param bool $autoEncode If TRUE, url encode automatically, detailed. Use this option, $encode value should be TRUE
1539
	 * @return string URL
1540
	 */
1541
	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...
1542
	{
1543
		static $site_module_info = null;
1544
		static $current_info = null;
1545
1546
		$self = self::getInstance();
1547
1548
		// retrieve virtual site information
1549
		if(is_null($site_module_info))
1550
		{
1551
			$site_module_info = self::get('site_module_info');
1552
		}
1553
1554
		// If $domain is set, handle it (if $domain is vid type, remove $domain and handle with $vid)
1555
		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...
1556
		{
1557
			$vid = $domain;
1558
			$domain = '';
1559
		}
1560
1561
		// If $domain, $vid are not set, use current site information
1562
		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...
1563
		{
1564
			if($site_module_info->domain && isSiteID($site_module_info->domain))
1565
			{
1566
				$vid = $site_module_info->domain;
1567
			}
1568
			else
1569
			{
1570
				$domain = $site_module_info->domain;
1571
			}
1572
		}
1573
1574
		// if $domain is set, compare current URL. If they are same, remove the domain, otherwise link to the domain.
1575
		if($domain)
1576
		{
1577
			$domain_info = parse_url($domain);
1578
			if(is_null($current_info))
1579
			{
1580
				$current_info = parse_url(($_SERVER['HTTPS'] == 'on' ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . getScriptPath());
1581
			}
1582
			if($domain_info['host'] . $domain_info['path'] == $current_info['host'] . $current_info['path'])
1583
			{
1584
				unset($domain);
1585
			}
1586
			else
1587
			{
1588
				$domain = preg_replace('/^(http|https):\/\//i', '', trim($domain));
1589
				if(substr_compare($domain, '/', -1) !== 0)
1590
				{
1591
					$domain .= '/';
1592
				}
1593
			}
1594
		}
1595
1596
		$get_vars = array();
1597
1598
		// If there is no GET variables or first argument is '' to reset variables
1599
		if(!$self->get_vars || $args_list[0] == '')
1600
		{
1601
			// rearrange args_list
1602
			if(is_array($args_list) && $args_list[0] == '')
1603
			{
1604
				array_shift($args_list);
1605
			}
1606
		}
1607
		else
1608
		{
1609
			// Otherwise, make GET variables into array
1610
			$get_vars = get_object_vars($self->get_vars);
1611
		}
1612
1613
		// arrange args_list
1614
		for($i = 0, $c = count($args_list); $i < $c; $i += 2)
1615
		{
1616
			$key = $args_list[$i];
1617
			$val = trim($args_list[$i + 1]);
1618
1619
			// If value is not set, remove the key
1620
			if(!isset($val) || !strlen($val))
1621
			{
1622
				unset($get_vars[$key]);
1623
				continue;
1624
			}
1625
			// set new variables
1626
			$get_vars[$key] = $val;
1627
		}
1628
1629
		// remove vid, rnd
1630
		unset($get_vars['rnd']);
1631
		if($vid)
1632
		{
1633
			$get_vars['vid'] = $vid;
1634
		}
1635
		else
1636
		{
1637
			unset($get_vars['vid']);
1638
		}
1639
1640
		// for compatibility to lower versions
1641
		$act = $get_vars['act'];
1642
		$act_alias = array(
1643
			'dispMemberFriend' => 'dispCommunicationFriend',
1644
			'dispMemberMessages' => 'dispCommunicationMessages',
1645
			'dispDocumentAdminManageDocument' => 'dispDocumentManageDocument',
1646
			'dispModuleAdminSelectList' => 'dispModuleSelectList'
1647
		);
1648
		if($act_alias[$act])
1649
		{
1650
			$get_vars['act'] = $act_alias[$act];
1651
		}
1652
1653
		// organize URL
1654
		$query = '';
1655
		if(count($get_vars) > 0)
1656
		{
1657
			// if using rewrite mod
1658
			if($self->allow_rewrite)
1659
			{
1660
				$var_keys = array_keys($get_vars);
1661
				sort($var_keys);
1662
1663
				$target = join('.', $var_keys);
1664
1665
				$act = $get_vars['act'];
1666
				$vid = $get_vars['vid'];
1667
				$mid = $get_vars['mid'];
1668
				$key = $get_vars['key'];
1669
				$srl = $get_vars['document_srl'];
1670
1671
				$tmpArray = array('rss' => 1, 'atom' => 1, 'api' => 1);
1672
				$is_feed = isset($tmpArray[$act]);
1673
1674
				$target_map = array(
1675
					'vid' => $vid,
1676
					'mid' => $mid,
1677
					'mid.vid' => "$vid/$mid",
1678
					'entry.mid' => "$mid/entry/" . $get_vars['entry'],
1679
					'entry.mid.vid' => "$vid/$mid/entry/" . $get_vars['entry'],
1680
					'document_srl' => $srl,
1681
					'document_srl.mid' => "$mid/$srl",
1682
					'document_srl.vid' => "$vid/$srl",
1683
					'document_srl.mid.vid' => "$vid/$mid/$srl",
1684
					'act' => ($is_feed && $act !== 'api') ? $act : '',
1685
					'act.mid' => $is_feed ? "$mid/$act" : '',
1686
					'act.mid.vid' => $is_feed ? "$vid/$mid/$act" : '',
1687
					'act.document_srl.key' => ($act == 'trackback') ? "$srl/$key/$act" : '',
1688
					'act.document_srl.key.mid' => ($act == 'trackback') ? "$mid/$srl/$key/$act" : '',
1689
					'act.document_srl.key.vid' => ($act == 'trackback') ? "$vid/$srl/$key/$act" : '',
1690
					'act.document_srl.key.mid.vid' => ($act == 'trackback') ? "$vid/$mid/$srl/$key/$act" : ''
1691
				);
1692
1693
				$query = $target_map[$target];
1694
			}
1695
1696
			if(!$query)
1697
			{
1698
				$queries = array();
1699 View Code Duplication
				foreach($get_vars as $key => $val)
1700
				{
1701
					if(is_array($val) && count($val) > 0)
1702
					{
1703
						foreach($val as $k => $v)
1704
						{
1705
							$queries[] = $key . '[' . $k . ']=' . urlencode($v);
1706
						}
1707
					}
1708
					elseif(!is_array($val))
1709
					{
1710
						$queries[] = $key . '=' . urlencode($val);
1711
					}
1712
				}
1713
				if(count($queries) > 0)
1714
				{
1715
					$query = 'index.php?' . join('&', $queries);
1716
				}
1717
			}
1718
		}
1719
1720
		// If using SSL always
1721
		$_use_ssl = $self->get('_use_ssl');
1722
		if($_use_ssl == 'always')
1723
		{
1724
			$query = $self->getRequestUri(ENFORCE_SSL, $domain) . $query;
1725
			// optional SSL use
1726
		}
1727
		elseif($_use_ssl == 'optional')
1728
		{
1729
			$ssl_mode = (($self->get('module') === 'admin') || ($get_vars['module'] === 'admin') || (isset($get_vars['act']) && $self->isExistsSSLAction($get_vars['act']))) ? ENFORCE_SSL : RELEASE_SSL;
1730
			$query = $self->getRequestUri($ssl_mode, $domain) . $query;
1731
			// no SSL
1732
		}
1733
		else
1734
		{
1735
			// currently on SSL but target is not based on SSL
1736
			if($_SERVER['HTTPS'] == 'on')
1737
			{
1738
				$query = $self->getRequestUri(ENFORCE_SSL, $domain) . $query;
1739
			}
1740
			else if($domain) // if $domain is set
1741
			{
1742
				$query = $self->getRequestUri(FOLLOW_REQUEST_SSL, $domain) . $query;
1743
			}
1744
			else
1745
			{
1746
				$query = getScriptPath() . $query;
1747
			}
1748
		}
1749
1750
		if(!$encode)
1751
		{
1752
			return $query;
1753
		}
1754
1755
		if(!$autoEncode)
1756
		{
1757
			return htmlspecialchars($query, ENT_COMPAT | ENT_HTML401, 'UTF-8', FALSE);
1758
		}
1759
1760
		$output = array();
1761
		$encode_queries = array();
1762
		$parsedUrl = parse_url($query);
1763
		parse_str($parsedUrl['query'], $output);
1764
		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...
1765
		{
1766
			if(preg_match('/&([a-z]{2,}|#\d+);/', urldecode($value)))
1767
			{
1768
				$value = urlencode(htmlspecialchars_decode(urldecode($value)));
1769
			}
1770
			$encode_queries[] = $key . '=' . $value;
1771
		}
1772
1773
		return htmlspecialchars($parsedUrl['path'] . '?' . join('&', $encode_queries), ENT_COMPAT | ENT_HTML401, 'UTF-8', FALSE);
1774
	}
1775
1776
	/**
1777
	 * Return after removing an argument on the requested URL
1778
	 *
1779
	 * @param string $ssl_mode SSL mode
1780
	 * @param string $domain Domain
1781
	 * @retrun string converted URL
1782
	 */
1783
	function getRequestUri($ssl_mode = FOLLOW_REQUEST_SSL, $domain = null)
1784
	{
1785
		static $url = array();
1786
1787
		// Check HTTP Request
1788
		if(!isset($_SERVER['SERVER_PROTOCOL']))
1789
		{
1790
			return;
1791
		}
1792
1793
		if(self::get('_use_ssl') == 'always')
1794
		{
1795
			$ssl_mode = ENFORCE_SSL;
1796
		}
1797
1798
		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...
1799
		{
1800
			$domain_key = md5($domain);
1801
		}
1802
		else
1803
		{
1804
			$domain_key = 'default';
1805
		}
1806
1807
		if(isset($url[$ssl_mode][$domain_key]))
1808
		{
1809
			return $url[$ssl_mode][$domain_key];
1810
		}
1811
1812
		$current_use_ssl = ($_SERVER['HTTPS'] == 'on');
1813
1814
		switch($ssl_mode)
1815
		{
1816
			case FOLLOW_REQUEST_SSL: $use_ssl = $current_use_ssl;
1817
				break;
1818
			case ENFORCE_SSL: $use_ssl = TRUE;
1819
				break;
1820
			case RELEASE_SSL: $use_ssl = FALSE;
1821
				break;
1822
		}
1823
1824
		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...
1825
		{
1826
			$target_url = trim($domain);
1827
			if(substr_compare($target_url, '/', -1) !== 0)
1828
			{
1829
				$target_url.= '/';
1830
			}
1831
		}
1832
		else
1833
		{
1834
			$target_url = $_SERVER['HTTP_HOST'] . getScriptPath();
1835
		}
1836
1837
		$url_info = parse_url('http://' . $target_url);
1838
1839
		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...
1840
		{
1841
			unset($url_info['port']);
1842
		}
1843
1844
		if($use_ssl)
1845
		{
1846
			$port = self::get('_https_port');
1847 View Code Duplication
			if($port && $port != 443)
1848
			{
1849
				$url_info['port'] = $port;
1850
			}
1851
			elseif($url_info['port'] == 443)
1852
			{
1853
				unset($url_info['port']);
1854
			}
1855
		}
1856 View Code Duplication
		else
1857
		{
1858
			$port = self::get('_http_port');
1859
			if($port && $port != 80)
1860
			{
1861
				$url_info['port'] = $port;
1862
			}
1863
			elseif($url_info['port'] == 80)
1864
			{
1865
				unset($url_info['port']);
1866
			}
1867
		}
1868
1869
		$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']);
1870
1871
		return $url[$ssl_mode][$domain_key];
1872
	}
1873
1874
	/**
1875
	 * Set a context value with a key
1876
	 *
1877
	 * @param string $key Key
1878
	 * @param string $val Value
1879
	 * @param mixed $set_to_get_vars If not FALSE, Set to get vars.
1880
	 * @return void
1881
	 */
1882
	function set($key, $val, $set_to_get_vars = 0)
1883
	{
1884
		$self = self::getInstance();
1885
		$self->context->{$key} = $val;
1886
		if($set_to_get_vars === FALSE)
1887
		{
1888
			return;
1889
		}
1890
		if($val === NULL || $val === '')
1891
		{
1892
			unset($self->get_vars->{$key});
1893
			return;
1894
		}
1895
		if($set_to_get_vars || $self->get_vars->{$key})
1896
		{
1897
			$self->get_vars->{$key} = $val;
1898
		}
1899
	}
1900
1901
	/**
1902
	 * Return key's value
1903
	 *
1904
	 * @param string $key Key
1905
	 * @return string Key
1906
	 */
1907
	function get($key)
1908
	{
1909
		$self = self::getInstance();
1910
1911
		if(!isset($self->context->{$key}))
1912
		{
1913
			return null;
1914
		}
1915
		return $self->context->{$key};
1916
	}
1917
1918
	/**
1919
	 * Get one more vars in object vars with given arguments(key1, key2, key3,...)
1920
	 *
1921
	 * @return object
1922
	 */
1923
	function gets()
1924
	{
1925
		$num_args = func_num_args();
1926
		if($num_args < 1)
1927
		{
1928
			return;
1929
		}
1930
		$self = self::getInstance();
1931
1932
		$args_list = func_get_args();
1933
		$output = new stdClass();
1934
		foreach($args_list as $v)
1935
		{
1936
			$output->{$v} = $self->get($v);
1937
		}
1938
		return $output;
1939
	}
1940
1941
	/**
1942
	 * Return all data
1943
	 *
1944
	 * @return object All data
1945
	 */
1946
	function getAll()
1947
	{
1948
		$self = self::getInstance();
1949
		return $self->context;
1950
	}
1951
1952
	/**
1953
	 * Return values from the GET/POST/XMLRPC
1954
	 *
1955
	 * @return Object Request variables.
1956
	 */
1957
	function getRequestVars()
1958
	{
1959
		$self = self::getInstance();
1960
		if($self->get_vars)
1961
		{
1962
			return clone($self->get_vars);
1963
		}
1964
		return new stdClass;
1965
	}
1966
1967
	/**
1968
	 * Register if an action is to be encrypted by SSL. Those actions are sent to https in common/js/xml_handler.js
1969
	 *
1970
	 * @param string $action act name
1971
	 * @return void
1972
	 */
1973
	function addSSLAction($action)
1974
	{
1975
		$self = self::getInstance();
1976
1977
		if(!is_readable($self->sslActionCacheFile))
1978
		{
1979
			$buff = '<?php if(!defined("__XE__"))exit;';
1980
			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...
1981
		}
1982
1983 View Code Duplication
		if(!isset($self->ssl_actions[$action]))
1984
		{
1985
			$self->ssl_actions[$action] = 1;
1986
			$sslActionCacheString = sprintf('$sslActions[\'%s\'] = 1;', $action);
1987
			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...
1988
		}
1989
	}
1990
1991
	/**
1992
	 * Register if actions are to be encrypted by SSL. Those actions are sent to https in common/js/xml_handler.js
1993
	 *
1994
	 * @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...
1995
	 * @return void
1996
	 */
1997
	function addSSLActions($action_array)
1998
	{
1999
		$self = self::getInstance();
2000
2001
		if(!is_readable($self->sslActionCacheFile))
2002
		{
2003
			unset($self->ssl_actions);
2004
			$buff = '<?php if(!defined("__XE__"))exit;';
2005
			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...
2006
		}
2007
2008
		foreach($action_array as $action)
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
	/**
2020
	 * Delete if action is registerd to be encrypted by SSL.
2021
	 *
2022
	 * @param string $action act name
2023
	 * @return void
2024
	 */
2025
	function subtractSSLAction($action)
2026
	{
2027
		$self = self::getInstance();
2028
2029
		if($self->isExistsSSLAction($action))
2030
		{
2031
			$sslActionCacheString = sprintf('$sslActions[\'%s\'] = 1;', $action);
2032
			$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...
2033
			$buff = str_replace($sslActionCacheString, '', $buff);
2034
			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...
2035
		}
2036
	}
2037
2038
	/**
2039
	 * Get SSL Action
2040
	 *
2041
	 * @return string acts in array
2042
	 */
2043
	function getSSLActions()
2044
	{
2045
		$self = self::getInstance();
2046
		if($self->getSslStatus() == 'optional')
2047
		{
2048
			return $self->ssl_actions;
2049
		}
2050
	}
2051
2052
	/**
2053
	 * Check SSL action are existed
2054
	 *
2055
	 * @param string $action act name
2056
	 * @return bool If SSL exists, return TRUE.
2057
	 */
2058
	function isExistsSSLAction($action)
2059
	{
2060
		$self = self::getInstance();
2061
		return isset($self->ssl_actions[$action]);
2062
	}
2063
2064
	/**
2065
	 * Normalize file path
2066
	 *
2067
	 * @deprecated
2068
	 * @param string $file file path
2069
	 * @return string normalized file path
2070
	 */
2071
	function normalizeFilePath($file)
2072
	{
2073
		if($file{0} != '/' && $file{0} != '.' && strpos($file, '://') === FALSE)
2074
		{
2075
			$file = './' . $file;
2076
		}
2077
		$file = preg_replace('@/\./|(?<!:)\/\/@', '/', $file);
2078
		while(strpos($file, '/../') !== FALSE)
2079
		{
2080
			$file = preg_replace('/\/([^\/]+)\/\.\.\//s', '/', $file, 1);
2081
		}
2082
2083
		return $file;
2084
	}
2085
2086
	/**
2087
	 * Get abstract file url
2088
	 *
2089
	 * @deprecated
2090
	 * @param string $file file path
2091
	 * @return string Converted file path
2092
	 */
2093
	function getAbsFileUrl($file)
2094
	{
2095
		$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...
2096
		if(strpos($file, './') === 0)
2097
		{
2098
			$file = dirname($_SERVER['SCRIPT_NAME']) . '/' . substr($file, 2);
2099
		}
2100 View Code Duplication
		elseif(strpos($file, '../') === 0)
2101
		{
2102
			$file = self::normalizeFilePath(dirname($_SERVER['SCRIPT_NAME']) . "/{$file}");
0 ignored issues
show
Deprecated Code introduced by
The method Context::normalizeFilePath() has been deprecated.

This method has been deprecated.

Loading history...
2103
		}
2104
2105
		return $file;
2106
	}
2107
2108
	/**
2109
	 * Load front end file
2110
	 *
2111
	 * @param array $args array
2112
	 * case js :
2113
	 * 		$args[0]: file name,
2114
	 * 		$args[1]: type (head | body),
2115
	 * 		$args[2]: target IE,
2116
	 * 		$args[3]: index
2117
	 * case css :
2118
	 * 		$args[0]: file name,
2119
	 * 		$args[1]: media,
2120
	 * 		$args[2]: target IE,
2121
	 * 		$args[3]: index
2122
	 *
2123
	 */
2124
	function loadFile($args)
2125
	{
2126
		$self = self::getInstance();
2127
2128
		$self->oFrontEndFileHandler->loadFile($args);
2129
	}
2130
2131
	/**
2132
	 * Unload front end file
2133
	 *
2134
	 * @param string $file File name with path
2135
	 * @param string $targetIe Target IE
2136
	 * @param string $media Media query
2137
	 * @return void
2138
	 */
2139
	function unloadFile($file, $targetIe = '', $media = 'all')
2140
	{
2141
		$self = self::getInstance();
2142
		$self->oFrontEndFileHandler->unloadFile($file, $targetIe, $media);
2143
	}
2144
2145
	/**
2146
	 * Unload front end file all
2147
	 *
2148
	 * @param string $type Unload target (optional - all|css|js)
2149
	 * @return void
2150
	 */
2151
	function unloadAllFiles($type = 'all')
2152
	{
2153
		$self = self::getInstance();
2154
		$self->oFrontEndFileHandler->unloadAllFiles($type);
2155
	}
2156
2157
	/**
2158
	 * Add the js file
2159
	 *
2160
	 * @deprecated
2161
	 * @param string $file File name with path
2162
	 * @param string $optimized optimized (That seems to not use)
2163
	 * @param string $targetie target IE
2164
	 * @param string $index index
2165
	 * @param string $type Added position. (head:<head>..</head>, body:<body>..</body>)
2166
	 * @param bool $isRuleset Use ruleset
2167
	 * @param string $autoPath If path not readed, set the path automatically.
2168
	 * @return void
2169
	 */
2170
	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...
2171
	{
2172
		if($isRuleset)
2173
		{
2174
			if(strpos($file, '#') !== FALSE)
2175
			{
2176
				$file = str_replace('#', '', $file);
2177
				if(!is_readable($file))
2178
				{
2179
					$file = $autoPath;
2180
				}
2181
			}
2182
			$validator = new Validator($file);
2183
			$validator->setCacheDir('files/cache');
2184
			$file = $validator->getJsPath();
2185
		}
2186
2187
		$self = self::getInstance();
2188
		$self->oFrontEndFileHandler->loadFile(array($file, $type, $targetie, $index));
2189
	}
2190
2191
	/**
2192
	 * Remove the js file
2193
	 *
2194
	 * @deprecated
2195
	 * @param string $file File name with path
2196
	 * @param string $optimized optimized (That seems to not use)
2197
	 * @param string $targetie target IE
2198
	 * @return void
2199
	 */
2200
	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...
2201
	{
2202
		$self = self::getInstance();
2203
		$self->oFrontEndFileHandler->unloadFile($file, $targetie);
2204
	}
2205
2206
	/**
2207
	 * Unload all javascript files
2208
	 *
2209
	 * @return void
2210
	 */
2211
	function unloadAllJsFiles()
2212
	{
2213
		$self = self::getInstance();
2214
		$self->oFrontEndFileHandler->unloadAllFiles('js');
2215
	}
2216
2217
	/**
2218
	 * Add javascript filter
2219
	 *
2220
	 * @param string $path File path
2221
	 * @param string $filename File name
2222
	 * @return void
2223
	 */
2224
	function addJsFilter($path, $filename)
2225
	{
2226
		$oXmlFilter = new XmlJSFilter($path, $filename);
2227
		$oXmlFilter->compile();
2228
	}
2229
2230
	/**
2231
	 * Same as array_unique but works only for file subscript
2232
	 *
2233
	 * @deprecated
2234
	 * @param array $files File list
2235
	 * @return array File list
2236
	 */
2237
	function _getUniqueFileList($files)
2238
	{
2239
		ksort($files);
2240
		$files = array_values($files);
2241
		$filenames = array();
2242
		for($i = 0, $c = count($files); $i < $c; ++$i)
2243
		{
2244
			if(in_array($files[$i]['file'], $filenames))
2245
			{
2246
				unset($files[$i]);
2247
			}
2248
			$filenames[] = $files[$i]['file'];
2249
		}
2250
2251
		return $files;
2252
	}
2253
2254
	/**
2255
	 * Returns the list of javascripts that matches the given type.
2256
	 *
2257
	 * @param string $type Added position. (head:<head>..</head>, body:<body>..</body>)
2258
	 * @return array Returns javascript file list. Array contains file, targetie.
2259
	 */
2260
	function getJsFile($type = 'head')
2261
	{
2262
		$self = self::getInstance();
2263
		return $self->oFrontEndFileHandler->getJsFileList($type);
2264
	}
2265
2266
	/**
2267
	 * Add CSS file
2268
	 *
2269
	 * @deprecated
2270
	 * @param string $file File name with path
2271
	 * @param string $optimized optimized (That seems to not use)
2272
	 * @param string $media Media query
2273
	 * @param string $targetie target IE
2274
	 * @param string $index index
2275
	 * @return void
2276
	 *
2277
	 */
2278
	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...
2279
	{
2280
		$self = self::getInstance();
2281
		$self->oFrontEndFileHandler->loadFile(array($file, $media, $targetie, $index));
2282
	}
2283
2284
	/**
2285
	 * Remove css file
2286
	 *
2287
	 * @deprecated
2288
	 * @param string $file File name with path
2289
	 * @param string $optimized optimized (That seems to not use)
2290
	 * @param string $media Media query
2291
	 * @param string $targetie target IE
2292
	 * @return void
2293
	 */
2294
	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...
2295
	{
2296
		$self = self::getInstance();
2297
		$self->oFrontEndFileHandler->unloadFile($file, $targetie, $media);
2298
	}
2299
2300
	/**
2301
	 * Unload all css files
2302
	 *
2303
	 * @return void
2304
	 */
2305
	function unloadAllCSSFiles()
2306
	{
2307
		$self = self::getInstance();
2308
		$self->oFrontEndFileHandler->unloadAllFiles('css');
2309
	}
2310
2311
	/**
2312
	 * Return a list of css files
2313
	 *
2314
	 * @return array Returns css file list. Array contains file, media, targetie.
2315
	 */
2316
	function getCSSFile()
2317
	{
2318
		$self = self::getInstance();
2319
		return $self->oFrontEndFileHandler->getCssFileList();
2320
	}
2321
2322
	/**
2323
	 * Returns javascript plugin file info
2324
	 * @param string $pluginName
2325
	 * @return stdClass
2326
	 */
2327
	function getJavascriptPluginInfo($pluginName)
2328
	{
2329
		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...
2330
		{
2331
			$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...
2332
		}
2333
2334
		$plugin_path = './common/js/plugins/' . $pluginName . '/';
2335
		$info_file = $plugin_path . 'plugin.load';
2336
		if(!is_readable($info_file))
2337
		{
2338
			return;
2339
		}
2340
2341
		$list = file($info_file);
2342
		$result = new stdClass();
2343
		$result->jsList = array();
2344
		$result->cssList = array();
2345
2346
		foreach($list as $filename)
2347
		{
2348
			$filename = trim($filename);
2349
			if(!$filename)
2350
			{
2351
				continue;
2352
			}
2353
2354
			if(strncasecmp('./', $filename, 2) === 0)
2355
			{
2356
				$filename = substr($filename, 2);
2357
			}
2358
2359
			if(substr_compare($filename, '.js', -3) === 0)
2360
			{
2361
				$result->jsList[] = $plugin_path . $filename;
2362
			}
2363
			elseif(substr_compare($filename, '.css', -4) === 0)
2364
			{
2365
				$result->cssList[] = $plugin_path . $filename;
2366
			}
2367
		}
2368
2369
		if(is_dir($plugin_path . 'lang'))
2370
		{
2371
			$result->langPath = $plugin_path . 'lang';
2372
		}
2373
2374
		return $result;
2375
	}
2376
	/**
2377
	 * Load javascript plugin
2378
	 *
2379
	 * @param string $plugin_name plugin name
2380
	 * @return void
2381
	 */
2382
	function loadJavascriptPlugin($plugin_name)
2383
	{
2384
		static $loaded_plugins = array();
2385
2386
		$self = self::getInstance();
2387
		if($plugin_name == 'ui.datepicker')
2388
		{
2389
			$plugin_name = 'ui';
2390
		}
2391
2392
		if($loaded_plugins[$plugin_name])
2393
		{
2394
			return;
2395
		}
2396
		$loaded_plugins[$plugin_name] = TRUE;
2397
2398
		$plugin_path = './common/js/plugins/' . $plugin_name . '/';
2399
		$info_file = $plugin_path . 'plugin.load';
2400
		if(!is_readable($info_file))
2401
		{
2402
			return;
2403
		}
2404
2405
		$list = file($info_file);
2406
		foreach($list as $filename)
2407
		{
2408
			$filename = trim($filename);
2409
			if(!$filename)
2410
			{
2411
				continue;
2412
			}
2413
2414
			if(strncasecmp('./', $filename, 2) === 0)
2415
			{
2416
				$filename = substr($filename, 2);
2417
			}
2418 View Code Duplication
			if(substr_compare($filename, '.js', -3) === 0)
2419
			{
2420
				$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...
2421
			}
2422 View Code Duplication
			if(substr_compare($filename, '.css', -4) === 0)
2423
			{
2424
				$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...
2425
			}
2426
		}
2427
2428
		if(is_dir($plugin_path . 'lang'))
2429
		{
2430
			$self->loadLang($plugin_path . 'lang');
2431
		}
2432
	}
2433
2434
	/**
2435
	 * Add html code before </head>
2436
	 *
2437
	 * @param string $header add html code before </head>.
2438
	 * @return void
2439
	 */
2440
	function addHtmlHeader($header)
2441
	{
2442
		$self = self::getInstance();
2443
		$self->html_header .= "\n" . $header;
2444
	}
2445
2446
	function clearHtmlHeader()
2447
	{
2448
		$self = self::getInstance();
2449
		$self->html_header = '';
2450
	}
2451
2452
	/**
2453
	 * Returns added html code by addHtmlHeader()
2454
	 *
2455
	 * @return string Added html code before </head>
2456
	 */
2457
	function getHtmlHeader()
2458
	{
2459
		$self = self::getInstance();
2460
		return $self->html_header;
2461
	}
2462
2463
	/**
2464
	 * Add css class to Html Body
2465
	 *
2466
	 * @param string $class_name class name
2467
	 */
2468
	function addBodyClass($class_name)
2469
	{
2470
		$self = self::getInstance();
2471
		$self->body_class[] = $class_name;
2472
	}
2473
2474
	/**
2475
	 * Return css class to Html Body
2476
	 *
2477
	 * @return string Return class to html body
2478
	 */
2479
	function getBodyClass()
2480
	{
2481
		$self = self::getInstance();
2482
		$self->body_class = array_unique($self->body_class);
2483
2484
		return (count($self->body_class) > 0) ? sprintf(' class="%s"', join(' ', $self->body_class)) : '';
2485
	}
2486
2487
	/**
2488
	 * Add html code after <body>
2489
	 *
2490
	 * @param string $header Add html code after <body>
2491
	 */
2492
	function addBodyHeader($header)
2493
	{
2494
		$self = self::getInstance();
2495
		$self->body_header .= "\n" . $header;
2496
	}
2497
2498
	/**
2499
	 * Returns added html code by addBodyHeader()
2500
	 *
2501
	 * @return string Added html code after <body>
2502
	 */
2503
	function getBodyHeader()
2504
	{
2505
		$self = self::getInstance();
2506
		return $self->body_header;
2507
	}
2508
2509
	/**
2510
	 * Add html code before </body>
2511
	 *
2512
	 * @param string $footer Add html code before </body>
2513
	 */
2514
	function addHtmlFooter($footer)
2515
	{
2516
		$self = self::getInstance();
2517
		$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...
2518
	}
2519
2520
	/**
2521
	 * Returns added html code by addHtmlHeader()
2522
	 *
2523
	 * @return string Added html code before </body>
2524
	 */
2525
	function getHtmlFooter()
2526
	{
2527
		$self = self::getInstance();
2528
		return $self->html_footer;
2529
	}
2530
2531
	/**
2532
	 * Get config file
2533
	 *
2534
	 * @retrun string The path of the config file that contains database settings
2535
	 */
2536
	function getConfigFile()
2537
	{
2538
		return _XE_PATH_ . 'files/config/db.config.php';
2539
	}
2540
2541
	/**
2542
	 * Get FTP config file
2543
	 *
2544
	 * @return string The path of the config file that contains FTP settings
2545
	 */
2546
	function getFTPConfigFile()
2547
	{
2548
		return _XE_PATH_ . 'files/config/ftp.config.php';
2549
	}
2550
2551
	/**
2552
	 * Checks whether XE is installed
2553
	 *
2554
	 * @return bool True if the config file exists, otherwise FALSE.
2555
	 */
2556
	function isInstalled()
2557
	{
2558
		return FileHandler::hasContent(self::getConfigFile());
2559
	}
2560
2561
	/**
2562
	 * Transforms codes about widget or other features into the actual code, deprecatred
2563
	 *
2564
	 * @param string Transforms codes
2565
	 * @return string Transforms codes
2566
	 */
2567
	function transContent($content)
2568
	{
2569
		return $content;
2570
	}
2571
2572
	/**
2573
	 * Check whether it is allowed to use rewrite mod
2574
	 *
2575
	 * @return bool True if it is allowed to use rewrite mod, otherwise FALSE
2576
	 */
2577
	function isAllowRewrite()
2578
	{
2579
		$oContext = self::getInstance();
2580
		return $oContext->allow_rewrite;
2581
	}
2582
2583
	/**
2584
	 * Converts a local path into an URL
2585
	 *
2586
	 * @param string $path URL path
2587
	 * @return string Converted path
2588
	 */
2589
	function pathToUrl($path)
2590
	{
2591
		$xe = _XE_PATH_;
2592
		$path = strtr($path, "\\", "/");
2593
2594
		$base_url = preg_replace('@^https?://[^/]+/?@', '', self::getRequestUri());
2595
2596
		$_xe = explode('/', $xe);
2597
		$_path = explode('/', $path);
2598
		$_base = explode('/', $base_url);
2599
2600
		if(!$_base[count($_base) - 1])
2601
		{
2602
			array_pop($_base);
2603
		}
2604
2605
		foreach($_xe as $idx => $dir)
2606
		{
2607
			if($_path[0] != $dir)
2608
			{
2609
				break;
2610
			}
2611
			array_shift($_path);
2612
		}
2613
2614
		$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...
2615
		while($idx--)
2616
		{
2617
			if(count($_base) > 0)
2618
			{
2619
				array_shift($_base);
2620
			}
2621
			else
2622
			{
2623
				array_unshift($_base, '..');
2624
			}
2625
		}
2626
2627
		if(count($_base) > 0)
2628
		{
2629
			array_unshift($_path, join('/', $_base));
2630
		}
2631
2632
		$path = '/' . join('/', $_path);
2633
		if(substr_compare($path, '/', -1) !== 0)
2634
		{
2635
			$path .= '/';
2636
		}
2637
		return $path;
2638
	}
2639
2640
	/**
2641
	 * Get meta tag
2642
	 * @return array The list of meta tags
2643
	 */
2644
	function getMetaTag()
2645
	{
2646
		$self = self::getInstance();
2647
2648
		if(!is_array($self->meta_tags))
2649
		{
2650
			$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...
2651
		}
2652
2653
		$ret = array();
2654
		foreach($self->meta_tags as $key => $val)
2655
		{
2656
			list($name, $is_http_equiv) = explode("\t", $key);
2657
			$ret[] = array('name' => $name, 'is_http_equiv' => $is_http_equiv, 'content' => $val);
2658
		}
2659
2660
		return $ret;
2661
	}
2662
2663
	/**
2664
	 * Add the meta tag
2665
	 *
2666
	 * @param string $name name of meta tag
2667
	 * @param string $content content of meta tag
2668
	 * @param mixed $is_http_equiv value of http_equiv
2669
	 * @return void
2670
	 */
2671
	function addMetaTag($name, $content, $is_http_equiv = FALSE)
2672
	{
2673
		$self = self::getInstance();
2674
		$self->meta_tags[$name . "\t" . ($is_http_equiv ? '1' : '0')] = $content;
2675
	}
2676
2677
}
2678
/* End of file Context.class.php */
2679
/* Location: ./classes/context/Context.class.php */
2680