utils.inc.php 48 KB

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