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 ( 2d2fdb...3cb0fc )
by gyeong-won
11:13
created

func.inc.php ➔ debugPrint()   F

Complexity

Conditions 22
Paths 291

Size

Total Lines 89
Code Lines 48

Duplication

Lines 4
Ratio 4.49 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 22
eloc 48
c 1
b 0
f 0
nc 291
nop 3
dl 4
loc 89
rs 3.5977

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

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