GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — develop ( 241768...d6138d )
by gyeong-won
19:18 queued 09:58
created

Context::loadDBInfo()   D

Complexity

Conditions 14
Paths 385

Size

Total Lines 74
Code Lines 47

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 14
eloc 47
nc 385
nop 0
dl 0
loc 74
rs 4.0377
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Documentation Bug introduced by
It seems like \FileHandler::getRealPat...is->sslActionCacheFile) of type string is incompatible with the declared type array of property $sslActionCacheFile.

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

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

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

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

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

Loading history...
189
			{
190
				$this->ssl_actions = $sslActions;
191
			}
192
		}
193
	}
194
195
	/**
196
	 * Initialization, it sets DB information, request arguments and so on.
197
	 *
198
	 * @see This function should be called only once
199
	 * @return void
200
	 */
201
	function init()
202
	{
203
		// fix missing HTTP_RAW_POST_DATA in PHP 5.6 and above
204
		if(!isset($GLOBALS['HTTP_RAW_POST_DATA']) && version_compare(PHP_VERSION, '5.6.0', '>=') === TRUE)
205
		{
206
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents("php://input");
207
			
208
			// If content is not XML JSON, unset
209
			if(!preg_match('/^[\<\{\[]/', $GLOBALS['HTTP_RAW_POST_DATA']) && strpos($_SERVER['CONTENT_TYPE'], 'json') === FALSE && strpos($_SERVER['HTTP_CONTENT_TYPE'], 'json') === FALSE)
210
			{
211
				unset($GLOBALS['HTTP_RAW_POST_DATA']);
212
			}
213
		}
214
215
		// set context variables in $GLOBALS (to use in display handler)
216
		$this->context = &$GLOBALS['__Context__'];
217
		$this->context->lang = &$GLOBALS['lang'];
218
		$this->context->_COOKIE = $_COOKIE;
219
220
		// 20140429 editor/image_link
221
		$this->_checkGlobalVars();
222
223
		$this->setRequestMethod('');
224
225
		$this->_setXmlRpcArgument();
226
		$this->_setJSONRequestArgument();
227
		$this->_setRequestArgument();
228
		$this->_setUploadedArgument();
229
230
		$this->loadDBInfo();
231
		if($this->db_info->use_sitelock == 'Y')
232
		{
233
			if(is_array($this->db_info->sitelock_whitelist)) $whitelist = $this->db_info->sitelock_whitelist;
234
235
			if(!IpFilter::filter($whitelist))
0 ignored issues
show
Bug introduced by
The variable $whitelist does not seem to be defined for all execution paths leading up to this point.

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

Let’s take a look at an example:

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

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

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

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

Available Fixes

  1. Check for existence of the variable explicitly:

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

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

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
236
			{
237
				$title = ($this->db_info->sitelock_title) ? $this->db_info->sitelock_title : 'Maintenance in progress...';
238
				$message = $this->db_info->sitelock_message;
239
240
				define('_XE_SITELOCK_', TRUE);
241
				define('_XE_SITELOCK_TITLE_', $title);
242
				define('_XE_SITELOCK_MESSAGE_', $message);
243
244
				header("HTTP/1.1 403 Forbidden");
245
				if(FileHandler::exists(_XE_PATH_ . 'common/tpl/sitelock.user.html'))
0 ignored issues
show
Bug Best Practice introduced by
The expression \FileHandler::exists(_XE...pl/sitelock.user.html') of type string|false is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

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

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

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

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
246
				{
247
					include _XE_PATH_ . 'common/tpl/sitelock.user.html';
248
				}
249
				else
250
				{
251
					include _XE_PATH_ . 'common/tpl/sitelock.html';
252
				}
253
				exit;
254
			}
255
		}
256
257
		// If XE is installed, get virtual site information
258
		if(self::isInstalled())
259
		{
260
			$oModuleModel = getModel('module');
261
			$site_module_info = $oModuleModel->getDefaultMid();
262
263
			if(!isset($site_module_info))
264
			{
265
				$site_module_info = new stdClass();
266
			}
267
268
			// if site_srl of site_module_info is 0 (default site), compare the domain to default_url of db_config
269
			if($site_module_info->site_srl == 0 && $site_module_info->domain != $this->db_info->default_url)
270
			{
271
				$site_module_info->domain = $this->db_info->default_url;
272
			}
273
274
			$this->set('site_module_info', $site_module_info);
275
			if($site_module_info->site_srl && isSiteID($site_module_info->domain))
276
			{
277
				$this->set('vid', $site_module_info->domain, TRUE);
0 ignored issues
show
Documentation introduced by
TRUE is of type boolean, but the function expects a integer.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
278
			}
279
280
			if(!isset($this->db_info))
281
			{
282
				$this->db_info = new stdClass();
283
			}
284
285
			$this->db_info->lang_type = $site_module_info->default_language;
286
			if(!$this->db_info->lang_type)
287
			{
288
				$this->db_info->lang_type = 'en';
289
			}
290
			if(!$this->db_info->use_db_session)
291
			{
292
				$this->db_info->use_db_session = 'N';
293
			}
294
		}
295
296
		// Load Language File
297
		$lang_supported = $this->loadLangSelected();
298
299
		// Retrieve language type set in user's cookie
300
		if($this->lang_type = $this->get('l'))
301
		{
302
			if($_COOKIE['lang_type'] != $this->lang_type)
303
			{
304
				setcookie('lang_type', $this->lang_type, $_SERVER['REQUEST_TIME'] + 3600 * 24 * 1000, '/');
305
			}
306
		}
307
		elseif($_COOKIE['lang_type'])
308
		{
309
			$this->lang_type = $_COOKIE['lang_type'];
310
		}
311
312
		// If it's not exists, follow default language type set in db_info
313
		if(!$this->lang_type)
314
		{
315
			$this->lang_type = $this->db_info->lang_type;
316
		}
317
318
		// if still lang_type has not been set or has not-supported type , set as English.
319
		if(!$this->lang_type)
320
		{
321
			$this->lang_type = 'en';
322
		}
323
		if(is_array($lang_supported) && !isset($lang_supported[$this->lang_type]))
324
		{
325
			$this->lang_type = 'en';
326
		}
327
328
		$this->set('lang_supported', $lang_supported);
0 ignored issues
show
Documentation introduced by
$lang_supported is of type null|array, but the function expects a string.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
329
		$this->setLangType($this->lang_type);
330
331
		// load module module's language file according to language setting
332
		$this->loadLang(_XE_PATH_ . 'modules/module/lang');
333
334
		// set session handler
335
		if(self::isInstalled() && $this->db_info->use_db_session == 'Y')
336
		{
337
			$oSessionModel = getModel('session');
338
			$oSessionController = getController('session');
339
			session_set_save_handler(
340
					array(&$oSessionController, 'open'), array(&$oSessionController, 'close'), array(&$oSessionModel, 'read'), array(&$oSessionController, 'write'), array(&$oSessionController, 'destroy'), array(&$oSessionController, 'gc')
341
			);
342
		}
343
344
		if($sess = $_POST[session_name()]) session_id($sess);
345
		session_start();
346
347
		// set authentication information in Context and session
348
		if(self::isInstalled())
349
		{
350
			$oModuleModel = getModel('module');
351
			$oModuleModel->loadModuleExtends();
352
353
			$oMemberModel = getModel('member');
354
			$oMemberController = getController('member');
355
356
			if($oMemberController && $oMemberModel)
357
			{
358
				// if signed in, validate it.
359
				if($oMemberModel->isLogged())
360
				{
361
					$oMemberController->setSessionInfo();
362
				}
363
				// check auto sign-in
364
				elseif($_COOKIE['xeak'])
365
				{
366
					$oMemberController->doAutologin();
367
				}
368
369
				$this->set('is_logged', $oMemberModel->isLogged());
370
				$this->set('logged_info', $oMemberModel->getLoggedInfo());
371
			}
372
		}
373
374
		// load common language file
375
		$this->lang = &$GLOBALS['lang'];
376
		$this->loadLang(_XE_PATH_ . 'common/lang/');
377
378
		// check if using rewrite module
379
		$this->allow_rewrite = ($this->db_info->use_rewrite == 'Y' ? TRUE : FALSE);
380
381
		// set locations for javascript use
382
		$url = array();
0 ignored issues
show
Unused Code introduced by
$url is not used, you could remove the assignment.

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

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

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

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

Loading history...
383
		$current_url = self::getRequestUri();
0 ignored issues
show
Unused Code introduced by
$current_url is not used, you could remove the assignment.

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

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

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

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

Loading history...
384
		if($_SERVER['REQUEST_METHOD'] == 'GET')
385
		{
386
			if($this->get_vars)
387
			{
388
				$url = array();
389 View Code Duplication
				foreach($this->get_vars as $key => $val)
390
				{
391
					if(is_array($val) && count($val) > 0)
392
					{
393
						foreach($val as $k => $v)
394
						{
395
							$url[] = $key . '[' . $k . ']=' . urlencode($v);
396
						}
397
					}
398
					elseif($val)
399
					{
400
						$url[] = $key . '=' . urlencode($val);
401
					}
402
				}
403
404
				$current_url = self::getRequestUri();
405
				if($url) $current_url .= '?' . join('&', $url);
0 ignored issues
show
Bug Best Practice introduced by
The expression $url of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

Loading history...
406
			}
407
			else
408
			{
409
				$current_url = $this->getUrl();
410
			}
411
		}
412
		else
413
		{
414
			$current_url = self::getRequestUri();
415
		}
416
417
		$this->set('current_url', $current_url);
418
		$this->set('request_uri', self::getRequestUri());
419
420
		if(strpos($current_url, 'xn--') !== FALSE)
421
		{
422
			$this->set('current_url', self::decodeIdna($current_url));
423
		}
424
425
		if(strpos(self::getRequestUri(), 'xn--') !== FALSE)
426
		{
427
			$this->set('request_uri', self::decodeIdna(self::getRequestUri()));
428
		}
429
	}
430
431
	/**
432
	 * Finalize using resources, such as DB connection
433
	 *
434
	 * @return void
435
	 */
436
	function close()
437
	{
438
		session_write_close();
439
	}
440
441
	/**
442
	 * Load the database information
443
	 *
444
	 * @return void
445
	 */
446
	function loadDBInfo()
447
	{
448
		$self = self::getInstance();
449
450
		if(!$self->isInstalled())
451
		{
452
			return;
453
		}
454
455
		include($self::getConfigFile());
456
457
		// If master_db information does not exist, the config file needs to be updated
458
		if(!isset($db_info->master_db))
459
		{
460
			$db_info->master_db = array();
0 ignored issues
show
Bug introduced by
The variable $db_info does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

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

This method has been deprecated.

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