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 ( 594959...601687 )
by gyeong-won
08:31
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
 * Put a given tail after trimming string to the specified size
499
 *
500
 * @param string $string The original string to trim
501
 * @param int $cut_size The size to be
502
 * @param string $tail Tail to put in the end of the string after trimming
503
 * @return string
504
 */
505
function cut_str($string, $cut_size = 0, $tail = '...')
506
{
507
	if($cut_size < 1 || !$string)
508
	{
509
		return $string;
510
	}
511
512
	if($GLOBALS['use_mb_strimwidth'] || function_exists('mb_strimwidth'))
513
	{
514
		$GLOBALS['use_mb_strimwidth'] = TRUE;
515
		return mb_strimwidth($string, 0, $cut_size + 4, $tail, 'utf-8');
516
	}
517
518
	$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);
519
	$max_width = $cut_size * $chars[0] / 2;
520
	$char_width = 0;
521
522
	$string_length = strlen($string);
523
	$char_count = 0;
524
525
	$idx = 0;
526
	while($idx < $string_length && $char_count < $cut_size && $char_width <= $max_width)
527
	{
528
		$c = ord(substr($string, $idx, 1));
529
		$char_count++;
530
		if($c < 128)
531
		{
532
			$char_width += (int) $chars[$c - 32];
533
			$idx++;
534
		}
535
		else if(191 < $c && $c < 224)
536
		{
537
			$char_width += $chars[4];
538
			$idx += 2;
539
		}
540
		else
541
		{
542
			$char_width += $chars[0];
543
			$idx += 3;
544
		}
545
	}
546
547
	$output = substr($string, 0, $idx);
548
	if(strlen($output) < $string_length)
549
	{
550
		$output .= $tail;
551
	}
552
553
	return $output;
554
}
555
556
/**
557
 * Get a time gap between server's timezone and XE's timezone
558
 *
559
 * @return int
560
 */
561
function zgap()
562
{
563
	$time_zone = $GLOBALS['_time_zone'];
564
	if($time_zone < 0)
565
	{
566
		$to = -1;
567
	}
568
	else
569
	{
570
		$to = 1;
571
	}
572
573
	$t_hour = substr($time_zone, 1, 2) * $to;
574
	$t_min = substr($time_zone, 3, 2) * $to;
575
576
	$server_time_zone = date("O");
577
	if($server_time_zone < 0)
578
	{
579
		$so = -1;
580
	}
581
	else
582
	{
583
		$so = 1;
584
	}
585
586
	$c_hour = substr($server_time_zone, 1, 2) * $so;
587
	$c_min = substr($server_time_zone, 3, 2) * $so;
588
589
	$g_min = $t_min - $c_min;
590
	$g_hour = $t_hour - $c_hour;
591
592
	$gap = $g_min * 60 + $g_hour * 60 * 60;
593
	return $gap;
594
}
595
596
/**
597
 * YYYYMMDDHHIISS format changed to unix time value
598
 *
599
 * @param string $str Time value in format of YYYYMMDDHHIISS
600
 * @return int
601
 */
602
function ztime($str)
603
{
604
	if(!$str)
605
	{
606
		return;
607
	}
608
609
	$hour = (int) substr($str, 8, 2);
610
	$min = (int) substr($str, 10, 2);
611
	$sec = (int) substr($str, 12, 2);
612
	$year = (int) substr($str, 0, 4);
613
	$month = (int) substr($str, 4, 2);
614
	$day = (int) substr($str, 6, 2);
615
	if(strlen($str) <= 8)
616
	{
617
		$gap = 0;
618
	}
619
	else
620
	{
621
		$gap = zgap();
622
	}
623
624
	return mktime($hour, $min, $sec, $month ? $month : 1, $day ? $day : 1, $year) + $gap;
625
}
626
627
/**
628
 * 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.
629
 *
630
 * @param string $date Time value in format of YYYYMMDDHHIISS
631
 * @param string $format If gap is within a day, returns this format.
632
 * @return string
633
 */
634
function getTimeGap($date, $format = 'Y.m.d')
635
{
636
	$gap = $_SERVER['REQUEST_TIME'] + zgap() - ztime($date);
637
638
	$lang_time_gap = Context::getLang('time_gap');
639
	if($gap < 60)
640
	{
641
		$buff = sprintf($lang_time_gap['min'], (int) ($gap / 60) + 1);
642
	}
643
	elseif($gap < 60 * 60)
644
	{
645
		$buff = sprintf($lang_time_gap['mins'], (int) ($gap / 60) + 1);
646
	}
647 View Code Duplication
	elseif($gap < 60 * 60 * 2)
648
	{
649
		$buff = sprintf($lang_time_gap['hour'], (int) ($gap / 60 / 60) + 1);
650
	}
651 View Code Duplication
	elseif($gap < 60 * 60 * 24)
652
	{
653
		$buff = sprintf($lang_time_gap['hours'], (int) ($gap / 60 / 60) + 1);
654
	}
655
	else
656
	{
657
		$buff = zdate($date, $format);
658
	}
659
660
	return $buff;
661
}
662
663
/**
664
 * Name of the month return
665
 *
666
 * @param int $month Month
667
 * @param boot $short If set, returns short string
668
 * @return string
669
 */
