source: trunk/inc/utils.inc.php

Last change on this file was 2, checked in by george, 14 years ago
  • Přidáno: Trunk revize 13719.
File size: 32.0 KB
Line 
1<?php
2
3/***************************************************************************
4* Dolphin Smart Community Builder
5* -----------------
6* begin : Mon Mar 23 2006
7* copyright : (C) 2006 BoonEx Group
8* website : http://www.boonex.com/
9* This file is part of Dolphin - Smart Community Builder
10*
11* Dolphin is free software. This work is licensed under a Creative Commons Attribution 3.0 License.
12* http://creativecommons.org/licenses/by/3.0/
13*
14* Dolphin is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
15* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
16* See the Creative Commons Attribution 3.0 License for more details.
17* You should have received a copy of the Creative Commons Attribution 3.0 License along with Dolphin,
18* see license.txt file; if not, write to marketing@boonex.com
19***************************************************************************/
20
21require_once("header.inc.php");
22
23bx_import('BxDolModule');
24bx_import('BxDolEmailTemplates');
25
26define('BX_DOL_LOCALE_TIME', 2);
27define('BX_DOL_LOCALE_DATE_SHORT', 4);
28define('BX_DOL_LOCALE_DATE', 5);
29
30define('BX_DOL_LOCALE_PHP', 1);
31define('BX_DOL_LOCALE_DB', 2);
32
33define('BX_TAGS_NO_ACTION', 0); // default
34define('BX_TAGS_STRIP', 1);
35define('BX_TAGS_SPECIAL_CHARS', 8);
36define('BX_TAGS_VALIDATE', 16);
37define('BX_TAGS_STRIP_AND_NL2BR', 32);
38
39define('BX_SLASHES_AUTO', 0); // default
40define('BX_SLASHES_ADD', 1);
41define('BX_SLASHES_STRIP', 2);
42define('BX_SLASHES_NO_ACTION', 3);
43
44/**
45 * The following two functions are needed to convert title to uri and back.
46 * It usefull when titles are used in URLs, like in Categories and Tags.
47 */
48function title2uri($sValue) {
49 return str_replace(
50 array('&', '/', '\\', '"', '+'),
51 array('[and]', '[slash]', '[backslash]', '[quote]', '[plus]'),
52 $sValue
53 );
54}
55function uri2title($sValue) {
56 return str_replace(
57 array('[and]', '[slash]', '[backslash]', '[quote]', '[plus]'),
58 array('&', '/', '\\', '"', '+'),
59 $sValue
60 );
61}
62
63/**
64 * Convert date(timestamp) in accordance with requested format code.
65 *
66 * @param string $sTimestamp - timestamp
67 * @param integer $iCode - format code
68 * 1(4) - short date format. @see sys_options -> short_date_format_php
69 * 2 - time format. @see sys_options -> time_format_php
70 * 3(5) - long date format. @see sys_options -> date_format_php
71 * 6 - RFC 2822 date format.
72 */
73function getLocaleDate($sTimestamp = '', $iCode = BX_DOL_LOCALE_DATE_SHORT) {
74 $sFormat = (int)$iCode == 6 ? 'r' : getLocaleFormat($iCode);
75
76 return date($sFormat, $sTimestamp);
77}
78/**
79 * Get data format in accordance with requested format code and format type.
80 *
81 * @param integer $iCode - format code
82 * 1(4) - short date format. @see sys_options -> short_date_format_php
83 * 2 - time format. @see sys_options -> time_format_php
84 * 3(5) - long date format. @see sys_options -> date_format_php
85 * 6 - RFC 2822 date format.
86 * @param integer $iType - format type
87 * 1 - for PHP code.
88 * 2 - for database.
89 */
90function getLocaleFormat($iCode = BX_DOL_LOCALE_DATE_SHORT, $iType = BX_DOL_LOCALE_PHP) {
91 $sPostfix = (int)$iType == BX_DOL_LOCALE_PHP ? '_php' : '';
92
93 $sResult = '';
94 switch ($iCode) {
95 case 2:
96 $sResult = getParam('time_format' . $sPostfix);
97 break;
98 case 1:
99 case 4:
100 $sResult = getParam('short_date_format' . $sPostfix);
101 break;
102 case 3:
103 case 5:
104 $sResult = getParam('date_format' . $sPostfix);
105 break;
106 }
107
108 return $sResult;
109}
110
111/**
112 * Function will check on blocked status;
113 *
114 * @param : $iFirstProfile (integer) - first profile's id;
115 * @param : $iSecondProfile (integer) - second profile's id;
116 * @return : (boolean) - true if pair will blocked;
117 */
118function isBlocked($iFirstProfile, $iSecondProfile)
119{
120 $iFirstProfile = (int)$iFirstProfile;
121 $iSecondProfile = (int)$iSecondProfile;
122 $sQuery = "SELECT COUNT(*) FROM `sys_block_list` WHERE `ID` = {$iFirstProfile} AND `Profile` = {$iSecondProfile}";
123 return db_value( $sQuery) ? true : false;
124}
125
126/*
127 * function for work with profile
128 */
129function is_friends($id1, $id2) {
130 $id1 = (int)$id1;
131 $id2 = (int)$id2;
132 if ($id1 == 0 || $id2 == 0)
133 return;
134 $cnt = db_arr("SELECT SUM(`Check`) AS 'cnt' FROM `sys_friend_list` WHERE `ID`='{$id1}' AND `Profile`='{$id2}' OR `ID`='{$id2}' AND `Profile`='{$id1}'");
135 return ($cnt['cnt'] > 0 ? true : false);
136}
137
138/*
139 * functions for limiting maximal word length (returned from ash).
140 */
141function WordWrapStr($input, $len = 35) {
142 $output = wordwrap($input, $len, " ", true);
143 return $output;
144}
145
146/*
147 * functions for limiting maximal word length
148 */
149function strmaxwordlen($input, $len = 100) {
150 return $input;
151}
152
153/*
154 * functions for limiting maximal text length
155 */
156function strmaxtextlen($input, $len = 60) {
157 if ( strlen($input) > $len )
158 return mb_substr($input, 0, $len - 4) . "...";
159 else
160 return $input;
161}
162
163function html2txt($content, $tags = "") {
164 while($content != strip_tags($content, $tags)) {
165 $content = strip_tags($content, $tags);
166 }
167
168 return $content;
169}
170
171function html_encode($text) {
172 $searcharray = array(
173 "'([-_\w\d.]+@[-_\w\d.]+)'",
174 "'((?:(?!://).{3}|^.{0,2}))(www\.[-\d\w\.\/]+)'",
175 "'(http[s]?:\/\/[-_~\w\d\.\/]+)'");
176
177 $replacearray = array(
178 "<a href=\"mailto:\\1\">\\1</a>",
179 "\\1http://\\2",
180 "<a href=\"\\1\" target=_blank>\\1</a>");
181
182 return preg_replace($searcharray, $replacearray, stripslashes($text));
183}
184
185/*
186 * functions for input data into database
187 * @param $text string to pass to database
188 * @param $strip_tags tags parameter:
189 * BX_TAGS_STRIP - strip tags
190 * BX_TAGS_SPECIAL_CHARS - translate to special html chars (not good to use this, it is better to do such thing during output to browser)
191 * BX_TAGS_VALIDATE - validate HTML
192 * BX_TAGS_NO_ACTION - do not perform any action with tags
193 * @param $addslashes slashes parameter:
194 * BX_SLASHES_AUTO - automatically detect magic_quotes_gpc setting
195 * BX_SLASHES_STRIP - strip slashes
196 * BX_SLASHES_ADD - add slashes
197 * BX_SLASHES_NO_ACTION - do not perform any action with slashes
198 */
199function process_db_input( $text, $strip_tags = 0, $addslashes = 0 ) {
200
201 if (is_array($text)) {
202 foreach ($text as $k => $v)
203 $text[$k] = process_db_input($v, $strip_tags, $addslashes);
204 return $text;
205 }
206
207 if ((get_magic_quotes_gpc() && $addslashes == BX_SLASHES_AUTO) || $addslashes == BX_SLASHES_STRIP)
208 $text = stripslashes($text);
209 elseif ($addslashes == BX_SLASHES_ADD)
210 $text = addslashes($text);
211
212 switch ($strip_tags) {
213 case BX_TAGS_STRIP_AND_NL2BR:
214 return mysql_real_escape_string(nl2br(strip_tags($text)));
215 case BX_TAGS_STRIP:
216 return mysql_real_escape_string(strip_tags($text));
217 case BX_TAGS_SPECIAL_CHARS:
218 return mysql_real_escape_string(htmlspecialchars($text, ENT_QUOTES, 'UTF-8'));
219 case BX_TAGS_VALIDATE:
220 return mysql_real_escape_string(clear_xss($text));
221 case BX_TAGS_NO_ACTION:
222 default:
223 return mysql_real_escape_string($text);
224 }
225}
226
227/*
228 * function for processing pass data
229 *
230 * This function cleans the GET/POST/COOKIE data if magic_quotes_gpc() is on
231 * for data which should be outputed immediately after submit
232 */
233function process_pass_data( $text, $strip_tags = 0 ) {
234 if ( $strip_tags )
235 $text = strip_tags($text);
236
237 if ( !get_magic_quotes_gpc() )
238 return $text;
239 else
240 return stripslashes($text);
241}
242
243/*
244 * function for output data from database into html
245 */
246function htmlspecialchars_adv( $string ) {
247 return htmlspecialchars($string, ENT_COMPAT, 'UTF-8');
248
249 /*
250 $patterns = array( "/(?!&#\d{2,};)&/m", "/>/m", "/</m", "/\"/m", "/'/m" );
251 $replaces = array( "&amp;", "&gt;", "&lt;", "&quot;", "&#039;" );
252 return preg_replace( $patterns, $replaces, $string );
253 */
254}
255
256function process_text_output( $text, $maxwordlen = 100 ) {
257 return ( htmlspecialchars_adv( strmaxwordlen( $text, $maxwordlen ) ) );
258}
259
260function process_textarea_output( $text, $maxwordlen = 100 ) {
261 return htmlspecialchars_adv( strmaxwordlen( $text, $maxwordlen ) );
262}
263
264function process_text_withlinks_output( $text, $maxwordlen = 100 ) {
265 return nl2br( html_encode( htmlspecialchars_adv( strmaxwordlen( $text, $maxwordlen ) ) ) );
266}
267
268function process_line_output( $text, $maxwordlen = 100 ) {
269 return htmlspecialchars_adv( strmaxwordlen( $text, $maxwordlen ) );
270}
271
272function process_html_output( $text, $maxwordlen = 100 ) {
273 return strmaxwordlen( $text, $maxwordlen );
274}
275
276/**
277* Used to construct sturctured arrays in GET or POST data. Supports multidimensional arrays.
278*
279* @param array $Values Specifies values and values names, that should be submitted. Can be multidimensional.
280*
281* @return string HTML code, which contains <input type="hidden"...> tags with names and values, specified in $Values array.
282*/
283function ConstructHiddenValues($Values) {
284 /**
285 * Recursive function, processes multidimensional arrays
286 *
287 * @param string $Name Full name of array, including all subarrays' names
288 *
289 * @param array $Value Array of values, can be multidimensional
290 *
291 * @return string Properly consctructed <input type="hidden"...> tags
292 */
293 function ConstructHiddenSubValues($Name, $Value) {
294 if (is_array($Value)) {
295 $Result = "";
296 foreach ($Value as $KeyName => $SubValue) {
297 $Result .= ConstructHiddenSubValues("{$Name}[{$KeyName}]", $SubValue);
298 }
299 } else
300 // Exit recurse
301 $Result = "<input type=\"hidden\" name=\"".htmlspecialchars($Name)."\" value=\"".htmlspecialchars($Value)."\" />\n";
302
303 return $Result;
304 }
305 /* End of ConstructHiddenSubValues function */
306
307 $Result = '';
308 if (is_array($Values)) {
309 foreach ($Values as $KeyName => $Value) {
310 $Result .= ConstructHiddenSubValues($KeyName, $Value);
311 }
312 }
313
314 return $Result;
315}
316
317/**
318* Returns HTML/javascript code, which redirects to another URL with passing specified data (through specified method)
319*
320* @param string $ActionURL destination URL
321*
322* @param array $Params Parameters to be passed (through GET or POST)
323*
324* @param string $Method Submit mode. Only two values are valid: 'get' and 'post'
325*
326* @return mixed Correspondent HTML/javascript code or false, if input data is wrong
327*/
328function RedirectCode($ActionURL, $Params = NULL, $Method = "get", $Title = 'Redirect') {
329 if ((strcasecmp(trim($Method), "get") && strcasecmp(trim($Method), "post")) || (trim($ActionURL) == ""))
330 return false;
331
332 ob_start();
333
334?>
335<html>
336 <head>
337 <title><?= $Title ?></title>
338 </head>
339 <body>
340 <form name="RedirectForm" action="<?= htmlspecialchars($ActionURL) ?>" method="<?= $Method ?>">
341
342<?= ConstructHiddenValues($Params) ?>
343
344 </form>
345 <script type="text/javascript">
346 <!--
347 document.forms['RedirectForm'].submit();
348 -->
349 </script>
350 </body>
351</html>
352<?
353
354 $Result = ob_get_contents();
355 ob_end_clean();
356
357 return $Result;
358}
359
360/**
361* Redirects browser to another URL, passing parameters through POST or GET
362* Actually just prints code, returned by RedirectCode (see RedirectCode)
363*/
364function Redirect($ActionURL, $Params = NULL, $Method = "get", $Title = 'Redirect') {
365 $RedirectCodeValue = RedirectCode($ActionURL, $Params, $Method, $Title);
366 if ($RedirectCodeValue !== false)
367 echo $RedirectCodeValue;
368}
369
370function ErrorHandler($errno, $errstr, $errfile, $errline) {
371 switch ($errno) {
372 case FATAL:
373 echo "<b>FATAL</b> [$errno] $errstr<br>\n";
374 echo " Fatal error in line ".$errline." of file ".$errfile;
375 echo ", PHP ".PHP_VERSION." (".PHP_OS.")<br>\n";
376 echo "Aborting...<br>\n";
377 exit(1);
378 break;
379 case ERROR:
380 echo "<b>ERROR</b> [$errno] $errstr<br>\n";
381 break;
382 case WARNING:
383 // echo "<b></b> [$errno] $errstr<br>\n";
384 break;
385 default:
386 break;
387 }
388}
389
390function isRWAccessible($sFileName) {
391 clearstatcache();
392 $perms = fileperms($sFileName);
393 return ( $perms & 0x0004 && $perms & 0x0002 ) ? true : false;
394}
395
396/**
397 * Send email function
398 *
399 * @param string $sRecipientEmail - Email where email should be send
400 * @param string $sMailSubject - subject of the message
401 * @param string $sMailBody - Body of the message
402 * @param integer $iRecipientID - ID of recipient profile
403 * @param array $aPlus - Array of additional information
404 *
405 *
406 * @return boolean - trie if message was send
407 * - false if not
408 */
409function sendMail( $sRecipientEmail, $sMailSubject, $sMailBody, $iRecipientID = 0, $aPlus = array(), $sEmailFlag = 'html' ) {
410 global $site;
411
412 if($iRecipientID)
413 $aRecipientInfo = getProfileInfo( $iRecipientID );
414
415 $sEmailNotify = isset($GLOBALS['site']['email_notify']) ? $GLOBALS['site']['email_notify'] : getParam('site_email_notify');
416 $sSiteTitle = isset($GLOBALS['site']['title']) ? $GLOBALS['site']['title'] : getParam('site_title');
417 $sMailHeader = "From: =?UTF-8?B?" . base64_encode( $sSiteTitle ) . "?= <{$sEmailNotify}>";
418 $sMailParameters = "-f{$sEmailNotify}";
419
420 if ($aPlus || $iRecipientID) {
421 if(!is_array($aPlus))
422 $aPlus = array();
423 $oEmailTemplates = new BxDolEmailTemplates();
424 $sMailSubject = $oEmailTemplates->parseContent($sMailSubject, $aPlus, $iRecipientID);
425 $sMailBody = $oEmailTemplates->parseContent($sMailBody, $aPlus, $iRecipientID);
426 }
427
428 $sMailSubject = '=?UTF-8?B?' . base64_encode( $sMailSubject ) . '?=';
429
430 $sMailHeader = "MIME-Version: 1.0\r\n" . $sMailHeader;
431
432 if( 'html' == $sEmailFlag) {
433 $sMailHeader = "Content-type: text/html; charset=UTF-8\r\n" . $sMailHeader;
434 $iSendingResult = mail( $sRecipientEmail, $sMailSubject, $sMailBody, $sMailHeader, $sMailParameters );
435 } else {
436 $sMailHeader = "Content-type: text/plain; charset=UTF-8\r\n" . $sMailHeader;
437 $sMailBody = html2txt($sMailBody);
438 $iSendingResult = mail( $sRecipientEmail, $sMailSubject, html2txt($sMailBody), $sMailHeader, $sMailParameters );
439 }
440
441 //--- create system event
442 bx_import('BxDolAlerts');
443 $aAlertData = array(
444 'email' => $sRecipientEmail,
445 'subject' => $sMailSubject,
446 'body' => $sMailBody,
447 'header' => $sMailHeader,
448 'params' => $sMailParameters,
449 'html' => 'html' == $sEmailFlag ? true : false,
450 );
451
452 $oZ = new BxDolAlerts('profile', 'send_mail', $aRecipientInfo['ID'], '', $aAlertData);
453 $oZ -> alert();
454
455 return $iSendingResult;
456}
457
458/*
459 * Getting Array with Templates Names
460*/
461
462function get_templates_array() {
463 $path = BX_DIRECTORY_PATH_ROOT . 'templates/';
464 $templ_choices = array();
465 $handle = opendir( $path );
466
467 while ( false !== ($sFileName = readdir($handle)) ) {
468 if ( is_dir($path.$sFileName) && substr($sFileName, 0, 5) == 'tmpl_' ) {
469 $sTemplName = '';
470 @include( $path.$sFileName.'/scripts/BxTemplName.php' );
471 if( $sTemplName )
472 $templ_choices[substr($sFileName, 5)] = $sTemplName;
473 }
474 }
475 closedir( $handle );
476 return $templ_choices;
477}
478
479/*
480 * The Function Show a Line with Templates Names
481*/
482
483function templates_select_txt() {
484 $templ_choices = get_templates_array();
485 $current_template = ( strlen( $_GET['skin'] ) ) ? $_GET['skin'] : $_COOKIE['skin'];
486
487 foreach ($templ_choices as $tmpl_key => $tmpl_value) {
488 if ($current_template == $tmpl_key) {
489 $ReturnResult .= $tmpl_value . ' | ';
490 } else {
491 foreach ($_GET as $param_key => $param_value) {
492 $sGetTransfer .= ('skin' != $param_key) ? "&{$param_key}={$param_value}" : '';
493 }
494 $ReturnResult .= '<a href="' . $_SERVER['PHP_SELF'] . '?skin='. $tmpl_key . $sGetTransfer . '">' . $tmpl_value . '</a> | ';
495 }
496 }
497 return $ReturnResult;
498}
499
500function extFileExists( $sFileSrc ) {
501 return (file_exists( $sFileSrc ) && is_file( $sFileSrc )) ? true : false;
502}
503
504/*function extDirExists( $sDirSrc ) {
505 if( file_exists( $sDirSrc ) && is_dir( $sDirSrc ) ) {
506 $ret = true;
507 } else {
508 $ret = false;
509 }
510
511 return $ret;
512}*/
513
514function getVisitorIP() {
515 $ip = "0.0.0.0";
516 if( ( isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) && ( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) ) {
517 $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
518 } elseif( ( isset( $_SERVER['HTTP_CLIENT_IP'])) && (!empty($_SERVER['HTTP_CLIENT_IP'] ) ) ) {
519 $ip = explode(".",$_SERVER['HTTP_CLIENT_IP']);
520 $ip = $ip[3].".".$ip[2].".".$ip[1].".".$ip[0];
521 } elseif((!isset( $_SERVER['HTTP_X_FORWARDED_FOR'])) || (empty($_SERVER['HTTP_X_FORWARDED_FOR']))) {
522 if ((!isset( $_SERVER['HTTP_CLIENT_IP'])) && (empty($_SERVER['HTTP_CLIENT_IP']))) {
523 $ip = $_SERVER['REMOTE_ADDR'];
524 }
525 }
526 return $ip;
527}
528
529function genFlag( $country ) {
530 return '<img src="' . genFlagUrl($country) . '" />';
531}
532
533function genFlagUrl($country) {
534 return $GLOBALS['site']['flags'] . strtolower($country) . '.gif';
535}
536
537// print debug information ( e.g. arrays )
538function echoDbg( $what, $desc = '' ) {
539 if ( $desc )
540 echo "<b>$desc:</b> ";
541 echo "<pre>";
542 print_r( $what );
543 echo "</pre>\n";
544}
545
546function echoDbgLog($mWhat, $sDesc = '', $sFileName = 'debug.log') {
547 global $dir;
548
549 $sCont =
550 '--- ' . date('r') . ' (' . BX_DOL_START_TIME . ") ---\n" .
551 $sDesc . "\n" .
552 print_r($mWhat, true) . "\n\n\n";
553
554 $rFile = fopen($dir['tmp'] . $sFileName, 'a');
555 fwrite($rFile, $sCont);
556 fclose($rFile);
557}
558
559function clear_xss($val) {
560 // HTML Purifier plugin
561 global $oHtmlPurifier;
562 require_once( BX_DIRECTORY_PATH_PLUGINS . 'htmlpurifier/HTMLPurifier.standalone.php' );
563 if (!isset($oHtmlPurifier)) {
564 HTMLPurifier_Bootstrap::registerAutoload();
565 // spl_autoload_register(array('HTMLPurifier_Bootstrap', 'autoload'));
566
567 $oConfig = HTMLPurifier_Config::createDefault();
568 $oConfig->set('Filter.YouTube', true);
569
570 $oHtmlPurifier = new HTMLPurifier($oConfig);
571 }
572
573 $res = $oHtmlPurifier->purify($val);
574
575 return $res;
576}
577
578function _format_when ($iSec) {
579 $s = '';
580
581 if ($iSec>0) {
582 if ($iSec < 3600) {
583 $i = round($iSec/60);
584 $s .= (0 == $i || 1 == $i) ? _t('_x_minute_ago', '1') : _t('_x_minute_ago', $i, 's');
585 } else if ($iSec < 86400) {
586 $i = round($iSec/60/60);
587 $s .= (0 == $i || 1 == $i) ? _t('_x_hour_ago', '1') : _t('_x_hour_ago', $i, 's');
588 } else {
589 $i = round($iSec/60/60/24);
590 $s .= (0 == $i || 1 == $i) ? _t('_x_day_ago', '1') : _t('_x_day_ago', $i, 's');
591 }
592 } else {
593 if ($iSec > -3600) {
594 $i = round($iSec/60);
595 $s .= (0 == $i || 1 == $i) ? _t('_in_x_minute', '1') : _t('_in_x_minute', -$i, 's');
596 } else if ($iSec > -86400) {
597 $i = round($iSec/60/60);
598 $s .= (0 == $i || 1 == $i) ? _t('_in_x_hour', '1') : _t('_in_x_hour', -$i, 's');
599 } elseif ($iSec < -86400) {
600 $i = round($iSec/60/60/24);
601 $s .= (0 == $i || 1 == $i) ? _t('_in_x_day', '1') : _t('_in_x_day', -$i, 's');
602 }
603 }
604 return $s;
605}
606
607function defineTimeInterval($iTime) {
608 $iTime = time() - (int)$iTime;
609 $sCode = _format_when($iTime);
610 return $sCode;
611}
612
613function execSqlFile($sFileName) {
614 if (! $f = fopen($sFileName, "r"))
615 return false;
616
617 db_res( "SET NAMES 'utf8'" );
618
619 $s_sql = "";
620 while ( $s = fgets ( $f, 10240) ) {
621 $s = trim( $s ); //Utf with BOM only
622
623 if( !strlen( $s ) ) continue;
624 if ( mb_substr( $s, 0, 1 ) == '#' ) continue; //pass comments
625 if ( mb_substr( $s, 0, 2 ) == '--' ) continue;
626
627 $s_sql .= $s;
628
629 if ( mb_substr( $s, -1 ) != ';' ) continue;
630
631 db_res( $s_sql );
632 $s_sql = "";
633 }
634
635 fclose($f);
636 return true;
637}
638
639function replace_full_uris( $text ) {
640 $text = preg_replace_callback( '/([\s\n\r]src\=")([^"]+)(")/', 'replace_full_uri', $text );
641 return $text;
642}
643
644function replace_full_uri( $matches ) {
645 if( substr( $matches[2], 0, 7 ) != 'http://' and substr( $matches[2], 0, 6 ) != 'ftp://' )
646 $matches[2] = BX_DOL_URL_ROOT . $matches[2];
647
648 return $matches[1] . $matches[2] . $matches[3];
649}
650
651//--------------------------------------- friendly permalinks --------------------------------------//
652//------------------------------------------- main functions ---------------------------------------//
653function uriGenerate ($s, $sTable, $sField, $iMaxLen = 255) {
654 $s = uriFilter($s);
655
656 if (uriCheckUniq($s, $sTable, $sField)) return $s;
657
658 // try to add date
659
660 if (get_mb_len($s) > 240)
661 $s = get_mb_substr ($s, 0, 240);
662
663 $s .= '-' . date('Y-m-d');
664
665 if (uriCheckUniq($s, $sTable, $sField)) return $s;
666
667 // try to add number
668
669 for ($i = 0 ; $i < 999 ; ++$i) {
670 if (uriCheckUniq($s . '-' . $i, $sTable, $sField)) {
671 return ($s . '-' . $i);
672 }
673 }
674 return rand(0, 999999999);
675}
676
677function uriFilter ($s) {
678
679 //$s = get_mb_replace ('/[^\pL^\pN]+/u', '-', $s); // unicode characters
680 $s = get_mb_replace ('/([^\d^\w]+)/u', '-', $s); // latin characters only
681
682 $s = get_mb_replace ('/([-^]+)/', '-', $s);
683 $s = get_mb_replace ('/([-]+)$/', '', $s); // remove trailing dash
684 if (!$s) $s = '-';
685 return $s;
686}
687
688function uriCheckUniq ($s, $sTable, $sField) {
689 return !db_arr("SELECT 1 FROM $sTable WHERE $sField = '$s' LIMIT 1");
690}
691
692function get_mb_replace ($sPattern, $sReplace, $s) {
693 return preg_replace ($sPattern, $sReplace, $s);
694}
695
696function get_mb_len ($s) {
697 return (function_exists('mb_strlen')) ? mb_strlen($s) : strlen($s);
698}
699
700function get_mb_substr ($s, $iStart, $iLen) {
701 return (function_exists('mb_substr')) ? mb_substr ($s, $iStart, $iLen) : substr ($s, $iStart, $iLen);
702}
703
704function isIPLoggedBanned() {
705 $iIPGlobalType = (int)getParam('ipListGlobalType');
706
707 //1 - all allowed except listed, 2 - all blocked except listed, 0 - disabled
708 switch ($iIPGlobalType) {
709 case 1:
710 $sCurIP = getVisitorIP();
711 //$in_addr = inet_pton($sCurIP);
712 $sCurLongIP = ip2long($sCurIP);
713 $sCheckSQL = "SELECT * FROM `sys_ip_list` WHERE `Type`='deny' AND `LastDT` > UNIX_TIMESTAMP()";
714 $vIPRes = db_res($sCheckSQL);
715 if (db_affected_rows()>0) {
716 while ( $aCheckIP = mysql_fetch_assoc($vIPRes) ) {
717 if ($aCheckIP['To']==0 && $aCheckIP['From']==$sCurLongIP) {
718 return true;
719 } elseif ($aCheckIP['To']>0 && $aCheckIP['From']<=$sCurLongIP && $aCheckIP['To']>=$sCurLongIP) {
720 return true;
721 }
722 }
723 }
724 break;
725 case 2:
726 $sCurIP = getVisitorIP();
727 $sCurLongIP = ip2long($sCurIP);
728 $sCheckSQL = "SELECT * FROM `sys_ip_list` WHERE `Type`='allow' AND `LastDT` > UNIX_TIMESTAMP()";
729 $vIPRes = db_res($sCheckSQL);
730 if (db_affected_rows()>0) {
731 while ( $aCheckIP = mysql_fetch_assoc($vIPRes) ) {
732 if ($aCheckIP['To']==0 && $aCheckIP['From']==$sCurLongIP) {
733 return false;
734 } elseif ($aCheckIP['To']>0 && $aCheckIP['From']<=$sCurLongIP && $aCheckIP['To']>=$sCurLongIP) {
735 return false;
736 }
737 }
738 }
739 return true;
740 break;
741 case 0:
742 default:
743 break;
744 }
745 return false;
746}
747
748function getmicrotime() {
749 list($usec, $sec) = explode(" ", microtime());
750 return ((float)$usec + (float)$sec);
751}
752
753/**
754** @description: Function will clear received cache file ;
755** @param : $sCacheFile (string) name of cache file ;
756** @param : $bAllFiles (boolean) if isset this param that all files into `db_cached` will cleared ;
757** @return :
758*/
759function clearCacheFile( $sCacheFile, $bAllFiles = false ) {
760 $bResult = true;
761
762 if(!$bAllFiles && file_exists($sCacheFile))
763 $bResult = @unlink($sCacheFile);
764 else if($bAllFiles) {
765 $rHandle = opendir(BX_DIRECTORY_PATH_DBCACHE);
766 while(($sFileName = readdir($rHandle)) !== false)
767 if(is_file(BX_DIRECTORY_PATH_DBCACHE . $sFileName))
768 $bResult = $bResult && @unlink(BX_DIRECTORY_PATH_DBCACHE . $sFileName);
769 }
770
771 return $bResult;
772}
773
774/**
775** @description : function will create cache file with all SQL queries ;
776** @return :
777*/
778function genSiteStatCache() {
779 $aAdmin = '';
780 $sAdd = '_a';
781
782 $sqlQuery = "SELECT `Name` as `name`,
783 `Title` as `capt`,
784 `UserQuery` as `query`,
785 `UserLink` as `link`,
786 `IconName` as `icon`,
787 `AdminQuery` as `adm_query`,
788 `AdminLink` as `adm_link`
789 FROM `sys_stat_site`
790 ORDER BY `StatOrder` ASC, `ID` ASC";
791
792 $rData = db_res($sqlQuery);
793
794 $fStat = @fopen( BX_DIRECTORY_PATH_DBCACHE . 'sys_stat_site.inc', 'w' );
795 if( !$fStat )
796 return false;
797
798 fwrite($fStat, "return array( \n");
799 $sLine = '';
800
801 while ($aVal = mysql_fetch_assoc($rData)) {
802 $sCode .= getSiteStatBody($aVal, 'admin');
803 $sLine .= genSiteStatFile($aVal);
804 }
805
806 $sLine = rtrim($sLine, ",\n")."\n);";
807 fwrite($fStat, $sLine);
808 fclose($fStat);
809
810 $sCode .= '</div><div class="clear_both"></div>';
811
812 return $sCode;
813}
814
815/**
816 * Function will cute the parameter from received string;
817 * remove received parameter from 'GET' query ;
818 *
819 * @param : $aExceptNames (string) - name of unnecessary parameter;
820 * @return : cleared string;
821 */
822function getClearedParam( $sExceptParam, $sString ) {
823 return preg_replace( "/(&amp;|&){$sExceptParam}=([a-z0-9\_\-]{1,})/i",'', $sString);
824}
825
826/**
827 * import class file, it detect class path by its prefix or module array
828 *
829 * @param $sClassName - full class name or class postfix in a case of module class
830 * @param $aModule - module array or true to get module array from global variable
831 */
832function bx_import($sClassName, $aModule = array()) {
833 if (class_exists($sClassName))
834 return;
835
836 if ($aModule) {
837 $a = (true === $aModule) ? $GLOABLS['aModule'] : $aModule;
838 if (class_exists($a['class_prefix'] . $sClassName))
839 return;
840 require_once (BX_DIRECTORY_PATH_MODULES . $a['path'] . 'classes/' . $a['class_prefix'] . $sClassName . '.php');
841 }
842
843 if (0 == strncmp($sClassName, 'BxDol', 5)) {
844 require_once(BX_DIRECTORY_PATH_CLASSES . $sClassName . '.php');
845 return;
846 }
847 if (0 == strncmp($sClassName, 'BxBase', 6)) {
848 require_once(BX_DIRECTORY_PATH_BASE . 'scripts/' . $sClassName . '.php');
849 return;
850 }
851 if (0 == strncmp($sClassName, 'BxTempl', 7) && !class_exists($sClassName)) {
852 if(isset($GLOBALS['iAdminPage']) && (int)$GLOBALS['iAdminPage'] == 1)
853 require_once(BX_DIRECTORY_PATH_ROOT . "templates/tmpl_uni/scripts/" . $sClassName . '.php');
854 else
855 require_once(BX_DIRECTORY_PATH_ROOT . "templates/tmpl_{$GLOBALS['tmpl']}/scripts/" . $sClassName . '.php');
856 return;
857 }
858}
859
860/**
861 * Gets an instance of class pathing necessary parameters if it's necessary.
862 *
863 * @param string $sClassName class name.
864 * @param array $aParams an array of parameters to be pathed to the constructor of the class.
865 * @param array $aModule an array with module description. Is used when the requested class is located in some module.
866 * @return unknown
867 */
868function bx_instance($sClassName, $aParams = array(), $aModule = array()) {
869 if(isset($GLOBALS['bxDolClasses'][$sClassName]))
870 return $GLOBALS['bxDolClasses'][$sClassName];
871 else {
872 bx_import((empty($aModule) ? $sClassName : str_replace($aModule['class_prefix'], '', $sClassName)), $aModule);
873
874 if(empty($aParams))
875 $GLOBALS['bxDolClasses'][$sClassName] = new $sClassName();
876 else {
877 $sParams = "";
878 foreach($aParams as $mixedKey => $mixedValue)
879 $sParams .= "\$aParams[" . $mixedKey . "], ";
880 $sParams = substr($sParams, 0, -2);
881
882 $GLOBALS['bxDolClasses'][$sClassName] = eval("return new " . $sClassName . "(" . $sParams . ");");
883 }
884
885 return $GLOBALS['bxDolClasses'][$sClassName];
886 }
887}
888/**
889 * Gets file contents by URL.
890 *
891 * @param string $sFileUrl - file URL to be read.
892 * @param array $aParams - an array of parameters to be pathed with URL.
893 * @return string the file's contents.
894 */
895function bx_file_get_contents($sFileUrl, $aParams = array()) {
896 $sParams = '?';
897 foreach($aParams as $sKey => $sValue)
898 $sParams .= $sKey . '=' . $sValue . '&';
899 $sParams = substr($sParams, 0, -1);
900
901 $sResult = '';
902 if(function_exists('curl_init')) {
903 $rConnect = curl_init();
904
905 curl_setopt($rConnect, CURLOPT_URL, $sFileUrl . $sParams);
906 curl_setopt($rConnect, CURLOPT_HEADER, 0);
907 curl_setopt($rConnect, CURLOPT_RETURNTRANSFER, 1);
908 curl_setopt($rConnect, CURLOPT_FOLLOWLOCATION, 1);
909
910 $sAllCookies = '';
911 foreach($_COOKIE as $sKey=>$sValue){
912 $sAllCookies .= $sKey."=".$sValue.";";
913 }
914 curl_setopt($rConnect, CURLOPT_COOKIE, $sAllCookies);
915
916 $sResult = curl_exec($rConnect);
917 curl_close($rConnect);
918 }
919 else
920 $sResult = @file_get_contents($sFileUrl . $sParams);
921
922 return $sResult;
923}
924
925/**
926 * perform write log into 'tmp/log.txt' (for any debug development)
927 *
928 * @param $sNewLineText - New line debug text
929 */
930function writeLog($sNewLineText = 'test') {
931 $sFileName = BX_DIRECTORY_PATH_ROOT . 'tmp/log.txt';
932
933 if (is_writable($sFileName)) {
934 if (! $vHandle = fopen($sFileName, 'a')) {
935 echo "Unable to open ({$sFileName})";
936 }
937 if (fwrite($vHandle, $sNewLineText . "\r\n") === FALSE) {
938 echo "Unable write to ({$sFileName})";
939 }
940 fclose($vHandle);
941
942 } else {
943 echo "{$sFileName} is not writeable";
944 }
945}
946
947function getLinkSet ($sLinkString, $sUrlPrefix, $sDivider = ';,', $bUriConvert = false) {
948 $aSet = preg_split( '/['.$sDivider.']/', $sLinkString, 0, PREG_SPLIT_NO_EMPTY);
949
950 foreach ($aSet as $sKey) {
951 $sLink = $sUrlPrefix . urlencode($bUriConvert ? title2uri($sKey) : $sKey);
952 $sFinalSet .= '<a href="' . $sUrlPrefix . urlencode(title2uri($sKey)) . '">' . $sKey . '</a> ';
953 }
954
955 return trim($sFinalSet, ' ');
956}
957
958function getRelatedWords (&$aInfo) {
959 $sString = implode(' ', $aInfo);
960 $aRes = array_unique(explode(' ', $sString));
961 $sString = implode(' ', $aRes);
962 return addslashes($sString);
963}
964
965function getSiteInfo($sSourceUrl)
966{
967 $aResult = array();
968 $sContent = bx_file_get_contents($sSourceUrl);
969
970 if (strlen($sContent))
971 {
972 preg_match("/<title>(.*)<\/title>/", $sContent, $aMatch);
973 $aResult['title'] = $aMatch[1];
974
975 preg_match("/<meta.*name[='\" ]+description['\"].*content[='\" ]+(.*)['\"].*><\/meta>/", $sContent, $aMatch);
976 $aResult['description'] = $aMatch[1];
977 }
978
979 return $aResult;
980}
981
982// simple comparator for strings etc
983function simple_cmp($a, $b) {
984 if ($a == $b) {
985 return 0;
986 }
987 return ($a < $b) ? -1 : 1;
988}
989
990// calculation ini_get('upload_max_filesize') in bytes as example
991function return_bytes($val) {
992 $val = trim($val);
993 $last = strtolower($val{strlen($val)-1});
994 $val = (int)$val;
995 switch($last) {
996 // The 'G' modifier is available since PHP 5.1.0
997 case 'k':
998 $val *= 1024;
999 break;
1000 case 'm':
1001 $val *= 1024 * 1024;
1002 break;
1003 case 'g':
1004 $val *= 1024 * 1024 * 1024;
1005 break;
1006 }
1007 return $val;
1008}
1009
1010// Generate Random Password
1011function genRndPwd() {
1012 return base64_encode(substr(md5(microtime()), 2, 6));
1013}
1014
1015// Generate Random Salt for Password encryption
1016function genRndSalt() {
1017 return base64_encode(substr(md5(microtime()), 2, 6));
1018}
1019
1020// Encrypt User Password
1021function encryptUserPwd($sPwd, $sSalt) {
1022 return sha1(md5($sPwd) . $sSalt);
1023}
1024
1025// Advanced stripslashes. Strips strings and arrays
1026function stripslashes_adv($s) {
1027 if (is_string($s))
1028 return stripslashes($s);
1029 elseif (is_array($s)) {
1030 foreach ($s as $k => $v) {
1031 $s[$k] = stripslashes($v);
1032 }
1033 return $s;
1034 } else
1035 return $s;
1036}
Note: See TracBrowser for help on using the repository browser.