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
Pull Request — develop (#1930)
by
unknown
13:51
created

func.inc.php ➔ removeSrcHack()   F

Complexity

Conditions 29
Paths 2818

Size

Total Lines 93
Code Lines 45

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 29
eloc 45
c 1
b 1
f 0
nc 2818
nop 1
dl 0
loc 93
rs 2

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