670
function getMonthName($month, $short = TRUE)
671
{
672
	$short_month = array('', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
673
	$long_month = array('', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
674
	return !$short ? $long_month[$month] : $short_month[$month];
675
}
676
677
/**
678
 * Change the time format YYYYMMDDHHIISS to the user defined format
679
 *
680
 * @param string|int $str YYYYMMDDHHIISS format time values
681
 * @param string $format Time format of php date() function
682
 * @param bool $conversion Means whether to convert automatically according to the language
683
 * @return string
684
 */
685
function zdate($str, $format = 'Y-m-d H:i:s', $conversion = TRUE)
686
{
687
	// return null if no target time is specified
688
	if(!$str)
689
	{
690
		return;
691
	}
692
	// convert the date format according to the language
693
	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...
694
	{
695
		switch(Context::getLangType())
696
		{
697
			case 'en' :
698
			case 'es' :
699 View Code Duplication
				if($format == 'Y-m-d')
700
				{
701
					$format = 'M d, Y';
702
				}
703
				elseif($format == 'Y-m-d H:i:s')
704
				{
705
					$format = 'M d, Y H:i:s';
706
				}
707
				elseif($format == 'Y-m-d H:i')
708
				{
709
					$format = 'M d, Y H:i';
710
				}
711
				break;
712
			case 'vi' :
713 View Code Duplication
				if($format == 'Y-m-d')
714
				{
715
					$format = 'd-m-Y';
716
				}
717
				elseif($format == 'Y-m-d H:i:s')
718
				{
719
					$format = 'H:i:s d-m-Y';
720
				}
721
				elseif($format == 'Y-m-d H:i')
722
				{
723
					$format = 'H:i d-m-Y';
724
				}
725
				break;
726
		}
727
	}
728
729
	// If year value is less than 1970, handle it separately.
730
	if((int) substr($str, 0, 4) < 1970)
731
	{
732
		$hour = (int) substr($str, 8, 2);
733
		$min = (int) substr($str, 10, 2);
734
		$sec = (int) substr($str, 12, 2);
735
		$year = (int) substr($str, 0, 4);
736
		$month = (int) substr($str, 4, 2);
737
		$day = (int) substr($str, 6, 2);
738
739
		$trans = array(
740
			'Y' => $year,
741
			'y' => sprintf('%02d', $year % 100),
742
			'm' => sprintf('%02d', $month),
743
			'n' => $month,
744
			'd' => sprintf('%02d', $day),
745
			'j' => $day,
746
			'G' => $hour,
747
			'H' => sprintf('%02d', $hour),
748
			'g' => $hour % 12,
749
			'h' => sprintf('%02d', $hour % 12),
750
			'i' => sprintf('%02d', $min),
751
			's' => sprintf('%02d', $sec),
752
			'M' => getMonthName($month),
753
			'F' => getMonthName($month, FALSE)
754
		);
755
756
		$string = strtr($format, $trans);
757
	}
758
	else
759
	{
760
		// if year value is greater than 1970, get unixtime by using ztime() for date() function's argument. 
761
		$string = date($format, ztime($str));
762
	}
763
	// change day and am/pm for each language
764
	$unit_week = Context::getLang('unit_week');
765
	$unit_meridiem = Context::getLang('unit_meridiem');
766
	$string = str_replace(array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'), $unit_week, $string);
767
	$string = str_replace(array('am', 'pm', 'AM', 'PM'), $unit_meridiem, $string);
768
	return $string;
769
}
770
771
/**
772
 * Returns encoded value of given email address for email scraping
773
 *
774
 * @param string $email The email
775
 * @return string
776
 */
777
function getEncodeEmailAddress($email)
778
{
779
	$return = '';
780
	for($i = 0, $c = strlen($email); $i < $c; $i++)
781
	{
782
		$return .= '&#' . (rand(0, 1) == 0 ? ord($email[$i]) : 'X' . dechex(ord($email[$i]))) . ';';
783
	}
784
	return $return;
785
}
786
787
/**
788
 * Prints debug messages 
789
 *
790
 * Display $buff contents into the file ./files/_debug_message.php.
791
 * You can see the file on your prompt by command: tail-f./files/_debug_message.php
792
 *
793
 * @param mixed $debug_output Target object to be printed
794
 * @param bool $display_option boolean Flag whether to print seperator (default:true)
795
 * @param string $file Target file name
796
 * @return void
797
 */
798
function debugPrint($debug_output = NULL, $display_option = TRUE, $file = '_debug_message.php')
799
{
800
	static $debug_file;
801
802
	if(!(__DEBUG__ & 1))
803
	{
804
		return;
805
	}
806
807
	static $firephp;
808
	$bt = debug_backtrace();
809
	if(is_array($bt))
810
	{
811
		$bt_debug_print = array_shift($bt);
812
		$bt_called_function = array_shift($bt);
813
	}
814
	$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...
815
	$line_num = $bt_debug_print['line'];
816
	$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...
817
818
	if(__DEBUG_OUTPUT__ == 2 && version_compare(PHP_VERSION, '6.0.0') === -1)
819
	{
820
		if(!isset($firephp))
821
		{
822
			$firephp = FirePHP::getInstance(TRUE);
823
		}
824
		$type = FirePHP::INFO;
825
826
		$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()));
827
828
		// Check a FirePHP option
829
		if($display_option === 'TABLE')
830
		{
831
			$label = $display_option;
832
		}
833
		if($display_option === 'ERROR')
834
		{
835
			$type = $display_option;
836
		}
837
		// Check if the IP specified by __DEBUG_PROTECT__ option is same as the access IP.
838
		if(__DEBUG_PROTECT__ === 1 && __DEBUG_PROTECT_IP__ != $_SERVER['REMOTE_ADDR'])
839
		{
840
			$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';
841
			$label = NULL;
842
		}
843
844
		$firephp->fb($debug_output, $label, $type);
845
	}
846
	else
847
	{
848
		if(__DEBUG_PROTECT__ === 1 && __DEBUG_PROTECT_IP__ != $_SERVER['REMOTE_ADDR'])
849
		{
850
			return;
851
		}
852
853
		$print = array();
854
		if(!$debug_file)
855
		{
856
			$debug_file = _XE_PATH_ . 'files/' . $file;
857
		}
858
		if(!file_exists($debug_file)) $print[] = '<?php exit() ?>';
859
860
		if($display_option === TRUE || $display_option === 'ERROR')
861
		{
862
			$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()));;
863
			$print[] = str_repeat('=', 80);
864
		}
865
		$type = gettype($debug_output);
866
		if(!in_array($type, array('array', 'object', 'resource')))
867
		{
868
			if($display_option === 'ERROR')
869
			{
870
				$print[] = 'ERROR : ' . var_export($debug_output, TRUE);
871
			}
872
			else
873
			{
874
				$print[] = 'DEBUG : ' . $type . '(' . var_export($debug_output, TRUE) . ')';
875
			}
876
		}
877
		else
878
		{
879
			$print[] = 'DEBUG : ' . trim(preg_replace('/\r?\n/', "\n" . '        ', print_r($debug_output, true)));
880
		}
881
		$backtrace_args = defined('\DEBUG_BACKTRACE_IGNORE_ARGS') ? \DEBUG_BACKTRACE_IGNORE_ARGS : 0;
882
		$backtrace = debug_backtrace($backtrace_args);
883
884 View Code Duplication
		if(count($backtrace) > 1 && $backtrace[1]['function'] === 'debugPrint' && !$backtrace[1]['class'])
885
		{
886
			array_shift($backtrace);
887
		}
888
		foreach($backtrace as $val)
889
		{
890
			$print[] = '        - ' . $val['file'] . ' : ' . $val['line'];
891
		}
892
		$print[] = PHP_EOL;
893
		@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...
894
	}
