utils.inc.php 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408
  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 TridentCore Trident 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. define('BX_MAINTENANCE_FILE', '.bx_maintenance'); ///< file name to use as mantenance mode indicator
  29. /**
  30. * The following two functions are needed to convert title to uri and back.
  31. * It usefull when titles are used in URLs, like in Categories and Tags.
  32. */
  33. function title2uri($sValue)
  34. {
  35. return str_replace(
  36. array('&', '/', '\\', '"', '+'),
  37. array('[and]', '[slash]', '[backslash]', '[quote]', '[plus]'),
  38. $sValue
  39. );
  40. }
  41. function uri2title($sValue)
  42. {
  43. return str_replace(
  44. array('[and]', '[slash]', '[backslash]', '[quote]', '[plus]'),
  45. array('&', '/', '\\', '"', '+'),
  46. $sValue
  47. );
  48. }
  49. /*
  50. * functions for limiting maximal text length
  51. */
  52. function strmaxtextlen($sInput, $iMaxLen = 60, $sEllipsisSign = '&#8230;')
  53. {
  54. $sTail = '';
  55. $s = trim(strip_tags($sInput));
  56. if (mb_strlen($s) > $iMaxLen) {
  57. $s = mb_substr($s, 0, $iMaxLen);
  58. $sTail = $sEllipsisSign;
  59. }
  60. return htmlspecialchars_adv($s) . $sTail;
  61. }
  62. function html2txt($content, $tags = "")
  63. {
  64. while($content != strip_tags($content, $tags)) {
  65. $content = strip_tags($content, $tags);
  66. }
  67. return $content;
  68. }
  69. /**
  70. * Functions to process user input.
  71. * DON'T use to process data before passing to SQL query - use db prepare instead @see BxDolDb::prepare.
  72. * It is ok to use bx_process_input and then db prepare.
  73. * @param $mixedData data to process
  74. * @param $iDataType how to handle data, possible valies:
  75. * BX_DATA_INT - integer value
  76. * BX_DATA_FLOAT - float values
  77. * BX_DATA_CHECKBOX - 'on' or empty string
  78. * BX_DATA_TEXT - text data, single line (default)
  79. * BX_DATA_TEXT_MULTILINE - text data, multiple lines
  80. * BX_DATA_HTML - HTML data
  81. * BX_DATA_DATE - date data type stored as yyyy-mm-dd
  82. * BX_DATA_DATE_TS' - date data type stored as unixtimestamp
  83. * BX_DATA_DATETIME_TS - date/time data type stored as unixtimestamp
  84. * @param $mixedParams optional parameters to pass for validation
  85. * @return the filtered data, or FALSE if the filter fails.
  86. */
  87. function bx_process_input ($mixedData, $iDataType = BX_DATA_TEXT, $mixedParams = false, $isCheckMagicQuotes = true)
  88. {
  89. if (is_array($mixedData)) {
  90. foreach ($mixedData as $k => $v)
  91. $mixedData[$k] = bx_process_input($v, $iDataType, $mixedParams);
  92. return $mixedData;
  93. }
  94. if (get_magic_quotes_gpc() && $isCheckMagicQuotes)
  95. $mixedData = stripslashes($mixedData);
  96. switch ($iDataType) {
  97. case BX_DATA_INT:
  98. return filter_var(trim($mixedData), FILTER_VALIDATE_INT);
  99. case BX_DATA_FLOAT:
  100. return filter_var(trim($mixedData), FILTER_VALIDATE_FLOAT);
  101. case BX_DATA_CHECKBOX:
  102. return 'on' == trim($mixedData) ? 'on' : '';
  103. case BX_DATA_DATE:
  104. // maybe consider using strtotime
  105. $mixedData = trim($mixedData);
  106. if (!preg_match('/^\d{4}-\d{1,2}-\d{1,2}$/', $mixedData))
  107. return false;
  108. list($iYear, $iMonth, $iDay) = explode('-', $mixedData); // 1985-10-28
  109. $iDay = intval($iDay);
  110. $iMonth = intval($iMonth);
  111. $iYear = intval($iYear);
  112. return sprintf("%04d-%02d-%02d", $iYear, $iMonth, $iDay);
  113. case BX_DATA_DATE_TS:
  114. $mixedData = trim($mixedData);
  115. if (!preg_match('/^\d{4}-\d{1,2}-\d{1,2}$/', $mixedData))
  116. return false;
  117. list($iYear, $iMonth, $iDay) = explode('-', $mixedData);
  118. $iDay = intval($iDay);
  119. $iMonth = intval($iMonth);
  120. $iYear = intval($iYear);
  121. $iRet = mktime (0, 0, 0, $iMonth, $iDay, $iYear);
  122. return $iRet > 0 ? $iRet : false;
  123. case BX_DATA_DATETIME_TS:
  124. if (!preg_match('#(\d+)\-(\d+)\-(\d+)[\sT]{1}(\d+):(\d+):(\d+)#', $mixedData, $m) && !preg_match('#(\d+)\-(\d+)\-(\d+)[\sT]{1}(\d+):(\d+)#', $mixedData, $m))
  125. return bx_process_input ($mixedData, BX_DATA_DATE_TS, $mixedParams, $isCheckMagicQuotes);
  126. $iDay = $m[3];
  127. $iMonth = $m[2];
  128. $iYear = $m[1];
  129. $iH = $m[4];
  130. $iM = $m[5];
  131. $iS = isset($m[6]) ? $m[6] : 0;
  132. $iRet = mktime ($iH, $iM, $iS, $iMonth, $iDay, $iYear);
  133. return $iRet > 0 ? $iRet : false;
  134. case BX_DATA_HTML:
  135. return clear_xss($mixedData);
  136. case BX_DATA_TEXT_MULTILINE:
  137. return nl2br(htmlspecialchars_adv($mixedData));
  138. case BX_DATA_TEXT:
  139. default:
  140. return $mixedData;
  141. }
  142. }
  143. /*
  144. * Functions to process user output.
  145. * Always use this function before output data which was entered by user before.
  146. * @param $mixedData string to process
  147. * @param $iDataType how to handle data, possible valies the same as in bx_process_input function, see bx_process_input.
  148. * @param $mixedParams optional parameters to pass for validation
  149. * @return the filtered data, or FALSE if the filter fails.
  150. */
  151. function bx_process_output ($mixedData, $iDataType = BX_DATA_TEXT, $mixedParams = false)
  152. {
  153. if (is_array($mixedData)) {
  154. foreach ($mixedData as $k => $v)
  155. $mixedData[$k] = bx_process_output($v, $iDataType, $mixedParams);
  156. return $mixedData;
  157. }
  158. switch ($iDataType) {
  159. case BX_DATA_INT:
  160. return filter_var($mixedData, FILTER_VALIDATE_INT);
  161. case BX_DATA_FLOAT:
  162. return filter_var($mixedData, FILTER_VALIDATE_FLOAT);
  163. case BX_DATA_CHECKBOX:
  164. return 'on' == trim($mixedData) ? 'on' : '';
  165. case BX_DATA_DATE:
  166. return $mixedData;
  167. case BX_DATA_DATE_TS:
  168. return empty($mixedData) ? '' : date("Y-m-d", $mixedData);
  169. case BX_DATA_DATETIME_TS:
  170. return empty($mixedData) ? '' : date("Y-m-d H:i", $mixedData);
  171. case BX_DATA_HTML:
  172. return $mixedData;
  173. case BX_DATA_TEXT_MULTILINE:
  174. return $mixedData;
  175. case BX_DATA_TEXT:
  176. default:
  177. return htmlspecialchars_adv($mixedData);
  178. }
  179. }
  180. /*
  181. * This function apply bx_process_input and then bx_process_output.
  182. * Use this function to output data immediately after receiving, without saving to database.
  183. * Patams are the same as bx_process_input function - @see bx_process_input
  184. */
  185. function bx_process_pass ($mixedData, $iDataType = BX_DATA_TEXT, $mixedParams = false, $isCheckMagicQuotes = true)
  186. {
  187. return bx_process_output(bx_process_input ($mixedData, $iDataType, $mixedParams, $isCheckMagicQuotes), $iDataType, $mixedParams);
  188. }
  189. /**
  190. * DEPRECATED
  191. * use bx_process_input + bx_process_output instead
  192. * --------
  193. * function for processing pass data
  194. *
  195. * This function cleans the GET/POST/COOKIE data if magic_quotes_gpc() is on
  196. * for data which should be outputed immediately after submit
  197. */
  198. /*
  199. function process_pass_data( $text, $strip_tags = 0 )
  200. {
  201. if ( $strip_tags )
  202. $text = strip_tags($text);
  203. if ( !get_magic_quotes_gpc() )
  204. return $text;
  205. else
  206. return stripslashes($text);
  207. }
  208. */
  209. /*
  210. * function for output data from database into html
  211. */
  212. function htmlspecialchars_adv( $string )
  213. {
  214. return htmlspecialchars($string, ENT_COMPAT, 'UTF-8', false);
  215. }
  216. /**
  217. * Send mail to user by parsing email template
  218. */
  219. function sendMailTemplate($sTemplateName, $iAccountId = 0, $iProfileId = 0, $aReplaceVars = array(), $iEmailType = BX_EMAIL_NOTIFY)
  220. {
  221. $oAccount = BxDolAccount::getInstance($iAccountId);
  222. $oProfile = BxDolProfile::getInstance($iProfileId);
  223. $oEmailTemplates = BxDolEmailTemplates::getInstance();
  224. if (!$oAccount || !$oProfile || !$oEmailTemplates)
  225. return false;
  226. $aTemplate = $oEmailTemplates->parseTemplate($sTemplateName, $aReplaceVars, $iAccountId, (int)$iProfileId);
  227. if (!$aTemplate)
  228. return false;
  229. return sendMail($oAccount->getEmail(), $aTemplate['Subject'], $aTemplate['Body'], 0, array(), $iEmailType);
  230. }
  231. /**
  232. * Send system email
  233. */
  234. function sendMailTemplateSystem($sTemplateName, $aReplaceVars = array(), $iEmailType = BX_EMAIL_SYSTEM)
  235. {
  236. $oEmailTemplates = BxDolEmailTemplates::getInstance();
  237. if (!$oEmailTemplates)
  238. return false;
  239. $aTemplate = $oEmailTemplates->parseTemplate($sTemplateName, $aReplaceVars);
  240. if (!$aTemplate)
  241. return false;
  242. return sendMail(getParam('site_email'), $aTemplate['Subject'], $aTemplate['Body'], 0, array(), $iEmailType);
  243. }
  244. /**
  245. * Send email function
  246. *
  247. * @param $sRecipientEmail - Email where email should be send
  248. * @param $sMailSubject - subject of the message
  249. * @param $sMailBody - Body of the message
  250. * @param $iRecipientID - ID of recipient profile
  251. * @param $aPlus - Array of additional information
  252. * @param $iEmailType - email message type: BX_EMAIL_SYSTEM, BX_EMAIL_NOTIFY or BX_EMAIL_MASS
  253. * @return true if message was send or false otherwise
  254. */
  255. function sendMail($sRecipientEmail, $sMailSubject, $sMailBody, $iRecipientID = 0, $aPlus = array(), $iEmailType = BX_EMAIL_NOTIFY, $sEmailFlag = 'html', $isDisableAlert = false)
  256. {
  257. // make sure that recipient's email is valid and message isn't empty
  258. if (!$sMailBody || !$sRecipientEmail || preg_match('/\(2\)$/', $sRecipientEmail))
  259. return false;
  260. // get recipient account
  261. $oAccount = !$isDisableAlert ? BxDolAccount::getInstance($sRecipientEmail) : null;
  262. $aAccountInfo = $oAccount ? $oAccount->getInfo() : false;
  263. // don't send bulk emails if user didn't subscribed to site news or email is unconfirmed
  264. if ($aAccountInfo && BX_EMAIL_MASS == $iEmailType && (!$aAccountInfo['email_confirmed'] || !$aAccountInfo['receive_news']))
  265. return false;
  266. // don't send email notifications if user didn't subscribed to notifications or email is unconfirmed
  267. if ($aAccountInfo && BX_EMAIL_NOTIFY == $iEmailType && (!$aAccountInfo['email_confirmed'] || !$aAccountInfo['receive_updates']))
  268. return false;
  269. // if profile id is provided - get profile's info
  270. $aRecipientInfo = false;
  271. if ($iRecipientID) {
  272. $oProfile = BxDolProfile::getInstance($iRecipientID);
  273. if ($oProfile)
  274. $aRecipientInfo = $oProfile->getInfo();
  275. }
  276. // get site vars
  277. $sEmailNotify = !$isDisableAlert ? getParam('site_email_notify') : $sRecipientEmail;
  278. $sSiteTitle = !$isDisableAlert ? getParam('site_title') : 'Trident ' . BX_DOL_VERSION;
  279. // add unsubscribe link
  280. if (!$isDisableAlert && empty($aPlus['unsubscribe'])) {
  281. $aPlus['unsubscribe'] = '';
  282. if ($oAccount && (BX_EMAIL_MASS == $iEmailType || BX_EMAIL_NOTIFY == $iEmailType))
  283. $aPlus['unsubscribe'] = ($sLink = $oAccount->getUnsubscribeLink($iEmailType)) ? '<a href="' . BX_DOL_URL_ROOT . $sLink . '">' . _t('_sys_et_txt_unsubscribe') . '</a>' : '';
  284. }
  285. // parse template
  286. if ($aPlus || $iRecipientID) {
  287. if(!is_array($aPlus))
  288. $aPlus = array();
  289. $oEmailTemplates = BxDolEmailTemplates::getInstance();
  290. $sMailSubject = $oEmailTemplates->parseContent($sMailSubject, $aPlus, $iRecipientID);
  291. $sMailBody = $oEmailTemplates->parseContent($sMailBody, $aPlus, $iRecipientID);
  292. }
  293. // email message headers
  294. $sMailHeader = "From: =?UTF-8?B?" . base64_encode( $sSiteTitle ) . "?= <{$sEmailNotify}>";
  295. $sMailParameters = "-f{$sEmailNotify}";
  296. $sMailSubject = '=?UTF-8?B?' . base64_encode( $sMailSubject ) . '?=';
  297. $sMailHeader = "MIME-Version: 1.0\r\n" . $sMailHeader;
  298. // build data for alert handler
  299. $bResult = null;
  300. $aAlert = array(
  301. 'email' => $sRecipientEmail,
  302. 'subject' => $sMailSubject,
  303. 'body' => $sMailBody,
  304. 'header' => $sMailHeader,
  305. 'params' => $sMailParameters,
  306. 'recipient' => $aRecipientInfo,
  307. 'html' => 'html' == $sEmailFlag ? true : false,
  308. 'override_result' => &$bResult,
  309. );
  310. // system alert
  311. if (!$isDisableAlert) {
  312. bx_alert('system', 'before_send_mail', (isset($aRecipientInfo['ID']) ? $aRecipientInfo['ID'] : 0), '', $aAlert);
  313. if ($bResult !== null)
  314. return $bResult;
  315. unset($aAlert['override_result']);
  316. }
  317. // send mail
  318. if( 'html' == $sEmailFlag) {
  319. $sMailHeader = "Content-type: text/html; charset=UTF-8\r\n" . $sMailHeader;
  320. $iSendingResult = mail( $sRecipientEmail, $sMailSubject, $sMailBody, $sMailHeader, $sMailParameters );
  321. } else {
  322. $sMailHeader = "Content-type: text/plain; charset=UTF-8\r\n" . $sMailHeader;
  323. $sMailBody = html2txt($sMailBody);
  324. $iSendingResult = mail( $sRecipientEmail, $sMailSubject, html2txt($sMailBody), $sMailHeader, $sMailParameters );
  325. }
  326. // system alert
  327. if (!$isDisableAlert)
  328. bx_alert('system', 'send_mail', (isset($aRecipientInfo['ID']) ? $aRecipientInfo['ID'] : 0), '', $aAlert);
  329. return $iSendingResult;
  330. }
  331. /*
  332. * Getting an array with Templates' Names
  333. */
  334. function get_templates_array($bEnabledOnly = true, $bShortInfo = true)
  335. {
  336. $oDb = BxDolDb::getInstance();
  337. $sWhereAddon = $bEnabledOnly ? " AND `enabled`='1'" : "";
  338. if($bShortInfo)
  339. return $oDb->getPairs("SELECT `uri`, `title` FROM `sys_modules` WHERE 1 AND `type`='" . BX_DOL_MODULE_TYPE_TEMPLATE . "'" . $sWhereAddon, "uri", "title");
  340. else
  341. return $oDb->getAllWithKey("SELECT * FROM `sys_modules` WHERE 1 AND `type`='" . BX_DOL_MODULE_TYPE_TEMPLATE . "'" . $sWhereAddon, "uri");
  342. }
  343. function extFileExists( $sFileSrc )
  344. {
  345. return (file_exists( $sFileSrc ) && is_file( $sFileSrc )) ? true : false;
  346. }
  347. function getVisitorIP()
  348. {
  349. $ip = "0.0.0.0";
  350. if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  351. $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
  352. } elseif (isset( $_SERVER['HTTP_CLIENT_IP']) && !empty($_SERVER['HTTP_CLIENT_IP'])) {
  353. $ip = explode(".",$_SERVER['HTTP_CLIENT_IP']);
  354. $ip = $ip[3].".".$ip[2].".".$ip[1].".".$ip[0];
  355. } elseif (!isset( $_SERVER['HTTP_X_FORWARDED_FOR']) || empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  356. if (!isset( $_SERVER['HTTP_CLIENT_IP']) && empty($_SERVER['HTTP_CLIENT_IP']) && isset($_SERVER['REMOTE_ADDR']))
  357. $ip = $_SERVER['REMOTE_ADDR'];
  358. }
  359. return $ip;
  360. }
  361. function genFlag($sLang = '', $oTemplate = null)
  362. {
  363. if (!$oTemplate)
  364. $oTemplate = BxDolTemplate::getInstance();
  365. $oTemplate->addCss(BX_DIRECTORY_PATH_PLUGINS_PUBLIC . 'flag-icon-css/css/|flag-icon.min.css');
  366. $sFlag = BxDolLanguages::getInstance()->getLangFlag($sLang);
  367. return '<span title="' . $sFlag . '" class="flag-icon flag-icon-' . $sFlag . '"></span>';
  368. }
  369. // print debug information ( e.g. arrays )
  370. function echoDbg( $what, $desc = '' )
  371. {
  372. if ( $desc )
  373. echo "<b>$desc:</b> ";
  374. echo "<pre>";
  375. print_r( $what );
  376. echo "</pre>\n";
  377. }
  378. function echoDbgLog($mWhat, $sDesc = '', $sFileName = 'debug.log')
  379. {
  380. $sCont =
  381. '--- ' . date('r') . ' (' . BX_DOL_START . ") ---\n" .
  382. $sDesc . "\n" .
  383. print_r($mWhat, true) . "\n\n\n";
  384. $rFile = fopen(BX_DIRECTORY_PATH_LOGS . $sFileName, 'a');
  385. fwrite($rFile, $sCont);
  386. fclose($rFile);
  387. }
  388. function clear_xss($val)
  389. {
  390. if ($GLOBALS['logged']['admin'])
  391. return $val;
  392. // HTML Purifier plugin
  393. global $oHtmlPurifier;
  394. require_once( BX_DIRECTORY_PATH_PLUGINS . 'htmlpurifier/HTMLPurifier.standalone.php' );
  395. if (!isset($oHtmlPurifier)) {
  396. HTMLPurifier_Bootstrap::registerAutoload();
  397. $oConfig = HTMLPurifier_Config::createDefault();
  398. $oConfig->set('Cache.SerializerPath', rtrim(BX_DIRECTORY_PATH_CACHE, '/'));
  399. $oConfig->set('Cache.SerializerPermissions', BX_DOL_DIR_RIGHTS);
  400. $oConfig->set('HTML.SafeObject', 'true');
  401. $oConfig->set('Output.FlashCompat', 'true');
  402. $oConfig->set('HTML.FlashAllowFullScreen', 'true');
  403. if (getParam('sys_add_nofollow')) {
  404. $sHost = parse_url(BX_DOL_URL_ROOT, PHP_URL_HOST);
  405. $oConfig->set('URI.Host', $sHost);
  406. $oConfig->set('HTML.Nofollow', 'true');
  407. }
  408. $oConfig->set('Filter.Custom', array (new HTMLPurifier_Filter_YouTube(), new HTMLPurifier_Filter_YoutubeIframe()));
  409. $oDef = $oConfig->getHTMLDefinition(true);
  410. $oDef->addAttribute('a', 'target', 'Enum#_blank,_self,_target,_top');
  411. $oHtmlPurifier = new HTMLPurifier($oConfig);
  412. }
  413. return $oHtmlPurifier->purify($val);
  414. }
  415. //--------------------------------------- friendly permalinks --------------------------------------//
  416. //------------------------------------------- main functions ---------------------------------------//
  417. function uriGenerate ($s, $sTable, $sField, $sEmpty = '-')
  418. {
  419. $s = uriFilter($s, $sEmpty);
  420. if(uriCheckUniq($s, $sTable, $sField))
  421. return $s;
  422. // cut off redundant part
  423. if(get_mb_len($s) > 240)
  424. $s = get_mb_substr($s, 0, 240);
  425. // try to add date
  426. $s .= '-' . date('Y-m-d');
  427. if(uriCheckUniq($s, $sTable, $sField))
  428. return $s;
  429. // try to add number
  430. for($i = 0 ; $i < 999 ; ++$i)
  431. if(uriCheckUniq($s . '-' . $i, $sTable, $sField))
  432. return ($s . '-' . $i);
  433. return rand(0, 999999999);
  434. }
  435. function uriFilter ($s, $sEmpty = '-')
  436. {
  437. if (BxTemplConfig::getInstance()->bAllowUnicodeInPreg)
  438. $s = get_mb_replace ('/[^\pL^\pN]+/u', '-', $s); // unicode characters
  439. else
  440. $s = get_mb_replace ('/([^\d^\w]+)/u', '-', $s); // latin characters only
  441. $s = get_mb_replace ('/([-^]+)/', '-', $s);
  442. $s = get_mb_replace ('/([-]+)$/', '', $s); // remove trailing dash
  443. if (!$s) $s = $sEmpty;
  444. return $s;
  445. }
  446. function uriCheckUniq ($s, $sTable, $sField)
  447. {
  448. $oDb = BxDolDb::getInstance();
  449. $sSql = $oDb->prepare("SELECT 1 FROM `$sTable` WHERE `$sField`=? LIMIT 1", $s);
  450. return !$oDb->query($sSql);
  451. }
  452. function get_mb_replace ($sPattern, $sReplace, $s)
  453. {
  454. return preg_replace ($sPattern, $sReplace, $s);
  455. }
  456. function get_mb_len ($s)
  457. {
  458. return (function_exists('mb_strlen')) ? mb_strlen($s) : strlen($s);
  459. }
  460. function get_mb_substr ($s, $iStart, $iLen)
  461. {
  462. return (function_exists('mb_substr')) ? mb_substr ($s, $iStart, $iLen) : substr ($s, $iStart, $iLen);
  463. }
  464. function bx_mb_substr_replace($s, $sReplace, $iPosStart, $iLength)
  465. {
  466. return mb_substr($s, 0, $iPosStart) . $sReplace . mb_substr($s, $iPosStart + $iLength);
  467. }
  468. function bx_mb_strpos ($s, $sReplacement, $iStart = 0)
  469. {
  470. return mb_strpos($s, $sReplacement, $iStart);
  471. }
  472. /**
  473. * Import class file, it automatically detects class path by its prefix or module array/name
  474. *
  475. * @param $sClassName - full class name or class postfix(withoit prefix) in the case of module class
  476. * @param $mixedModule - module array or module name in the case of module class
  477. */
  478. function bx_import($sClassName, $mixedModule = array())
  479. {
  480. if (class_exists($sClassName, false))
  481. return;
  482. $aModule = false;
  483. if ($mixedModule) {
  484. if (is_array($mixedModule)) {
  485. $aModule = $mixedModule;
  486. } elseif (is_string($mixedModule)) {
  487. $o = BxDolModule::getInstance($mixedModule);
  488. $aModule = $o->_aModule;
  489. } elseif (is_bool($mixedModule) && true === $mixedModule) {
  490. $aModule = $GLOBALS['aModule'];
  491. }
  492. }
  493. if ($aModule) {
  494. if (class_exists($aModule['class_prefix'] . $sClassName, false))
  495. return;
  496. require_once (BX_DIRECTORY_PATH_MODULES . $aModule['path'] . 'classes/' . $aModule['class_prefix'] . $sClassName . '.php');
  497. return;
  498. }
  499. if (0 == strncmp($sClassName, 'BxDol', 5)) {
  500. if (0 == strncmp($sClassName, 'BxDolStudio', 11))
  501. require_once(BX_DOL_DIR_STUDIO_CLASSES . $sClassName . '.php');
  502. else
  503. require_once(BX_DIRECTORY_PATH_CLASSES . $sClassName . '.php');
  504. return;
  505. }
  506. if (0 == strncmp($sClassName, 'BxBase', 6)) {
  507. if (0 == strncmp($sClassName, 'BxBaseMod', 9)) {
  508. $aMatches = array();
  509. if (preg_match('/BxBaseMod([A-Z][a-z]+)/', $sClassName, $aMatches)) {
  510. require_once(BX_DIRECTORY_PATH_MODULES . 'base/' . strtolower($aMatches[1]) . '/classes/' . $sClassName . '.php');
  511. return;
  512. }
  513. } if (0 == strncmp($sClassName, 'BxBaseStudio', 12)) {
  514. require_once(BX_DOL_DIR_STUDIO_BASE . 'scripts/' . $sClassName . '.php');
  515. return;
  516. } else {
  517. require_once(BX_DIRECTORY_PATH_BASE . 'scripts/' . $sClassName . '.php');
  518. return;
  519. }
  520. }
  521. if (0 == strncmp($sClassName, 'BxTempl', 7)) {
  522. if(0 == strncmp($sClassName, 'BxTemplStudio', 13)) {
  523. $sPath = BX_DIRECTORY_PATH_MODULES . BxDolStudioTemplate::getInstance()->getPath() . 'data/template/studio/scripts/' . $sClassName . '.php';
  524. } else {
  525. $sPath = BX_DIRECTORY_PATH_MODULES . BxDolTemplate::getInstance()->getPath() . 'data/template/system/scripts/' . $sClassName . '.php';
  526. }
  527. if (file_exists($sPath)) {
  528. require_once($sPath);
  529. return;
  530. }
  531. trigger_error ("bx_import fatal error: class (" . $sClassName . ") wasn't found", E_USER_ERROR);
  532. }
  533. }
  534. /**
  535. * used in spl_autoload_register() function, so no need to call bx_import for system classes
  536. */
  537. function bx_autoload($sClassName)
  538. {
  539. if (0 == strncmp($sClassName, 'BxDol', 5) || 0 == strncmp($sClassName, 'BxBase', 6) || 0 == strncmp($sClassName, 'BxTempl', 7))
  540. bx_import($sClassName);
  541. }
  542. /**
  543. * Gets an instance of class pathing necessary parameters if it's necessary.
  544. *
  545. * @param string $sClassName class name.
  546. * @param array $aParams an array of parameters to be pathed to the constructor of the class.
  547. * @param array $aModule an array with module description. Is used when the requested class is located in some module.
  548. * @return unknown
  549. */
  550. function bx_instance($sClassName, $aParams = array(), $mixedModule = array())
  551. {
  552. if(isset($GLOBALS['bxDolClasses'][$sClassName]))
  553. return $GLOBALS['bxDolClasses'][$sClassName];
  554. if ($mixedModule) {
  555. if (!is_array($mixedModule)) {
  556. $o = BxDolModule::getInstance($mixedModule);
  557. $mixedModule = $o->_aModule;
  558. }
  559. $sClassName = bx_ltrim_str($sClassName, $mixedModule['class_prefix']);
  560. bx_import($sClassName, $mixedModule);
  561. $sClassName = $mixedModule['class_prefix'] . $sClassName;
  562. }
  563. $oClass = new ReflectionClass($sClassName);
  564. $GLOBALS['bxDolClasses'][$sClassName] = empty($aParams) ? $oClass->newInstance() : $oClass->newInstanceArgs($aParams);
  565. return $GLOBALS['bxDolClasses'][$sClassName];
  566. }
  567. /**
  568. * Escapes string/array ready to pass to js script with filtered symbols like ', " etc
  569. *
  570. * @param $mixedInput - string/array which should be filtered
  571. * @param $iQuoteType - string escaping method: BX_ESCAPE_STR_AUTO(default), BX_ESCAPE_STR_APOS or BX_ESCAPE_STR_QUOTE
  572. * @return converted string / array
  573. */
  574. function bx_js_string ($mixedInput, $iQuoteType = BX_ESCAPE_STR_AUTO)
  575. {
  576. $aUnits = array(
  577. "\n" => "\\n",
  578. "\r" => "",
  579. );
  580. if (BX_ESCAPE_STR_APOS == $iQuoteType) {
  581. $aUnits["'"] = "\\'";
  582. $aUnits['<script'] = "<scr' + 'ipt";
  583. $aUnits['</script>'] = "</scr' + 'ipt>";
  584. } elseif (BX_ESCAPE_STR_QUOTE == $iQuoteType) {
  585. $aUnits['"'] = '\\"';
  586. $aUnits['<script'] = '<scr" + "ipt';
  587. $aUnits['</script>'] = '</scr" + "ipt>';
  588. } else {
  589. $aUnits['"'] = '&quot;';
  590. $aUnits["'"] = '&apos;';
  591. $aUnits["<script>"] = '&lt;script&gt;';
  592. $aUnits["</script>"] = '&lt;/script&gt;';
  593. }
  594. return str_replace(array_keys($aUnits), array_values($aUnits), $mixedInput);
  595. }
  596. /**
  597. * Return input string/array ready to pass to html attribute with filtered symbols like ', " etc
  598. *
  599. * @param mixed $mixedInput - string/array which should be filtered
  600. * @return converted string / array
  601. */
  602. function bx_html_attribute ($mixedInput, $iQuoteType = BX_ESCAPE_STR_AUTO)
  603. {
  604. $aUnits = array ();
  605. if (BX_ESCAPE_STR_APOS == $iQuoteType)
  606. $aUnits["'"] = "\\'";
  607. elseif (BX_ESCAPE_STR_QUOTE == $iQuoteType)
  608. $aUnits['"'] = '&quot;';
  609. else
  610. $aUnits = array("\"" => "&quot;", "'" => "&apos;");
  611. return str_replace(array_keys($aUnits), array_values($aUnits), $mixedInput);
  612. }
  613. /**
  614. * Escapes string/array ready to pass to php script with filtered symbols like ', " etc
  615. *
  616. * @param mixed $mixedInput - string/array which should be filtered
  617. * @return converted string / array
  618. */
  619. function bx_php_string_apos ($mixedInput)
  620. {
  621. return str_replace("'", "\\'", $mixedInput);
  622. }
  623. function bx_php_string_quot ($mixedInput)
  624. {
  625. return str_replace('"', '\\"', $mixedInput);
  626. }
  627. /**
  628. * Gets file contents by URL.
  629. *
  630. * @param string $sFileUrl - file URL to be read.
  631. * @param array $aParams - an array of parameters to be pathed with URL.
  632. * @return string the file's contents.
  633. */
  634. function bx_file_get_contents($sFileUrl, $aParams = array(), $bChangeTimeout = false)
  635. {
  636. if ($aParams)
  637. $sFileUrl = bx_append_url_params($sFileUrl, $aParams);
  638. $sResult = '';
  639. if(function_exists('curl_init')) {
  640. $rConnect = curl_init();
  641. curl_setopt($rConnect, CURLOPT_URL, $sFileUrl);
  642. curl_setopt($rConnect, CURLOPT_HEADER, 0);
  643. curl_setopt($rConnect, CURLOPT_RETURNTRANSFER, 1);
  644. curl_setopt($rConnect, CURLOPT_FOLLOWLOCATION, 1);
  645. if(bx_mb_strpos($sFileUrl, 'https') !== false) {
  646. curl_setopt($rConnect, CURLOPT_SSL_VERIFYPEER, 0);
  647. curl_setopt($rConnect, CURLOPT_SSL_VERIFYHOST, 0);
  648. }
  649. if ($bChangeTimeout) {
  650. curl_setopt($rConnect, CURLOPT_CONNECTTIMEOUT, 3);
  651. curl_setopt($rConnect, CURLOPT_TIMEOUT, 3);
  652. }
  653. $sAllCookies = '';
  654. foreach($_COOKIE as $sKey=>$sValue){
  655. $sAllCookies .= $sKey."=".$sValue.";";
  656. }
  657. curl_setopt($rConnect, CURLOPT_COOKIE, $sAllCookies);
  658. $sResult = curl_exec($rConnect);
  659. curl_close($rConnect);
  660. } else {
  661. $iSaveTimeout = false;
  662. if ($bChangeTimeout) {
  663. $iSaveTimeout = ini_get('default_socket_timeout');
  664. ini_set('default_socket_timeout', 3);
  665. }
  666. $sResult = @file_get_contents($sFileUrl);
  667. if ($bChangeTimeout && false !== $iSaveTimeout) {
  668. ini_set('default_socket_timeout', $iSaveTimeout);
  669. }
  670. }
  671. return $sResult;
  672. }
  673. function bx_get_site_info($sSourceUrl, $aProcessAdditionalTags = array())
  674. {
  675. $aResult = array();
  676. $sContent = bx_file_get_contents($sSourceUrl);
  677. if ($sContent) {
  678. $sCharset = '';
  679. preg_match("/<meta.+charset=([A-Za-z0-9-]+).+>/i", $sContent, $aMatch);
  680. if (isset($aMatch[1]))
  681. $sCharset = $aMatch[1];
  682. if (preg_match("/<title[^>]*>(.*)<\/title>/i", $sContent, $aMatch))
  683. $aResult['title'] = $aMatch[1];
  684. else
  685. $aResult['title'] = parse_url($sSourceUrl, PHP_URL_HOST);
  686. $aResult['description'] = bx_parse_html_tag($sContent, 'meta', 'name', 'description', 'content', $sCharset);
  687. $aResult['keywords'] = bx_parse_html_tag($sContent, 'meta', 'name', 'keywords', 'content', $sCharset);
  688. if ($aProcessAdditionalTags) {
  689. foreach ($aProcessAdditionalTags as $k => $a) {
  690. $aResult[$k] = bx_parse_html_tag(
  691. $sContent,
  692. isset($a['tag']) ? $a['tag'] : 'meta',
  693. isset($a['name_attr']) ? $a['name_attr'] : 'itemprop',
  694. isset($a['name']) ? $a['name'] : $k,
  695. isset($a['content_attr']) ? $a['content_attr'] : 'content',
  696. $sCharset);
  697. }
  698. }
  699. }
  700. return $aResult;
  701. }
  702. function bx_parse_html_tag ($sContent, $sTag, $sAttrNameName, $sAttrNameValue, $sAttrContentName, $sCharset = false)
  703. {
  704. if (!preg_match("/<{$sTag}\s+{$sAttrNameName}[='\" ]+{$sAttrNameValue}['\"]\s+{$sAttrContentName}[='\" ]+([^('>\")]*)['\"][^>]*>/i", $sContent, $aMatch) || !isset($aMatch[1]))
  705. preg_match("/<{$sTag}\s+{$sAttrContentName}[='\" ]+([^('>\")]*)['\"]\s+{$sAttrNameName}[='\" ]+{$sAttrNameValue}['\"][^>]*>/i", $sContent, $aMatch);
  706. $s = isset($aMatch[1]) ? $aMatch[1] : '';
  707. if ($s && $sCharset)
  708. $s = mb_convert_encoding($s, 'UTF-8', $sCharset);
  709. return $s;
  710. }
  711. // calculation ini_get('upload_max_filesize') in bytes as example
  712. function return_bytes($val)
  713. {
  714. $val = trim($val);
  715. $last = strtolower($val{strlen($val)-1});
  716. $val = (int)$val;
  717. switch($last) {
  718. // The 'G' modifier is available since PHP 5.1.0
  719. case 'k':
  720. $val *= 1024;
  721. break;
  722. case 'm':
  723. $val *= 1024 * 1024;
  724. break;
  725. case 'g':
  726. $val *= 1024 * 1024 * 1024;
  727. break;
  728. }
  729. return $val;
  730. }
  731. // Generate Random Password
  732. function genRndPwd($iLength = 8, $bSpecialCharacters = true)
  733. {
  734. $sPassword = '';
  735. $sChars = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
  736. if($bSpecialCharacters === true)
  737. $sChars .= "!?=/&+,.";
  738. srand((double)microtime()*1000000);
  739. for($i = 0; $i < $iLength; $i++) {
  740. $x = mt_rand(0, strlen($sChars) -1);
  741. $sPassword .= $sChars{$x};
  742. }
  743. return $sPassword;
  744. }
  745. // Generate Random Salt for Password encryption
  746. function genRndSalt()
  747. {
  748. return genRndPwd(8, true);
  749. }
  750. // Encrypt User Password
  751. function encryptUserPwd($sPwd, $sSalt)
  752. {
  753. $sAlgo = defined('BX_PWD_ALGO') ? BX_PWD_ALGO : '';
  754. switch ($sAlgo) {
  755. case 'crypt':
  756. return crypt($sPwd, BX_PWD_ALGO_SALT);
  757. case 'sha1_crypt_salt':
  758. return sha1(crypt($sPwd, BX_PWD_ALGO_SALT) . $sSalt);
  759. case 'sha1_md5_salt':
  760. default:
  761. return sha1(md5($sPwd) . $sSalt);
  762. }
  763. }
  764. function bx_get ($sName, $sMethod = false)
  765. {
  766. if (isset($_GET[$sName]) && ('get' == $sMethod || !$sMethod))
  767. return $_GET[$sName];
  768. elseif (isset($_POST[$sName]) && ('post' == $sMethod || !$sMethod))
  769. return $_POST[$sName];
  770. else
  771. return false;
  772. }
  773. function bx_encode_url_params ($a, $aExcludeKeys = array (), $aOnlyKeys = false)
  774. {
  775. $s = '';
  776. foreach ($a as $sKey => $sVal) {
  777. if (in_array($sKey, $aExcludeKeys))
  778. continue;
  779. if (false !== $aOnlyKeys && !in_array($sKey, $aOnlyKeys))
  780. continue;
  781. if (is_array($sVal)) {
  782. foreach ($sVal as $sSubVal) {
  783. $s .= rawurlencode($sKey) . '[]=' . rawurlencode(is_array($sSubVal) ? 'array' : $sSubVal) . '&';
  784. }
  785. } else {
  786. $s .= rawurlencode($sKey) . '=' . rawurlencode($sVal) . '&';
  787. }
  788. }
  789. return $s;
  790. }
  791. function bx_append_url_params ($sUrl, $mixedParams)
  792. {
  793. if (!$mixedParams)
  794. return $sUrl;
  795. $sParams = false == strpos($sUrl, '?') ? '?' : '&';
  796. if (is_array($mixedParams)) {
  797. foreach($mixedParams as $sKey => $sValue)
  798. $sParams .= $sKey . '=' . $sValue . '&';
  799. $sParams = substr($sParams, 0, -1);
  800. } else {
  801. $sParams .= $mixedParams;
  802. }
  803. return $sUrl . $sParams;
  804. }
  805. function bx_rrmdir($directory)
  806. {
  807. if (substr($directory,-1) == "/")
  808. $directory = substr($directory,0,-1);
  809. if (!file_exists($directory) || !is_dir($directory))
  810. return false;
  811. elseif (!is_readable($directory))
  812. return false;
  813. if (!($directoryHandle = opendir($directory)))
  814. return false;
  815. while ($contents = readdir($directoryHandle)) {
  816. if ($contents != '.' && $contents != '..') {
  817. $path = $directory . "/" . $contents;
  818. if (is_dir($path))
  819. bx_rrmdir($path);
  820. else
  821. unlink($path);
  822. }
  823. }
  824. closedir($directoryHandle);
  825. if (!rmdir($directory))
  826. return false;
  827. return true;
  828. }
  829. function bx_clear_folder ($sPath, $aExts = array ())
  830. {
  831. if (substr($$sPath,-1) == "/")
  832. $sPath = substr($sPath,0,-1);
  833. if (!file_exists($sPath) || !is_dir($sPath))
  834. return false;
  835. elseif (!is_readable($sPath))
  836. return false;
  837. if (!($h = opendir($sPath)))
  838. return false;
  839. while ($sFile = readdir($h)) {
  840. if ('.' == $sFile || '..' == $sFile)
  841. continue;
  842. $sFullPath = $sPath . '/' . $sFile;
  843. if (is_dir($sFullPath))
  844. continue;
  845. if (!$aExts || (($sExt = pathinfo($sFullPath, PATHINFO_EXTENSION)) && in_array($sExt, $aExts)))
  846. @unlink($sFullPath);
  847. }
  848. closedir($h);
  849. return true;
  850. }
  851. function bx_ltrim_str ($sString, $sPrefix, $sReplace = '')
  852. {
  853. if ($sReplace && substr($sString, 0, strlen($sReplace)) == $sReplace)
  854. return $sString;
  855. if (substr($sString, 0, strlen($sPrefix)) == $sPrefix)
  856. return $sReplace . substr($sString, strlen($sPrefix));
  857. return $sString;
  858. }
  859. function bx_rtrim_str ($sString, $sPrefix, $sReplace = '')
  860. {
  861. if ($sReplace && substr($sString, -strlen($sReplace)) == $sReplace)
  862. return $sString;
  863. if (substr($sString, -strlen($sPrefix)) == $sPrefix)
  864. return substr($sString, 0, -strlen($sPrefix)) . $sReplace;
  865. return $sString;
  866. }
  867. /**
  868. * Convert array to attributes string
  869. *
  870. * Example:
  871. * @code
  872. * $a = array('name' => 'test', 'value' => 5);
  873. * $s = bx_convert_array2attrs($a);
  874. * echo $s; // outputs: name="test" value="5"
  875. * @endcode
  876. *
  877. * @param $a - array of attributes
  878. * @param $sClasses - classes to merge with 'class' attribute
  879. * @param $sStyles - styles to merge with 'style' attribute
  880. * @return string
  881. */
  882. function bx_convert_array2attrs ($a, $sClasses = false, $sStyles = false)
  883. {
  884. $sRet = '';
  885. if (!$a || !is_array($a))
  886. $a = array();
  887. if ($sClasses) {
  888. $sClasses = trim($sClasses);
  889. $a['class'] = $sClasses . (!empty($a['class']) ? ' ' . $a['class'] : '');
  890. }
  891. if ($sStyles) {
  892. $sStyles = trim($sStyles);
  893. if (';' != $sStyles[strlen($sStyles)-1])
  894. $sStyles .= ';';
  895. $a['style'] = $sStyles . (!empty($a['style']) ? ' ' . $a['style'] : '');
  896. }
  897. foreach ($a as $sKey => $sValue) {
  898. if(is_null($sValue)) // pass NULL values
  899. continue;
  900. $sValueC = bx_html_attribute($sValue, BX_ESCAPE_STR_QUOTE);
  901. $sRet .= " $sKey=\"$sValueC\"";
  902. }
  903. return $sRet;
  904. }
  905. function bx_unicode_urldecode($s)
  906. {
  907. preg_match_all('/%u([[:alnum:]]{4})/', $s, $a);
  908. foreach ($a[1] as $uniord) {
  909. $dec = hexdec($uniord);
  910. $utf = '';
  911. if ($dec < 128) {
  912. $utf = chr($dec);
  913. } else if ($dec < 2048) {
  914. $utf = chr(192 + (($dec - ($dec % 64)) / 64));
  915. $utf .= chr(128 + ($dec % 64));
  916. } else {
  917. $utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
  918. $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
  919. $utf .= chr(128 + ($dec % 64));
  920. }
  921. $s = str_replace('%u'.$uniord, $utf, $s);
  922. }
  923. return urldecode($s);
  924. }
  925. /**
  926. * Raise an alert
  927. * @param string $sType - system type
  928. * @param string $sAction - system action
  929. * @param int $iObjectId - object id
  930. * @param int $iSenderId - sender (action's author) profile id, if it is false - then currectly logged in profile id is used
  931. */
  932. function bx_alert($sUnit, $sAction, $iObjectId, $iSender = false, $aExtras = array())
  933. {
  934. $o = new BxDolAlerts($sUnit, $sAction, $iObjectId, $iSender, $aExtras);
  935. $o->alert();
  936. }
  937. function bx_replace_markers($mixed, $aMarkers)
  938. {
  939. if (empty($aMarkers))
  940. return $mixed;
  941. if (is_array($mixed)) {
  942. foreach ($mixed as $sKey => $sValue)
  943. $mixed[$sKey] = bx_replace_markers ($sValue, $aMarkers);
  944. } else {
  945. foreach ($aMarkers as $sKey => $sValue)
  946. $mixed = str_replace('{' . $sKey . '}', $sValue, $mixed);
  947. }
  948. return $mixed;
  949. }
  950. function bx_site_hash($sSalt = '', $isSkipVersion = false)
  951. {
  952. return md5($sSalt . ($isSkipVersion ? '' : bx_get_ver()) . BX_DOL_SECRET . BX_DOL_URL_ROOT);
  953. }
  954. /**
  955. * Transform string to method name string, for example it changes 'some_method' string to 'SomeMethod' string
  956. * @param string where words are separated with underscore
  957. * @return string where every word begins with capital letter
  958. */
  959. function bx_gen_method_name ($s, $sWordsDelimiter = '_')
  960. {
  961. return str_replace(' ', '', ucwords(str_replace($sWordsDelimiter, ' ', $s)));
  962. }
  963. /**
  964. * Trigger user error
  965. * @param $sMsg message to display
  966. * @param $iNumLevelsBack add additional debug backtracing N levels back
  967. */
  968. function bx_trigger_error ($sMsg, $iNumLevelsBack = 0)
  969. {
  970. $a = debug_backtrace();
  971. $sMsgAdd = "<br />\n related code in <b>{$a[$iNumLevelsBack]['file']}</b> on line <b>{$a[$iNumLevelsBack]['line']}</b> <br />\n";
  972. trigger_error ($sMsg . $sMsgAdd, E_USER_ERROR);
  973. }
  974. /**
  975. * Get system DB version, for files version @see BX_DOL_VERSION, these versions must match
  976. */
  977. function bx_get_ver ($bInvalidateCache = false)
  978. {
  979. $oDb = BxDolDb::getInstance();
  980. if ($bInvalidateCache)
  981. $oDb->cleanMemory('sys_version');
  982. $sQuery = $oDb->prepare("SELECT `version` FROM `sys_modules` WHERE `name` = 'system'");
  983. return $oDb->fromMemory('sys_version', 'getOne', $sQuery);
  984. }
  985. /**
  986. * Check if site maintetance mode is enabled.
  987. * Maintetance mode is enabled when '.bx_maintenance' file exists in the script root folder,
  988. * please note that this is hidden file and some file managers don't show it.
  989. * @param $bShowHttpError show 503 HTTP error if site is in mainenance mode
  990. * @return true if site is in maintenance mode, or false otherwise
  991. */
  992. function bx_check_maintenance_mode ($bShowHttpError = false)
  993. {
  994. $bMaintetance = file_exists(BX_DIRECTORY_PATH_ROOT . BX_MAINTENANCE_FILE) && !defined('BX_DOL_UPGRADING');
  995. if ($bMaintetance && $bShowHttpError)
  996. bx_show_service_unavailable_error_and_exit ('Site is temporarily unavailable due to scheduled maintenance, please try again in a minute.', 600);
  997. return $bMaintetance;
  998. }
  999. /**
  1000. * Check for minimal requirements.
  1001. * if BX_DISABLE_REQUIREMENTS_CHECK is defined then this requirements checking is skipped.
  1002. * @param $bShowHttpError show 503 HTTP error if site doesn't meet minimal requirements
  1003. * @return false if requirements are met, or array of errors of requirements aren't met
  1004. */
  1005. function bx_check_minimal_requirements ($bShowHttpError = false)
  1006. {
  1007. if (defined('BX_DISABLE_REQUIREMENTS_CHECK'))
  1008. return false;
  1009. $aErrors = array();
  1010. $aErrors[] = (ini_get('register_globals') == 0) ? '' : '<b>register_globals</b> is on (you need to disable it, or your site will be unsafe)';
  1011. $aErrors[] = (ini_get('safe_mode') == 0) ? '' : '<b>safe_mode</b> is on (you need to disable it)';
  1012. $aErrors[] = (version_compare(PHP_VERSION, '5.3.0', '<')) ? 'PHP version is too old (please update to <b>PHP 5.3.0</b> at least)' : '';
  1013. $aErrors[] = (!extension_loaded( 'mbstring')) ? '<b>mbstring</b> extension not installed (the script cannot work without it)' : '';
  1014. $aErrors[] = (ini_get('allow_url_include') == 0) ? '' : '<b>allow_url_include</b> is on (you need to disable it, or your site will be unsafe)';
  1015. $aErrors = array_diff($aErrors, array('')); // delete empty
  1016. $bFailedMinimalRequirements = !empty($aErrors);
  1017. if ($bFailedMinimalRequirements && $bShowHttpError) {
  1018. $sErrors = implode(" <br /> ", $aErrors);
  1019. bx_show_service_unavailable_error_and_exit($sErrors);
  1020. }
  1021. return $bFailedMinimalRequirements ? $aErrors : false;
  1022. }
  1023. /**
  1024. * Check if redirect to the correct hostname is required, for example redirect from site.com to www.site.com
  1025. * @param $bProcessRedirect process redirect and exit if needed
  1026. */
  1027. function bx_check_redirect_to_correct_hostname ($bProcessRedirect = false)
  1028. {
  1029. $aUrl = parse_url(BX_DOL_URL_ROOT);
  1030. $bRedirectRequired = isset($_SERVER['HTTP_HOST']) && 0 != strcasecmp($_SERVER['HTTP_HOST'], $aUrl['host']) && 0 != strcasecmp($_SERVER['HTTP_HOST'], $aUrl['host'] . ':80');
  1031. if ($bRedirectRequired && $bProcessRedirect) {
  1032. header( "Location:{$aUrl['scheme']}://{$aUrl['host']}{$_SERVER['REQUEST_URI']}", true, 301 );
  1033. exit;
  1034. }
  1035. return $bRedirectRequired;
  1036. }
  1037. /**
  1038. * Check if redirect to remove install folder.
  1039. * If BX_SKIP_INSTALL_CHECK is defined then this redirect checking is skipped.
  1040. * @param $bProcessRedirect process redirect and exit if needed
  1041. */
  1042. function bx_check_redirect_to_remove_install_folder ($bProcessRedirect = false)
  1043. {
  1044. $bRemoveInstallFolder = !defined ('BX_SKIP_INSTALL_CHECK') && file_exists(BX_DIRECTORY_PATH_ROOT . 'install');
  1045. if ($bRemoveInstallFolder && $bProcessRedirect) {
  1046. header('Location:' . BX_DOL_URL_ROOT . 'install/index.php?action=remove_install');
  1047. exit;
  1048. }
  1049. return $bRemoveInstallFolder;
  1050. }
  1051. /**
  1052. * Show HTTP 503 service unavailable error and exit
  1053. */
  1054. function bx_show_service_unavailable_error_and_exit ($sMsg = false, $iRetryAfter = 86400)
  1055. {
  1056. header('HTTP/1.0 503 Service Unavailable', true, 503);
  1057. header('Retry-After: 600');
  1058. echo $sMsg ? $sMsg : 'Service temporarily unavailable';
  1059. exit;
  1060. }
  1061. /**
  1062. * The function is sumilar to php readfile, but it send all required headers and can send file by chunks and suports file seek
  1063. * @param $sPath path to file to output to the browser
  1064. * @param $sFilename filename without path, ig file is saved from browser, then this name is used, not used(empty) by default
  1065. * @param $sMimeType file mime type, by default 'application/octet-stream'
  1066. * @param $iCacheAge file cache age, by default 0
  1067. * @param $sCachePrivacy cache privacy 'public' (default value) or 'private'
  1068. * @return true on success or false on error
  1069. */
  1070. function bx_smart_readfile($sPath, $sFilename = '', $sMimeType = 'application/octet-stream', $iCacheAge = 0, $sCachePrivacy = 'public')
  1071. {
  1072. if (!file_exists($sPath))
  1073. return false;
  1074. $fp = @fopen($sPath, 'rb');
  1075. $size = filesize($sPath);
  1076. $length = $size;
  1077. $start = 0;
  1078. $end = $size - 1;
  1079. header('Content-type: ' . $sMimeType);
  1080. header('Cache-Control: ' . $sCachePrivacy . ', must-revalidate, max-age=' . $iCacheAge);
  1081. header("Accept-Ranges: 0-$length");
  1082. if ($sFilename)
  1083. header('Content-Disposition: inline; filename=' . $sFilename);
  1084. if (isset($_SERVER['HTTP_RANGE'])) {
  1085. $c_start = $start;
  1086. $c_end = $end;
  1087. list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
  1088. if (strpos($range, ',') !== false) {
  1089. header('HTTP/1.1 416 Requested Range Not Satisfiable');
  1090. header("Content-Range: bytes $start-$end/$size");
  1091. return false;
  1092. }
  1093. if ($range == '-') {
  1094. $c_start = $size - substr($range, 1);
  1095. }else{
  1096. $range = explode('-', $range);
  1097. $c_start = $range[0];
  1098. $c_end = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $size;
  1099. }
  1100. $c_end = ($c_end > $end) ? $end : $c_end;
  1101. if ($c_start > $c_end || $c_start > $size - 1 || $c_end >= $size) {
  1102. header('HTTP/1.1 416 Requested Range Not Satisfiable');
  1103. header("Content-Range: bytes $start-$end/$size");
  1104. return false;
  1105. }
  1106. $start = $c_start;
  1107. $end = $c_end;
  1108. $length = $end - $start + 1;
  1109. fseek($fp, $start);
  1110. header('HTTP/1.1 206 Partial Content');
  1111. }
  1112. header("Content-Range: bytes $start-$end/$size");
  1113. header("Content-Length: ".$length);
  1114. $buffer = 1024 * 8;
  1115. while(!feof($fp) && ($p = ftell($fp)) <= $end) {
  1116. if ($p + $buffer > $end) {
  1117. $buffer = $end - $p + 1;
  1118. }
  1119. set_time_limit(0);
  1120. echo fread($fp, $buffer);
  1121. flush();
  1122. }
  1123. fclose($fp);
  1124. return true;
  1125. }
  1126. /**
  1127. * Wrap in A tag links in TEXT string
  1128. * @param $sHtmlOrig - text string without tags
  1129. * @param $sAttrs - attributes string to add to the added A tag
  1130. * @return string where all links are wrapped in A tag
  1131. */
  1132. function bx_linkify($text, $sAttrs = '', $bHtmlSpecialChars = false)
  1133. {
  1134. if ($bHtmlSpecialChars)
  1135. $text = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8');
  1136. $re = "@\b((https?://)|(www\.))(([0-9a-zA-Z_!~*'().&=+$%-]+:)?[0-9a-zA-Z_!~*'().&=+$%-]+\@)?(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-zA-Z_!~*'()-]+\.)*([0-9a-zA-Z][0-9a-zA-Z-]{0,61})?[0-9a-zA-Z]\.[a-zA-Z]{2,6})(:[0-9]{1,4})?((/[0-9a-zA-Z_!~*'().;?:\@&=+$,%#-]+)*/?)@";
  1137. preg_match_all($re, $text, $matches, PREG_OFFSET_CAPTURE);
  1138. $matches = $matches[0];
  1139. if ($i = count($matches))
  1140. $bAddNofollow = getParam('sys_add_nofollow') == 'on';
  1141. while ($i--)
  1142. {
  1143. $url = $matches[$i][0];
  1144. if (!preg_match('@^https?://@', $url))
  1145. $url = 'http://'.$url;
  1146. if (strncmp(BX_DOL_URL_ROOT, $url, strlen(BX_DOL_URL_ROOT)) != 0) {
  1147. $sAttrs .= ' target="_blank" ';
  1148. if ($bAddNofollow)
  1149. $sAttrs .= ' rel="nofollow" ';
  1150. }
  1151. $text = substr_replace($text, '<a ' . $sAttrs . ' href="'.$url.'">'.$matches[$i][0].'</a>', $matches[$i][1], strlen($matches[$i][0]));
  1152. }
  1153. return $text;
  1154. }
  1155. /**
  1156. * Wrap in A tag links in HTML string, which aren't wrapped in A tag yet
  1157. * @param $sHtmlOrig - HTML string
  1158. * @param $sAttrs - attributes string to add to the added A tag
  1159. * @return modified HTML string, in case of errror original string is returned
  1160. */
  1161. function bx_linkify_html($sHtmlOrig, $sAttrs = '')
  1162. {
  1163. if (!trim($sHtmlOrig))
  1164. return $sHtmlOrig;
  1165. $sId = 'bx-linkify-' . md5(microtime());
  1166. $dom = new DOMDocument();
  1167. @$dom->loadHTML('<?xml encoding="UTF-8"><div id="' . $sId . '">' . $sHtmlOrig . '</div>');
  1168. $xpath = new DOMXpath($dom);
  1169. foreach ($xpath->query('//text()') as $text) {
  1170. $frag = $dom->createDocumentFragment();
  1171. $frag->appendXML(bx_linkify($text->nodeValue, $sAttrs, true));
  1172. $text->parentNode->replaceChild($frag, $text);
  1173. }
  1174. if (version_compare(PHP_VERSION, '5.3.6') >= 0)
  1175. $s = $dom->saveHTML($dom->getElementById($sId));
  1176. else
  1177. $s = $dom->saveXML($dom->getElementById($sId), LIBXML_NOEMPTYTAG);
  1178. if (false === $s) // in case of error return original string
  1179. return $sHtmlOrig;
  1180. if (false !== ($iPos = mb_strpos($s, '<html><body>')) && $iPos < mb_strpos($s, $sId))
  1181. $s = mb_substr($s, $iPos + 12, -15); // strip <html><body> tags and everything before them
  1182. return mb_substr($s, 54, -6); // strip added tags
  1183. }
  1184. /** @} */