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 ( eebdf0...99de18 )
by gyeong-won
08:25
created

func.inc.php ➔ saveCookie()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 26
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 14
nc 8
nop 4
dl 0
loc 26
rs 8.439
c 0
b 0
f 0
1
<?php
2
/* Copyright (C) NAVER <http://www.navercorp.com> */
3
4
/**
5
 * function library files for convenience
6
 *
7
 * @author NAVER ([email protected])
8
 */
9
if(!defined('__XE__'))
10
{
11
	exit();
12
}
13
14
// define an empty function to avoid errors when iconv function doesn't exist
15
if(!function_exists('iconv'))
16
{
17
	eval('
18
		function iconv($in_charset, $out_charset, $str)
19
		{
20
			return $str;
21
		}
22
	');
23
}
24
25
/**
26
 * Time zone
27
 * @var array
28
 */
29
$time_zone = array(
30
	'-1200' => '[GMT -12:00] Baker Island Time',
31
	'-1100' => '[GMT -11:00] Niue Time, Samoa Standard Time',
32
	'-1000' => '[GMT -10:00] Hawaii-Aleutian Standard Time, Cook Island Time',
33
	'-0930' => '[GMT -09:30] Marquesas Islands Time',
34
	'-0900' => '[GMT -09:00] Alaska Standard Time, Gambier Island Time',
35
	'-0800' => '[GMT -08:00] Pacific Standard Time',
36
	'-0700' => '[GMT -07:00] Mountain Standard Time',
37
	'-0600' => '[GMT -06:00] Central Standard Time',
38
	'-0500' => '[GMT -05:00] Eastern Standard Time',
39
	'-0400' => '[GMT -04:00] Atlantic Standard Time',
40
	'-0330' => '[GMT -03:30] Newfoundland Standard Time',
41
	'-0300' => '[GMT -03:00] Amazon Standard Time, Central Greenland Time',
42
	'-0200' => '[GMT -02:00] Fernando de Noronha Time, South Georgia &amp; the South Sandwich Islands Time',
43
	'-0100' => '[GMT -01:00] Azores Standard Time, Cape Verde Time, Eastern Greenland Time',
44
	'0000' => '[GMT  00:00] Western European Time, Greenwich Mean Time',
45
	'+0100' => '[GMT +01:00] Central European Time, West African Time',
46
	'+0200' => '[GMT +02:00] Eastern European Time, Central African Time',
47
	'+0300' => '[GMT +03:00] Moscow Standard Time, Eastern African Time',
48
	'+0330' => '[GMT +03:30] Iran Standard Time',
49
	'+0400' => '[GMT +04:00] Gulf Standard Time, Samara Standard Time',
50
	'+0430' => '[GMT +04:30] Afghanistan Time',
51
	'+0500' => '[GMT +05:00] Pakistan Standard Time, Yekaterinburg Standard Time',
52
	'+0530' => '[GMT +05:30] Indian Standard Time, Sri Lanka Time',
53
	'+0545' => '[GMT +05:45] Nepal Time',
54
	'+0600' => '[GMT +06:00] Bangladesh Time, Bhutan Time, Novosibirsk Standard Time',
55
	'+0630' => '[GMT +06:30] Cocos Islands Time, Myanmar Time',
56
	'+0700' => '[GMT +07:00] Indochina Time, Krasnoyarsk Standard Time',
57
	'+0800' => '[GMT +08:00] China Standard Time, Australian Western Standard Time, Irkutsk Standard Time',
58
	'+0845' => '[GMT +08:45] Southeastern Western Australia Standard Time',
59
	'+0900' => '[GMT +09:00] Korea Standard Time, Japan Standard Time',
60
	'+0930' => '[GMT +09:30] Australian Central Standard Time',
61
	'+1000' => '[GMT +10:00] Australian Eastern Standard Time, Vladivostok Standard Time',
62
	'+1030' => '[GMT +10:30] Lord Howe Standard Time',
63
	'+1100' => '[GMT +11:00] Solomon Island Time, Magadan Standard Time',
64
	'+1130' => '[GMT +11:30] Norfolk Island Time',
65
	'+1200' => '[GMT +12:00] New Zealand Time, Fiji Time, Kamchatka Standard Time',
66
	'+1245' => '[GMT +12:45] Chatham Islands Time',
67
	'+1300' => '[GMT +13:00] Tonga Time, Phoenix Islands Time',
68
	'+1400' => '[GMT +14:00] Line Island Time'
69
);
70
71
/**
72
 * Define a function to use {@see ModuleHandler::getModuleObject()} ($module_name, $type)
73
 *
74
 * @param string $module_name The module name to get a instance
75
 * @param string $type disp, proc, controller, class
76
 * @param string $kind admin, null
77
 * @return mixed Module instance
78
 */
79
function getModule($module_name, $type = 'view', $kind = '')
80
{
81
	return ModuleHandler::getModuleInstance($module_name, $type, $kind);
82
}
83
84
/**
85
 * Create a controller instance of the module
86
 *
87
 * @param string $module_name The module name to get a controller instance
88
 * @return mixed Module controller instance
89
 */
90
function getController($module_name)
91
{
92
	return getModule($module_name, 'controller');
93
}
94
95
/**
96
 * Create a admin controller instance of the module
97
 *
98
 * @param string $module_name The module name to get a admin controller instance
99
 * @return mixed Module admin controller instance
100
 */
101
function getAdminController($module_name)
102
{
103
	return getModule($module_name, 'controller', 'admin');
104
}
105
106
/**
107
 * Create a view instance of the module
108
 *
109
 * @param string $module_name The module name to get a view instance
110
 * @return mixed Module view instance
111
 */
112
function getView($module_name)
113
{
114
	return getModule($module_name, 'view');
115
}
116
117
/**
118
 * Create a mobile instance of the module
119
 *
120
 * @param string $module_name The module name to get a mobile instance
121
 * @return mixed Module mobile instance
122
 */
123
function &getMobile($module_name)
124
{
125
	return getModule($module_name, 'mobile');
126
}
127
128
/**
129
 * Create a admin view instance of the module
130
 *
131
 * @param string $module_name The module name to get a admin view instance
132
 * @return mixed Module admin view instance
133
 */
134
function getAdminView($module_name)
135
{
136
	return getModule($module_name, 'view', 'admin');
137
}
138
139
/**
140
 * Create a model instance of the module
141
 *
142
 * @param string $module_name The module name to get a model instance
143
 * @return mixed Module model instance
144
 */
145
function getModel($module_name)
146
{
147
	return getModule($module_name, 'model');
148
}
149
150
/**
151
 * Create an admin model instance of the module
152
 *
153
 * @param string $module_name The module name to get a admin model instance
154
 * @return mixed Module admin model instance
155
 */
156
function getAdminModel($module_name)
157
{
158
	return getModule($module_name, 'model', 'admin');
159
}
160
161
/**
162
 * Create an api instance of the module
163
 *
164
 * @param string $module_name The module name to get a api instance
165
 * @return mixed Module api class instance
166
 */
167
function getAPI($module_name)
168
{
169
	return getModule($module_name, 'api');
170
}
171
172
/**
173
 * Create a wap instance of the module
174
 *
175
 * @param string $module_name The module name to get a wap instance
176
 * @return mixed Module wap class instance
177
 */
178
function getWAP($module_name)
179
{
180
	return getModule($module_name, 'wap');
181
}
182
183
/**
184
 * Create a class instance of the module
185
 *
186
 * @param string $module_name The module name to get a class instance
187
 * @return mixed Module class instance
188
 */
189
function getClass($module_name)
190
{
191
	return getModule($module_name, 'class');
192
}
193
194
/**
195
 * The alias of DB::executeQuery()
196
 *
197
 * @see DB::executeQuery()
198
 * @param string $query_id (module name.query XML file)
199
 * @param object $args values of args object
200
 * @param string[] $arg_columns Column list
201
 * @return object Query result data
202
 */
203
function executeQuery($query_id, $args = NULL, $arg_columns = NULL)
204
{
205
	$oDB = DB::getInstance();
206
	return $oDB->executeQuery($query_id, $args, $arg_columns);
207
}
208
209
/**
210
 * Function to handle the result of DB::executeQuery() as an array
211
 *
212
 * @see DB::executeQuery()
213
 * @see executeQuery()
214
 * @param string $query_id (module name.query XML file)
215
 * @param object $args values of args object
216
 * @param string[] $arg_columns Column list
217
 * @return object Query result data
218
 */
219
function executeQueryArray($query_id, $args = NULL, $arg_columns = NULL)
220
{
221
	$oDB = DB::getInstance();
222
	$output = $oDB->executeQuery($query_id, $args, $arg_columns);
223
	if(!is_array($output->data) && count($output->data) > 0)
224
	{
225
		$output->data = array($output->data);
226
	}
227
	return $output;
228
}
229
230
/**
231
 * Alias of DB::getNextSequence()
232
 *
233
 * @see DB::getNextSequence()
234
 * @return int
235
 */
236
function getNextSequence()
237
{
238
	$oDB = DB::getInstance();
239
	$seq = $oDB->getNextSequence();
240
	setUserSequence($seq);
241
	return $seq;
242
}
243
244
/**
245
 * Set Sequence number to session
246
 *
247
 * @param int $seq sequence number
248
 * @return void
249
 */
250
function setUserSequence($seq)
251
{
252
	$arr_seq = array();
253
	if(isset($_SESSION['seq']))
254
	{
255
		$arr_seq = $_SESSION['seq'];
256
	}
257
	$arr_seq[] = $seq;
258
	$_SESSION['seq'] = $arr_seq;
259
}
260
261
/**
262
 * Check Sequence number grant
263
 *
264
 * @param int $seq sequence number
265
 * @return boolean
266
 */
267
function checkUserSequence($seq)
268
{
269
	if(!isset($_SESSION['seq']))
270
	{
271
		return false;
272
	}
273
	if(!in_array($seq, $_SESSION['seq']))
274
	{
275
		return false;
276
	}
277
278
	return true;
279
}
280
281
/**
282
 * Get a encoded url. Define a function to use Context::getUrl()
283
 *
284
 * getUrl() returns the URL transformed from given arguments of RequestURI
285
 * <ol>
286
 *  <li>argument format follows as (key, value).
287
 * ex) getUrl('key1', 'val1', 'key2',''): transform key1 and key2 to val1 and '' respectively</li>
288
 * <li>returns URL without the argument if no argument is given.</li>
289
 * <li>URL made of args_list added to RequestUri if the first argument value is ''.</li>
290
 * </ol>
291
 *
292
 * @return string
293
 */
294
function getUrl()
295
{
296
	$num_args = func_num_args();
297
	$args_list = func_get_args();
298
299
	if($num_args)
300
		$url = Context::getUrl($num_args, $args_list);
301
	else
302
		$url = Context::getRequestUri();
303
304
	return preg_replace('@\berror_return_url=[^&]*|\w+=(?:&|$)@', '', $url);
305
}
306
307
/**
308
 * Get a not encoded(html entity) url
309
 *
310
 * @see getUrl()
311
 * @return string
312
 */
313 View Code Duplication
function getNotEncodedUrl()
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
314
{
315
	$num_args = func_num_args();
316
	$args_list = func_get_args();
317
318
	if($num_args)
319
	{
320
		$url = Context::getUrl($num_args, $args_list, NULL, FALSE);
321
	}
322
	else
323
	{
324
		$url = Context::getRequestUri();
325
	}
326
327
	return preg_replace('@\berror_return_url=[^&]*|\w+=(?:&|$)@', '', $url);
328
}
329
330
/**
331
 * Get a encoded url. If url is encoded, not encode. Otherwise html encode the url.
332
 *
333
 * @see getUrl()
334
 * @return string
335
 */
336 View Code Duplication
function getAutoEncodedUrl()
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
337
{
338
	$num_args = func_num_args();
339
	$args_list = func_get_args();
340
341
	if($num_args)
342
	{
343
		$url = Context::getUrl($num_args, $args_list, NULL, TRUE, TRUE);
344
	}
345
	else
346
	{
347
		$url = Context::getRequestUri();
348
	}
349
350
	return preg_replace('@\berror_return_url=[^&]*|\w+=(?:&|$)@', '', $url);
351
}
352
353
/**
354
 * Return the value adding request uri to getUrl() to get the full url
355
 *
356
 * @return string
357
 */
358
function getFullUrl()
359
{
360
	$num_args = func_num_args();
361
	$args_list = func_get_args();
362
	$request_uri = Context::getRequestUri();
363
	if(!$num_args)
364
	{
365
		return $request_uri;
366
	}
367
368
	$url = Context::getUrl($num_args, $args_list);
369 View Code Duplication
	if(strncasecmp('http', $url, 4) !== 0)
370
	{
371
		preg_match('/^(http|https):\/\/([^\/]+)\//', $request_uri, $match);
372
		return substr($match[0], 0, -1) . $url;
373
	}
374
	return $url;
375
}
376
377
/**
378
 * Return the value adding request uri to getUrl() to get the not encoded full url
379
 *
380
 * @return string
381
 */
382
function getNotEncodedFullUrl()
383
{
384
	$num_args = func_num_args();
385
	$args_list = func_get_args();
386
	$request_uri = Context::getRequestUri();
387
	if(!$num_args)
388
	{
389
		return $request_uri;
390
	}
391
392
	$url = Context::getUrl($num_args, $args_list, NULL, FALSE);
393 View Code Duplication
	if(strncasecmp('http', $url, 4) !== 0)
394
	{
395
		preg_match('/^(http|https):\/\/([^\/]+)\//', $request_uri, $match);
396
		$url = Context::getUrl($num_args, $args_list, NULL, FALSE);
397
		return substr($match[0], 0, -1) . $url;
398
	}
399
	return $url;
400
}
401
402
/**
403
 * getSiteUrl() returns the URL by transforming the given argument value of domain
404
 * The first argument should consist of domain("http://" not included) and path
405
 * 
406
 * @return string
407
 */
408 View Code Duplication
function getSiteUrl()
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
409
{
410
	$num_args = func_num_args();
411
	$args_list = func_get_args();
412
413
	if(!$num_args)
414
	{
415
		return Context::getRequestUri();
416
	}
417
418
	$domain = array_shift($args_list);
419
	$num_args = count($args_list);
420
421
	return Context::getUrl($num_args, $args_list, $domain);
422
}
423
424
/**
425
 * getSiteUrl() returns the not encoded URL by transforming the given argument value of domain
426
 * The first argument should consist of domain("http://" not included) and path
427
 * 
428
 * @return string
429
 */
430 View Code Duplication
function getNotEncodedSiteUrl()
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
431
{
432
	$num_args = func_num_args();
433
	$args_list = func_get_args();
434
435
	if(!$num_args)
436
	{
437
		return Context::getRequestUri();
438
	}
439
440
	$domain = array_shift($args_list);
441
	$num_args = count($args_list);
442
443
	return Context::getUrl($num_args, $args_list, $domain, FALSE);
444
}
445
446
/**
447
 * Return the value adding request uri to the getSiteUrl() To get the full url
448
 *
449
 * @return string
450
 */
451
function getFullSiteUrl()
452
{
453
	$num_args = func_num_args();
454
	$args_list = func_get_args();
455
456
	$request_uri = Context::getRequestUri();
457
	if(!$num_args)
458
	{
459
		return $request_uri;
460
	}
461
462
	$domain = array_shift($args_list);
463
	$num_args = count($args_list);
464
465
	$url = Context::getUrl($num_args, $args_list, $domain);
466 View Code Duplication
	if(strncasecmp('http', $url, 4) !== 0)
467
	{
468
		preg_match('/^(http|https):\/\/([^\/]+)\//', $request_uri, $match);
469
		return substr($match[0], 0, -1) . $url;
470
	}
471
	return $url;
472
}
473
474
/**
475
 * Return the exact url of the current page
476
 *
477
 * @return string
478
 */
479
function getCurrentPageUrl()
480
{
481
	$protocol = $_SERVER['HTTPS'] == 'on' ? 'https://' : 'http://';
482
	$url = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
483
	return htmlspecialchars($url, ENT_COMPAT, 'UTF-8', FALSE);
484
}
485
486
/**
487
 * Return if domain of the virtual site is url type or id type
488
 *
489
 * @param string $domain
490
 * @return bool
491
 */
492
function isSiteID($domain)
493
{
494
	return preg_match('/^([a-zA-Z0-9\_]+)$/', $domain);
495
}
496
497
498
/**
499
 * setcookie 간소화
500
 *
501
 * @param      string   $name
502
 * @param      string   $value
503
 * @param      boolean  $httponly
504
 * @param      integer  $expire
505
 * @return     boolean
506
 */
507
function saveCookie($name, $value = '', $httponly = false, $expire = 0)
508
{
509
	static $secure = null;
510
	static $db_info = null;
511
512
	if($db_info === null)
513
	{
514
		$db_info = Context::getDBInfo();
515
	}
516
517
	$path = '/';
518
	$domain = '';
519
520
	if($db_info->disable_cookie_secure !== 'Y')
521
	{
522
		if($secure === null)
523
		{
524
			$secure = (Context::getSslStatus() === 'always') ? true : false;
525
		}
526
	} else {
527
		$httponly = false;
528
		$secure = false;
529
	}
530
531
	return setcookie($name, $value, $expire, $path, $domain, $secure, $httponly);
532
}
533
534
535
/**
536
 * Put a given tail after trimming string to the specified size
537
 *
538
 * @param string $string The original string to trim
539
 * @param int $cut_size The size to be
540
 * @param string $tail Tail to put in the end of the string after trimming
541
 * @return string
542
 */
543
function cut_str($string, $cut_size = 0, $tail = '...')
544
{
545
	if($cut_size < 1 || !$string)
546
	{
547
		return $string;
548
	}
549
550
	if($GLOBALS['use_mb_strimwidth'] || function_exists('mb_strimwidth'))
551
	{
552
		$GLOBALS['use_mb_strimwidth'] = TRUE;
553
		return mb_strimwidth($string, 0, $cut_size + 4, $tail, 'utf-8');
554
	}
555
556
	$chars = array(12, 4, 3, 5, 7, 7, 11, 8, 4, 5, 5, 6, 6, 4, 6, 4, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 4, 4, 8, 6, 8, 6, 10, 8, 8, 9, 8, 8, 7, 9, 8, 3, 6, 7, 7, 11, 8, 9, 8, 9, 8, 8, 7, 8, 8, 10, 8, 8, 8, 6, 11, 6, 6, 6, 4, 7, 7, 7, 7, 7, 3, 7, 7, 3, 3, 6, 3, 9, 7, 7, 7, 7, 4, 7, 3, 7, 6, 10, 6, 6, 7, 6, 6, 6, 9);
557
	$max_width = $cut_size * $chars[0] / 2;
558
	$char_width = 0;
559
560
	$string_length = strlen($string);
561
	$char_count = 0;
562
563
	$idx = 0;
564
	while($idx < $string_length && $char_count < $cut_size && $char_width <= $max_width)
565
	{
566
		$c = ord(substr($string, $idx, 1));
567
		$char_count++;
568
		if($c < 128)
569
		{
570
			$char_width += (int) $chars[$c - 32];
571
			$idx++;
572
		}
573
		else if(191 < $c && $c < 224)
574
		{
575
			$char_width += $chars[4];
576
			$idx += 2;
577
		}
578
		else
579
		{
580
			$char_width += $chars[0];
581
			$idx += 3;
582
		}
583
	}
584
585
	$output = substr($string, 0, $idx);
586
	if(strlen($output) < $string_length)
587
	{
588
		$output .= $tail;
589
	}
590
591
	return $output;
592
}
593
594
/**
595
 * Get a time gap between server's timezone and XE's timezone
596
 *
597
 * @return int
598
 */
599
function zgap()
600
{
601
	$time_zone = $GLOBALS['_time_zone'];
602
	if($time_zone < 0)
603
	{
604
		$to = -1;
605
	}
606
	else
607
	{
608
		$to = 1;
609
	}
610
611
	$t_hour = substr($time_zone, 1, 2) * $to;
612
	$t_min = substr($time_zone, 3, 2) * $to;
613
614
	$server_time_zone = date("O");
615
	if($server_time_zone < 0)
616
	{
617
		$so = -1;
618
	}
619
	else
620
	{
621
		$so = 1;
622
	}
623
624
	$c_hour = substr($server_time_zone, 1, 2) * $so;
625
	$c_min = substr($server_time_zone, 3, 2) * $so;
626
627
	$g_min = $t_min - $c_min;
628
	$g_hour = $t_hour - $c_hour;
629
630
	$gap = $g_min * 60 + $g_hour * 60 * 60;
631
	return $gap;
632
}
633
634
/**
635
 * YYYYMMDDHHIISS format changed to unix time value
636
 *
637
 * @param string $str Time value in format of YYYYMMDDHHIISS
638
 * @return int
639
 */
640
function ztime($str)
641
{
642
	if(!$str)
643
	{
644
		return;
645
	}
646
647
	$hour = (int) substr($str, 8, 2);
648
	$min = (int) substr($str, 10, 2);
649
	$sec = (int) substr($str, 12, 2);
650
	$year = (int) substr($str, 0, 4);
651
	$month = (int) substr($str, 4, 2);
652
	$day = (int) substr($str, 6, 2);
653
	if(strlen($str) <= 8)
654
	{
655
		$gap = 0;
656
	}
657
	else
658
	{
659
		$gap = zgap();
660
	}
661
662
	return mktime($hour, $min, $sec, $month ? $month : 1, $day ? $day : 1, $year) + $gap;
663
}
664
665
/**
666
 * If the recent post within a day, output format of YmdHis is "min/hours ago from now". If not within a day, it return format string.
667
 *
668
 * @param string $date Time value in format of YYYYMMDDHHIISS
669
 * @param string $format If gap is within a day, returns this format.
670
 * @return string
671
 */
672
function getTimeGap($date, $format = 'Y.m.d')
673
{
674
	$gap = $_SERVER['REQUEST_TIME'] + zgap() - ztime($date);
675
676
	$lang_time_gap = Context::getLang('time_gap');
677
	if($gap < 60)
678
	{
679
		$buff = sprintf($lang_time_gap['min'], (int) ($gap / 60) + 1);
680
	}
681
	elseif($gap < 60 * 60)
682
	{
683
		$buff = sprintf($lang_time_gap['mins'], (int) ($gap / 60) + 1);
684
	}
685 View Code Duplication
	elseif($gap < 60 * 60 * 2)
686
	{
687
		$buff = sprintf($lang_time_gap['hour'], (int) ($gap / 60 / 60) + 1);
688
	}
689 View Code Duplication
	elseif($gap < 60 * 60 * 24)
690
	{
691
		$buff = sprintf($lang_time_gap['hours'], (int) ($gap / 60 / 60) + 1);
692
	}
693
	else
694
	{
695
		$buff = zdate($date, $format);
696
	}
697
698
	return $buff;
699
}
700
701
/**
702
 * Name of the month return
703
 *
704
 * @param int $month Month
705
 * @param boot $short If set, returns short string
706
 * @return string
707
 */
708
function getMonthName($month, $short = TRUE)
709
{
710
	$short_month = array('', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
711
	$long_month = array('', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
712
	return !$short ? $long_month[$month] : $short_month[$month];
713
}
714
715
/**
716
 * Change the time format YYYYMMDDHHIISS to the user defined format
717
 *
718
 * @param string|int $str YYYYMMDDHHIISS format time values
719
 * @param string $format Time format of php date() function
720
 * @param bool $conversion Means whether to convert automatically according to the language
721
 * @return string
722
 */
723
function zdate($str, $format = 'Y-m-d H:i:s', $conversion = TRUE)
724
{
725
	// return null if no target time is specified
726
	if(!$str)
727
	{
728
		return;
729
	}
730
	// convert the date format according to the language
731
	if($conversion == TRUE)
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

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

Loading history...
732
	{
733
		switch(Context::getLangType())
734
		{
735
			case 'en' :
736
			case 'es' :
737 View Code Duplication
				if($format == 'Y-m-d')
738
				{
739
					$format = 'M d, Y';
740
				}
741
				elseif($format == 'Y-m-d H:i:s')
742
				{
743
					$format = 'M d, Y H:i:s';
744
				}
745
				elseif($format == 'Y-m-d H:i')
746
				{
747
					$format = 'M d, Y H:i';
748
				}
749
				break;
750
			case 'vi' :
751 View Code Duplication
				if($format == 'Y-m-d')
752
				{
753
					$format = 'd-m-Y';
754
				}
755
				elseif($format == 'Y-m-d H:i:s')
756
				{
757
					$format = 'H:i:s d-m-Y';
758
				}
759
				elseif($format == 'Y-m-d H:i')
760
				{
761
					$format = 'H:i d-m-Y';
762
				}
763
				break;
764
		}
765
	}
766
767
	// If year value is less than 1970, handle it separately.
768
	if((int) substr($str, 0, 4) < 1970)
769
	{
770
		$hour = (int) substr($str, 8, 2);
771
		$min = (int) substr($str, 10, 2);
772
		$sec = (int) substr($str, 12, 2);
773
		$year = (int) substr($str, 0, 4);
774
		$month = (int) substr($str, 4, 2);
775
		$day = (int) substr($str, 6, 2);
776
777
		$trans = array(
778
			'Y' => $year,
779
			'y' => sprintf('%02d', $year % 100),
780
			'm' => sprintf('%02d', $month),
781
			'n' => $month,
782
			'd' => sprintf('%02d', $day),
783
			'j' => $day,
784
			'G' => $hour,
785
			'H' => sprintf('%02d', $hour),
786
			'g' => $hour % 12,
787
			'h' => sprintf('%02d', $hour % 12),
788
			'i' => sprintf('%02d', $min),
789
			's' => sprintf('%02d', $sec),
790
			'M' => getMonthName($month),
791
			'F' => getMonthName($month, FALSE)
792
		);
793
794
		$string = strtr($format, $trans);
795
	}
796
	else
797
	{
798
		// if year value is greater than 1970, get unixtime by using ztime() for date() function's argument. 
799
		$string = date($format, ztime($str));
800
	}
801
	// change day and am/pm for each language
802
	$unit_week = Context::getLang('unit_week');
803
	$unit_meridiem = Context::getLang('unit_meridiem');
804
	$string = str_replace(array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'), $unit_week, $string);
805
	$string = str_replace(array('am', 'pm', 'AM', 'PM'), $unit_meridiem, $string);
806
	return $string;
807
}
808
809
/**
810
 * Returns encoded value of given email address for email scraping
811
 *
812
 * @param string $email The email
813
 * @return string
814
 */
815
function getEncodeEmailAddress($email)
816
{
817
	$return = '';
818
	for($i = 0, $c = strlen($email); $i < $c; $i++)
819
	{
820
		$return .= '&#' . (rand(0, 1) == 0 ? ord($email[$i]) : 'X' . dechex(ord($email[$i]))) . ';';
821
	}
822
	return $return;
823
}
824
825
/**
826
 * Prints debug messages 
827
 *
828
 * Display $buff contents into the file ./files/_debug_message.php.
829
 * You can see the file on your prompt by command: tail-f./files/_debug_message.php
830
 *
831
 * @param mixed $debug_output Target object to be printed
832
 * @param bool $display_option boolean Flag whether to print seperator (default:true)
833
 * @param string $file Target file name
834
 * @return void
835
 */
836
function debugPrint($debug_output = NULL, $display_option = TRUE, $file = '_debug_message.php')
837
{
838
	static $debug_file;
839
840
	if(!(__DEBUG__ & 1))
841
	{
842
		return;
843
	}
844
845
	static $firephp;
846
	$bt = debug_backtrace();
847
	if(is_array($bt))
848
	{
849
		$bt_debug_print = array_shift($bt);
850
		$bt_called_function = array_shift($bt);
851
	}
852
	$file_name = str_replace(_XE_PATH_, '', $bt_debug_print['file']);
0 ignored issues
show
Bug introduced by
The variable $bt_debug_print 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...
853
	$line_num = $bt_debug_print['line'];
854
	$function = $bt_called_function['class'] . $bt_called_function['type'] . $bt_called_function['function'];
0 ignored issues
show
Bug introduced by
The variable $bt_called_function 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...
855
856
	if(__DEBUG_OUTPUT__ == 2 && version_compare(PHP_VERSION, '6.0.0') === -1)
857
	{
858
		if(!isset($firephp))
859
		{
860
			$firephp = FirePHP::getInstance(TRUE);
861
		}
862
		$type = FirePHP::INFO;
863
864
		$label = sprintf('[%s:%d] %s() (Memory usage: current=%s, peak=%s)', $file_name, $line_num, $function, FileHandler::filesize(memory_get_usage()), FileHandler::filesize(memory_get_peak_usage()));
865
866
		// Check a FirePHP option
867
		if($display_option === 'TABLE')
868
		{
869
			$label = $display_option;
870
		}
871
		if($display_option === 'ERROR')
872
		{
873
			$type = $display_option;
874
		}
875
		// Check if the IP specified by __DEBUG_PROTECT__ option is same as the access IP.
876
		if(__DEBUG_PROTECT__ === 1 && __DEBUG_PROTECT_IP__ != $_SERVER['REMOTE_ADDR'])
877
		{
878
			$debug_output = 'The IP address is not allowed. Change the value of __DEBUG_PROTECT_IP__ into your IP address in config/config.user.inc.php or config/config.inc.php';
879
			$label = NULL;
880
		}
881
882
		$firephp->fb($debug_output, $label, $type);
883
	}
884
	else
885
	{
886
		if(__DEBUG_PROTECT__ === 1 && __DEBUG_PROTECT_IP__ != $_SERVER['REMOTE_ADDR'])
887
		{
888
			return;
889
		}
890
891
		$print = array();
892
		if(!$debug_file)
893
		{
894
			$debug_file = _XE_PATH_ . 'files/' . $file;
895
		}
896
		if(!file_exists($debug_file)) $print[] = '<?php exit() ?>';
897
898
		if($display_option === TRUE || $display_option === 'ERROR')
899
		{
900
			$print[] = sprintf("[%s %s:%d] %s() - mem(%s)", date('Y-m-d H:i:s'), $file_name, $line_num, $function, FileHandler::filesize(memory_get_usage()));;
901
			$print[] = str_repeat('=', 80);
902
		}
903
		$type = gettype($debug_output);
904
		if(!in_array($type, array('array', 'object', 'resource')))
905
		{
906
			if($display_option === 'ERROR')
907
			{
908
				$print[] = 'ERROR : ' . var_export($debug_output, TRUE);
909
			}
910
			else
911
			{
912
				$print[] = 'DEBUG : ' . $type . '(' . var_export($debug_output, TRUE) . ')';
913
			}
914
		}
915
		else
916
		{
917
			$print[] = 'DEBUG : ' . trim(preg_replace('/\r?\n/', "\n" . '        ', print_r($debug_output, true)));
918
		}
919
		$backtrace_args = defined('\DEBUG_BACKTRACE_IGNORE_ARGS') ? \DEBUG_BACKTRACE_IGNORE_ARGS : 0;
920
		$backtrace = debug_backtrace($backtrace_args);
921
922 View Code Duplication
		if(count($backtrace) > 1 && $backtrace[1]['function'] === 'debugPrint' && !$backtrace[1]['class'])
923
		{
924
			array_shift($backtrace);
925
		}
926
		foreach($backtrace as $val)
927
		{
928
			$print[] = '        - ' . $val['file'] . ' : ' . $val['line'];
929
		}
930
		$print[] = PHP_EOL;
931
		@file_put_contents($debug_file, implode(PHP_EOL, $print), FILE_APPEND|LOCK_EX);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
932
	}
933
}
934
935
/**
936
 * @param string $type query, trigger
937
 * @param float $elapsed_time
938
 * @param object $obj
939
 */
940
function writeSlowlog($type, $elapsed_time, $obj)
941
{
942
	if(!__LOG_SLOW_TRIGGER__ && !__LOG_SLOW_ADDON__ && !__LOG_SLOW_WIDGET__ && !__LOG_SLOW_QUERY__) return;
943
944
	static $log_filename = array(
945
		'query' => 'files/_slowlog_query.php',
946
		'trigger' => 'files/_slowlog_trigger.php',
947
		'addon' => 'files/_slowlog_addon.php',
948
		'widget' => 'files/_slowlog_widget.php'
949
	);
950
	$write_file = true;
951
952
	$log_file = _XE_PATH_ . $log_filename[$type];
953
954
	$buff = array();
955
	$buff[] = '<?php exit(); ?>';
956
	$buff[] = date('c');
957
958
	if($type == 'trigger' && __LOG_SLOW_TRIGGER__ > 0 && $elapsed_time > __LOG_SLOW_TRIGGER__)
959
	{
960
		$buff[] = "\tCaller : " . $obj->caller;
961
		$buff[] = "\tCalled : " . $obj->called;
962
	}
963
	else if($type == 'addon' && __LOG_SLOW_ADDON__ > 0 && $elapsed_time > __LOG_SLOW_ADDON__)
964
	{
965
		$buff[] = "\tAddon : " . $obj->called;
966
		$buff[] = "\tCalled position : " . $obj->caller;
967
	}
968
	else if($type == 'widget' && __LOG_SLOW_WIDGET__ > 0 && $elapsed_time > __LOG_SLOW_WIDGET__)
969
	{
970
		$buff[] = "\tWidget : " . $obj->called;
971
	}
972
	else if($type == 'query' && __LOG_SLOW_QUERY__ > 0 && $elapsed_time > __LOG_SLOW_QUERY__)
973
	{
974
975
		$buff[] = $obj->query;
976
		$buff[] = "\tQuery ID   : " . $obj->query_id;
977
		$buff[] = "\tCaller     : " . $obj->caller;
978
		$buff[] = "\tConnection : " . $obj->connection;
979
	}
980
	else
981
	{
982
		$write_file = false;
983
	}
984
985
	if($write_file)
986
	{
987
		$buff[] = sprintf("\t%0.6f sec", $elapsed_time);
988
		$buff[] = PHP_EOL . PHP_EOL;
989
		file_put_contents($log_file, implode(PHP_EOL, $buff), FILE_APPEND);
990
	}
991
992
	if($type != 'query')
993
	{
994
		$trigger_args = $obj;
995
		$trigger_args->_log_type = $type;
996
		$trigger_args->_elapsed_time = $elapsed_time;
997
		ModuleHandler::triggerCall('XE.writeSlowlog', 'after', $trigger_args);
998
	}
999
}
1000
1001
/**
1002
 * @param void
1003
 */
1004
function flushSlowlog()
1005
{
1006
	$trigger_args = new stdClass();
1007
	$trigger_args->_log_type = 'flush';
1008
	$trigger_args->_elapsed_time = 0;
1009
	ModuleHandler::triggerCall('XE.writeSlowlog', 'after', $trigger_args);
1010
}
1011
1012
/**
1013
 * microtime() return
1014
 *
1015
 * @return float
1016
 */
1017
function getMicroTime()
1018
{
1019
	list($time1, $time2) = explode(' ', microtime());
1020
	return (float) $time1 + (float) $time2;
1021
}
1022
1023
/**
1024
 * Delete the second object vars from the first argument
1025
 *
1026
 * @param object $target_obj An original object
1027
 * @param object $del_obj BaseObject vars to delete from the original object
1028
 * @return object
1029
 */
1030
function delObjectVars($target_obj, $del_obj)
1031
{
1032
	if(!is_object($target_obj))
1033
	{
1034
		return;
1035
	}
1036
	if(!is_object($del_obj))
1037
	{
1038
		return;
1039
	}
1040
1041
	$target_vars = get_object_vars($target_obj);
1042
	$del_vars = get_object_vars($del_obj);
1043
1044
	$target = array_keys($target_vars);
1045
	$del = array_keys($del_vars);
1046
	if(!count($target) || !count($del))
1047
	{
1048
		return $target_obj;
1049
	}
1050
1051
	$return_obj = new stdClass();
1052
1053
	$target_count = count($target);
1054
	for($i = 0; $i < $target_count; $i++)
1055
	{
1056
		$target_key = $target[$i];
1057
		if(!in_array($target_key, $del))
1058
		{
1059
			$return_obj->{$target_key} = $target_obj->{$target_key};
1060
		}
1061
	}
1062
1063
	return $return_obj;
1064
}
1065
1066
function getDestroyXeVars(&$vars)
1067
{
1068
	$del_vars = array('error_return_url', 'success_return_url', 'ruleset', 'xe_validator_id');
1069
1070
	foreach($del_vars as $var)
1071
	{
1072
		if(is_array($vars)) unset($vars[$var]);
1073
		else if(is_object($vars)) unset($vars->$var);
1074
	}
1075
1076
	return $vars;
1077
}
1078
1079
/**
1080
 * Change error_handing to debugPrint on php5 higher 
1081
 *
1082
 * @param int $errno
1083
 * @param string $errstr
1084
 * @param string $file
1085
 * @param int $line
1086
 * @return void
1087
 */
1088
function handleError($errno, $errstr, $file, $line)
1089
{
1090
	if(!__DEBUG__)
1091
	{
1092
		return;
1093
	}
1094
	$errors = array(E_USER_ERROR, E_ERROR, E_PARSE);
1095
	if(!in_array($errno, $errors))
1096
	{
1097
		return;
1098
	}
1099
1100
	$output = sprintf("Fatal error : %s - %d", $file, $line);
1101
	$output .= sprintf("%d - %s", $errno, $errstr);
1102
1103
	debugPrint($output);
1104
}
1105
1106
/**
1107
 * Trim a given number to a fiven size recursively
1108
 *
1109
 * @param int $no A given number
1110
 * @param int $size A given digits
1111
 */
1112
function getNumberingPath($no, $size = 3)
1113
{
1114
	$mod = pow(10, $size);
1115
	$output = sprintf('%0' . $size . 'd/', $no % $mod);
1116
	if($no >= $mod)
1117
	{
1118
		$output .= getNumberingPath((int) $no / $mod, $size);
1119
	}
1120
	return $output;
1121
}
1122
1123
/**
1124
 * Decode the URL in Korean
1125
 *
1126
 * @param string $str The url
1127
 * @return string
1128
 */
1129
function url_decode($str)
1130
{
1131
	return preg_replace('/%u([[:alnum:]]{4})/', '&#x\\1;', $str);
1132
}
1133
1134
function purifierHtml(&$content)
1135
{
1136
	require_once(_XE_PATH_ . 'classes/security/Purifier.class.php');
1137
	$oPurifier = Purifier::getInstance();
1138
	$oPurifier->purify($content);
1139
}
1140
1141
/**
1142
 * Pre-block the codes which may be hacking attempts
1143
 *
1144
 * @param string $content Taget content
1145
 * @return string
1146
 */
1147
function removeHackTag($content)
1148
{
1149
	require_once(_XE_PATH_ . 'classes/security/EmbedFilter.class.php');
1150
	$oEmbedFilter = EmbedFilter::getInstance();
1151
	$oEmbedFilter->check($content);
1152
1153
	purifierHtml($content);
1154
1155
	// change the specific tags to the common texts
1156
	$content = preg_replace('@<(\/?(?:html|body|head|title|meta|base|link|script|style|applet)(/*).*?>)@i', '&lt;$1', $content);
1157
1158
	/**
1159
	 * Remove codes to abuse the admin session in src by tags of imaages and video postings
1160
	 * - Issue reported by Sangwon Kim
1161
	 */
1162
	$content = preg_replace_callback('@<(/?)([a-z]+[0-9]?)((?>"[^"]*"|\'[^\']*\'|[^>])*?\b(?:on[a-z]+|data|style|background|href|(?:dyn|low)?src)\s*=[\s\S]*?)(/?)($|>|<)@i', 'removeSrcHack', $content);
1163
1164
	$content = checkXmpTag($content);
1165
	$content = blockWidgetCode($content);
1166
1167
	return $content;
1168
}
1169
1170
/**
1171
 * blocking widget code
1172
 *
1173
 * @param string $content Taget content
1174
 * @return string
1175
 **/
1176
function blockWidgetCode($content)
1177
{
1178
	$content = preg_replace('/(<(?:img|div)(?:[^>]*))(widget)(?:(=([^>]*?)>))/is', '$1blocked-widget$3', $content);
1179
1180
	return $content;
1181
}
1182
1183
/**
1184
 * check uploaded file which may be hacking attempts
1185
 *
1186
 * @param string $file Taget file path
1187
 * @return bool
1188
 */
1189
function checkUploadedFile($file)
1190
{
1191
	require_once(_XE_PATH_ . 'classes/security/UploadFileFilter.class.php');
1192
	return UploadFileFilter::check($file);
1193
}
1194
1195
/**
1196
 * Check xmp tag, close it.
1197
 *
1198
 * @param string $content Target content
1199
 * @return string
1200
 */
1201
function checkXmpTag($content)
1202
{
1203
	$content = preg_replace('@<(/?)xmp.*?>@i', '<\1xmp>', $content);
1204
1205
	if(($start_xmp = strrpos($content, '<xmp>')) !== FALSE)
1206
	{
1207
		if(($close_xmp = strrpos($content, '</xmp>')) === FALSE)
1208
		{
1209
			$content .= '</xmp>';
1210
		}
1211
		else if($close_xmp < $start_xmp)
1212
		{
1213
			$content .= '</xmp>';
1214
		}
1215
	}
1216
1217
	return $content;
1218
}
1219
1220
/**
1221
 * Remove src hack(preg_replace_callback)
1222
 *
1223
 * @param array $match
1224
 * @return string
1225
 */
1226
function removeSrcHack($match)
1227
{
1228
	$tag = strtolower($match[2]);
1229
1230
	// xmp tag ?뺣━
1231
	if($tag == 'xmp')
1232
	{
1233
		return "<{$match[1]}xmp>";
1234
	}
1235
	if($match[1])
1236
	{
1237
		return $match[0];
1238
	}
1239
	if($match[4])
1240
	{
1241
		$match[4] = ' ' . $match[4];
1242
	}
1243
1244
	$attrs = array();
1245
	if(preg_match_all('/([\w:-]+)\s*=(?:\s*(["\']))?(?(2)(.*?)\2|([^ ]+))/s', $match[3], $m))
1246
	{
1247
		foreach($m[1] as $idx => $name)
1248
		{
1249
			if(strlen($name) >= 2 && substr_compare($name, 'on', 0, 2) === 0)
1250
			{
1251
				continue;
1252
			}
1253
1254
			$val = preg_replace_callback('/&#(?:x([a-fA-F0-9]+)|0*(\d+));/', function($n) {return chr($n[1] ? ('0x00' . $n[1]) : ($n[2] + 0)); }, $m[3][$idx] . $m[4][$idx]);
1255
			$val = preg_replace('/^\s+|[\t\n\r]+/', '', $val);
1256
1257
			if(preg_match('/^[a-z]+script:/i', $val))
1258
			{
1259
				continue;
1260
			}
1261
1262
			$attrs[$name] = $val;
1263
		}
1264
	}
1265
1266
	$filter_arrts = array('style', 'src', 'href');
1267
1268
	if($tag === 'object') array_push($filter_arrts, 'data');
1269
	if($tag === 'param') array_push($filter_arrts, 'value');
1270
1271
	foreach($filter_arrts as $attr)
1272
	{
1273
		if(!isset($attrs[$attr])) continue;
1274
1275
		$attr_value = rawurldecode($attrs[$attr]);
1276
		$attr_value = htmlspecialchars_decode($attr_value, ENT_COMPAT);
1277
		$attr_value = preg_replace('/\s+|[\t\n\r]+/', '', $attr_value);
1278
		if(preg_match('@(\?|&|;)(act=(\w+))@i', $attr_value, $m) && $m[3] !== 'procFileDownload')
1279
		{
1280
			unset($attrs[$attr]);
1281
		}
1282
	}
1283
1284
	if(isset($attrs['style']) && preg_match('@(?:/\*|\*/|\n|:\s*expression\s*\()@i', $attrs['style']))
1285
	{
1286
		unset($attrs['style']);
1287
	}
1288
1289
	$attr = array();
1290
	foreach($attrs as $name => $val)
1291
	{
1292
		if($tag == 'object' || $tag == 'embed' || $tag == 'a')
1293
		{
1294
			$attribute = strtolower(trim($name));
1295
			if($attribute == 'data' || $attribute == 'src' || $attribute == 'href')
1296
			{
1297
				if(stripos($val, 'data:') === 0)
1298
				{
1299
					continue;
1300
				}
1301
			}
1302
		}
1303
1304
		if($tag == 'img')
1305
		{
1306
			$attribute = strtolower(trim($name));
0 ignored issues
show
Unused Code introduced by
$attribute 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...
1307
			if(stripos($val, 'data:') === 0)
1308
			{
1309
				continue;
1310
			}
1311
		}
1312
		$val = str_replace('"', '&quot;', $val);
1313
		$attr[] = $name . "=\"{$val}\"";
1314
	}
1315
	$attr = count($attr) ? ' ' . implode(' ', $attr) : '';
1316
1317
	return "<{$match[1]}{$tag}{$attr}{$match[4]}>";
1318
}
1319
1320
// convert hexa value to RGB
1321
if(!function_exists('hexrgb'))
1322
{
1323
1324
	/**
1325
	 * Convert hexa value to RGB
1326
	 *
1327
	 * @param string $hexstr
1328
	 * @return array
1329
	 */
1330
	function hexrgb($hexstr)
1331
	{
1332
		$int = hexdec($hexstr);
1333
1334
		return array('red' => 0xFF & ($int >> 0x10),
1335
			'green' => 0xFF & ($int >> 0x8),
1336
			'blue' => 0xFF & $int);
1337
	}
1338
1339
}
1340
1341
/**
1342
 * Php function for mysql old_password()
1343
 * provides backward compatibility for zero board4 which uses old_password() of mysql 4.1 earlier versions. 
1344
 * the function implemented by referring to the source codes of password.c file in mysql
1345
 *
1346
 * @param string $password
1347
 * @return string
1348
 */
1349
function mysql_pre4_hash_password($password)
1350
{
1351
	$nr = 1345345333;
1352
	$add = 7;
1353
	$nr2 = 0x12345671;
1354
1355
	settype($password, "string");
1356
1357
	for($i = 0; $i < strlen($password); $i++)
1358
	{
1359
		if($password[$i] == ' ' || $password[$i] == '\t')
1360
		{
1361
			continue;
1362
		}
1363
		$tmp = ord($password[$i]);
1364
		$nr ^= ((($nr & 63) + $add) * $tmp) + ($nr << 8);
1365
		$nr2 += ($nr2 << 8) ^ $nr;
1366
		$add += $tmp;
1367
	}
1368
	$result1 = sprintf("%08lx", $nr & ((1 << 31) - 1));
1369
	$result2 = sprintf("%08lx", $nr2 & ((1 << 31) - 1));
1370
1371
	if($result1 == '80000000')
1372
	{
1373
		$nr += 0x80000000;
1374
	}
1375
	if($result2 == '80000000')
1376
	{
1377
		$nr2 += 0x80000000;
1378
	}
1379
1380
	return sprintf("%08lx%08lx", $nr, $nr2);
1381
}
1382
1383
/**
1384
 * Return the requested script path
1385
 *
1386
 * @return string
1387
 */
1388
function getScriptPath()
1389
{
1390
	static $url = NULL;
1391
	if($url == NULL)
1392
	{
1393
		$script_path = filter_var($_SERVER['SCRIPT_NAME'], FILTER_SANITIZE_STRING);
1394
		$url = str_ireplace('/tools/', '/', preg_replace('/index.php.*/i', '', str_replace('\\', '/', $script_path)));
1395
	}
1396
	return $url;
1397
}
1398
1399
/**
1400
 * Return the requested script path
1401
 *
1402
 * @return string
1403
 */
1404
function getRequestUriByServerEnviroment()
1405
{
1406
	return str_replace('<', '&lt;', $_SERVER['REQUEST_URI']);
1407
}
1408
1409
/**
1410
 * PHP unescape function of javascript's escape
1411
 * Function converts an Javascript escaped string back into a string with specified charset (default is UTF-8).
1412
 * Modified function from http://pure-essence.net/stuff/code/utf8RawUrlDecode.phps
1413
 *
1414
 * @param string $source
1415
 * @return string
1416
 */
1417
function utf8RawUrlDecode($source)
1418
{
1419
	$decodedStr = '';
1420
	$pos = 0;
1421
	$len = strlen($source);
1422
	while($pos < $len)
1423
	{
1424
		$charAt = substr($source, $pos, 1);
1425
		if($charAt == '%')
1426
		{
1427
			$pos++;
1428
			$charAt = substr($source, $pos, 1);
1429
			if($charAt == 'u')
1430
			{
1431
				// we got a unicode character
1432
				$pos++;
1433
				$unicodeHexVal = substr($source, $pos, 4);
1434
				$unicode = hexdec($unicodeHexVal);
1435
				$decodedStr .= _code2utf($unicode);
1436
				$pos += 4;
1437
			}
1438
			else
1439
			{
1440
				// we have an escaped ascii character
1441
				$hexVal = substr($source, $pos, 2);
1442
				$decodedStr .= chr(hexdec($hexVal));
1443
				$pos += 2;
1444
			}
1445
		}
1446
		else
1447
		{
1448
			$decodedStr .= $charAt;
1449
			$pos++;
1450
		}
1451
	}
1452
	return $decodedStr;
1453
}
1454
1455
/**
1456
 * Returns utf-8 string of given code
1457
 *
1458
 * @param int $num
1459
 * @return string
1460
 */
1461
function _code2utf($num)
1462
{
1463
	if($num < 128)
1464
	{
1465
		return chr($num);
1466
	}
1467
	if($num < 2048)
1468
	{
1469
		return chr(($num >> 6) + 192) . chr(($num & 63) + 128);
1470
	}
1471
	if($num < 65536)
1472
	{
1473
		return chr(($num >> 12) + 224) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
1474
	}
1475
	if($num < 2097152)
1476
	{
1477
		return chr(($num >> 18) + 240) . chr((($num >> 12) & 63) + 128) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
1478
	}
1479
	return '';
1480
}
1481
1482
/**
1483
 * Get whether utf8 or not given string
1484
 *
1485
 * @param string $string
1486
 * @param bool $return_convert If set, returns converted string
1487
 * @param bool $urldecode
1488
 * @return bool|string
1489
 */
1490
function detectUTF8($string, $return_convert = FALSE, $urldecode = TRUE)
1491
{
1492
	if($urldecode)
1493
	{
1494
		$string = urldecode($string);
1495
	}
1496
1497
	$sample = iconv('utf-8', 'utf-8', $string);
1498
	$is_utf8 = (md5($sample) === md5($string));
1499
1500
	if(!$urldecode)
1501
	{
1502
		$string = urldecode($string);
1503
	}
1504
1505
	if($return_convert)
1506
	{
1507
		return ($is_utf8) ? $string : iconv('euc-kr', 'utf-8', $string);
1508
	}
1509
1510
	return $is_utf8;
1511
}
1512
1513
/**
1514
 * get json encoded string of data
1515
 *
1516
 * @param mixed $data
1517
 * @return string
1518
 */
1519
function json_encode2($data)
1520
{
1521
	switch(gettype($data))
1522
	{
1523
		case 'boolean':
1524
			return $data ? 'true' : 'false';
1525
		case 'integer':
1526
		case 'double':
1527
			return $data;
1528
		case 'string':
1529
			return '"' . strtr($data, array('\\' => '\\\\', '"' => '\\"')) . '"';
1530
		case 'object':
1531
			$data = get_object_vars($data);
1532
		case 'array':
1533
			$rel = FALSE; // relative array?
1534
			$key = array_keys($data);
1535
			foreach($key as $v)
1536
			{
1537
				if(!is_int($v))
1538
				{
1539
					$rel = TRUE;
1540
					break;
1541
				}
1542
			}
1543
1544
			$arr = array();
1545
			foreach($data as $k => $v)
1546
			{
1547
				$arr[] = ($rel ? '"' . strtr($k, array('\\' => '\\\\', '"' => '\\"')) . '":' : '') . json_encode2($v);
1548
			}
1549
1550
			return $rel ? '{' . join(',', $arr) . '}' : '[' . join(',', $arr) . ']';
1551
		default:
1552
			return '""';
1553
	}
1554
}
1555
1556
/**
1557
 * Get is current user crawler
1558
 *
1559
 * @param string $agent if set, use this value instead HTTP_USER_AGENT
1560
 * @return bool
1561
 */
1562
function isCrawler($agent = NULL)
1563
{
1564
	if(!$agent)
0 ignored issues
show
Bug Best Practice introduced by
The expression $agent 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...
1565
	{
1566
		$agent = $_SERVER['HTTP_USER_AGENT'];
1567
	}
1568
1569
	$check_agent = array('bot', 'spider', 'spyder', 'crawl', 'http://', 'google', 'yahoo', 'slurp', 'yeti', 'daum', 'teoma', 'fish', 'hanrss', 'facebook', 'yandex', 'infoseek', 'askjeeves', 'stackrambler');
1570
	$check_ip = array(
1571
		/*'211.245.21.110-211.245.21.119' mixsh is closed */
1572
	);
1573
1574
	foreach($check_agent as $str)
1575
	{
1576
		if(stristr($agent, $str) != FALSE)
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing stristr($agent, $str) of type string to the boolean FALSE. If you are specifically checking for a non-empty string, consider using the more explicit !== '' instead.
Loading history...
1577
		{
1578
			return TRUE;
1579
		}
1580
	}
1581
1582
	return IpFilter::filter($check_ip);
1583
}
1584
1585
/**
1586
 * Remove embed media for admin
1587
 *
1588
 * @param string $content
1589
 * @param int $writer_member_srl
1590
 * @return void
1591
 */
1592
function stripEmbedTagForAdmin(&$content, $writer_member_srl)
1593
{
1594
	if(!Context::get('is_logged'))
1595
	{
1596
		return;
1597
	}
1598
1599
	$oModuleModel = getModel('module');
1600
	$logged_info = Context::get('logged_info');
1601
1602
	if($writer_member_srl != $logged_info->member_srl && ($logged_info->is_admin == "Y" || $oModuleModel->isSiteAdmin($logged_info)))
1603
	{
1604
		if($writer_member_srl)
1605
		{
1606
			$oMemberModel = getModel('member');
1607
			$member_info = $oMemberModel->getMemberInfoByMemberSrl($writer_member_srl);
1608
			if($member_info->is_admin == "Y")
1609
			{
1610
				return;
1611
			}
1612
		}
1613
		$security_msg = "<div style='border: 1px solid #DDD; background: #FAFAFA; text-align:center; margin: 1em 0;'><p style='margin: 1em;'>" . Context::getLang('security_warning_embed') . "</p></div>";
1614
		$content = preg_replace('/<object[^>]+>(.*?<\/object>)?/is', $security_msg, $content);
1615
		$content = preg_replace('/<embed[^>]+>(\s*<\/embed>)?/is', $security_msg, $content);
1616
		$content = preg_replace('/<img[^>]+editor_component="multimedia_link"[^>]*>(\s*<\/img>)?/is', $security_msg, $content);
1617
	}
1618
1619
	return;
1620
}
1621
1622
/**
1623
 * Require pear
1624
 *
1625
 * @return void
1626
 */
1627
function requirePear()
1628
{
1629
	static $required = false;
1630
	if($required)
1631
	{
1632
		return;
1633
	}
1634
1635
	if(version_compare(PHP_VERSION, "5.3.0") < 0)
1636
	{
1637
		set_include_path(_XE_PATH_ . "libs/PEAR" . PATH_SEPARATOR . get_include_path());
1638
	}
1639
	else
1640
	{
1641
		set_include_path(_XE_PATH_ . "libs/PEAR.1.9.5" . PATH_SEPARATOR . get_include_path());
1642
	}
1643
1644
	$required = true;
1645
}
1646
1647
function checkCSRF()
1648
{
1649
	static $disable_csrf_token = null;
1650
1651
	if($_SERVER['REQUEST_METHOD'] != 'POST')
1652
	{
1653
		return FALSE;
1654
	}
1655
1656
	if($disable_csrf_token === null)
1657
	{
1658
		$db_info = Context::getDBinfo();
1659
		$disable_csrf_token = $db_info->disable_csrf_token;
1660
	}
1661
1662
	if($disable_csrf_token !== 'Y')
1663
	{
1664
		$csrf_token = ($_SERVER['HTTP_X_CSRF_TOKEN']) ? $_SERVER['HTTP_X_CSRF_TOKEN'] : $_POST['_token'];
1665
1666
		// Token
1667
		if(!$csrf_token || $_SESSION['csrf_token'] !== $csrf_token)
1668
		{
1669
			header("HTTP/1.1 403 Forbidden");
1670
			return FALSE;
1671
		}
1672
	}
1673
1674
	$default_url = Context::getDefaultUrl();
1675
	$referer = $_SERVER["HTTP_REFERER"];
1676
1677
	if(strpos($default_url, 'xn--') !== FALSE && strpos($referer, 'xn--') === FALSE)
1678
	{
1679
		require_once(_XE_PATH_ . 'libs/idna_convert/idna_convert.class.php');
1680
		$IDN = new idna_convert(array('idn_version' => 2008));
1681
		$referer = $IDN->encode($referer);
1682
	}
1683
1684
	$default_url = parse_url($default_url);
1685
	$referer = parse_url($referer);
1686
1687
	$oModuleModel = getModel('module');
1688
	$siteModuleInfo = $oModuleModel->getDefaultMid();
1689
1690
	if($siteModuleInfo->site_srl == 0)
1691
	{
1692
		if($default_url['host'] !== $referer['host'])
1693
		{
1694
			return FALSE;
1695
		}
1696
	}
1697
	else
1698
	{
1699
		$virtualSiteInfo = $oModuleModel->getSiteInfo($siteModuleInfo->site_srl);
1700
		if(strtolower($virtualSiteInfo->domain) != strtolower(Context::get('vid')) && !strstr(strtolower($virtualSiteInfo->domain), strtolower($referer['host'])))
1701
		{
1702
			return FALSE;
1703
		}
1704
	}
1705
1706
	return TRUE;
1707
}
1708
1709
/**
1710
 * menu exposure check by isShow column
1711
 * @param array $menu
1712
 * @return void
1713
 */
1714
function recurciveExposureCheck(&$menu)
1715
{
1716
	if(is_array($menu))
1717
	{
1718
		foreach($menu AS $key=>$value)
1719
		{
1720
			if(!$value['isShow'])
1721
			{
1722
				unset($menu[$key]);
1723
			}
1724
			if(is_array($value['list']) && count($value['list']) > 0)
1725
			{
1726
				recurciveExposureCheck($menu[$key]['list']);
1727
			}
1728
		}
1729
	}
1730
}
1731
1732
function changeValueInUrl($key, $requestKey, $dbKey, $urlName = 'success_return_url')
1733
{
1734
	if($requestKey != $dbKey)
1735
	{
1736
		$arrayUrl = parse_url(Context::get('success_return_url'));
1737
		if($arrayUrl['query'])
1738
		{
1739
			parse_str($arrayUrl['query'], $parsedStr);
1740
1741
			if(isset($parsedStr[$key]))
1742
			{
1743
				$parsedStr[$key] = $requestKey;
1744
				$successReturnUrl .= $arrayUrl['path'].'?'.http_build_query($parsedStr);
0 ignored issues
show
Bug introduced by
The variable $successReturnUrl 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...
1745
				Context::set($urlName, $successReturnUrl);
1746
			}
1747
		}
1748
	}
1749
}
1750
1751
/**
1752
 * Print raw html header
1753
 *
1754
 * @return void
1755
 */
1756
function htmlHeader()
1757
{
1758
	echo '<!DOCTYPE html>
1759
<html lang="ko">
1760
<head>
1761
<meta charset="utf-8" />
1762
</head>
1763
<body>';
1764
}
1765
1766
/**
1767
 * Print raw html footer
1768
 *
1769
 * @return void
1770
 */
1771
function htmlFooter()
1772
{
1773
	echo '</body></html>';
1774
}
1775
1776
/**
1777
 * Print raw alert message script
1778
 *
1779
 * @param string $msg
1780
 * @return void
1781
 */
1782
function alertScript($msg)
1783
{
1784
	if(!$msg)
1785
	{
1786
		return;
1787
	}
1788
1789
	echo '<script type="text/javascript">
1790
//<![CDATA[
1791
alert("' . $msg . '");
1792
//]]>
1793
</script>';
1794
}
1795
1796
/**
1797
 * Print raw close window script
1798
 *
1799
 * @return void
1800
 */
1801
function closePopupScript()
1802
{
1803
	echo '<script type="text/javascript">
1804
//<![CDATA[
1805
window.close();
1806
//]]>
1807
</script>';
1808
}
1809
1810
/**
1811
 * Print raw reload script
1812
 *
1813
 * @param bool $isOpener
1814
 * @return void
1815
 */
1816
function reload($isOpener = FALSE)
1817
{
1818
	$reloadScript = $isOpener ? 'window.opener.location.reload()' : 'document.location.reload()';
1819
1820
	echo '<script type="text/javascript">
1821
//<![CDATA[
1822
' . $reloadScript . '
1823
//]]>
1824
</script>';
1825
}
1826
1827
/* End of file func.inc.php */
1828
/* Location: ./config/func.inc.php */
1829