895
}
896
897
/**
898
 * @param string $type query, trigger
899
 * @param float $elapsed_time
900
 * @param object $obj
901
 */
902
function writeSlowlog($type, $elapsed_time, $obj)
903
{
904
	if(!__LOG_SLOW_TRIGGER__ && !__LOG_SLOW_ADDON__ && !__LOG_SLOW_WIDGET__ && !__LOG_SLOW_QUERY__) return;
905
906
	static $log_filename = array(
907
		'query' => 'files/_slowlog_query.php',
908
		'trigger' => 'files/_slowlog_trigger.php',
909
		'addon' => 'files/_slowlog_addon.php',
910
		'widget' => 'files/_slowlog_widget.php'
911
	);
912
	$write_file = true;
913
914
	$log_file = _XE_PATH_ . $log_filename[$type];
915
916
	$buff = array();
917
	$buff[] = '<?php exit(); ?>';
918
	$buff[] = date('c');
919
920
	if($type == 'trigger' && __LOG_SLOW_TRIGGER__ > 0 && $elapsed_time > __LOG_SLOW_TRIGGER__)
921
	{
922
		$buff[] = "\tCaller : " . $obj->caller;
923
		$buff[] = "\tCalled : " . $obj->called;
924
	}
925
	else if($type == 'addon' && __LOG_SLOW_ADDON__ > 0 && $elapsed_time > __LOG_SLOW_ADDON__)
926
	{
927
		$buff[] = "\tAddon : " . $obj->called;
928
		$buff[] = "\tCalled position : " . $obj->caller;
929
	}
930
	else if($type == 'widget' && __LOG_SLOW_WIDGET__ > 0 && $elapsed_time > __LOG_SLOW_WIDGET__)
931
	{
932
		$buff[] = "\tWidget : " . $obj->called;
933
	}
934
	else if($type == 'query' && __LOG_SLOW_QUERY__ > 0 && $elapsed_time > __LOG_SLOW_QUERY__)
935
	{
936
937
		$buff[] = $obj->query;
938
		$buff[] = "\tQuery ID   : " . $obj->query_id;
939
		$buff[] = "\tCaller     : " . $obj->caller;
940
		$buff[] = "\tConnection : " . $obj->connection;
941
	}
942
	else
943
	{
944
		$write_file = false;
945
	}
946
947
	if($write_file)
948
	{
949
		$buff[] = sprintf("\t%0.6f sec", $elapsed_time);
950
		$buff[] = PHP_EOL . PHP_EOL;
951
		file_put_contents($log_file, implode(PHP_EOL, $buff), FILE_APPEND);
952
	}
953
954
	if($type != 'query')
955
	{
956
		$trigger_args = $obj;
957
		$trigger_args->_log_type = $type;
958
		$trigger_args->_elapsed_time = $elapsed_time;
959
		ModuleHandler::triggerCall('XE.writeSlowlog', 'after', $trigger_args);
960
	}
961
}
962
963
/**
964
 * @param void
965
 */
