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 ( d948ba...eebdf0 )
by gyeong-won
08:16
created

func.inc.php ➔ saveCookie()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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