utils.inc.php 44 KB

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