966
function flushSlowlog()
967
{
968
	$trigger_args = new stdClass();
969
	$trigger_args->_log_type = 'flush';
970
	$trigger_args->_elapsed_time = 0;
971
	ModuleHandler::triggerCall('XE.writeSlowlog', 'after', $trigger_args);
972
}
973
974
/**
975
 * microtime() return
976
 *
977
 * @return float
978
 */
979
function getMicroTime()
980
{
981
	list($time1, $time2) = explode(' ', microtime());
982
	return (float) $time1 + (float) $time2;
983
}
984
985
/**
986
 * Delete the second object vars from the first argument
987
 *
988
 * @param object $target_obj An original object
989
 * @param object $del_obj BaseObject vars to delete from the original object
990
 * @return object
991
 */
992
function delObjectVars($target_obj, $del_obj)
993
{
994
	if(!is_object($target_obj))
995
	{
996
		return;
997
	}
998
	if(!is_object($del_obj))
999
	{
1000
		return;
1001
	}
1002
1003
	$target_vars = get_object_vars($target_obj);
1004
	$del_vars = get_object_vars($del_obj);
1005
1006
	$target = array_keys($target_vars);
1007
	$del = array_keys($del_vars);
1008
	if(!count($target) || !count($del))
1009
	{
1010
		return $target_obj;
1011
	}
1012
1013
	$return_obj = new stdClass();
1014
1015
	$target_count = count($target);
1016
	for($i = 0; $i < $target_count; $i++)
1017
	{
1018
		$target_key = $target[$i];
1019
		if(!in_array($target_key, $del))
1020
		{
1021
			$return_obj->{$target_key} = $target_obj->{$target_key};
1022
		}
1023
	}
1024
1025
	return $return_obj;
1026
}
1027
1028
function getDestroyXeVars(&$vars)
1029
{
1030
	$del_vars = array('error_return_url', 'success_return_url', 'ruleset', 'xe_validator_id');
1031
1032
	foreach($del_vars as $var)
1033
	{
1034
		if(is_array($vars)) unset($vars[$var]);
1035
		else if(is_object($vars)) unset($vars->$var);
1036
	}
1037
1038
	return $vars;
1039
}
1040
1041
/**
1042
 * Change error_handing to debugPrint on php5 higher 
1043
 *
1044
 * @param int $errno
1045
 * @param string $errstr
1046
 * @param string $file
1047
 * @param int $line
1048
 * @return void
1049
 */
1050
function handleError($errno, $errstr, $file, $line)
1051
{
1052
	if(!__DEBUG__)
1053
	{
1054
		return;
1055
	}
1056
	$errors = array(E_USER_ERROR, E_ERROR, E_PARSE);
1057
	if(!in_array($errno, $errors))
1058
	{
1059
		return;
1060
	}
1061
1062
	$output = sprintf("Fatal error : %s - %d", $file, $line);
1063
	$output .= sprintf("%d - %s", $errno, $errstr);
1064
1065
	debugPrint($output);
1066
}
1067
1068
/**
1069
 * Trim a given number to a fiven size recursively
1070
 *
1071
 * @param int $no A given number
1072
 * @param int $size A given digits
1073
 */
1074
function getNumberingPath($no, $size = 3)
1075
{
1076
	$mod = pow(10, $size);
1077
	$output = sprintf('%0' . $size . 'd/', $no % $mod);
1078
	if($no >= $mod)
1079
	{
1080
		$output .= getNumberingPath((int) $no / $mod, $size);
1081
	}
1082
	return $output;
1083
}
1084
1085
/**
1086
 * Decode the URL in Korean
1087
 *
1088
 * @param string $str The url
1089
 * @return string
1090
 */
1091
function url_decode($str)
1092
{
1093
	return preg_replace('/%u([[:alnum:]]{4})/', '&#x\\1;', $str);
1094
}
1095
1096
function purifierHtml(&$content)
1097
{
1098
	require_once(_XE_PATH_ . 'classes/security/Purifier.class.php');
1099
	$oPurifier = Purifier::getInstance();
1100
	$oPurifier->purify($content);
1101
}
1102
1103
/**
1104
 * Pre-block the codes which may be hacking attempts
1105
 *
1106
 * @param string $content Taget content
1107
 * @return string
1108
 */
1109
function removeHackTag($content)
1110
{
1111
	require_once(_XE_PATH_ . 'classes/security/EmbedFilter.class.php');
1112
	$oEmbedFilter = EmbedFilter::getInstance();
1113
	$oEmbedFilter->check($content);
1114
1115
	purifierHtml($content);
1116
1117
	// change the specific tags to the common texts
1118
	$content = preg_replace('@<(\/?(?:html|body|head|title|meta|base|link|script|style|applet)(/*).*?>)@i', '&lt;$1', $content);
1119
1120
	/**
1121
	 * Remove codes to abuse the admin session in src by tags of imaages and video postings
1122
	 * - Issue reported by Sangwon Kim
1123
	 */
1124
	$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);
