utils.inc.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050
  1. <?php defined('BX_DOL') or defined('BX_DOL_INSTALL') or die('hack attempt');
  2. /**
  3. * Copyright (c) BoonEx Pty Limited - http://www.boonex.com/
  4. * CC-BY License - http://creativecommons.org/licenses/by/3.0/
  5. *
  6. * @defgroup DolphinCore Dolphin Core
  7. * @{
  8. */
  9. define('BX_DATA_TEXT', 1); ///< regular text data type
  10. define('BX_DATA_TEXT_MULTILINE', 2); ///< regular multiline text data type
  11. define('BX_DATA_INT', 3); ///< integer data type
  12. define('BX_DATA_FLOAT', 4); ///< float data type
  13. define('BX_DATA_CHECKBOX', 5); ///< checkbox data type, 'on' or empty value
  14. define('BX_DATA_HTML', 6); ///< HTML data type
  15. define('BX_DATA_DATE', 7); ///< date data type stored as yyyy-mm-dd
  16. define('BX_DATA_DATE_TS', 8); ///< date data type stored as unixtimestamp
  17. define('BX_DATA_DATETIME_TS', 9); ///< date/time data type stored as unixtimestamp
  18. define('BX_SLASHES_AUTO', 0);
  19. define('BX_SLASHES_ADD', 1);
  20. define('BX_SLASHES_STRIP', 2);
  21. define('BX_SLASHES_NO_ACTION', 3);
  22. define('BX_ESCAPE_STR_AUTO', 0); ///< turn apostropes and quote signs into html special chars, for use in @see bx_js_string and @see bx_html_attribute
  23. define('BX_ESCAPE_STR_APOS', 1); ///< escape apostrophes only, for js strings enclosed in apostrophes, for use in @see bx_js_string and @see bx_html_attribute
  24. define('BX_ESCAPE_STR_QUOTE', 2); ///< escape quotes only, for js strings enclosed in quotes, for use in @see bx_js_string and @see bx_html_attribute
  25. define('BX_EMAIL_SYSTEM', 0); ///< system email without unsubscribe link, like forgot password or email verification
  26. define('BX_EMAIL_NOTIFY', 1); ///< notification message, with unsubscribe link
  27. define('BX_EMAIL_MASS', 2); ///< mass email, one mesage send to manu users, with unsubscribe link
  28. /**
  29. * The following two functions are needed to convert title to uri and back.
  30. * It usefull when titles are used in URLs, like in Categories and Tags.
  31. */
  32. function title2uri($sValue) {
  33. return str_replace(
  34. array('&', '/', '\\', '"', '+'),
  35. array('[and]', '[slash]', '[backslash]', '[quote]', '[plus]'),
  36. $sValue
  37. );
  38. }
  39. function uri2title($sValue) {
  40. return str_replace(
  41. array('[and]', '[slash]', '[backslash]', '[quote]', '[plus]'),
  42. array('&', '/', '\\', '"', '+'),
  43. $sValue
  44. );
  45. }
  46. /*
  47. * functions for limiting maximal text length
  48. */
  49. function strmaxtextlen($sInput, $iMaxLen = 60, $sEllipsisSign = '&#8230;') {
  50. $sTail = '';
  51. $s = trim(strip_tags($sInput));
  52. if (mb_strlen($s) > $iMaxLen) {
  53. $s = mb_substr($s, 0, $iMaxLen);
  54. $sTail = $sEllipsisSign;
  55. }
  56. return htmlspecialchars_adv($s) . $sTail;
  57. }
  58. function html2txt($content, $tags = "") {
  59. while($content != strip_tags($content, $tags)) {
  60. $content = strip_tags($content, $tags);
  61. }
  62. return $content;
  63. }
  64. function html_encode($text) {
  65. $searcharray = array(
  66. "'([-_\w\d.]+@[-_\w\d.]+)'",
  67. "'((?:(?!://).{3}|^.{0,2}))(www\.[-\d\w\.\/]+)'",
  68. "'(http[s]?:\/\/[-_~\w\d\.\/]+)'");
  69. $replacearray = array(
  70. "<a href=\"mailto:\\1\">\\1</a>",
  71. "\\1http://\\2",
  72. "<a href=\"\\1\" target=_blank>\\1</a>");
  73. return preg_replace($searcharray, $replacearray, stripslashes($text));
  74. }
  75. /**
  76. * Functions to process user input.
  77. * DON'T use to process data before passing to SQL query - use db prepare instead @see BxDolDb::prepare.
  78. * It is ok to use bx_process_input and then db prepare.
  79. * @param $mixedData data to process
  80. * @param $iDataType how to handle data, possible valies:
  81. * BX_DATA_INT - integer value
  82. * BX_DATA_FLOAT - float values
  83. * BX_DATA_CHECKBOX - 'on' or empty string
  84. * BX_DATA_TEXT - text data, single line (default)
  85. * BX_DATA_TEXT_MULTILINE - text data, multiple lines
  86. * BX_DATA_HTML - HTML data
  87. * BX_DATA_DATE - date data type stored as yyyy-mm-dd
  88. * BX_DATA_DATE_TS' - date data type stored as unixtimestamp
  89. * BX_DATA_DATETIME_TS - date/time data type stored as unixtimestamp
  90. * @param $mixedParams optional parameters to pass for validation
  91. * @return the filtered data, or FALSE if the filter fails.
  92. */
  93. function bx_process_input ($mixedData, $iDataType = BX_DATA_TEXT, $mixedParams = false, $isCheckMagicQuotes = true) {
  94. if (is_array($mixedData)) {
  95. foreach ($mixedData as $k => $v)
  96. $mixedData[$k] = bx_process_input($v, $iDataType, $mixedParams);
  97. return $mixedData;
  98. }
  99. if (get_magic_quotes_gpc() && $isCheckMagicQuotes)
  100. $mixedData = stripslashes($mixedData);
  101. switch ($iDataType) {
  102. case BX_DATA_INT:
  103. return filter_var(trim($mixedData), FILTER_VALIDATE_INT);
  104. case BX_DATA_FLOAT:
  105. return filter_var(trim($mixedData), FILTER_VALIDATE_FLOAT);
  106. case BX_DATA_CHECKBOX:
  107. return 'on' == trim($mixedData) ? 'on' : '';
  108. case BX_DATA_DATE:
  109. // maybe consider using strtotime
  110. $mixedData = trim($mixedData);
  111. if (!preg_match('/^\d{4}-\d{1,2}-\d{1,2}$/', $mixedData))
  112. return false;
  113. list($iYear, $iMonth, $iDay) = explode('-', $mixedData); // 1985-10-28
  114. $iDay = intval($iDay);
  115. $iMonth = intval($iMonth);
  116. $iYear = intval($iYear);
  117. return sprintf("%04d-%02d-%02d", $iYear, $iMonth, $iDay);
  118. case BX_DATA_DATE_TS:
  119. $mixedData = trim($mixedData);
  120. if (!preg_match('/^\d{4}-\d{1,2}-\d{1,2}$/', $mixedData))
  121. return false;
  122. list($iYear, $iMonth, $iDay) = explode('-', $mixedData);
  123. $iDay = intval($iDay);
  124. $iMonth = intval($iMonth);
  125. $iYear = intval($iYear);
  126. $iRet = mktime (0, 0, 0, $iMonth, $iDay, $iYear);
  127. return $iRet > 0 ? $iRet : false;
  128. case BX_DATA_DATETIME_TS:
  129. if (!preg_match('#(\d+)\-(\d+)\-(\d+)[\sT]{1}(\d+):(\d+):(\d+)#', $mixedData, $m) && !preg_match('#(\d+)\-(\d+)\-(\d+)[\sT]{1}(\d+):(\d+)#', $mixedData, $m))
  130. return bx_process_input ($mixedData, BX_DATA_DATE_TS, $mixedParams, $isCheckMagicQuotes);
  131. $iDay = $m[3];
  132. $iMonth = $m[2];
  133. $iYear = $m[1];
  134. $iH = $m[4];
  135. $iM = $m[5];
  136. $iS = isset($m[6]) ? $m[6] : 0;
  137. $iRet = mktime ($iH, $iM, $iS, $iMonth, $iDay, $iYear);
  138. return $iRet > 0 ? $iRet : false;
  139. case BX_DATA_HTML:
  140. return clear_xss($mixedData);
  141. case BX_DATA_TEXT_MULTILINE:
  142. return nl2br(htmlspecialchars_adv($mixedData));
  143. case BX_DATA_TEXT:
  144. default:
  145. return $mixedData;
  146. }
  147. }
  148. /*
  149. * Functions to process user output.
  150. * Always use this function before output data which was entered by user before.
  151. * @param $mixedData string to process
  152. * @param $iDataType how to handle data, possible valies the same as in bx_process_input function, see bx_process_input.
  153. * @param $mixedParams optional parameters to pass for validation
  154. * @return the filtered data, or FALSE if the filter fails.
  155. */
  156. function bx_process_output ($mixedData, $iDataType = BX_DATA_TEXT, $mixedParams = false) {
  157. if (is_array($mixedData)) {
  158. foreach ($mixedData as $k => $v)
  159. $mixedData[$k] = bx_process_output($v, $iDataType, $mixedParams);
  160. return $mixedData;
  161. }
  162. switch ($iDataType) {
  163. case BX_DATA_INT:
  164. return filter_var($mixedData, FILTER_VALIDATE_INT);
  165. case BX_DATA_FLOAT:
  166. return filter_var($mixedData, FILTER_VALIDATE_FLOAT);
  167. case BX_DATA_CHECKBOX:
  168. return 'on' == trim($mixedData) ? 'on' : '';
  169. case BX_DATA_DATE:
  170. return $mixedData;
  171. case BX_DATA_DATE_TS:
  172. return empty($mixedData) ? '' : date("Y-m-d", $mixedData);
  173. case BX_DATA_DATETIME_TS:
  174. return empty($mixedData) ? '' : date("Y-m-d H:i", $mixedData);
  175. case BX_DATA_HTML:
  176. return $mixedData;
  177. case BX_DATA_TEXT_MULTILINE:
  178. return $mixedData;
  179. case BX_DATA_TEXT:
  180. default:
  181. return htmlspecialchars_adv($mixedData);
  182. }
  183. }
  184. /*
  185. * This function apply bx_process_input and then bx_process_output.
  186. * Use this function to output data immediately after receiving, without saving to database.
  187. * Patams are the same as bx_process_input function - @see bx_process_input
  188. */
  189. function bx_process_pass ($mixedData, $iDataType = BX_DATA_TEXT, $mixedParams = false, $isCheckMagicQuotes = true) {
  190. return bx_process_output(bx_process_input ($mixedData, $iDataType, $mixedParams, $isCheckMagicQuotes), $iDataType, $mixedParams);
  191. }
  192. /**
  193. * DEPRECATED
  194. * use bx_process_input + bx_process_output instead
  195. * --------
  196. * function for processing pass data
  197. *
  198. * This function cleans the GET/POST/COOKIE data if magic_quotes_gpc() is on
  199. * for data which should be outputed immediately after submit
  200. */
  201. /*
  202. function process_pass_data( $text, $strip_tags = 0 ) {
  203. if ( $strip_tags )
  204. $text = strip_tags($text);
  205. if ( !get_magic_quotes_gpc() )
  206. return $text;
  207. else
  208. return stripslashes($text);
  209. }
  210. */
  211. /*
  212. * function for output data from database into html
  213. */
  214. function htmlspecialchars_adv( $string ) {
  215. return htmlspecialchars($string, ENT_COMPAT, 'UTF-8');
  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. bx_import('BxDolAccount');
  222. $oAccount = BxDolAccount::getInstance($iAccountId);
  223. bx_import('BxDolProfile');
  224. $oProfile = BxDolProfile::getInstance($iProfileId);
  225. bx_import('BxDolEmailTemplates');
  226. $oEmailTemplates = BxDolEmailTemplates::getInstance();
  227. if (!$oAccount || !$oProfile || !$oEmailTemplates)
  228. return false;
  229. $aTemplate = $oEmailTemplates->parseTemplate($sTemplateName, $aReplaceVars, $iAccountId, $iProfileId);
  230. if (!$aTemplate)
  231. return false;
  232. return sendMail($oAccount->getEmail(), $aTemplate['Subject'], $aTemplate['Body'], 0, array(), $iEmailType);
  233. }
  234. /**
  235. * Send email function
  236. *
  237. * @param $sRecipientEmail - Email where email should be send
  238. * @param $sMailSubject - subject of the message
  239. * @param $sMailBody - Body of the message
  240. * @param $iRecipientID - ID of recipient profile
  241. * @param $aPlus - Array of additional information
  242. * @param $iEmailType - email message type: BX_EMAIL_SYSTEM, BX_EMAIL_NOTIFY or BX_EMAIL_MASS
  243. * @return true if message was send or false otherwise
  244. */
  245. function sendMail($sRecipientEmail, $sMailSubject, $sMailBody, $iRecipientID = 0, $aPlus = array(), $iEmailType = BX_EMAIL_NOTIFY, $sEmailFlag = 'html', $isDisableAlert = false) {
  246. // make sure that recipient's email is valid and message isn't empty
  247. if (!$sMailBody || !$sRecipientEmail || preg_match('/\(2\)$/', $sRecipientEmail))
  248. return false;
  249. // get recipient account
  250. bx_import('BxDolAccount');
  251. $oAccount = BxDolAccount::getInstance($sRecipientEmail);
  252. $aAccountInfo = $oAccount ? $oAccount->getInfo() : false;
  253. // don't send bulk emails if user didn't subscribed to site news or email is unconfirmed
  254. if ($aAccountInfo && BX_EMAIL_MASS == $iEmailType && (!$aAccountInfo['email_confirmed'] || !$aAccountInfo['receive_news']))
  255. return false;
  256. // don't send email notifications if user didn't subscribed to notifications or email is unconfirmed
  257. if ($aAccountInfo && BX_EMAIL_NOTIFY == $iEmailType && (!$aAccountInfo['email_confirmed'] || !$aAccountInfo['receive_updates']))
  258. return false;
  259. // if profile id is provided - get profile's info
  260. $aRecipientInfo = false;
  261. if ($iRecipientID) {
  262. bx_import('BxDolProfile');
  263. $oProfile = BxDolProfile::getInstance($iRecipientID);
  264. if ($oProfile)
  265. $aRecipientInfo = $oProfile->getInfo();
  266. }
  267. // get site vars
  268. $sEmailNotify = getParam('site_email_notify');
  269. $sSiteTitle = getParam('site_title');
  270. // add unsubscribe link
  271. if (empty($aPlus['unsubscribe'])) {
  272. $aPlus['unsubscribe'] = '';
  273. if ($oAccount && (BX_EMAIL_MASS == $iEmailType || BX_EMAIL_NOTIFY == $iEmailType))
  274. $aPlus['unsubscribe'] = ($sLink = $oAccount->getUnsubscribeLink($iEmailType)) ? '<a href="' . BX_DOL_URL_ROOT . $sLink . '">' . _t('_sys_et_txt_unsubscribe') . '</a>' : '';
  275. }
  276. // parse template
  277. if ($aPlus || $iRecipientID) {
  278. if(!is_array($aPlus))
  279. $aPlus = array();
  280. bx_import('BxDolEmailTemplates');
  281. $oEmailTemplates = BxDolEmailTemplates::getInstance();
  282. $sMailSubject = $oEmailTemplates->parseContent($sMailSubject, $aPlus, $iRecipientID);
  283. $sMailBody = $oEmailTemplates->parseContent($sMailBody, $aPlus, $iRecipientID);
  284. }
  285. // email message headers
  286. $sMailHeader = "From: =?UTF-8?B?" . base64_encode( $sSiteTitle ) . "?= <{$sEmailNotify}>";
  287. $sMailParameters = "-f{$sEmailNotify}";
  288. $sMailSubject = '=?UTF-8?B?' . base64_encode( $sMailSubject ) . '?=';
  289. $sMailHeader = "MIME-Version: 1.0\r\n" . $sMailHeader;
  290. // build data for alert handler
  291. $bResult = null;
  292. $aAlert = array(
  293. 'email' => $sRecipientEmail,
  294. 'subject' => $sMailSubject,
  295. 'body' => $sMailBody,
  296. 'header' => $sMailHeader,
  297. 'params' => $sMailParameters,
  298. 'recipient' => $aRecipientInfo,
  299. 'html' => 'html' == $sEmailFlag ? true : false,
  300. 'override_result' => &$bResult,
  301. );
  302. // system alert
  303. if (!$isDisableAlert) {
  304. bx_alert('system', 'before_send_mail', (isset($aRecipientInfo['ID']) ? $aRecipientInfo['ID'] : 0), '', $aAlert);
  305. if ($bResult !== null)
  306. return $bResult;
  307. unset($aAlert['override_result']);
  308. }
  309. // send mail
  310. if( 'html' == $sEmailFlag) {
  311. $sMailHeader = "Content-type: text/html; charset=UTF-8\r\n" . $sMailHeader;
  312. $iSendingResult = mail( $sRecipientEmail, $sMailSubject, $sMailBody, $sMailHeader, $sMailParameters );
  313. } else {
  314. $sMailHeader = "Content-type: text/plain; charset=UTF-8\r\n" . $sMailHeader;
  315. $sMailBody = html2txt($sMailBody);
  316. $iSendingResult = mail( $sRecipientEmail, $sMailSubject, html2txt($sMailBody), $sMailHeader, $sMailParameters );
  317. }
  318. // system alert
  319. if (!$isDisableAlert)
  320. bx_alert('system', 'send_mail', (isset($aRecipientInfo['ID']) ? $aRecipientInfo['ID'] : 0), '', $aAlert);
  321. return $iSendingResult;
  322. }
  323. /*
  324. * Getting an array with Templates' Names
  325. */
  326. function get_templates_array($bEnabledOnly = true, $bShortInfo = true) {
  327. bx_import('BxDolDb');
  328. $oDb = BxDolDb::getInstance();
  329. $sWhereAddon = $bEnabledOnly ? " AND `enabled`='1'" : "";
  330. if($bShortInfo)
  331. return $oDb->getPairs("SELECT `uri`, `title` FROM `sys_modules` WHERE 1 AND `type`='" . BX_DOL_MODULE_TYPE_TEMPLATE . "'" . $sWhereAddon, "uri", "title");
  332. else
  333. return $oDb->getAllWithKey("SELECT * FROM `sys_modules` WHERE 1 AND `type`='" . BX_DOL_MODULE_TYPE_TEMPLATE . "'" . $sWhereAddon, "uri");
  334. }
  335. /*
  336. * The Function Show a Line with Templates Names
  337. */
  338. function templates_select_txt() {
  339. $templ_choices = get_templates_array();
  340. $current_template = ( strlen( $_GET['skin'] ) ) ? $_GET['skin'] : $_COOKIE['skin'];
  341. foreach ($templ_choices as $tmpl_key => $tmpl_value) {
  342. if ($current_template == $tmpl_key) {
  343. $ReturnResult .= $tmpl_value . ' | ';
  344. } else {
  345. $sGetTransfer = bx_encode_url_params($_GET, array('skin'));
  346. $ReturnResult .= '<a href="' . bx_html_attribute($_SERVER['PHP_SELF']) . '?' . $sGetTransfer . 'skin=' . $tmpl_key . '">' . $tmpl_value . '</a> | ';
  347. }
  348. }
  349. return $ReturnResult;
  350. }
  351. function extFileExists( $sFileSrc ) {
  352. return (file_exists( $sFileSrc ) && is_file( $sFileSrc )) ? true : false;
  353. }
  354. function getVisitorIP() {
  355. $ip = "0.0.0.0";
  356. if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  357. $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
  358. } elseif (isset( $_SERVER['HTTP_CLIENT_IP']) && !empty($_SERVER['HTTP_CLIENT_IP'])) {
  359. $ip = explode(".",$_SERVER['HTTP_CLIENT_IP']);
  360. $ip = $ip[3].".".$ip[2].".".$ip[1].".".$ip[0];
  361. } elseif (!isset( $_SERVER['HTTP_X_FORWARDED_FOR']) || empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  362. if (!isset( $_SERVER['HTTP_CLIENT_IP']) && empty($_SERVER['HTTP_CLIENT_IP']) && isset($_SERVER['REMOTE_ADDR']))
  363. $ip = $_SERVER['REMOTE_ADDR'];
  364. }
  365. return $ip;
  366. }
  367. function genFlag( $country ) {
  368. return '<img src="' . genFlagUrl($country) . '" />';
  369. }
  370. function genFlagUrl($country) {
  371. bx_import('BxDolTemplate');
  372. return BxDolTemplate::getInstance()->getIconUrl('sys_fl_' . strtolower($country) . '.gif');
  373. }
  374. // print debug information ( e.g. arrays )
  375. function echoDbg( $what, $desc = '' ) {
  376. if ( $desc )
  377. echo "<b>$desc:</b> ";
  378. echo "<pre>";
  379. print_r( $what );
  380. echo "</pre>\n";
  381. }
  382. function echoDbgLog($mWhat, $sDesc = '', $sFileName = 'debug.log') {
  383. $sCont =
  384. '--- ' . date('r') . ' (' . BX_DOL_START_TIME . ") ---\n" .
  385. $sDesc . "\n" .
  386. print_r($mWhat, true) . "\n\n\n";
  387. $rFile = fopen(BxDolConfig::getInstance()->get('path_dynamic', 'tmp') . $sFileName, 'a');
  388. fwrite($rFile, $sCont);
  389. fclose($rFile);
  390. }
  391. function clear_xss($val) {
  392. if ($GLOBALS['logged']['admin'])
  393. return $val;
  394. // HTML Purifier plugin
  395. global $oHtmlPurifier;
  396. require_once( BX_DIRECTORY_PATH_PLUGINS . 'htmlpurifier/HTMLPurifier.standalone.php' );
  397. if (!isset($oHtmlPurifier)) {
  398. HTMLPurifier_Bootstrap::registerAutoload();
  399. $oConfig = HTMLPurifier_Config::createDefault();
  400. $oConfig->set('Cache.SerializerPath', rtrim(BX_DIRECTORY_PATH_CACHE, '/'));
  401. $oConfig->set('HTML.SafeObject', 'true');
  402. $oConfig->set('Output.FlashCompat', 'true');
  403. $oConfig->set('HTML.FlashAllowFullScreen', 'true');
  404. if (getParam('sys_add_nofollow')) { // TODO: add to "Security" settings
  405. $sHost = parse_url(BX_DOL_URL_ROOT, PHP_URL_HOST);
  406. $oConfig->set('URI.Host', $sHost);
  407. $oConfig->set('HTML.Nofollow', 'true');
  408. }
  409. $oConfig->set('Filter.Custom', array (new HTMLPurifier_Filter_YouTube(), new HTMLPurifier_Filter_YoutubeIframe()));
  410. $oDef = $oConfig->getHTMLDefinition(true);
  411. $oDef->addAttribute('a', 'target', 'Enum#_blank,_self,_target,_top');
  412. $oHtmlPurifier = new HTMLPurifier($oConfig);
  413. }
  414. return $oHtmlPurifier->purify($val);
  415. }
  416. //--------------------------------------- friendly permalinks --------------------------------------//
  417. //------------------------------------------- main functions ---------------------------------------//
  418. function uriGenerate ($s, $sTable, $sField, $sEmpty = '-') {
  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. bx_import('BxTemplConfig');
  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. bx_import('BxDolDb');
  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. return preg_replace ($sPattern, $sReplace, $s);
  454. }
  455. function get_mb_len ($s) {
  456. return (function_exists('mb_strlen')) ? mb_strlen($s) : strlen($s);
  457. }
  458. function get_mb_substr ($s, $iStart, $iLen) {
  459. return (function_exists('mb_substr')) ? mb_substr ($s, $iStart, $iLen) : substr ($s, $iStart, $iLen);
  460. }
  461. function bx_mb_substr_replace($s, $sReplace, $iPosStart, $iLength) {
  462. return mb_substr($s, 0, $iPosStart) . $sReplace . mb_substr($s, $iPosStart + $iLength);
  463. }
  464. function bx_mb_strpos ($s, $sReplacement, $iStart = 0) {
  465. return mb_strpos($s, $sReplacement, $iStart);
  466. }
  467. /**
  468. * Import class file, it automatically detects class path by its prefix or module array/name
  469. *
  470. * @param $sClassName - full class name or class postfix(withoit prefix) in the case of module class
  471. * @param $mixedModule - module array or module name in the case of module class
  472. */
  473. function bx_import($sClassName, $mixedModule = array()) {
  474. if (class_exists($sClassName))
  475. return;
  476. $aModule = false;
  477. if ($mixedModule) {
  478. if (is_array($mixedModule)) {
  479. $aModule = $mixedModule;
  480. } elseif (is_string($mixedModule)) {
  481. bx_import('BxDolModule');
  482. $o = BxDolModule::getInstance($mixedModule);
  483. $aModule = $o->_aModule;
  484. } elseif (is_bool($mixedModule) && true === $mixedModule) {
  485. $aModule = $GLOBALS['aModule'];
  486. }
  487. }
  488. if ($aModule) {
  489. if (class_exists($aModule['class_prefix'] . $sClassName))
  490. return;
  491. require_once (BX_DIRECTORY_PATH_MODULES . $aModule['path'] . 'classes/' . $aModule['class_prefix'] . $sClassName . '.php');
  492. return;
  493. }
  494. if (0 == strncmp($sClassName, 'BxDol', 5)) {
  495. if (0 == strncmp($sClassName, 'BxDolStudio', 11))
  496. require_once(BX_DOL_DIR_STUDIO_CLASSES . $sClassName . '.php');
  497. else
  498. require_once(BX_DIRECTORY_PATH_CLASSES . $sClassName . '.php');
  499. return;
  500. }
  501. if (0 == strncmp($sClassName, 'BxBase', 6)) {
  502. if (0 == strncmp($sClassName, 'BxBaseMod', 9)) {
  503. $aMatches = array();
  504. if (preg_match('/BxBaseMod([A-Z][a-z]+)/', $sClassName, $aMatches)) {
  505. require_once(BX_DIRECTORY_PATH_MODULES . 'base/' . strtolower($aMatches[1]) . '/classes/' . $sClassName . '.php');
  506. return;
  507. }
  508. } if (0 == strncmp($sClassName, 'BxBaseStudio', 12)) {
  509. require_once(BX_DOL_DIR_STUDIO_BASE . 'scripts/' . $sClassName . '.php');
  510. return;
  511. } else {
  512. require_once(BX_DIRECTORY_PATH_BASE . 'scripts/' . $sClassName . '.php');
  513. return;
  514. }
  515. }
  516. if (0 == strncmp($sClassName, 'BxTempl', 7) && !class_exists($sClassName)) {
  517. if(0 == strncmp($sClassName, 'BxTemplStudio', 13)) {
  518. bx_import('BxDolStudioTemplate');
  519. $sPath = BX_DIRECTORY_PATH_MODULES . BxDolStudioTemplate::getInstance()->getPath() . 'data/template/studio/scripts/' . $sClassName . '.php';
  520. }
  521. else {
  522. bx_import('BxDolTemplate');
  523. $sPath = BX_DIRECTORY_PATH_MODULES . BxDolTemplate::getInstance()->getPath() . 'data/template/system/scripts/' . $sClassName . '.php';
  524. }
  525. if (file_exists($sPath)) {
  526. require_once($sPath);
  527. return;
  528. }
  529. trigger_error ("bx_import fatal error: class (" . $sClassName . ") wasn't found", E_USER_ERROR);
  530. }
  531. }
  532. /**
  533. * Gets an instance of class pathing necessary parameters if it's necessary.
  534. *
  535. * @param string $sClassName class name.
  536. * @param array $aParams an array of parameters to be pathed to the constructor of the class.
  537. * @param array $aModule an array with module description. Is used when the requested class is located in some module.
  538. * @return unknown
  539. */
  540. function bx_instance($sClassName, $aParams = array(), $aModule = array()) {
  541. if(isset($GLOBALS['bxDolClasses'][$sClassName]))
  542. return $GLOBALS['bxDolClasses'][$sClassName];
  543. bx_import((empty($aModule) ? $sClassName : str_replace($aModule['class_prefix'], '', $sClassName)), $aModule);
  544. $oClass = new ReflectionClass($sClassName);
  545. $GLOBALS['bxDolClasses'][$sClassName] = empty($aParams) ? $oClass->newInstance() : $oClass->newInstanceArgs($aParams);
  546. return $GLOBALS['bxDolClasses'][$sClassName];
  547. }
  548. /**
  549. * Escapes string/array ready to pass to js script with filtered symbols like ', " etc
  550. *
  551. * @param $mixedInput - string/array which should be filtered
  552. * @param $iQuoteType - string escaping method: BX_ESCAPE_STR_AUTO(default), BX_ESCAPE_STR_APOS or BX_ESCAPE_STR_QUOTE
  553. * @return converted string / array
  554. */
  555. function bx_js_string ($mixedInput, $iQuoteType = BX_ESCAPE_STR_AUTO) {
  556. $aUnits = array(
  557. "\n" => "\\n",
  558. "\r" => "",
  559. );
  560. if (BX_ESCAPE_STR_APOS == $iQuoteType) {
  561. $aUnits["'"] = "\\'";
  562. $aUnits['<script'] = "<scr' + 'ipt";
  563. $aUnits['</script>'] = "</scr' + 'ipt>";
  564. } elseif (BX_ESCAPE_STR_QUOTE == $iQuoteType) {
  565. $aUnits['"'] = '\\"';
  566. $aUnits['<script'] = '<scr" + "ipt';
  567. $aUnits['</script>'] = '</scr" + "ipt>';
  568. } else {
  569. $aUnits['"'] = '&quote;';
  570. $aUnits["'"] = '&apos;';
  571. $aUnits["<"] = '&lt;';
  572. $aUnits[">"] = '&gt;';
  573. }
  574. return str_replace(array_keys($aUnits), array_values($aUnits), $mixedInput);
  575. }
  576. /**
  577. * Return input string/array ready to pass to html attribute with filtered symbols like ', " etc
  578. *
  579. * @param mixed $mixedInput - string/array which should be filtered
  580. * @return converted string / array
  581. */
  582. function bx_html_attribute ($mixedInput, $iQuoteType = BX_ESCAPE_STR_AUTO) {
  583. $aUnits = array ();
  584. if (BX_ESCAPE_STR_APOS == $iQuoteType)
  585. $aUnits["'"] = "\\'";
  586. elseif (BX_ESCAPE_STR_QUOTE == $iQuoteType)
  587. $aUnits['"'] = '&quot;';
  588. else
  589. $aUnits = array("\"" => "&quot;", "'" => "&apos;");
  590. return str_replace(array_keys($aUnits), array_values($aUnits), $mixedInput);
  591. }
  592. /**
  593. * Escapes string/array ready to pass to php script with filtered symbols like ', " etc
  594. *
  595. * @param mixed $mixedInput - string/array which should be filtered
  596. * @return converted string / array
  597. */
  598. function bx_php_string_apos ($mixedInput) {
  599. return str_replace("'", "\\'", $mixedInput);
  600. }
  601. function bx_php_string_quot ($mixedInput) {
  602. return str_replace('"', '\\"', $mixedInput);
  603. }
  604. /**
  605. * Gets file contents by URL.
  606. *
  607. * @param string $sFileUrl - file URL to be read.
  608. * @param array $aParams - an array of parameters to be pathed with URL.
  609. * @return string the file's contents.
  610. */
  611. function bx_file_get_contents($sFileUrl, $aParams = array(), $bChangeTimeout = false) {
  612. if ($aParams)
  613. $sFileUrl = bx_append_url_params($sFileUrl, $aParams);
  614. $sResult = '';
  615. if(function_exists('curl_init')) {
  616. $rConnect = curl_init();
  617. curl_setopt($rConnect, CURLOPT_URL, $sFileUrl);
  618. curl_setopt($rConnect, CURLOPT_HEADER, 0);
  619. curl_setopt($rConnect, CURLOPT_RETURNTRANSFER, 1);
  620. curl_setopt($rConnect, CURLOPT_FOLLOWLOCATION, 1);
  621. if ($bChangeTimeout) {
  622. curl_setopt($rConnect, CURLOPT_CONNECTTIMEOUT, 3);
  623. curl_setopt($rConnect, CURLOPT_TIMEOUT, 3);
  624. }
  625. $sAllCookies = '';
  626. foreach($_COOKIE as $sKey=>$sValue){
  627. $sAllCookies .= $sKey."=".$sValue.";";
  628. }
  629. curl_setopt($rConnect, CURLOPT_COOKIE, $sAllCookies);
  630. $sResult = curl_exec($rConnect);
  631. curl_close($rConnect);
  632. } else {
  633. $iSaveTimeout = false;
  634. if ($bChangeTimeout) {
  635. $iSaveTimeout = ini_get('default_socket_timeout');
  636. ini_set('default_socket_timeout', 3);
  637. }
  638. $sResult = @file_get_contents($sFileUrl);
  639. if ($bChangeTimeout && false !== $iSaveTimeout) {
  640. ini_set('default_socket_timeout', $iSaveTimeout);
  641. }
  642. }
  643. return $sResult;
  644. }
  645. // calculation ini_get('upload_max_filesize') in bytes as example
  646. function return_bytes($val) {
  647. $val = trim($val);
  648. $last = strtolower($val{strlen($val)-1});
  649. $val = (int)$val;
  650. switch($last) {
  651. // The 'G' modifier is available since PHP 5.1.0
  652. case 'k':
  653. $val *= 1024;
  654. break;
  655. case 'm':
  656. $val *= 1024 * 1024;
  657. break;
  658. case 'g':
  659. $val *= 1024 * 1024 * 1024;
  660. break;
  661. }
  662. return $val;
  663. }
  664. // Generate Random Password
  665. function genRndPwd($iLength = 8, $bSpecialCharacters = true) {
  666. $sPassword = '';
  667. $sChars = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
  668. if($bSpecialCharacters === true)
  669. $sChars .= "!?=/&+,.";
  670. srand((double)microtime()*1000000);
  671. for($i = 0; $i < $iLength; $i++) {
  672. $x = mt_rand(0, strlen($sChars) -1);
  673. $sPassword .= $sChars{$x};
  674. }
  675. return $sPassword;
  676. }
  677. // Generate Random Salt for Password encryption
  678. function genRndSalt() {
  679. return genRndPwd(8, true);
  680. }
  681. // Encrypt User Password
  682. function encryptUserPwd($sPwd, $sSalt) {
  683. return sha1(md5($sPwd) . $sSalt);
  684. }
  685. function bx_get ($sName) {
  686. if (isset($_GET[$sName]))
  687. return $_GET[$sName];
  688. elseif (isset($_POST[$sName]))
  689. return $_POST[$sName];
  690. else
  691. return false;
  692. }
  693. function bx_encode_url_params ($a, $aExcludeKeys = array (), $aOnlyKeys = false) {
  694. $s = '';
  695. foreach ($a as $sKey => $sVal) {
  696. if (in_array($sKey, $aExcludeKeys))
  697. continue;
  698. if (false !== $aOnlyKeys && !in_array($sKey, $aOnlyKeys))
  699. continue;
  700. if (is_array($sVal)) {
  701. foreach ($sVal as $sSubVal) {
  702. $s .= rawurlencode($sKey) . '[]=' . rawurlencode(is_array($sSubVal) ? 'array' : $sSubVal) . '&';
  703. }
  704. } else {
  705. $s .= rawurlencode($sKey) . '=' . rawurlencode($sVal) . '&';
  706. }
  707. }
  708. return $s;
  709. }
  710. function bx_append_url_params ($sUrl, $mixedParams) {
  711. if (!$mixedParams)
  712. return $sUrl;
  713. $sParams = false == strpos($sUrl, '?') ? '?' : '&';
  714. if (is_array($mixedParams)) {
  715. foreach($mixedParams as $sKey => $sValue)
  716. $sParams .= $sKey . '=' . $sValue . '&';
  717. $sParams = substr($sParams, 0, -1);
  718. } else {
  719. $sParams .= $mixedParams;
  720. }
  721. return $sUrl . $sParams;
  722. }
  723. function bx_rrmdir($directory) {
  724. if (substr($directory,-1) == "/")
  725. $directory = substr($directory,0,-1);
  726. if (!file_exists($directory) || !is_dir($directory))
  727. return false;
  728. elseif (!is_readable($directory))
  729. return false;
  730. if (!($directoryHandle = opendir($directory)))
  731. return false;
  732. while ($contents = readdir($directoryHandle)) {
  733. if ($contents != '.' && $contents != '..') {
  734. $path = $directory . "/" . $contents;
  735. if (is_dir($path))
  736. bx_rrmdir($path);
  737. else
  738. unlink($path);
  739. }
  740. }
  741. closedir($directoryHandle);
  742. if (!rmdir($directory))
  743. return false;
  744. return true;
  745. }
  746. function bx_clear_folder ($sPath, $aExts = array ()) {
  747. if (substr($$sPath,-1) == "/")
  748. $sPath = substr($sPath,0,-1);
  749. if (!file_exists($sPath) || !is_dir($sPath))
  750. return false;
  751. elseif (!is_readable($sPath))
  752. return false;
  753. if (!($h = opendir($sPath)))
  754. return false;
  755. while ($sFile = readdir($h)) {
  756. if ('.' == $sFile || '..' == $sFile)
  757. continue;
  758. $sFullPath = $sPath . '/' . $sFile;
  759. if (is_dir($sFullPath))
  760. continue;
  761. if (!$aExts || (($sExt = pathinfo($sFullPath, PATHINFO_EXTENSION)) && in_array($sExt, $aExts)))
  762. @unlink($sFullPath);
  763. }
  764. closedir($h);
  765. return true;
  766. }
  767. function bx_ltrim_str ($sString, $sPrefix, $sReplace = '') {
  768. if ($sReplace && substr($sString, 0, strlen($sReplace)) == $sReplace)
  769. return $sString;
  770. if (substr($sString, 0, strlen($sPrefix)) == $sPrefix)
  771. return $sReplace . substr($sString, strlen($sPrefix));
  772. return $sString;
  773. }
  774. /**
  775. * Convert array to attributes string
  776. *
  777. * Example:
  778. * @code
  779. * $a = array('name' => 'test', 'value' => 5);
  780. * $s = bx_convert_array2attrs($a);
  781. * echo $s; // outputs: name="test" value="5"
  782. * @endcode
  783. *
  784. * @param $a - array of attributes
  785. * @param $sClasses - classes to merge with 'class' attribute
  786. * @param $sStyles - styles to merge with 'style' attribute
  787. * @return string
  788. */
  789. function bx_convert_array2attrs ($a, $sClasses = false, $sStyles = false) {
  790. $sRet = '';
  791. if (!$a || !is_array($a))
  792. $a = array();
  793. if ($sClasses) {
  794. $sClasses = trim($sClasses);
  795. $a['class'] = $sClasses . (!empty($a['class']) ? ' ' . $a['class'] : '');
  796. }
  797. if ($sStyles) {
  798. $sStyles = trim($sStyles);
  799. if (';' != $sStyles[strlen($sStyles)-1])
  800. $sStyles .= ';';
  801. $a['style'] = $sStyles . (!empty($a['style']) ? ' ' . $a['style'] : '');
  802. }
  803. foreach ($a as $sKey => $sValue) {
  804. if(is_null($sValue)) // pass NULL values
  805. continue;
  806. $sValueC = bx_html_attribute($sValue, BX_ESCAPE_STR_QUOTE);
  807. $sRet .= " $sKey=\"$sValueC\"";
  808. }
  809. return $sRet;
  810. }
  811. function bx_unicode_urldecode($s) {
  812. preg_match_all('/%u([[:alnum:]]{4})/', $s, $a);
  813. foreach ($a[1] as $uniord)
  814. {
  815. $dec = hexdec($uniord);
  816. $utf = '';
  817. if ($dec < 128)
  818. {
  819. $utf = chr($dec);
  820. }
  821. else if ($dec < 2048)
  822. {
  823. $utf = chr(192 + (($dec - ($dec % 64)) / 64));
  824. $utf .= chr(128 + ($dec % 64));
  825. }
  826. else
  827. {
  828. $utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
  829. $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
  830. $utf .= chr(128 + ($dec % 64));
  831. }
  832. $s = str_replace('%u'.$uniord, $utf, $s);
  833. }
  834. return urldecode($s);
  835. }
  836. /**
  837. * Raise an alert
  838. * @param string $sType - system type
  839. * @param string $sAction - system action
  840. * @param int $iObjectId - object id
  841. * @param int $iSenderId - sender (action's author) profile id, if it is false - then currectly logged in profile id is used
  842. */
  843. function bx_alert($sUnit, $sAction, $iObjectId, $iSender = false, $aExtras = array()) {
  844. $o = new BxDolAlerts($sUnit, $sAction, $iObjectId, $iSender, $aExtras);
  845. $o->alert();
  846. }
  847. function bx_replace_markers($mixed, $aMarkers) {
  848. if (empty($aMarkers))
  849. return $mixed;
  850. if (is_array($mixed)) {
  851. foreach ($mixed as $sKey => $sValue)
  852. $mixed[$sKey] = bx_replace_markers ($sValue, $aMarkers);
  853. } else {
  854. foreach ($aMarkers as $sKey => $sValue)
  855. $mixed = str_replace('{' . $sKey . '}', $sValue, $mixed);
  856. }
  857. return $mixed;
  858. }
  859. function bx_site_hash($sSalt = '', $isSkipVersion = false) {
  860. return md5($sSalt . ($isSkipVersion ? '' : getParam('sys_version')) . BX_DOL_SECRET . BX_DOL_URL_ROOT);
  861. }
  862. /**
  863. * Transform string to method name string, for example it changes 'some_method' string to 'SomeMethod' string
  864. * @param string where words are separated with underscore
  865. * @return string where every word begins with capital letter
  866. */
  867. function bx_gen_method_name ($s, $sWordsDelimiter = '_') {
  868. return str_replace(' ', '', ucwords(str_replace($sWordsDelimiter, ' ', $s)));
  869. }
  870. /**
  871. * Trigger user error
  872. * @param $sMsg message to display
  873. * @param $iNumLevelsBack add additional debug backtracing N levels back
  874. */
  875. function bx_trigger_error ($sMsg, $iNumLevelsBack = 0) {
  876. $a = debug_backtrace();
  877. $sMsgAdd = "<br />\n related code in <b>{$a[$iNumLevelsBack]['file']}</b> on line <b>{$a[$iNumLevelsBack]['line']}</b> <br />\n";
  878. trigger_error ($sMsg . $sMsgAdd, E_USER_ERROR);
  879. }
  880. /** @} */