utils.inc.php 47 KB

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