1125
1126
	$content = checkXmpTag($content);
1127
	$content = blockWidgetCode($content);
1128
1129
	return $content;
1130
}
1131
1132
/**
1133
 * blocking widget code
1134
 *
1135
 * @param string $content Taget content
1136
 * @return string
1137
 **/
1138
function blockWidgetCode($content)
1139
{
1140
	$content = preg_replace('/(<(?:img|div)(?:[^>]*))(widget)(?:(=([^>]*?)>))/is', '$1blocked-widget$3', $content);
1141
1142
	return $content;
1143
}
1144
1145
/**
1146
 * check uploaded file which may be hacking attempts
1147
 *
1148
 * @param string $file Taget file path
1149
 * @return bool
1150
 */
1151
function checkUploadedFile($file)
1152
{
1153
	require_once(_XE_PATH_ . 'classes/security/UploadFileFilter.class.php');
1154
	return UploadFileFilter::check($file);
1155
}
1156
1157
/**
1158
 * Check xmp tag, close it.
1159
 *
1160
 * @param string $content Target content
1161
 * @return string
1162
 */
1163
function checkXmpTag($content)
1164
{
1165
	$content = preg_replace('@<(/?)xmp.*?>@i', '<\1xmp>', $content);
1166
1167
	if(($start_xmp = strrpos($content, '<xmp>')) !== FALSE)
1168
	{
1169
		if(($close_xmp = strrpos($content, '</xmp>')) === FALSE)
1170
		{
1171
			$content .= '</xmp>';
1172
		}
1173
		else if($close_xmp < $start_xmp)
1174
		{
1175
			$content .= '</xmp>';
1176
		}
1177
	}
1178
1179
	return $content;
1180
}
1181
1182
/**
1183
 * Remove src hack(preg_replace_callback)
1184
 *
1185
 * @param array $match
1186
 * @return string
1187
 */
1188
function removeSrcHack($match)
1189
{
1190
	$tag = strtolower($match[2]);
1191
1192
	// xmp tag ?뺣━
1193
	if($tag == 'xmp')
1194
	{
1195
		return "<{$match[1]}xmp>";
1196
	}
1197
	if($match[1])
1198
	{
1199
		return $match[0];
1200
	}
1201
	if($match[4])
1202
	{
1203
		$match[4] = ' ' . $match[4];
1204
	}
1205
1206
	$attrs = array();
1207
	if(preg_match_all('/([\w:-]+)\s*=(?:\s*(["\']))?(?(2)(.*?)\2|([^ ]+))/s', $match[3], $m))
1208
	{
1209
		foreach($m[1] as $idx => $name)
1210
		{
1211
			if(strlen($name) >= 2 && substr_compare($name, 'on', 0, 2) === 0)
1212
			{
1213
				continue;
1214
			}
1215
1216
			$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]);
1217
			$val = preg_replace('/^\s+|[\t\n\r]+/', '', $val);
1218
1219
			if(preg_match('/^[a-z]+script:/i', $val))
1220
			{
1221
				continue;
1222
			}
1223
1224
			$attrs[$name] = $val;
1225
		}
1226
	}
1227
1228
	$filter_arrts = array('style', 'src', 'href');
1229
1230
	if($tag === 'object') array_push($filter_arrts, 'data');
1231
	if($tag === 'param') array_push($filter_arrts, 'value');
1232
1233
	foreach($filter_arrts as $attr)
1234
	{
1235
		if(!isset($attrs[$attr])) continue;
1236
1237
		$attr_value = rawurldecode($attrs[$attr]);
1238
		$attr_value = htmlspecialchars_decode($attr_value, ENT_COMPAT);
1239
		$attr_value = preg_replace('/\s+|[\t\n\r]+/', '', $attr_value);
1240
		if(preg_match('@(\?|&|;)(act=(\w+))@i', $attr_value, $m) && $m[3] !== 'procFileDownload')
1241
		{
1242
			unset($attrs[$attr]);
1243
		}
1244
	}
1245
1246
	if(isset($attrs['style']) && preg_match('@(?:/\*|\*/|\n|:\s*expression\s*\()@i', $attrs['style']))
1247
	{
1248
		unset($attrs['style']);
1249
	}
1250
1251
	$attr = array();
1252
	foreach($attrs as $name => $val)
1253
	{
1254
		if($tag == 'object' || $tag == 'embed' || $tag == 'a')
1255
		{
1256
			$attribute = strtolower(trim($name));
1257
			if($attribute == 'data' || $attribute == 'src' || $attribute == 'href')
1258
			{
1259
				if(stripos($val, 'data:') === 0)
1260
				{
1261
					continue;
1262
				}
1263
			}
1264
		}
1265
1266
		if($tag == 'img')
1267
		{
1268
			$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...
1269
			if(stripos($val, 'data:') === 0)
1270
			{
1271
				continue;
1272
			}
1273
		}
1274
		$val = str_replace('"', '&quot;', $val);
1275
		$attr[] = $name . "=\"{$val}\"";
1276
	}
