utils.inc.php 43 KB

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