utils.inc.php 36 KB

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