1277
	$attr = count($attr) ? ' ' . implode(' ', $attr) : '';
1278
1279
	return "<{$match[1]}{$tag}{$attr}{$match[4]}>";
1280
}
1281
1282
// convert hexa value to RGB
1283
if(!function_exists('hexrgb'))
1284
{
1285
1286
	/**
1287
	 * Convert hexa value to RGB
1288
	 *
1289
	 * @param string $hexstr
1290
	 * @return array
1291
	 */
1292
	function hexrgb($hexstr)
1293
	{
1294
		$int = hexdec($hexstr);
1295
1296
		return array('red' => 0xFF & ($int >> 0x10),
1297
			'green' => 0xFF & ($int >> 0x8),
1298
			'blue' => 0xFF & $int);
1299
	}
1300
1301
}
1302
1303
/**
1304
 * Php function for mysql old_password()
1305
 * provides backward compatibility for zero board4 which uses old_password() of mysql 4.1 earlier versions. 
1306
 * the function implemented by referring to the source codes of password.c file in mysql
1307
 *
1308
 * @param string $password
1309
 * @return string
1310
 */
1311
function mysql_pre4_hash_password($password)
1312
{
1313
	$nr = 1345345333;
1314
	$add = 7;
1315
	$nr2 = 0x12345671;
1316
1317
	settype($password, "string");
1318
1319
	for($i = 0; $i < strlen($password); $i++)
1320
	{
1321
		if($password[$i] == ' ' || $password[$i] == '\t')
1322
		{
1323
			continue;
1324
		}
1325
		$tmp = ord($password[$i]);
1326
		$nr ^= ((($nr & 63) + $add) * $tmp) + ($nr << 8);
1327
		$nr2 += ($nr2 << 8) ^ $nr;
1328
		$add += $tmp;
1329
	}
1330
	$result1 = sprintf("%08lx", $nr & ((1 << 31) - 1));
1331
	$result2 = sprintf("%08lx", $nr2 & ((1 << 31) - 1));
1332
1333
	if($result1 == '80000000')
1334
	{
1335
		$nr += 0x80000000;
1336
	}
1337
	if($result2 == '80000000')
1338
	{
1339
		$nr2 += 0x80000000;
1340
	}
1341
1342
	return sprintf("%08lx%08lx", $nr, $nr2);
1343
}
1344
1345
/**
1346
 * Return the requested script path
1347
 *
1348
 * @return string
1349
 */
1350
function getScriptPath()
1351
{
1352
	static $url = NULL;
1353
	if($url == NULL)
1354
	{
1355
		$script_path = filter_var($_SERVER['SCRIPT_NAME'], FILTER_SANITIZE_STRING);
1356
		$url = str_ireplace('/tools/', '/', preg_replace('/index.php.*/i', '', str_replace('\\', '/', $script_path)));
1357
	}
1358
	return $url;
1359
}
1360
1361
/**
1362
 * Return the requested script path
1363
 *
1364
 * @return string
1365
 */
1366
function getRequestUriByServerEnviroment()
1367
{
1368
	return str_replace('<', '&lt;', $_SERVER['REQUEST_URI']);
1369
}
1370
1371
/**
1372
 * PHP unescape function of javascript's escape
1373
 * Function converts an Javascript escaped string back into a string with specified charset (default is UTF-8).
1374
 * Modified function from http://pure-essence.net/stuff/code/utf8RawUrlDecode.phps
1375
 *
1376
 * @param string $source
1377
 * @return string
1378
 */
1379
function utf8RawUrlDecode($source)
1380
{
1381
	$decodedStr = '';
1382
	$pos = 0;
1383
	$len = strlen($source);
1384
	while($pos < $len)
1385
	{
1386
		$charAt = substr($source, $pos, 1);
1387
		if($charAt == '%')
1388
		{
1389
			$pos++;
1390
			$charAt = substr($source, $pos, 1);
1391
			if($charAt == 'u')
1392
			{
1393
				// we got a unicode character
1394
				$pos++;
1395
				$unicodeHexVal = substr($source, $pos, 4);
1396
				$unicode = hexdec($unicodeHexVal);
1397
				$decodedStr .= _code2utf($unicode);
1398
				$pos += 4;
1399
			}
1400
			else
1401
			{
1402
				// we have an escaped ascii character
1403
				$hexVal = substr($source, $pos, 2);
1404
				$decodedStr .= chr(hexdec($hexVal));
1405
				$pos += 2;
1406
			}
1407
		}
1408
		else
1409
		{
1410
			$decodedStr .= $charAt;
1411
			$pos++;
1412
		}
1413
	}
1414
	return $decodedStr;
1415
}
1416
1417
/**
1418
 * Returns utf-8 string of given code
1419
 *
1420
 * @param int $num
1421
 * @return string
1422
 */
