utils.inc.php 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200
  1. <?php defined('BX_DOL') or defined('BX_DOL_INSTALL') or die('hack attempt');
  2. /**
  3. * Copyright (c) BoonEx Pty Limited - http://www.boonex.com/
  4. * CC-BY License - http://creativecommons.org/licenses/by/3.0/
  5. *
  6. * @defgroup DolphinCore Dolphin Core
  7. * @{
  8. */
  9. define('BX_DATA_TEXT', 1); ///< regular text data type
  10. define('BX_DATA_TEXT_MULTILINE', 2); ///< regular multiline text data type
  11. define('BX_DATA_INT', 3); ///< integer data type
  12. define('BX_DATA_FLOAT', 4); ///< float data type
  13. define('BX_DATA_CHECKBOX', 5); ///< checkbox data type, 'on' or empty value
  14. define('BX_DATA_HTML', 6); ///< HTML data type
  15. define('BX_DATA_DATE', 7); ///< date data type stored as yyyy-mm-dd
  16. define('BX_DATA_DATE_TS', 8); ///< date data type stored as unixtimestamp
  17. define('BX_DATA_DATETIME_TS', 9); ///< date/time data type stored as unixtimestamp
  18. define('BX_SLASHES_AUTO', 0);
  19. define('BX_SLASHES_ADD', 1);
  20. define('BX_SLASHES_STRIP', 2);
  21. define('BX_SLASHES_NO_ACTION', 3);
  22. define('BX_ESCAPE_STR_AUTO', 0); ///< turn apostropes and quote signs into html special chars, for use in @see bx_js_string and @see bx_html_attribute
  23. define('BX_ESCAPE_STR_APOS', 1); ///< escape apostrophes only, for js strings enclosed in apostrophes, for use in @see bx_js_string and @see bx_html_attribute
  24. define('BX_ESCAPE_STR_QUOTE', 2); ///< escape quotes only, for js strings enclosed in quotes, for use in @see bx_js_string and @see bx_html_attribute
  25. define('BX_EMAIL_SYSTEM', 0); ///< system email without unsubscribe link, like forgot password or email verification
  26. define('BX_EMAIL_NOTIFY', 1); ///< notification message, with unsubscribe link
  27. define('BX_EMAIL_MASS', 2); ///< mass email, one mesage send to manu users, with unsubscribe link
  28. 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(BxDolConfig::getInstance()->get('path_dynamic', 'tmp') . $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('HTML.SafeObject', 'true');
  423. $oConfig->set('Output.FlashCompat', 'true');
  424. $oConfig->set('HTML.FlashAllowFullScreen', 'true');
  425. if (getParam('sys_add_nofollow')) {
  426. $sHost = parse_url(BX_DOL_URL_ROOT, PHP_URL_HOST);
  427. $oConfig->set('URI.Host', $sHost);
  428. $oConfig->set('HTML.Nofollow', 'true');
  429. }
  430. $oConfig->set('Filter.Custom', array (new HTMLPurifier_Filter_YouTube(), new HTMLPurifier_Filter_YoutubeIframe()));
  431. $oDef = $oConfig->getHTMLDefinition(true);
  432. $oDef->addAttribute('a', 'target', 'Enum#_blank,_self,_target,_top');
  433. $oHtmlPurifier = new HTMLPurifier($oConfig);
  434. }
  435. return $oHtmlPurifier->purify($val);
  436. }
  437. //--------------------------------------- friendly permalinks --------------------------------------//
  438. //------------------------------------------- main functions ---------------------------------------//
  439. function uriGenerate ($s, $sTable, $sField, $sEmpty = '-')
  440. {
  441. $s = uriFilter($s, $sEmpty);
  442. if(uriCheckUniq($s, $sTable, $sField))
  443. return $s;
  444. // cut off redundant part
  445. if(get_mb_len($s) > 240)
  446. $s = get_mb_substr($s, 0, 240);
  447. // try to add date
  448. $s .= '-' . date('Y-m-d');
  449. if(uriCheckUniq($s, $sTable, $sField))
  450. return $s;
  451. // try to add number
  452. for($i = 0 ; $i < 999 ; ++$i)
  453. if(uriCheckUniq($s . '-' . $i, $sTable, $sField))
  454. return ($s . '-' . $i);
  455. return rand(0, 999999999);
  456. }
  457. function uriFilter ($s, $sEmpty = '-')
  458. {
  459. bx_import('BxTemplConfig');
  460. if (BxTemplConfig::getInstance()->bAllowUnicodeInPreg)
  461. $s = get_mb_replace ('/[^\pL^\pN]+/u', '-', $s); // unicode characters
  462. else
  463. $s = get_mb_replace ('/([^\d^\w]+)/u', '-', $s); // latin characters only
  464. $s = get_mb_replace ('/([-^]+)/', '-', $s);
  465. $s = get_mb_replace ('/([-]+)$/', '', $s); // remove trailing dash
  466. if (!$s) $s = $sEmpty;
  467. return $s;
  468. }
  469. function uriCheckUniq ($s, $sTable, $sField)
  470. {
  471. bx_import('BxDolDb');
  472. $oDb = BxDolDb::getInstance();
  473. $sSql = $oDb->prepare("SELECT 1 FROM `$sTable` WHERE `$sField`=? LIMIT 1", $s);
  474. return !$oDb->query($sSql);
  475. }
  476. function get_mb_replace ($sPattern, $sReplace, $s)
  477. {
  478. return preg_replace ($sPattern, $sReplace, $s);
  479. }
  480. function get_mb_len ($s)
  481. {
  482. return (function_exists('mb_strlen')) ? mb_strlen($s) : strlen($s);
  483. }
  484. function get_mb_substr ($s, $iStart, $iLen)
  485. {
  486. return (function_exists('mb_substr')) ? mb_substr ($s, $iStart, $iLen) : substr ($s, $iStart, $iLen);
  487. }
  488. function bx_mb_substr_replace($s, $sReplace, $iPosStart, $iLength)
  489. {
  490. return mb_substr($s, 0, $iPosStart) . $sReplace . mb_substr($s, $iPosStart + $iLength);
  491. }
  492. function bx_mb_strpos ($s, $sReplacement, $iStart = 0)
  493. {
  494. return mb_strpos($s, $sReplacement, $iStart);
  495. }
  496. /**
  497. * Import class file, it automatically detects class path by its prefix or module array/name
  498. *
  499. * @param $sClassName - full class name or class postfix(withoit prefix) in the case of module class
  500. * @param $mixedModule - module array or module name in the case of module class
  501. */
  502. function bx_import($sClassName, $mixedModule = array())
  503. {
  504. if (class_exists($sClassName))
  505. return;
  506. $aModule = false;
  507. if ($mixedModule) {
  508. if (is_array($mixedModule)) {
  509. $aModule = $mixedModule;
  510. } elseif (is_string($mixedModule)) {
  511. bx_import('BxDolModule');
  512. $o = BxDolModule::getInstance($mixedModule);
  513. $aModule = $o->_aModule;
  514. } elseif (is_bool($mixedModule) && true === $mixedModule) {
  515. $aModule = $GLOBALS['aModule'];
  516. }
  517. }
  518. if ($aModule) {
  519. if (class_exists($aModule['class_prefix'] . $sClassName))
  520. return;
  521. require_once (BX_DIRECTORY_PATH_MODULES . $aModule['path'] . 'classes/' . $aModule['class_prefix'] . $sClassName . '.php');
  522. return;
  523. }
  524. if (0 == strncmp($sClassName, 'BxDol', 5)) {
  525. if (0 == strncmp($sClassName, 'BxDolStudio', 11))
  526. require_once(BX_DOL_DIR_STUDIO_CLASSES . $sClassName . '.php');
  527. else
  528. require_once(BX_DIRECTORY_PATH_CLASSES . $sClassName . '.php');
  529. return;
  530. }
  531. if (0 == strncmp($sClassName, 'BxBase', 6)) {
  532. if (0 == strncmp($sClassName, 'BxBaseMod', 9)) {
  533. $aMatches = array();
  534. if (preg_match('/BxBaseMod([A-Z][a-z]+)/', $sClassName, $aMatches)) {
  535. require_once(BX_DIRECTORY_PATH_MODULES . 'base/' . strtolower($aMatches[1]) . '/classes/' . $sClassName . '.php');
  536. return;
  537. }
  538. } if (0 == strncmp($sClassName, 'BxBaseStudio', 12)) {
  539. require_once(BX_DOL_DIR_STUDIO_BASE . 'scripts/' . $sClassName . '.php');
  540. return;
  541. } else {
  542. require_once(BX_DIRECTORY_PATH_BASE . 'scripts/' . $sClassName . '.php');
  543. return;
  544. }
  545. }
  546. if (0 == strncmp($sClassName, 'BxTempl', 7) && !class_exists($sClassName)) {
  547. if(0 == strncmp($sClassName, 'BxTemplStudio', 13)) {
  548. bx_import('BxDolStudioTemplate');
  549. $sPath = BX_DIRECTORY_PATH_MODULES . BxDolStudioTemplate::getInstance()->getPath() . 'data/template/studio/scripts/' . $sClassName . '.php';
  550. } else {
  551. bx_import('BxDolTemplate');
  552. $sPath = BX_DIRECTORY_PATH_MODULES . BxDolTemplate::getInstance()->getPath() . 'data/template/system/scripts/' . $sClassName . '.php';
  553. }
  554. if (file_exists($sPath)) {
  555. require_once($sPath);
  556. return;
  557. }
  558. trigger_error ("bx_import fatal error: class (" . $sClassName . ") wasn't found", E_USER_ERROR);
  559. }
  560. }
  561. /**
  562. * Gets an instance of class pathing necessary parameters if it's necessary.
  563. *
  564. * @param string $sClassName class name.
  565. * @param array $aParams an array of parameters to be pathed to the constructor of the class.
  566. * @param array $aModule an array with module description. Is used when the requested class is located in some module.
  567. * @return unknown
  568. */
  569. function bx_instance($sClassName, $aParams = array(), $aModule = array())
  570. {
  571. if(isset($GLOBALS['bxDolClasses'][$sClassName]))
  572. return $GLOBALS['bxDolClasses'][$sClassName];
  573. bx_import((empty($aModule) ? $sClassName : str_replace($aModule['class_prefix'], '', $sClassName)), $aModule);
  574. $oClass = new ReflectionClass($sClassName);
  575. $GLOBALS['bxDolClasses'][$sClassName] = empty($aParams) ? $oClass->newInstance() : $oClass->newInstanceArgs($aParams);
  576. return $GLOBALS['bxDolClasses'][$sClassName];
  577. }
  578. /**
  579. * Escapes string/array ready to pass to js script with filtered symbols like ', " etc
  580. *
  581. * @param $mixedInput - string/array which should be filtered
  582. * @param $iQuoteType - string escaping method: BX_ESCAPE_STR_AUTO(default), BX_ESCAPE_STR_APOS or BX_ESCAPE_STR_QUOTE
  583. * @return converted string / array
  584. */
  585. function bx_js_string ($mixedInput, $iQuoteType = BX_ESCAPE_STR_AUTO)
  586. {
  587. $aUnits = array(
  588. "\n" => "\\n",
  589. "\r" => "",
  590. );
  591. if (BX_ESCAPE_STR_APOS == $iQuoteType) {
  592. $aUnits["'"] = "\\'";
  593. $aUnits['<script'] = "<scr' + 'ipt";
  594. $aUnits['</script>'] = "</scr' + 'ipt>";
  595. } elseif (BX_ESCAPE_STR_QUOTE == $iQuoteType) {
  596. $aUnits['"'] = '\\"';
  597. $aUnits['<script'] = '<scr" + "ipt';
  598. $aUnits['</script>'] = '</scr" + "ipt>';
  599. } else {
  600. $aUnits['"'] = '&quote;';
  601. $aUnits["'"] = '&apos;';
  602. $aUnits["<"] = '&lt;';
  603. $aUnits[">"] = '&gt;';
  604. }
  605. return str_replace(array_keys($aUnits), array_values($aUnits), $mixedInput);
  606. }
  607. /**
  608. * Return input string/array ready to pass to html attribute with filtered symbols like ', " etc
  609. *
  610. * @param mixed $mixedInput - string/array which should be filtered
  611. * @return converted string / array
  612. */
  613. function bx_html_attribute ($mixedInput, $iQuoteType = BX_ESCAPE_STR_AUTO)
  614. {
  615. $aUnits = array ();
  616. if (BX_ESCAPE_STR_APOS == $iQuoteType)
  617. $aUnits["'"] = "\\'";
  618. elseif (BX_ESCAPE_STR_QUOTE == $iQuoteType)
  619. $aUnits['"'] = '&quot;';
  620. else
  621. $aUnits = array("\"" => "&quot;", "'" => "&apos;");
  622. return str_replace(array_keys($aUnits), array_values($aUnits), $mixedInput);
  623. }
  624. /**
  625. * Escapes string/array ready to pass to php script with filtered symbols like ', " etc
  626. *
  627. * @param mixed $mixedInput - string/array which should be filtered
  628. * @return converted string / array
  629. */
  630. function bx_php_string_apos ($mixedInput)
  631. {
  632. return str_replace("'", "\\'", $mixedInput);
  633. }
  634. function bx_php_string_quot ($mixedInput)
  635. {
  636. return str_replace('"', '\\"', $mixedInput);
  637. }
  638. /**
  639. * Gets file contents by URL.
  640. *
  641. * @param string $sFileUrl - file URL to be read.
  642. * @param array $aParams - an array of parameters to be pathed with URL.
  643. * @return string the file's contents.
  644. */
  645. function bx_file_get_contents($sFileUrl, $aParams = array(), $bChangeTimeout = false)
  646. {
  647. if ($aParams)
  648. $sFileUrl = bx_append_url_params($sFileUrl, $aParams);
  649. $sResult = '';
  650. if(function_exists('curl_init')) {
  651. $rConnect = curl_init();
  652. curl_setopt($rConnect, CURLOPT_URL, $sFileUrl);
  653. curl_setopt($rConnect, CURLOPT_HEADER, 0);
  654. curl_setopt($rConnect, CURLOPT_RETURNTRANSFER, 1);
  655. curl_setopt($rConnect, CURLOPT_FOLLOWLOCATION, 1);
  656. if ($bChangeTimeout) {
  657. curl_setopt($rConnect, CURLOPT_CONNECTTIMEOUT, 3);
  658. curl_setopt($rConnect, CURLOPT_TIMEOUT, 3);
  659. }
  660. $sAllCookies = '';
  661. foreach($_COOKIE as $sKey=>$sValue){
  662. $sAllCookies .= $sKey."=".$sValue.";";
  663. }
  664. curl_setopt($rConnect, CURLOPT_COOKIE, $sAllCookies);
  665. $sResult = curl_exec($rConnect);
  666. curl_close($rConnect);
  667. } else {
  668. $iSaveTimeout = false;
  669. if ($bChangeTimeout) {
  670. $iSaveTimeout = ini_get('default_socket_timeout');
  671. ini_set('default_socket_timeout', 3);
  672. }
  673. $sResult = @file_get_contents($sFileUrl);
  674. if ($bChangeTimeout && false !== $iSaveTimeout) {
  675. ini_set('default_socket_timeout', $iSaveTimeout);
  676. }
  677. }
  678. return $sResult;
  679. }
  680. // calculation ini_get('upload_max_filesize') in bytes as example
  681. function return_bytes($val)
  682. {
  683. $val = trim($val);
  684. $last = strtolower($val{strlen($val)-1});
  685. $val = (int)$val;
  686. switch($last) {
  687. // The 'G' modifier is available since PHP 5.1.0
  688. case 'k':
  689. $val *= 1024;
  690. break;
  691. case 'm':
  692. $val *= 1024 * 1024;
  693. break;
  694. case 'g':
  695. $val *= 1024 * 1024 * 1024;
  696. break;
  697. }
  698. return $val;
  699. }
  700. // Generate Random Password
  701. function genRndPwd($iLength = 8, $bSpecialCharacters = true)
  702. {
  703. $sPassword = '';
  704. $sChars = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
  705. if($bSpecialCharacters === true)
  706. $sChars .= "!?=/&+,.";
  707. srand((double)microtime()*1000000);
  708. for($i = 0; $i < $iLength; $i++) {
  709. $x = mt_rand(0, strlen($sChars) -1);
  710. $sPassword .= $sChars{$x};
  711. }
  712. return $sPassword;
  713. }
  714. // Generate Random Salt for Password encryption
  715. function genRndSalt()
  716. {
  717. return genRndPwd(8, true);
  718. }
  719. // Encrypt User Password
  720. function encryptUserPwd($sPwd, $sSalt)
  721. {
  722. return sha1(md5($sPwd) . $sSalt);
  723. }
  724. function bx_get ($sName, $sMethod = false)
  725. {
  726. if (isset($_GET[$sName]) && ('get' == $sMethod || !$sMethod))
  727. return $_GET[$sName];
  728. elseif (isset($_POST[$sName]) && ('post' == $sMethod || !$sMethod))
  729. return $_POST[$sName];
  730. else
  731. return false;
  732. }
  733. function bx_encode_url_params ($a, $aExcludeKeys = array (), $aOnlyKeys = false)
  734. {
  735. $s = '';
  736. foreach ($a as $sKey => $sVal) {
  737. if (in_array($sKey, $aExcludeKeys))
  738. continue;
  739. if (false !== $aOnlyKeys && !in_array($sKey, $aOnlyKeys))
  740. continue;
  741. if (is_array($sVal)) {
  742. foreach ($sVal as $sSubVal) {
  743. $s .= rawurlencode($sKey) . '[]=' . rawurlencode(is_array($sSubVal) ? 'array' : $sSubVal) . '&';
  744. }
  745. } else {
  746. $s .= rawurlencode($sKey) . '=' . rawurlencode($sVal) . '&';
  747. }
  748. }
  749. return $s;
  750. }
  751. function bx_append_url_params ($sUrl, $mixedParams)
  752. {
  753. if (!$mixedParams)
  754. return $sUrl;
  755. $sParams = false == strpos($sUrl, '?') ? '?' : '&';
  756. if (is_array($mixedParams)) {
  757. foreach($mixedParams as $sKey => $sValue)
  758. $sParams .= $sKey . '=' . $sValue . '&';
  759. $sParams = substr($sParams, 0, -1);
  760. } else {
  761. $sParams .= $mixedParams;
  762. }
  763. return $sUrl . $sParams;
  764. }
  765. function bx_rrmdir($directory)
  766. {
  767. if (substr($directory,-1) == "/")
  768. $directory = substr($directory,0,-1);
  769. if (!file_exists($directory) || !is_dir($directory))
  770. return false;
  771. elseif (!is_readable($directory))
  772. return false;
  773. if (!($directoryHandle = opendir($directory)))
  774. return false;
  775. while ($contents = readdir($directoryHandle)) {
  776. if ($contents != '.' && $contents != '..') {
  777. $path = $directory . "/" . $contents;
  778. if (is_dir($path))
  779. bx_rrmdir($path);
  780. else
  781. unlink($path);
  782. }
  783. }
  784. closedir($directoryHandle);
  785. if (!rmdir($directory))
  786. return false;
  787. return true;
  788. }
  789. function bx_clear_folder ($sPath, $aExts = array ())
  790. {
  791. if (substr($$sPath,-1) == "/")
  792. $sPath = substr($sPath,0,-1);
  793. if (!file_exists($sPath) || !is_dir($sPath))
  794. return false;
  795. elseif (!is_readable($sPath))
  796. return false;
  797. if (!($h = opendir($sPath)))
  798. return false;
  799. while ($sFile = readdir($h)) {
  800. if ('.' == $sFile || '..' == $sFile)
  801. continue;
  802. $sFullPath = $sPath . '/' . $sFile;
  803. if (is_dir($sFullPath))
  804. continue;
  805. if (!$aExts || (($sExt = pathinfo($sFullPath, PATHINFO_EXTENSION)) && in_array($sExt, $aExts)))
  806. @unlink($sFullPath);
  807. }
  808. closedir($h);
  809. return true;
  810. }
  811. function bx_ltrim_str ($sString, $sPrefix, $sReplace = '')
  812. {
  813. if ($sReplace && substr($sString, 0, strlen($sReplace)) == $sReplace)
  814. return $sString;
  815. if (substr($sString, 0, strlen($sPrefix)) == $sPrefix)
  816. return $sReplace . substr($sString, strlen($sPrefix));
  817. return $sString;
  818. }
  819. /**
  820. * Convert array to attributes string
  821. *
  822. * Example:
  823. * @code
  824. * $a = array('name' => 'test', 'value' => 5);
  825. * $s = bx_convert_array2attrs($a);
  826. * echo $s; // outputs: name="test" value="5"
  827. * @endcode
  828. *
  829. * @param $a - array of attributes
  830. * @param $sClasses - classes to merge with 'class' attribute
  831. * @param $sStyles - styles to merge with 'style' attribute
  832. * @return string
  833. */
  834. function bx_convert_array2attrs ($a, $sClasses = false, $sStyles = false)
  835. {
  836. $sRet = '';
  837. if (!$a || !is_array($a))
  838. $a = array();
  839. if ($sClasses) {
  840. $sClasses = trim($sClasses);
  841. $a['class'] = $sClasses . (!empty($a['class']) ? ' ' . $a['class'] : '');
  842. }
  843. if ($sStyles) {
  844. $sStyles = trim($sStyles);
  845. if (';' != $sStyles[strlen($sStyles)-1])
  846. $sStyles .= ';';
  847. $a['style'] = $sStyles . (!empty($a['style']) ? ' ' . $a['style'] : '');
  848. }
  849. foreach ($a as $sKey => $sValue) {
  850. if(is_null($sValue)) // pass NULL values
  851. continue;
  852. $sValueC = bx_html_attribute($sValue, BX_ESCAPE_STR_QUOTE);
  853. $sRet .= " $sKey=\"$sValueC\"";
  854. }
  855. return $sRet;
  856. }
  857. function bx_unicode_urldecode($s)
  858. {
  859. preg_match_all('/%u([[:alnum:]]{4})/', $s, $a);
  860. foreach ($a[1] as $uniord) {
  861. $dec = hexdec($uniord);
  862. $utf = '';
  863. if ($dec < 128) {
  864. $utf = chr($dec);
  865. } else if ($dec < 2048) {
  866. $utf = chr(192 + (($dec - ($dec % 64)) / 64));
  867. $utf .= chr(128 + ($dec % 64));
  868. } else {
  869. $utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
  870. $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
  871. $utf .= chr(128 + ($dec % 64));
  872. }
  873. $s = str_replace('%u'.$uniord, $utf, $s);
  874. }
  875. return urldecode($s);
  876. }
  877. /**
  878. * Raise an alert
  879. * @param string $sType - system type
  880. * @param string $sAction - system action
  881. * @param int $iObjectId - object id
  882. * @param int $iSenderId - sender (action's author) profile id, if it is false - then currectly logged in profile id is used
  883. */
  884. function bx_alert($sUnit, $sAction, $iObjectId, $iSender = false, $aExtras = array())
  885. {
  886. $o = new BxDolAlerts($sUnit, $sAction, $iObjectId, $iSender, $aExtras);
  887. $o->alert();
  888. }
  889. function bx_replace_markers($mixed, $aMarkers)
  890. {
  891. if (empty($aMarkers))
  892. return $mixed;
  893. if (is_array($mixed)) {
  894. foreach ($mixed as $sKey => $sValue)
  895. $mixed[$sKey] = bx_replace_markers ($sValue, $aMarkers);
  896. } else {
  897. foreach ($aMarkers as $sKey => $sValue)
  898. $mixed = str_replace('{' . $sKey . '}', $sValue, $mixed);
  899. }
  900. return $mixed;
  901. }
  902. function bx_site_hash($sSalt = '', $isSkipVersion = false)
  903. {
  904. return md5($sSalt . ($isSkipVersion ? '' : bx_get_ver()) . BX_DOL_SECRET . BX_DOL_URL_ROOT);
  905. }
  906. /**
  907. * Transform string to method name string, for example it changes 'some_method' string to 'SomeMethod' string
  908. * @param string where words are separated with underscore
  909. * @return string where every word begins with capital letter
  910. */
  911. function bx_gen_method_name ($s, $sWordsDelimiter = '_')
  912. {
  913. return str_replace(' ', '', ucwords(str_replace($sWordsDelimiter, ' ', $s)));
  914. }
  915. /**
  916. * Trigger user error
  917. * @param $sMsg message to display
  918. * @param $iNumLevelsBack add additional debug backtracing N levels back
  919. */
  920. function bx_trigger_error ($sMsg, $iNumLevelsBack = 0)
  921. {
  922. $a = debug_backtrace();
  923. $sMsgAdd = "<br />\n related code in <b>{$a[$iNumLevelsBack]['file']}</b> on line <b>{$a[$iNumLevelsBack]['line']}</b> <br />\n";
  924. trigger_error ($sMsg . $sMsgAdd, E_USER_ERROR);
  925. }
  926. /**
  927. * Get Dolphin system DB version, for files version @see BX_DOL_VERSION, these versions must match
  928. */
  929. function bx_get_ver ($bInvalidateCache = false)
  930. {
  931. bx_import('BxDolDb');
  932. $oDb = BxDolDb::getInstance();
  933. if ($bInvalidateCache)
  934. $oDb->cleanMemory('sys_version');
  935. $sQuery = $oDb->prepare("SELECT `version` FROM `sys_modules` WHERE `name` = 'system'");
  936. return $oDb->fromMemory('sys_version', 'getOne', $sQuery);
  937. }
  938. /**
  939. * Check if site maintetance mode is enabled.
  940. * Maintetance mode is enabled when '.bx_maintenance' file exists in Dolphin root folder,
  941. * please note that this is hidden file and some file managers don't show it.
  942. * @param $bShowHttpError show 503 HTTP error if site is in mainenance mode
  943. * @return true if site is in maintenance mode, or false otherwise
  944. */
  945. function bx_check_maintenance_mode ($bShowHttpError = false)
  946. {
  947. $bMaintetance = file_exists(BX_DIRECTORY_PATH_ROOT . BX_MAINTENANCE_FILE) && !defined('BX_DOL_UPGRADING');
  948. if ($bMaintetance && $bShowHttpError)
  949. bx_show_service_unavailable_error_and_exit ('Site is temporarily unavailable due to scheduled maintenance, please try again in a minute.', 600);
  950. return $bMaintetance;
  951. }
  952. /**
  953. * Check for minimal requirements.
  954. * if DISABLE_DOLPHIN_REQUIREMENTS_CHECK is defined then this requirements checking is skipped.
  955. * @param $bShowHttpError show 503 HTTP error if site doesn't meet minimal requirements
  956. * @return false if requirements are met, or array of errors of requirements aren't met
  957. */
  958. function bx_check_minimal_requirements ($bShowHttpError = false)
  959. {
  960. if (defined('DISABLE_DOLPHIN_REQUIREMENTS_CHECK'))
  961. return false;
  962. $aErrors = array();
  963. $aErrors[] = (ini_get('register_globals') == 0) ? '' : '<b>register_globals</b> is on (you need to disable it, or your site will be unsafe)';
  964. $aErrors[] = (ini_get('safe_mode') == 0) ? '' : '<b>safe_mode</b> is on (you need to disable it)';
  965. $aErrors[] = (version_compare(PHP_VERSION, '5.2.0', '<')) ? 'PHP version is too old (please update to <b>PHP 5.2.0</b> at least)' : '';
  966. $aErrors[] = (!extension_loaded( 'mbstring')) ? '<b>mbstring</b> extension not installed (Dolphin cannot work without it)' : '';
  967. $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)';
  968. $aErrors = array_diff($aErrors, array('')); // delete empty
  969. $bFailedMinimalRequirements = !empty($aErrors);
  970. if ($bFailedMinimalRequirements && $bShowHttpError) {
  971. $sErrors = implode(" <br /> ", $aErrors);
  972. bx_show_service_unavailable_error_and_exit($sErrors);
  973. }
  974. return $bFailedMinimalRequirements ? $aErrors : false;
  975. }
  976. /**
  977. * Check if redirect to the correct hostname is required, for example redirect from site.com to www.site.com
  978. * @param $bProcessRedirect process redirect and exit if needed
  979. */
  980. function bx_check_redirect_to_correct_hostname ($bProcessRedirect = false)
  981. {
  982. $aUrl = parse_url(BX_DOL_URL_ROOT);
  983. $bRedirectRequired = isset($_SERVER['HTTP_HOST']) && 0 != strcasecmp($_SERVER['HTTP_HOST'], $aUrl['host']) && 0 != strcasecmp($_SERVER['HTTP_HOST'], $aUrl['host'] . ':80');
  984. if ($bRedirectRequired && $bProcessRedirect) {
  985. header( "Location:http://{$aUrl['host']}{$_SERVER['REQUEST_URI']}" );
  986. exit;
  987. }
  988. return $bRedirectRequired;
  989. }
  990. /**
  991. * Check if redirect to remove install folder.
  992. * If BX_SKIP_INSTALL_CHECK is defined then this redirect checking is skipped.
  993. * @param $bProcessRedirect process redirect and exit if needed
  994. */
  995. function bx_check_redirect_to_remove_install_folder ($bProcessRedirect = false)
  996. {
  997. $bRemoveInstallFolder = !defined ('BX_SKIP_INSTALL_CHECK') && file_exists(BX_DIRECTORY_PATH_ROOT . 'install');
  998. if ($bRemoveInstallFolder && $bProcessRedirect) {
  999. header('Location:' . BX_DOL_URL_ROOT . 'install/index.php?action=remove_install');
  1000. exit;
  1001. }
  1002. return $bRemoveInstallFolder;
  1003. }
  1004. /**
  1005. * Show HTTP 503 service unavailable error and exit
  1006. */
  1007. function bx_show_service_unavailable_error_and_exit ($sMsg = false, $iRetryAfter = 86400)
  1008. {
  1009. header('HTTP/1.0 503 Service Unavailable', true, 503);
  1010. header('Retry-After: 600');
  1011. echo $sMsg ? $sMsg : 'Service temporarily unavailable';
  1012. exit;
  1013. }
  1014. /** @} */