utils.inc.php 34 KB

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