1423
function _code2utf($num)
1424
{
1425
	if($num < 128)
1426
	{
1427
		return chr($num);
1428
	}
1429
	if($num < 2048)
1430
	{
1431
		return chr(($num >> 6) + 192) . chr(($num & 63) + 128);
1432
	}
1433
	if($num < 65536)
1434
	{
1435
		return chr(($num >> 12) + 224) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
1436
	}
1437
	if($num < 2097152)
1438
	{
1439
		return chr(($num >> 18) + 240) . chr((($num >> 12) & 63) + 128) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
1440
	}
1441
	return '';
1442
}
1443
1444
/**
1445
 * Get whether utf8 or not given string
1446
 *
1447
 * @param string $string
1448
 * @param bool $return_convert If set, returns converted string
1449
 * @param bool $urldecode
1450
 * @return bool|string
1451
 */
1452
function detectUTF8($string, $return_convert = FALSE, $urldecode = TRUE)
1453
{
1454
	if($urldecode)
1455
	{
1456
		$string = urldecode($string);
1457
	}
1458
1459
	$sample = iconv('utf-8', 'utf-8', $string);
1460
	$is_utf8 = (md5($sample) === md5($string));
1461
1462
	if(!$urldecode)
1463
	{
1464
		$string = urldecode($string);
1465
	}
1466
1467
	if($return_convert)
1468
	{
1469
		return ($is_utf8) ? $string : iconv('euc-kr', 'utf-8', $string);
1470
	}
1471
1472
	return $is_utf8;
1473
}
1474
1475
/**
1476
 * get json encoded string of data
1477
 *
1478
 * @param mixed $data
1479
 * @return string
1480
 */
1481
function json_encode2($data)
1482
{
1483
	switch(gettype($data))
1484
	{
1485
		case 'boolean':
1486
			return $data ? 'true' : 'false';
1487
		case 'integer':
1488
		case 'double':
1489
			return $data;
1490
		case 'string':
1491
			return '"' . strtr($data, array('\\' => '\\\\', '"' => '\\"')) . '"';
1492
		case 'object':
1493
			$data = get_object_vars($data);
1494
		case 'array':
1495
			$rel = FALSE; // relative array?
1496
			$key = array_keys($data);
1497
			foreach($key as $v)
1498
			{
1499
				if(!is_int($v))
1500
				{
1501
					$rel = TRUE;
1502
					break;
1503
				}
1504
			}
1505
1506
			$arr = array();
1507
			foreach($data as $k => $v)
1508
			{
1509
				$arr[] = ($rel ? '"' . strtr($k, array('\\' => '\\\\', '"' => '\\"')) . '":' : '') . json_encode2($v);
1510
			}
1511
1512
			return $rel ? '{' . join(',', $arr) . '}' : '[' . join(',', $arr) . ']';
1513
		default:
1514
			return '""';
1515
	}
1516
}
1517
1518
/**
1519
 * Get is current user crawler
1520
 *
1521
 * @param string $agent if set, use this value instead HTTP_USER_AGENT
1522
 * @return bool
1523
 */
1524
function isCrawler($agent = NULL)
1525
{
1526
	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...
1527
	{
1528
		$agent = $_SERVER['HTTP_USER_AGENT'];
1529
	}
1530
1531
	$check_agent = array('bot', 'spider', 'spyder', 'crawl', 'http://', 'google', 'yahoo', 'slurp', 'yeti', 'daum', 'teoma', 'fish', 'hanrss', 'facebook', 'yandex', 'infoseek', 'askjeeves', 'stackrambler');
1532
	$check_ip = array(
1533
		/*'211.245.21.110-211.245.21.119' mixsh is closed */
1534
	);
1535
1536
	foreach($check_agent as $str)
1537
	{
1538
		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...
1539
		{
1540
			return TRUE;
1541
		}
1542
	}
1543
1544
	return IpFilter::filter($check_ip);
1545
}
1546
1547
/**
1548
 * Remove embed media for admin
1549
 *
1550
 * @param string $content
1551
 * @param int $writer_member_srl
1552
 * @return void
1553
 */
1554
function stripEmbedTagForAdmin(&$content, $writer_member_srl)
1555
{
1556
	if(!Context::get('is_logged'))
1557
	{
1558
		return;
1559
	}
1560
1561
	$oModuleModel = getModel('module');
1562
	$logged_info = Context::get('logged_info');
1563
1564
	if($writer_member_srl != $logged_info->member_srl && ($logged_info->is_admin == "Y" || $oModuleModel->isSiteAdmin($logged_info)))
1565
	{
1566
		if($writer_member_srl)
1567
		{
1568
			$oMemberModel = getModel('member');
1569
			$member_info = $oMemberModel->getMemberInfoByMemberSrl($writer_member_srl);
1570
			if($member_info->is_admin == "Y")
1571
			{
1572
				return;
1573
			}
1574
		}
1575
		$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>";
1576
		$content = preg_replace('/<object[^>]+>(.*?<\/object>)?/is', $security_msg, $content);
1577
		$content = preg_replace('/<embed[^>]+>(\s*<\/embed>)?/is', $security_msg, $content);
1578
		$content = preg_replace('/<img[^>]+editor_component="multimedia_link"[^>]*>(\s*<\/img>)?/is', $security_msg, $content);
1579
	}
1580
1581
	return;
1582
}
1583
1584
/**
1585
 * Require pear
1586
 *
1587
 * @return void
1588
 */
