utils.inc.php 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278
  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('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. return sha1(md5($sPwd) . $sSalt);
  724. }
  725. function bx_get ($sName, $sMethod = false)
  726. {
  727. if (isset($_GET[$sName]) && ('get' == $sMethod || !$sMethod))
  728. return $_GET[$sName];
  729. elseif (isset($_POST[$sName]) && ('post' == $sMethod || !$sMethod))
  730. return $_POST[$sName];
  731. else
  732. return false;
  733. }
  734. function bx_encode_url_params ($a, $aExcludeKeys = array (), $aOnlyKeys = false)
  735. {
  736. $s = '';
  737. foreach ($a as $sKey => $sVal) {
  738. if (in_array($sKey, $aExcludeKeys))
  739. continue;
  740. if (false !== $aOnlyKeys && !in_array($sKey, $aOnlyKeys))
  741. continue;
  742. if (is_array($sVal)) {
  743. foreach ($sVal as $sSubVal) {
  744. $s .= rawurlencode($sKey) . '[]=' . rawurlencode(is_array($sSubVal) ? 'array' : $sSubVal) . '&';
  745. }
  746. } else {
  747. $s .= rawurlencode($sKey) . '=' . rawurlencode($sVal) . '&';
  748. }
  749. }
  750. return $s;
  751. }
  752. function bx_append_url_params ($sUrl, $mixedParams)
  753. {
  754. if (!$mixedParams)
  755. return $sUrl;
  756. $sParams = false == strpos($sUrl, '?') ? '?' : '&';
  757. if (is_array($mixedParams)) {
  758. foreach($mixedParams as $sKey => $sValue)
  759. $sParams .= $sKey . '=' . $sValue . '&';
  760. $sParams = substr($sParams, 0, -1);
  761. } else {
  762. $sParams .= $mixedParams;
  763. }
  764. return $sUrl . $sParams;
  765. }
  766. function bx_rrmdir($directory)
  767. {
  768. if (substr($directory,-1) == "/")
  769. $directory = substr($directory,0,-1);
  770. if (!file_exists($directory) || !is_dir($directory))
  771. return false;
  772. elseif (!is_readable($directory))
  773. return false;
  774. if (!($directoryHandle = opendir($directory)))
  775. return false;
  776. while ($contents = readdir($directoryHandle)) {
  777. if ($contents != '.' && $contents != '..') {
  778. $path = $directory . "/" . $contents;
  779. if (is_dir($path))
  780. bx_rrmdir($path);
  781. else
  782. unlink($path);
  783. }
  784. }
  785. closedir($directoryHandle);
  786. if (!rmdir($directory))
  787. return false;
  788. return true;
  789. }
  790. function bx_clear_folder ($sPath, $aExts = array ())
  791. {
  792. if (substr($$sPath,-1) == "/")
  793. $sPath = substr($sPath,0,-1);
  794. if (!file_exists($sPath) || !is_dir($sPath))
  795. return false;
  796. elseif (!is_readable($sPath))
  797. return false;
  798. if (!($h = opendir($sPath)))
  799. return false;
  800. while ($sFile = readdir($h)) {
  801. if ('.' == $sFile || '..' == $sFile)
  802. continue;
  803. $sFullPath = $sPath . '/' . $sFile;
  804. if (is_dir($sFullPath))
  805. continue;
  806. if (!$aExts || (($sExt = pathinfo($sFullPath, PATHINFO_EXTENSION)) && in_array($sExt, $aExts)))
  807. @unlink($sFullPath);
  808. }
  809. closedir($h);
  810. return true;
  811. }
  812. function bx_ltrim_str ($sString, $sPrefix, $sReplace = '')
  813. {
  814. if ($sReplace && substr($sString, 0, strlen($sReplace)) == $sReplace)
  815. return $sString;
  816. if (substr($sString, 0, strlen($sPrefix)) == $sPrefix)
  817. return $sReplace . substr($sString, strlen($sPrefix));
  818. return $sString;
  819. }
  820. /**
  821. * Convert array to attributes string
  822. *
  823. * Example:
  824. * @code
  825. * $a = array('name' => 'test', 'value' => 5);
  826. * $s = bx_convert_array2attrs($a);
  827. * echo $s; // outputs: name="test" value="5"
  828. * @endcode
  829. *
  830. * @param $a - array of attributes
  831. * @param $sClasses - classes to merge with 'class' attribute
  832. * @param $sStyles - styles to merge with 'style' attribute
  833. * @return string
  834. */
  835. function bx_convert_array2attrs ($a, $sClasses = false, $sStyles = false)
  836. {
  837. $sRet = '';
  838. if (!$a || !is_array($a))
  839. $a = array();
  840. if ($sClasses) {
  841. $sClasses = trim($sClasses);
  842. $a['class'] = $sClasses . (!empty($a['class']) ? ' ' . $a['class'] : '');
  843. }
  844. if ($sStyles) {
  845. $sStyles = trim($sStyles);
  846. if (';' != $sStyles[strlen($sStyles)-1])
  847. $sStyles .= ';';
  848. $a['style'] = $sStyles . (!empty($a['style']) ? ' ' . $a['style'] : '');
  849. }
  850. foreach ($a as $sKey => $sValue) {
  851. if(is_null($sValue)) // pass NULL values
  852. continue;
  853. $sValueC = bx_html_attribute($sValue, BX_ESCAPE_STR_QUOTE);
  854. $sRet .= " $sKey=\"$sValueC\"";
  855. }
  856. return $sRet;
  857. }
  858. function bx_unicode_urldecode($s)
  859. {
  860. preg_match_all('/%u([[:alnum:]]{4})/', $s, $a);
  861. foreach ($a[1] as $uniord) {
  862. $dec = hexdec($uniord);
  863. $utf = '';
  864. if ($dec < 128) {
  865. $utf = chr($dec);
  866. } else if ($dec < 2048) {
  867. $utf = chr(192 + (($dec - ($dec % 64)) / 64));
  868. $utf .= chr(128 + ($dec % 64));
  869. } else {
  870. $utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
  871. $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
  872. $utf .= chr(128 + ($dec % 64));
  873. }
  874. $s = str_replace('%u'.$uniord, $utf, $s);
  875. }
  876. return urldecode($s);
  877. }
  878. /**
  879. * Raise an alert
  880. * @param string $sType - system type
  881. * @param string $sAction - system action
  882. * @param int $iObjectId - object id
  883. * @param int $iSenderId - sender (action's author) profile id, if it is false - then currectly logged in profile id is used
  884. */
  885. function bx_alert($sUnit, $sAction, $iObjectId, $iSender = false, $aExtras = array())
  886. {
  887. $o = new BxDolAlerts($sUnit, $sAction, $iObjectId, $iSender, $aExtras);
  888. $o->alert();
  889. }
  890. function bx_replace_markers($mixed, $aMarkers)
  891. {
  892. if (empty($aMarkers))
  893. return $mixed;
  894. if (is_array($mixed)) {
  895. foreach ($mixed as $sKey => $sValue)
  896. $mixed[$sKey] = bx_replace_markers ($sValue, $aMarkers);
  897. } else {
  898. foreach ($aMarkers as $sKey => $sValue)
  899. $mixed = str_replace('{' . $sKey . '}', $sValue, $mixed);
  900. }
  901. return $mixed;
  902. }
  903. function bx_site_hash($sSalt = '', $isSkipVersion = false)
  904. {
  905. return md5($sSalt . ($isSkipVersion ? '' : bx_get_ver()) . BX_DOL_SECRET . BX_DOL_URL_ROOT);
  906. }
  907. /**
  908. * Transform string to method name string, for example it changes 'some_method' string to 'SomeMethod' string
  909. * @param string where words are separated with underscore
  910. * @return string where every word begins with capital letter
  911. */
  912. function bx_gen_method_name ($s, $sWordsDelimiter = '_')
  913. {
  914. return str_replace(' ', '', ucwords(str_replace($sWordsDelimiter, ' ', $s)));
  915. }
  916. /**
  917. * Trigger user error
  918. * @param $sMsg message to display
  919. * @param $iNumLevelsBack add additional debug backtracing N levels back
  920. */
  921. function bx_trigger_error ($sMsg, $iNumLevelsBack = 0)
  922. {
  923. $a = debug_backtrace();
  924. $sMsgAdd = "<br />\n related code in <b>{$a[$iNumLevelsBack]['file']}</b> on line <b>{$a[$iNumLevelsBack]['line']}</b> <br />\n";
  925. trigger_error ($sMsg . $sMsgAdd, E_USER_ERROR);
  926. }
  927. /**
  928. * Get Dolphin system DB version, for files version @see BX_DOL_VERSION, these versions must match
  929. */
  930. function bx_get_ver ($bInvalidateCache = false)
  931. {
  932. bx_import('BxDolDb');
  933. $oDb = BxDolDb::getInstance();
  934. if ($bInvalidateCache)
  935. $oDb->cleanMemory('sys_version');
  936. $sQuery = $oDb->prepare("SELECT `version` FROM `sys_modules` WHERE `name` = 'system'");
  937. return $oDb->fromMemory('sys_version', 'getOne', $sQuery);
  938. }
  939. /**
  940. * Check if site maintetance mode is enabled.
  941. * Maintetance mode is enabled when '.bx_maintenance' file exists in Dolphin root folder,
  942. * please note that this is hidden file and some file managers don't show it.
  943. * @param $bShowHttpError show 503 HTTP error if site is in mainenance mode
  944. * @return true if site is in maintenance mode, or false otherwise
  945. */
  946. function bx_check_maintenance_mode ($bShowHttpError = false)
  947. {
  948. $bMaintetance = file_exists(BX_DIRECTORY_PATH_ROOT . BX_MAINTENANCE_FILE) && !defined('BX_DOL_UPGRADING');
  949. if ($bMaintetance && $bShowHttpError)
  950. bx_show_service_unavailable_error_and_exit ('Site is temporarily unavailable due to scheduled maintenance, please try again in a minute.', 600);
  951. return $bMaintetance;
  952. }
  953. /**
  954. * Check for minimal requirements.
  955. * if DISABLE_DOLPHIN_REQUIREMENTS_CHECK is defined then this requirements checking is skipped.
  956. * @param $bShowHttpError show 503 HTTP error if site doesn't meet minimal requirements
  957. * @return false if requirements are met, or array of errors of requirements aren't met
  958. */
  959. function bx_check_minimal_requirements ($bShowHttpError = false)
  960. {
  961. if (defined('DISABLE_DOLPHIN_REQUIREMENTS_CHECK'))
  962. return false;
  963. $aErrors = array();
  964. $aErrors[] = (ini_get('register_globals') == 0) ? '' : '<b>register_globals</b> is on (you need to disable it, or your site will be unsafe)';
  965. $aErrors[] = (ini_get('safe_mode') == 0) ? '' : '<b>safe_mode</b> is on (you need to disable it)';
  966. $aErrors[] = (version_compare(PHP_VERSION, '5.3.0', '<')) ? 'PHP version is too old (please update to <b>PHP 5.3.0</b> at least)' : '';
  967. $aErrors[] = (!extension_loaded( 'mbstring')) ? '<b>mbstring</b> extension not installed (Dolphin cannot work without it)' : '';
  968. $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)';
  969. $aErrors = array_diff($aErrors, array('')); // delete empty
  970. $bFailedMinimalRequirements = !empty($aErrors);
  971. if ($bFailedMinimalRequirements && $bShowHttpError) {
  972. $sErrors = implode(" <br /> ", $aErrors);
  973. bx_show_service_unavailable_error_and_exit($sErrors);
  974. }
  975. return $bFailedMinimalRequirements ? $aErrors : false;
  976. }
  977. /**
  978. * Check if redirect to the correct hostname is required, for example redirect from site.com to www.site.com
  979. * @param $bProcessRedirect process redirect and exit if needed
  980. */
  981. function bx_check_redirect_to_correct_hostname ($bProcessRedirect = false)
  982. {
  983. $aUrl = parse_url(BX_DOL_URL_ROOT);
  984. $bRedirectRequired = isset($_SERVER['HTTP_HOST']) && 0 != strcasecmp($_SERVER['HTTP_HOST'], $aUrl['host']) && 0 != strcasecmp($_SERVER['HTTP_HOST'], $aUrl['host'] . ':80');
  985. if ($bRedirectRequired && $bProcessRedirect) {
  986. header( "Location:http://{$aUrl['host']}{$_SERVER['REQUEST_URI']}" );
  987. exit;
  988. }
  989. return $bRedirectRequired;
  990. }
  991. /**
  992. * Check if redirect to remove install folder.
  993. * If BX_SKIP_INSTALL_CHECK is defined then this redirect checking is skipped.
  994. * @param $bProcessRedirect process redirect and exit if needed
  995. */
  996. function bx_check_redirect_to_remove_install_folder ($bProcessRedirect = false)
  997. {
  998. $bRemoveInstallFolder = !defined ('BX_SKIP_INSTALL_CHECK') && file_exists(BX_DIRECTORY_PATH_ROOT . 'install');
  999. if ($bRemoveInstallFolder && $bProcessRedirect) {
  1000. header('Location:' . BX_DOL_URL_ROOT . 'install/index.php?action=remove_install');
  1001. exit;
  1002. }
  1003. return $bRemoveInstallFolder;
  1004. }
  1005. /**
  1006. * Show HTTP 503 service unavailable error and exit
  1007. */
  1008. function bx_show_service_unavailable_error_and_exit ($sMsg = false, $iRetryAfter = 86400)
  1009. {
  1010. header('HTTP/1.0 503 Service Unavailable', true, 503);
  1011. header('Retry-After: 600');
  1012. echo $sMsg ? $sMsg : 'Service temporarily unavailable';
  1013. exit;
  1014. }
  1015. /**
  1016. * The function is sumilar to php readfile, but it send all required headers and can send file by chunks and suports file seek
  1017. * @param $sPath path to file to output to the browser
  1018. * @param $sFilename filename without path, ig file is saved from browser, then this name is used, not used(empty) by default
  1019. * @param $sMimeType file mime type, by default 'application/octet-stream'
  1020. * @param $iCacheAge file cache age, by default 0
  1021. * @param $sCachePrivacy cache privacy 'public' (default value) or 'private'
  1022. * @return true on success or false on error
  1023. */
  1024. function bx_smart_readfile($sPath, $sFilename = '', $sMimeType = 'application/octet-stream', $iCacheAge = 0, $sCachePrivacy = 'public')
  1025. {
  1026. if (!file_exists($sPath))
  1027. return false;
  1028. $fp = @fopen($sPath, 'rb');
  1029. $size = filesize($sPath);
  1030. $length = $size;
  1031. $start = 0;
  1032. $end = $size - 1;
  1033. header('Content-type: ' . $sMimeType);
  1034. header('Cache-Control: ' . $sCachePrivacy . ', must-revalidate, max-age=' . $iCacheAge);
  1035. header("Accept-Ranges: 0-$length");
  1036. if ($sFilename)
  1037. header('Content-Disposition: inline; filename=' . $sFilename);
  1038. if (isset($_SERVER['HTTP_RANGE'])) {
  1039. $c_start = $start;
  1040. $c_end = $end;
  1041. list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
  1042. if (strpos($range, ',') !== false) {
  1043. header('HTTP/1.1 416 Requested Range Not Satisfiable');
  1044. header("Content-Range: bytes $start-$end/$size");
  1045. return false;
  1046. }
  1047. if ($range == '-') {
  1048. $c_start = $size - substr($range, 1);
  1049. }else{
  1050. $range = explode('-', $range);
  1051. $c_start = $range[0];
  1052. $c_end = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $size;
  1053. }
  1054. $c_end = ($c_end > $end) ? $end : $c_end;
  1055. if ($c_start > $c_end || $c_start > $size - 1 || $c_end >= $size) {
  1056. header('HTTP/1.1 416 Requested Range Not Satisfiable');
  1057. header("Content-Range: bytes $start-$end/$size");
  1058. return false;
  1059. }
  1060. $start = $c_start;
  1061. $end = $c_end;
  1062. $length = $end - $start + 1;
  1063. fseek($fp, $start);
  1064. header('HTTP/1.1 206 Partial Content');
  1065. }
  1066. header("Content-Range: bytes $start-$end/$size");
  1067. header("Content-Length: ".$length);
  1068. $buffer = 1024 * 8;
  1069. while(!feof($fp) && ($p = ftell($fp)) <= $end) {
  1070. if ($p + $buffer > $end) {
  1071. $buffer = $end - $p + 1;
  1072. }
  1073. set_time_limit(0);
  1074. echo fread($fp, $buffer);
  1075. flush();
  1076. }
  1077. fclose($fp);
  1078. return true;
  1079. }
  1080. /** @} */