utils.inc.php 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021
  1. <?php defined('BX_DOL') or defined('BX_DOL_INSTALL') or die('hack attempt');
  2. /**
  3. * Copyright (c) BoonEx Pty Limited - http://www.boonex.com/
  4. * CC-BY License - http://creativecommons.org/licenses/by/3.0/
  5. *
  6. * @defgroup DolphinCore Dolphin Core
  7. * @{
  8. */
  9. define('BX_DATA_TEXT', 1); ///< regular text data type
  10. define('BX_DATA_TEXT_MULTILINE', 2); ///< regular multiline text data type
  11. define('BX_DATA_INT', 3); ///< integer data type
  12. define('BX_DATA_FLOAT', 4); ///< float data type
  13. define('BX_DATA_CHECKBOX', 5); ///< checkbox data type, 'on' or empty value
  14. define('BX_DATA_HTML', 6); ///< HTML data type
  15. define('BX_DATA_DATE', 7); ///< date data type stored as yyyy-mm-dd
  16. define('BX_DATA_DATE_TS', 8); ///< date data type stored as unixtimestamp
  17. define('BX_DATA_DATETIME_TS', 9); ///< date/time data type stored as unixtimestamp
  18. define('BX_SLASHES_AUTO', 0);
  19. define('BX_SLASHES_ADD', 1);
  20. define('BX_SLASHES_STRIP', 2);
  21. define('BX_SLASHES_NO_ACTION', 3);
  22. define('BX_ESCAPE_STR_AUTO', 0); ///< turn apostropes and quote signs into html special chars, for use in @see bx_js_string and @see bx_html_attribute
  23. define('BX_ESCAPE_STR_APOS', 1); ///< escape apostrophes only, for js strings enclosed in apostrophes, for use in @see bx_js_string and @see bx_html_attribute
  24. define('BX_ESCAPE_STR_QUOTE', 2); ///< escape quotes only, for js strings enclosed in quotes, for use in @see bx_js_string and @see bx_html_attribute
  25. define('BX_EMAIL_SYSTEM', 0); ///< system email without unsubscribe link, like forgot password or email verification
  26. define('BX_EMAIL_NOTIFY', 1); ///< notification message, with unsubscribe link
  27. define('BX_EMAIL_MASS', 2); ///< mass email, one mesage send to manu users, with unsubscribe link
  28. /**
  29. * The following two functions are needed to convert title to uri and back.
  30. * It usefull when titles are used in URLs, like in Categories and Tags.
  31. */
  32. function title2uri($sValue) {
  33. return str_replace(
  34. array('&', '/', '\\', '"', '+'),
  35. array('[and]', '[slash]', '[backslash]', '[quote]', '[plus]'),
  36. $sValue
  37. );
  38. }
  39. function uri2title($sValue) {
  40. return str_replace(
  41. array('[and]', '[slash]', '[backslash]', '[quote]', '[plus]'),
  42. array('&', '/', '\\', '"', '+'),
  43. $sValue
  44. );
  45. }
  46. /*
  47. * functions for limiting maximal text length
  48. */
  49. function strmaxtextlen($sInput, $iMaxLen = 60, $sEllipsisSign = '&#8230;') {
  50. $sTail = '';
  51. $s = trim(strip_tags($sInput));
  52. if (mb_strlen($s) > $iMaxLen) {
  53. $s = mb_substr($s, 0, $iMaxLen);
  54. $sTail = $sEllipsisSign;
  55. }
  56. return htmlspecialchars_adv($s) . $sTail;
  57. }
  58. function html2txt($content, $tags = "") {
  59. while($content != strip_tags($content, $tags)) {
  60. $content = strip_tags($content, $tags);
  61. }
  62. return $content;
  63. }
  64. function html_encode($text) {
  65. $searcharray = array(
  66. "'([-_\w\d.]+@[-_\w\d.]+)'",
  67. "'((?:(?!://).{3}|^.{0,2}))(www\.[-\d\w\.\/]+)'",
  68. "'(http[s]?:\/\/[-_~\w\d\.\/]+)'");
  69. $replacearray = array(
  70. "<a href=\"mailto:\\1\">\\1</a>",
  71. "\\1http://\\2",
  72. "<a href=\"\\1\" target=_blank>\\1</a>");
  73. return preg_replace($searcharray, $replacearray, stripslashes($text));
  74. }
  75. /**
  76. * Functions to process user input.
  77. * DON'T use to process data before passing to SQL query - use db prepare instead @see BxDolDb::prepare.
  78. * It is ok to use bx_process_input and then db prepare.
  79. * @param $mixedData data to process
  80. * @param $iDataType how to handle data, possible valies:
  81. * BX_DATA_INT - integer value
  82. * BX_DATA_FLOAT - float values
  83. * BX_DATA_CHECKBOX - 'on' or empty string
  84. * BX_DATA_TEXT - text data, single line (default)
  85. * BX_DATA_TEXT_MULTILINE - text data, multiple lines
  86. * BX_DATA_HTML - HTML data
  87. * BX_DATA_DATE - date data type stored as yyyy-mm-dd
  88. * BX_DATA_DATE_TS' - date data type stored as unixtimestamp
  89. * BX_DATA_DATETIME_TS - date/time data type stored as unixtimestamp
  90. * @param $mixedParams optional parameters to pass for validation
  91. * @return the filtered data, or FALSE if the filter fails.
  92. */
  93. function bx_process_input ($mixedData, $iDataType = BX_DATA_TEXT, $mixedParams = false, $isCheckMagicQuotes = true) {
  94. if (is_array($mixedData)) {
  95. foreach ($mixedData as $k => $v)
  96. $mixedData[$k] = bx_process_input($v, $iDataType, $mixedParams);
  97. return $mixedData;
  98. }
  99. if (get_magic_quotes_gpc() && $isCheckMagicQuotes)
  100. $mixedData = stripslashes($mixedData);
  101. switch ($iDataType) {
  102. case BX_DATA_INT:
  103. return filter_var(trim($mixedData), FILTER_VALIDATE_INT);
  104. case BX_DATA_FLOAT:
  105. return filter_var(trim($mixedData), FILTER_VALIDATE_FLOAT);
  106. case BX_DATA_CHECKBOX:
  107. return 'on' == trim($mixedData) ? 'on' : '';
  108. case BX_DATA_DATE:
  109. // maybe consider using strtotime
  110. $mixedData = trim($mixedData);
  111. if (!preg_match('/^\d{4}-\d{1,2}-\d{1,2}$/', $mixedData))
  112. return false;
  113. list($iYear, $iMonth, $iDay) = explode('-', $mixedData); // 1985-10-28
  114. $iDay = intval($iDay);
  115. $iMonth = intval($iMonth);
  116. $iYear = intval($iYear);
  117. return sprintf("%04d-%02d-%02d", $iYear, $iMonth, $iDay);
  118. case BX_DATA_DATE_TS:
  119. $mixedData = trim($mixedData);
  120. if (!preg_match('/^\d{4}-\d{1,2}-\d{1,2}$/', $mixedData))
  121. return false;
  122. list($iYear, $iMonth, $iDay) = explode('-', $mixedData);
  123. $iDay = intval($iDay);
  124. $iMonth = intval($iMonth);
  125. $iYear = intval($iYear);
  126. $iRet = mktime (0, 0, 0, $iMonth, $iDay, $iYear);
  127. return $iRet > 0 ? $iRet : false;
  128. case BX_DATA_DATETIME_TS:
  129. if (!preg_match('#(\d+)\-(\d+)\-(\d+)[\sT]{1}(\d+):(\d+):(\d+)#', $mixedData, $m) && !preg_match('#(\d+)\-(\d+)\-(\d+)[\sT]{1}(\d+):(\d+)#', $mixedData, $m))
  130. return bx_process_input ($mixedData, BX_DATA_DATE_TS, $mixedParams, $isCheckMagicQuotes);
  131. $iDay = $m[3];
  132. $iMonth = $m[2];
  133. $iYear = $m[1];
  134. $iH = $m[4];
  135. $iM = $m[5];
  136. $iS = isset($m[6]) ? $m[6] : 0;
  137. $iRet = mktime ($iH, $iM, $iS, $iMonth, $iDay, $iYear);
  138. return $iRet > 0 ? $iRet : false;
  139. case BX_DATA_HTML:
  140. return clear_xss($mixedData);
  141. case BX_DATA_TEXT_MULTILINE:
  142. return nl2br(strip_tags($mixedData));
  143. case BX_DATA_TEXT:
  144. default:
  145. return $mixedData;
  146. }
  147. }
  148. /*
  149. * Functions to process user output.
  150. * Always use this function before output data which was entered by user before.
  151. * @param $mixedData string to process
  152. * @param $iDataType how to handle data, possible valies the same as in bx_process_input function, see bx_process_input.
  153. * @param $mixedParams optional parameters to pass for validation
  154. * @return the filtered data, or FALSE if the filter fails.
  155. */
  156. function bx_process_output ($mixedData, $iDataType = BX_DATA_TEXT, $mixedParams = false) {
  157. if (is_array($mixedData)) {
  158. foreach ($mixedData as $k => $v)
  159. $mixedData[$k] = bx_process_output($v, $iDataType, $mixedParams);
  160. return $mixedData;
  161. }
  162. switch ($iDataType) {
  163. case BX_DATA_INT:
  164. return filter_var($mixedData, FILTER_VALIDATE_INT);
  165. case BX_DATA_FLOAT:
  166. return filter_var($mixedData, FILTER_VALIDATE_FLOAT);
  167. case BX_DATA_CHECKBOX:
  168. return 'on' == trim($mixedData) ? 'on' : '';
  169. case BX_DATA_DATE:
  170. return $mixedData;
  171. case BX_DATA_DATE_TS:
  172. return empty($mixedData) ? '' : date("Y-m-d", $mixedData);
  173. case BX_DATA_DATETIME_TS:
  174. return empty($mixedData) ? '' : date("Y-m-d H:i", $mixedData);
  175. case BX_DATA_HTML:
  176. return $mixedData;
  177. case BX_DATA_TEXT_MULTILINE:
  178. return $mixedData;
  179. case BX_DATA_TEXT:
  180. default:
  181. return htmlspecialchars_adv($mixedData);
  182. }
  183. }
  184. /*
  185. * This function apply bx_process_input and then bx_process_output.
  186. * Use this function to output data immediately after receiving, without saving to database.
  187. * Patams are the same as bx_process_input function - @see bx_process_input
  188. */
  189. function bx_process_pass ($mixedData, $iDataType = BX_DATA_TEXT, $mixedParams = false, $isCheckMagicQuotes = true) {
  190. return bx_process_output(bx_process_input ($mixedData, $iDataType, $mixedParams, $isCheckMagicQuotes), $iDataType, $mixedParams);
  191. }
  192. /**
  193. * DEPRECATED
  194. * use bx_process_input + bx_process_output instead
  195. * --------
  196. * function for processing pass data
  197. *
  198. * This function cleans the GET/POST/COOKIE data if magic_quotes_gpc() is on
  199. * for data which should be outputed immediately after submit
  200. */
  201. /*
  202. function process_pass_data( $text, $strip_tags = 0 ) {
  203. if ( $strip_tags )
  204. $text = strip_tags($text);
  205. if ( !get_magic_quotes_gpc() )
  206. return $text;
  207. else
  208. return stripslashes($text);
  209. }
  210. */
  211. /*
  212. * function for output data from database into html
  213. */
  214. function htmlspecialchars_adv( $string ) {
  215. return htmlspecialchars($string, ENT_COMPAT, 'UTF-8');
  216. }
  217. /**
  218. * Send email function
  219. *
  220. * @param $sRecipientEmail - Email where email should be send
  221. * @param $sMailSubject - subject of the message
  222. * @param $sMailBody - Body of the message
  223. * @param $iRecipientID - ID of recipient profile
  224. * @param $aPlus - Array of additional information
  225. * @param $iEmailType - email message type: BX_EMAIL_SYSTEM, BX_EMAIL_NOTIFY or BX_EMAIL_MASS
  226. * @return true if message was send or false otherwise
  227. */
  228. function sendMail($sRecipientEmail, $sMailSubject, $sMailBody, $iRecipientID = 0, $aPlus = array(), $iEmailType = BX_EMAIL_NOTIFY, $sEmailFlag = 'html', $isDisableAlert = false) {
  229. // make sure that recipient's email is valid and message isn't empty
  230. if (!$sMailBody || !$sRecipientEmail || preg_match('/\(2\)$/', $sRecipientEmail))
  231. return false;
  232. // get recipient account
  233. bx_import('BxDolAccount');
  234. $oAccount = BxDolAccount::getInstance($sRecipientEmail);
  235. $aAccountInfo = $oAccount ? $oAccount->getInfo() : false;
  236. // don't send bulk emails if user didn't subscribed to site news or email is unconfirmed
  237. if ($aAccountInfo && BX_EMAIL_MASS == $iEmailType && (!$aAccountInfo['email_confirmed'] || !$aAccountInfo['receive_news']))
  238. return false;
  239. // don't send email notifications if user didn't subscribed to notifications or email is unconfirmed
  240. if ($aAccountInfo && BX_EMAIL_NOTIFY == $iEmailType && (!$aAccountInfo['email_confirmed'] || !$aAccountInfo['receive_updates']))
  241. return false;
  242. // if profile id is provided - get profile's info
  243. $aRecipientInfo = false;
  244. if ($iRecipientID) {
  245. bx_import('BxDolProfile');
  246. $oProfile = BxDolProfile::getInstance($iRecipientID);
  247. if ($oProfile)
  248. $aRecipientInfo = $oProfile->getInfo();
  249. }
  250. // get site vars
  251. $sEmailNotify = getParam('site_email_notify');
  252. $sSiteTitle = getParam('site_title');
  253. // add unsubscribe link
  254. if (empty($aPlus['unsubscribe'])) {
  255. $aPlus['unsubscribe'] = '';
  256. if ($oAccount && (BX_EMAIL_MASS == $iEmailType || BX_EMAIL_NOTIFY == $iEmailType))
  257. $aPlus['unsubscribe'] = ($sLink = $oAccount->getUnsubscribeLink($iEmailType)) ? '<a href="' . BX_DOL_URL_ROOT . $sLink . '">' . _t('_sys_et_txt_unsubscribe') . '</a>' : '';
  258. }
  259. // parse template
  260. if ($aPlus || $iRecipientID) {
  261. if(!is_array($aPlus))
  262. $aPlus = array();
  263. bx_import('BxDolEmailTemplates');
  264. $oEmailTemplates = BxDolEmailTemplates::getInstance();
  265. $sMailSubject = $oEmailTemplates->parseContent($sMailSubject, $aPlus, $iRecipientID);
  266. $sMailBody = $oEmailTemplates->parseContent($sMailBody, $aPlus, $iRecipientID);
  267. }
  268. // email message headers
  269. $sMailHeader = "From: =?UTF-8?B?" . base64_encode( $sSiteTitle ) . "?= <{$sEmailNotify}>";
  270. $sMailParameters = "-f{$sEmailNotify}";
  271. $sMailSubject = '=?UTF-8?B?' . base64_encode( $sMailSubject ) . '?=';
  272. $sMailHeader = "MIME-Version: 1.0\r\n" . $sMailHeader;
  273. // if SMPT mailer is installed and enabled - send mail throught it
  274. if (!$isDisableAlert && 'on' == getParam('bx_smtp_on')) { // TODO: remake to use alert: before_send_mail
  275. return BxDolService::call('bx_smtp', 'send', array($sRecipientEmail, $sMailSubject, $sMailBody, $sMailHeader, $sMailParameters, 'html' == $sEmailFlag, $aRecipientInfo));
  276. }
  277. // send mail
  278. if( 'html' == $sEmailFlag) {
  279. $sMailHeader = "Content-type: text/html; charset=UTF-8\r\n" . $sMailHeader;
  280. $iSendingResult = mail( $sRecipientEmail, $sMailSubject, $sMailBody, $sMailHeader, $sMailParameters );
  281. } else {
  282. $sMailHeader = "Content-type: text/plain; charset=UTF-8\r\n" . $sMailHeader;
  283. $sMailBody = html2txt($sMailBody);
  284. $iSendingResult = mail( $sRecipientEmail, $sMailSubject, html2txt($sMailBody), $sMailHeader, $sMailParameters );
  285. }
  286. // system alert
  287. if (!$isDisableAlert) {
  288. bx_alert('profile', 'send_mail', (isset($aRecipientInfo['ID']) ? $aRecipientInfo['ID'] : 0), '', array(
  289. 'email' => $sRecipientEmail,
  290. 'subject' => $sMailSubject,
  291. 'body' => $sMailBody,
  292. 'header' => $sMailHeader,
  293. 'params' => $sMailParameters,
  294. 'html' => 'html' == $sEmailFlag ? true : false,
  295. ));
  296. }
  297. return $iSendingResult;
  298. }
  299. /*
  300. * Getting an array with Templates' Names
  301. */
  302. function get_templates_array($bEnabledOnly = true, $bShortInfo = true) {
  303. bx_import('BxDolDb');
  304. $oDb = BxDolDb::getInstance();
  305. $sWhereAddon = $bEnabledOnly ? " AND `enabled`='1'" : "";
  306. if($bShortInfo)
  307. return $oDb->getPairs("SELECT `uri`, `title` FROM `sys_modules` WHERE 1 AND `type`='" . BX_DOL_MODULE_TYPE_TEMPLATE . "'" . $sWhereAddon, "uri", "title");
  308. else
  309. return $oDb->getAllWithKey("SELECT * FROM `sys_modules` WHERE 1 AND `type`='" . BX_DOL_MODULE_TYPE_TEMPLATE . "'" . $sWhereAddon, "uri");
  310. }
  311. /*
  312. * The Function Show a Line with Templates Names
  313. */
  314. function templates_select_txt() {
  315. $templ_choices = get_templates_array();
  316. $current_template = ( strlen( $_GET['skin'] ) ) ? $_GET['skin'] : $_COOKIE['skin'];
  317. foreach ($templ_choices as $tmpl_key => $tmpl_value) {
  318. if ($current_template == $tmpl_key) {
  319. $ReturnResult .= $tmpl_value . ' | ';
  320. } else {
  321. $sGetTransfer = bx_encode_url_params($_GET, array('skin'));
  322. $ReturnResult .= '<a href="' . bx_html_attribute($_SERVER['PHP_SELF']) . '?' . $sGetTransfer . 'skin=' . $tmpl_key . '">' . $tmpl_value . '</a> | ';
  323. }
  324. }
  325. return $ReturnResult;
  326. }
  327. function extFileExists( $sFileSrc ) {
  328. return (file_exists( $sFileSrc ) && is_file( $sFileSrc )) ? true : false;
  329. }
  330. function getVisitorIP() {
  331. $ip = "0.0.0.0";
  332. if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  333. $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
  334. } elseif (isset( $_SERVER['HTTP_CLIENT_IP']) && !empty($_SERVER['HTTP_CLIENT_IP'])) {
  335. $ip = explode(".",$_SERVER['HTTP_CLIENT_IP']);
  336. $ip = $ip[3].".".$ip[2].".".$ip[1].".".$ip[0];
  337. } elseif (!isset( $_SERVER['HTTP_X_FORWARDED_FOR']) || empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  338. if (!isset( $_SERVER['HTTP_CLIENT_IP']) && empty($_SERVER['HTTP_CLIENT_IP']) && isset($_SERVER['REMOTE_ADDR']))
  339. $ip = $_SERVER['REMOTE_ADDR'];
  340. }
  341. return $ip;
  342. }
  343. function genFlag( $country ) {
  344. return '<img src="' . genFlagUrl($country) . '" />';
  345. }
  346. function genFlagUrl($country) {
  347. bx_import('BxDolTemplate');
  348. return BxDolTemplate::getInstance()->getIconUrl('sys_fl_' . strtolower($country) . '.gif');
  349. }
  350. // print debug information ( e.g. arrays )
  351. function echoDbg( $what, $desc = '' ) {
  352. if ( $desc )
  353. echo "<b>$desc:</b> ";
  354. echo "<pre>";
  355. print_r( $what );
  356. echo "</pre>\n";
  357. }
  358. function echoDbgLog($mWhat, $sDesc = '', $sFileName = 'debug.log') {
  359. $sCont =
  360. '--- ' . date('r') . ' (' . BX_DOL_START_TIME . ") ---\n" .
  361. $sDesc . "\n" .
  362. print_r($mWhat, true) . "\n\n\n";
  363. $rFile = fopen(BxDolConfig::getInstance()->get('path_dynamic', 'tmp') . $sFileName, 'a');
  364. fwrite($rFile, $sCont);
  365. fclose($rFile);
  366. }
  367. function clear_xss($val) {
  368. if ($GLOBALS['logged']['admin'])
  369. return $val;
  370. // HTML Purifier plugin
  371. global $oHtmlPurifier;
  372. require_once( BX_DIRECTORY_PATH_PLUGINS . 'htmlpurifier/HTMLPurifier.standalone.php' );
  373. if (!isset($oHtmlPurifier)) {
  374. HTMLPurifier_Bootstrap::registerAutoload();
  375. $oConfig = HTMLPurifier_Config::createDefault();
  376. $oConfig->set('Cache.SerializerPath', rtrim(BX_DIRECTORY_PATH_CACHE, '/'));
  377. $oConfig->set('HTML.SafeObject', 'true');
  378. $oConfig->set('Output.FlashCompat', 'true');
  379. $oConfig->set('HTML.FlashAllowFullScreen', 'true');
  380. $oConfig->set('Filter.Custom', array (new HTMLPurifier_Filter_YouTube(), new HTMLPurifier_Filter_YoutubeIframe()));
  381. $oDef = $oConfig->getHTMLDefinition(true);
  382. $oDef->addAttribute('a', 'target', 'Enum#_blank,_self,_target,_top');
  383. $oHtmlPurifier = new HTMLPurifier($oConfig);
  384. }
  385. return $oHtmlPurifier->purify($val);
  386. }
  387. //--------------------------------------- friendly permalinks --------------------------------------//
  388. //------------------------------------------- main functions ---------------------------------------//
  389. function uriGenerate ($s, $sTable, $sField, $sEmpty = '-') {
  390. $s = uriFilter($s, $sEmpty);
  391. if(uriCheckUniq($s, $sTable, $sField))
  392. return $s;
  393. // cut off redundant part
  394. if(get_mb_len($s) > 240)
  395. $s = get_mb_substr($s, 0, 240);
  396. // try to add date
  397. $s .= '-' . date('Y-m-d');
  398. if(uriCheckUniq($s, $sTable, $sField))
  399. return $s;
  400. // try to add number
  401. for($i = 0 ; $i < 999 ; ++$i)
  402. if(uriCheckUniq($s . '-' . $i, $sTable, $sField))
  403. return ($s . '-' . $i);
  404. return rand(0, 999999999);
  405. }
  406. function uriFilter ($s, $sEmpty = '-') {
  407. bx_import('BxTemplConfig');
  408. if (BxTemplConfig::getInstance()->bAllowUnicodeInPreg)
  409. $s = get_mb_replace ('/[^\pL^\pN]+/u', '-', $s); // unicode characters
  410. else
  411. $s = get_mb_replace ('/([^\d^\w]+)/u', '-', $s); // latin characters only
  412. $s = get_mb_replace ('/([-^]+)/', '-', $s);
  413. $s = get_mb_replace ('/([-]+)$/', '', $s); // remove trailing dash
  414. if (!$s) $s = $sEmpty;
  415. return $s;
  416. }
  417. function uriCheckUniq ($s, $sTable, $sField) {
  418. bx_import('BxDolDb');
  419. $oDb = BxDolDb::getInstance();
  420. $sSql = $oDb->prepare("SELECT 1 FROM `$sTable` WHERE `$sField`=? LIMIT 1", $s);
  421. return !$oDb->query($sSql);
  422. }
  423. function get_mb_replace ($sPattern, $sReplace, $s) {
  424. return preg_replace ($sPattern, $sReplace, $s);
  425. }
  426. function get_mb_len ($s) {
  427. return (function_exists('mb_strlen')) ? mb_strlen($s) : strlen($s);
  428. }
  429. function get_mb_substr ($s, $iStart, $iLen) {
  430. return (function_exists('mb_substr')) ? mb_substr ($s, $iStart, $iLen) : substr ($s, $iStart, $iLen);
  431. }
  432. function bx_mb_substr_replace($s, $sReplace, $iPosStart, $iLength) {
  433. return mb_substr($s, 0, $iPosStart) . $sReplace . mb_substr($s, $iPosStart + $iLength);
  434. }
  435. function bx_mb_strpos ($s, $sReplacement, $iStart = 0) {
  436. return mb_strpos($s, $sReplacement, $iStart);
  437. }
  438. /**
  439. * Import class file, it automatically detects class path by its prefix or module array/name
  440. *
  441. * @param $sClassName - full class name or class postfix(withoit prefix) in the case of module class
  442. * @param $mixedModule - module array or module name in the case of module class
  443. */
  444. function bx_import($sClassName, $mixedModule = array()) {
  445. if (class_exists($sClassName))
  446. return;
  447. $aModule = false;
  448. if ($mixedModule) {
  449. if (is_array($mixedModule)) {
  450. $aModule = $mixedModule;
  451. } elseif (is_string($mixedModule)) {
  452. bx_import('BxDolModule');
  453. $o = BxDolModule::getInstance($mixedModule);
  454. $aModule = $o->_aModule;
  455. } elseif (is_bool($mixedModule) && true === $mixedModule) {
  456. $aModule = $GLOBALS['aModule'];
  457. }
  458. }
  459. if ($aModule) {
  460. if (class_exists($aModule['class_prefix'] . $sClassName))
  461. return;
  462. require_once (BX_DIRECTORY_PATH_MODULES . $aModule['path'] . 'classes/' . $aModule['class_prefix'] . $sClassName . '.php');
  463. return;
  464. }
  465. if (0 == strncmp($sClassName, 'BxDol', 5)) {
  466. if (0 == strncmp($sClassName, 'BxDolStudio', 11))
  467. require_once(BX_DOL_DIR_STUDIO_CLASSES . $sClassName . '.php');
  468. else
  469. require_once(BX_DIRECTORY_PATH_CLASSES . $sClassName . '.php');
  470. return;
  471. }
  472. if (0 == strncmp($sClassName, 'BxBase', 6)) {
  473. if (0 == strncmp($sClassName, 'BxBaseMod', 9)) {
  474. $aMatches = array();
  475. if (preg_match('/BxBaseMod([A-Z][a-z]+)/', $sClassName, $aMatches)) {
  476. require_once(BX_DIRECTORY_PATH_MODULES . 'base/' . strtolower($aMatches[1]) . '/classes/' . $sClassName . '.php');
  477. return;
  478. }
  479. } if (0 == strncmp($sClassName, 'BxBaseStudio', 12)) {
  480. require_once(BX_DOL_DIR_STUDIO_BASE . 'scripts/' . $sClassName . '.php');
  481. return;
  482. } else {
  483. require_once(BX_DIRECTORY_PATH_BASE . 'scripts/' . $sClassName . '.php');
  484. return;
  485. }
  486. }
  487. if (0 == strncmp($sClassName, 'BxTempl', 7) && !class_exists($sClassName)) {
  488. if(0 == strncmp($sClassName, 'BxTemplStudio', 13)) {
  489. bx_import('BxDolStudioTemplate');
  490. $sPath = BX_DIRECTORY_PATH_MODULES . BxDolStudioTemplate::getInstance()->getPath() . 'data/template/studio/scripts/' . $sClassName . '.php';
  491. }
  492. else {
  493. bx_import('BxDolTemplate');
  494. $sPath = BX_DIRECTORY_PATH_MODULES . BxDolTemplate::getInstance()->getPath() . 'data/template/system/scripts/' . $sClassName . '.php';
  495. }
  496. if (file_exists($sPath)) {
  497. require_once($sPath);
  498. return;
  499. }
  500. trigger_error ("bx_import fatal error: class (" . $sClassName . ") wasn't found", E_USER_ERROR);
  501. }
  502. }
  503. /**
  504. * Gets an instance of class pathing necessary parameters if it's necessary.
  505. *
  506. * @param string $sClassName class name.
  507. * @param array $aParams an array of parameters to be pathed to the constructor of the class.
  508. * @param array $aModule an array with module description. Is used when the requested class is located in some module.
  509. * @return unknown
  510. */
  511. function bx_instance($sClassName, $aParams = array(), $aModule = array()) {
  512. if(isset($GLOBALS['bxDolClasses'][$sClassName]))
  513. return $GLOBALS['bxDolClasses'][$sClassName];
  514. else {
  515. bx_import((empty($aModule) ? $sClassName : str_replace($aModule['class_prefix'], '', $sClassName)), $aModule);
  516. if(empty($aParams))
  517. $GLOBALS['bxDolClasses'][$sClassName] = new $sClassName();
  518. else {
  519. $sParams = "";
  520. foreach($aParams as $mixedKey => $mixedValue)
  521. $sParams .= "\$aParams[" . $mixedKey . "], ";
  522. $sParams = substr($sParams, 0, -2);
  523. $GLOBALS['bxDolClasses'][$sClassName] = eval("return new " . $sClassName . "(" . $sParams . ");"); // TODO: remake without eval
  524. }
  525. return $GLOBALS['bxDolClasses'][$sClassName];
  526. }
  527. }
  528. /**
  529. * Escapes string/array ready to pass to js script with filtered symbols like ', " etc
  530. *
  531. * @param $mixedInput - string/array which should be filtered
  532. * @param $iQuoteType - string escaping method: BX_ESCAPE_STR_AUTO(default), BX_ESCAPE_STR_APOS or BX_ESCAPE_STR_QUOTE
  533. * @return converted string / array
  534. */
  535. function bx_js_string ($mixedInput, $iQuoteType = BX_ESCAPE_STR_AUTO) {
  536. $aUnits = array(
  537. "\n" => "\\n",
  538. "\r" => "",
  539. );
  540. if (BX_ESCAPE_STR_APOS == $iQuoteType) {
  541. $aUnits["'"] = "\\'";
  542. $aUnits['<script'] = "<scr' + 'ipt";
  543. $aUnits['</script>'] = "</scr' + 'ipt>";
  544. } elseif (BX_ESCAPE_STR_QUOTE == $iQuoteType) {
  545. $aUnits['"'] = '\\"';
  546. $aUnits['<script'] = '<scr" + "ipt';
  547. $aUnits['</script>'] = '</scr" + "ipt>';
  548. } else {
  549. $aUnits['"'] = '&quote;';
  550. $aUnits["'"] = '&apos;';
  551. $aUnits["<"] = '&lt;';
  552. $aUnits[">"] = '&gt;';
  553. }
  554. return str_replace(array_keys($aUnits), array_values($aUnits), $mixedInput);
  555. }
  556. /**
  557. * Return input string/array ready to pass to html attribute with filtered symbols like ', " etc
  558. *
  559. * @param mixed $mixedInput - string/array which should be filtered
  560. * @return converted string / array
  561. */
  562. function bx_html_attribute ($mixedInput, $iQuoteType = BX_ESCAPE_STR_AUTO) {
  563. $aUnits = array ();
  564. if (BX_ESCAPE_STR_APOS == $iQuoteType)
  565. $aUnits["'"] = "\\'";
  566. elseif (BX_ESCAPE_STR_QUOTE == $iQuoteType)
  567. $aUnits['"'] = '&quot;';
  568. else
  569. $aUnits = array("\"" => "&quot;", "'" => "&apos;");
  570. return str_replace(array_keys($aUnits), array_values($aUnits), $mixedInput);
  571. }
  572. /**
  573. * Escapes string/array ready to pass to php script with filtered symbols like ', " etc
  574. *
  575. * @param mixed $mixedInput - string/array which should be filtered
  576. * @return converted string / array
  577. */
  578. function bx_php_string_apos ($mixedInput) {
  579. return str_replace("'", "\\'", $mixedInput);
  580. }
  581. function bx_php_string_quot ($mixedInput) {
  582. return str_replace('"', '\\"', $mixedInput);
  583. }
  584. /**
  585. * Gets file contents by URL.
  586. *
  587. * @param string $sFileUrl - file URL to be read.
  588. * @param array $aParams - an array of parameters to be pathed with URL.
  589. * @return string the file's contents.
  590. */
  591. function bx_file_get_contents($sFileUrl, $aParams = array(), $bChangeTimeout = false) {
  592. if ($aParams)
  593. $sFileUrl = bx_append_url_params($sFileUrl, $aParams);
  594. $sResult = '';
  595. if(function_exists('curl_init')) {
  596. $rConnect = curl_init();
  597. curl_setopt($rConnect, CURLOPT_URL, $sFileUrl);
  598. curl_setopt($rConnect, CURLOPT_HEADER, 0);
  599. curl_setopt($rConnect, CURLOPT_RETURNTRANSFER, 1);
  600. curl_setopt($rConnect, CURLOPT_FOLLOWLOCATION, 1);
  601. if ($bChangeTimeout) {
  602. curl_setopt($rConnect, CURLOPT_CONNECTTIMEOUT, 3);
  603. curl_setopt($rConnect, CURLOPT_TIMEOUT, 3);
  604. }
  605. $sAllCookies = '';
  606. foreach($_COOKIE as $sKey=>$sValue){
  607. $sAllCookies .= $sKey."=".$sValue.";";
  608. }
  609. curl_setopt($rConnect, CURLOPT_COOKIE, $sAllCookies);
  610. $sResult = curl_exec($rConnect);
  611. curl_close($rConnect);
  612. } else {
  613. $iSaveTimeout = false;
  614. if ($bChangeTimeout) {
  615. $iSaveTimeout = ini_get('default_socket_timeout');
  616. ini_set('default_socket_timeout', 3);
  617. }
  618. $sResult = @file_get_contents($sFileUrl);
  619. if ($bChangeTimeout && false !== $iSaveTimeout) {
  620. ini_set('default_socket_timeout', $iSaveTimeout);
  621. }
  622. }
  623. return $sResult;
  624. }
  625. // calculation ini_get('upload_max_filesize') in bytes as example
  626. function return_bytes($val) {
  627. $val = trim($val);
  628. $last = strtolower($val{strlen($val)-1});
  629. $val = (int)$val;
  630. switch($last) {
  631. // The 'G' modifier is available since PHP 5.1.0
  632. case 'k':
  633. $val *= 1024;
  634. break;
  635. case 'm':
  636. $val *= 1024 * 1024;
  637. break;
  638. case 'g':
  639. $val *= 1024 * 1024 * 1024;
  640. break;
  641. }
  642. return $val;
  643. }
  644. // Generate Random Password
  645. function genRndPwd($iLength = 8, $bSpecialCharacters = true) {
  646. $sPassword = '';
  647. $sChars = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
  648. if($bSpecialCharacters === true)
  649. $sChars .= "!?=/&+,.";
  650. srand((double)microtime()*1000000);
  651. for($i = 0; $i < $iLength; $i++) {
  652. $x = mt_rand(0, strlen($sChars) -1);
  653. $sPassword .= $sChars{$x};
  654. }
  655. return $sPassword;
  656. }
  657. // Generate Random Salt for Password encryption
  658. function genRndSalt() {
  659. return genRndPwd(8, true);
  660. }
  661. // Encrypt User Password
  662. function encryptUserPwd($sPwd, $sSalt) {
  663. return sha1(md5($sPwd) . $sSalt);
  664. }
  665. function bx_get ($sName) {
  666. if (isset($_GET[$sName]))
  667. return $_GET[$sName];
  668. elseif (isset($_POST[$sName]))
  669. return $_POST[$sName];
  670. else
  671. return false;
  672. }
  673. function bx_encode_url_params ($a, $aExcludeKeys = array (), $aOnlyKeys = false) {
  674. $s = '';
  675. foreach ($a as $sKey => $sVal) {
  676. if (in_array($sKey, $aExcludeKeys))
  677. continue;
  678. if (false !== $aOnlyKeys && !in_array($sKey, $aOnlyKeys))
  679. continue;
  680. if (is_array($sVal)) {
  681. foreach ($sVal as $sSubVal) {
  682. $s .= rawurlencode($sKey) . '[]=' . rawurlencode(is_array($sSubVal) ? 'array' : $sSubVal) . '&';
  683. }
  684. } else {
  685. $s .= rawurlencode($sKey) . '=' . rawurlencode($sVal) . '&';
  686. }
  687. }
  688. return $s;
  689. }
  690. function bx_append_url_params ($sUrl, $mixedParams) {
  691. if (!$mixedParams)
  692. return $sUrl;
  693. $sParams = false == strpos($sUrl, '?') ? '?' : '&';
  694. if (is_array($mixedParams)) {
  695. foreach($mixedParams as $sKey => $sValue)
  696. $sParams .= $sKey . '=' . $sValue . '&';
  697. $sParams = substr($sParams, 0, -1);
  698. } else {
  699. $sParams .= $mixedParams;
  700. }
  701. return $sUrl . $sParams;
  702. }
  703. function bx_rrmdir($directory) {
  704. if (substr($directory,-1) == "/")
  705. $directory = substr($directory,0,-1);
  706. if (!file_exists($directory) || !is_dir($directory))
  707. return false;
  708. elseif (!is_readable($directory))
  709. return false;
  710. if (!($directoryHandle = opendir($directory)))
  711. return false;
  712. while ($contents = readdir($directoryHandle)) {
  713. if ($contents != '.' && $contents != '..') {
  714. $path = $directory . "/" . $contents;
  715. if (is_dir($path))
  716. bx_rrmdir($path);
  717. else
  718. unlink($path);
  719. }
  720. }
  721. closedir($directoryHandle);
  722. if (!rmdir($directory))
  723. return false;
  724. return true;
  725. }
  726. function bx_clear_folder ($sPath, $aExts = array ()) {
  727. if (substr($$sPath,-1) == "/")
  728. $sPath = substr($sPath,0,-1);
  729. if (!file_exists($sPath) || !is_dir($sPath))
  730. return false;
  731. elseif (!is_readable($sPath))
  732. return false;
  733. if (!($h = opendir($sPath)))
  734. return false;
  735. while ($sFile = readdir($h)) {
  736. if ('.' == $sFile || '..' == $sFile)
  737. continue;
  738. $sFullPath = $sPath . '/' . $sFile;
  739. if (is_dir($sFullPath))
  740. continue;
  741. if (!$aExts || (($sExt = pathinfo($sFullPath, PATHINFO_EXTENSION)) && in_array($sExt, $aExts)))
  742. @unlink($sFullPath);
  743. }
  744. closedir($h);
  745. return true;
  746. }
  747. function bx_ltrim_str ($sString, $sPrefix, $sReplace = '') {
  748. if ($sReplace && substr($sString, 0, strlen($sReplace)) == $sReplace)
  749. return $sString;
  750. if (substr($sString, 0, strlen($sPrefix)) == $sPrefix)
  751. return $sReplace . substr($sString, strlen($sPrefix));
  752. return $sString;
  753. }
  754. /**
  755. * Convert array to attributes string
  756. *
  757. * Example:
  758. * @code
  759. * $a = array('name' => 'test', 'value' => 5);
  760. * $s = bx_convert_array2attrs($a);
  761. * echo $s; // outputs: name="test" value="5"
  762. * @endcode
  763. *
  764. * @param $a - array of attributes
  765. * @param $sClasses - classes to merge with 'class' attribute
  766. * @param $sStyles - styles to merge with 'style' attribute
  767. * @return string
  768. */
  769. function bx_convert_array2attrs ($a, $sClasses = false, $sStyles = false) {
  770. $sRet = '';
  771. if (!$a || !is_array($a))
  772. $a = array();
  773. if ($sClasses) {
  774. $sClasses = trim($sClasses);
  775. $a['class'] = $sClasses . (!empty($a['class']) ? ' ' . $a['class'] : '');
  776. }
  777. if ($sStyles) {
  778. $sStyles = trim($sStyles);
  779. if (';' != $sStyles[strlen($sStyles)-1])
  780. $sStyles .= ';';
  781. $a['style'] = $sStyles . (!empty($a['style']) ? ' ' . $a['style'] : '');
  782. }
  783. foreach ($a as $sKey => $sValue) {
  784. if(is_null($sValue)) // pass NULL values
  785. continue;
  786. $sValueC = bx_html_attribute($sValue, BX_ESCAPE_STR_QUOTE);
  787. $sRet .= " $sKey=\"$sValueC\"";
  788. }
  789. return $sRet;
  790. }
  791. function bx_unicode_urldecode($s) {
  792. preg_match_all('/%u([[:alnum:]]{4})/', $s, $a);
  793. foreach ($a[1] as $uniord)
  794. {
  795. $dec = hexdec($uniord);
  796. $utf = '';
  797. if ($dec < 128)
  798. {
  799. $utf = chr($dec);
  800. }
  801. else if ($dec < 2048)
  802. {
  803. $utf = chr(192 + (($dec - ($dec % 64)) / 64));
  804. $utf .= chr(128 + ($dec % 64));
  805. }
  806. else
  807. {
  808. $utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
  809. $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
  810. $utf .= chr(128 + ($dec % 64));
  811. }
  812. $s = str_replace('%u'.$uniord, $utf, $s);
  813. }
  814. return urldecode($s);
  815. }
  816. /**
  817. * Raise an alert
  818. * @param string $sType - system type
  819. * @param string $sAction - system action
  820. * @param int $iObjectId - object id
  821. * @param int $iSenderId - sender (action's author) profile id, if it is false - then currectly logged in profile id is used
  822. */
  823. function bx_alert($sUnit, $sAction, $iObjectId, $iSender = false, $aExtras = array()) {
  824. $o = new BxDolAlerts($sUnit, $sAction, $iObjectId, $iSender, $aExtras);
  825. $o->alert();
  826. }
  827. function bx_replace_markers($mixed, $aMarkers) {
  828. if (empty($aMarkers))
  829. return $mixed;
  830. if (is_array($mixed)) {
  831. foreach ($mixed as $sKey => $sValue)
  832. $mixed[$sKey] = bx_replace_markers ($sValue, $aMarkers);
  833. } else {
  834. foreach ($aMarkers as $sKey => $sValue)
  835. $mixed = str_replace('{' . $sKey . '}', $sValue, $mixed);
  836. }
  837. return $mixed;
  838. }
  839. function bx_site_hash($sSalt = '', $isSkipVersion = false) {
  840. return md5($sSalt . ($isSkipVersion ? '' : getParam('sys_version')) . BX_DOL_SECRET . BX_DOL_URL_ROOT);
  841. }
  842. /**
  843. * Transform string to method name string, for example it changes 'some_method' string to 'SomeMethod' string
  844. * @param string where words are separated with underscore
  845. * @return string where every word begins with capital letter
  846. */
  847. function bx_gen_method_name ($s, $sWordsDelimiter = '_') {
  848. return str_replace(' ', '', ucwords(str_replace($sWordsDelimiter, ' ', $s)));
  849. }
  850. /**
  851. * Trigger user error
  852. * @param $sMsg message to display
  853. * @param $iNumLevelsBack add additional debug backtracing N levels back
  854. */
  855. function bx_trigger_error ($sMsg, $iNumLevelsBack = 0) {
  856. $a = debug_backtrace();
  857. $sMsgAdd = "<br />\n related code in <b>{$a[$iNumLevelsBack]['file']}</b> on line <b>{$a[$iNumLevelsBack]['line']}</b> <br />\n";
  858. trigger_error ($sMsg . $sMsgAdd, E_USER_ERROR);
  859. }
  860. /** @} */