1589
function requirePear()
1590
{
1591
	static $required = false;
1592
	if($required)
1593
	{
1594
		return;
1595
	}
1596
1597
	if(version_compare(PHP_VERSION, "5.3.0") < 0)
1598
	{
1599
		set_include_path(_XE_PATH_ . "libs/PEAR" . PATH_SEPARATOR . get_include_path());
1600
	}
1601
	else
1602
	{
1603
		set_include_path(_XE_PATH_ . "libs/PEAR.1.9.5" . PATH_SEPARATOR . get_include_path());
1604
	}
1605
1606
	$required = true;
1607
}
1608
1609
function checkCSRF()
1610
{
1611
	if($_SERVER['REQUEST_METHOD'] != 'POST')
1612
	{
1613
		return FALSE;
1614
	}
1615
1616
	$default_url = Context::getDefaultUrl();
1617
	$referer = $_SERVER["HTTP_REFERER"];
1618
1619
	if(strpos($default_url, 'xn--') !== FALSE && strpos($referer, 'xn--') === FALSE)
1620
	{
1621
		require_once(_XE_PATH_ . 'libs/idna_convert/idna_convert.class.php');
1622
		$IDN = new idna_convert(array('idn_version' => 2008));
1623
		$referer = $IDN->encode($referer);
1624
	}
1625
1626
	$default_url = parse_url($default_url);
1627
	$referer = parse_url($referer);
1628
1629
	$oModuleModel = getModel('module');
1630
	$siteModuleInfo = $oModuleModel->getDefaultMid();
1631
1632
	if($siteModuleInfo->site_srl == 0)
1633
	{
1634
		if($default_url['host'] !== $referer['host'])
1635
		{
1636
			return FALSE;
1637
		}
1638
	}
1639
	else
1640
	{
1641
		$virtualSiteInfo = $oModuleModel->getSiteInfo($siteModuleInfo->site_srl);
1642
		if(strtolower($virtualSiteInfo->domain) != strtolower(Context::get('vid')) && !strstr(strtolower($virtualSiteInfo->domain), strtolower($referer['host'])))
1643
		{
1644
			return FALSE;
1645
		}
1646
	}
1647
1648
	return TRUE;
1649
}
1650
1651
/**
1652
 * menu exposure check by isShow column
1653
 * @param array $menu
1654
 * @return void
1655
 */
1656
function recurciveExposureCheck(&$menu)
1657
{
1658
	if(is_array($menu))
1659
	{
1660
		foreach($menu AS $key=>$value)
1661
		{
1662
			if(!$value['isShow'])
1663
			{
1664
				unset($menu[$key]);
1665
			}
1666
			if(is_array($value['list']) && count($value['list']) > 0)
1667
			{
1668
				recurciveExposureCheck($menu[$key]['list']);
1669
			}
1670
		}
1671
	}
1672
}
1673
1674
function changeValueInUrl($key, $requestKey, $dbKey, $urlName = 'success_return_url')
1675
{
1676
	if($requestKey != $dbKey)
1677
	{
1678
		$arrayUrl = parse_url(Context::get('success_return_url'));
1679
		if($arrayUrl['query'])
1680
		{
1681
			parse_str($arrayUrl['query'], $parsedStr);
1682
1683
			if(isset($parsedStr[$key]))
1684
			{
1685
				$parsedStr[$key] = $requestKey;
1686
				$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...
1687
				Context::set($urlName, $successReturnUrl);
1688
			}
1689
		}
1690
	}
1691
}
1692
1693
/**
1694
 * Print raw html header
1695
 *
1696
 * @return void
1697
 */
1698
function htmlHeader()
1699
{
1700
	echo '<!DOCTYPE html>
1701
<html lang="ko">
1702
<head>
1703
<meta charset="utf-8" />
1704
</head>
1705
<body>';
1706
}
1707
1708
/**
1709
 * Print raw html footer
1710
 *
1711
 * @return void
1712
 */
1713
function htmlFooter()
1714
{
1715
	echo '</body></html>';
1716
}
1717
1718
/**
1719
 * Print raw alert message script
1720
 *
1721
 * @param string $msg
1722
 * @return void
1723
 */
1724
function alertScript($msg)
1725
{
1726
	if(!$msg)
1727
	{
1728
		return;
1729
	}
1730
1731
	echo '<script type="text/javascript">
1732
//<![CDATA[
1733
alert("' . $msg . '");
1734
//]]>
1735
</script>';
1736
}
1737
1738
/**
1739
 * Print raw close window script
1740
 *
1741
 * @return void
1742
 */
1743
function closePopupScript()
1744
{
1745
	echo '<script type="text/javascript">
1746
//<![CDATA[
1747
window.close();
1748
//]]>
1749
</script>';
1750
}
1751
1752
/**
1753
 * Print raw reload script
1754
 *
1755
 * @param bool $isOpener
1756
 * @return void
1757
 */
1758
function reload($isOpener = FALSE)
1759
{
1760
	$reloadScript = $isOpener ? 'window.opener.location.reload()' : 'document.location.reload()';
1761
1762
	echo '<script type="text/javascript">
1763
//<![CDATA[
1764
' . $reloadScript . '
1765
//]]>
1766
</script>';
1767
}
1768
1769
/* End of file func.inc.php */
1770
/* Location: ./config/func.inc.php */
1771