utils.inc.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  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) {
  56. $sTail = '';
  57. $s = trim(strip_tags($sInput));
  58. if (mb_strlen($s) > $iMaxLen) {
  59. $s = mb_substr($s, 0, $iMaxLen);
  60. $sTail = '&#8230;';
  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 detect class path by its prefix or module array
  482. *
  483. * @param $sClassName - full class name or class postfix in a case of module class
  484. * @param $aModule - module array or true to get module array from global variable
  485. */
  486. function bx_import($sClassName, $aModule = array()) {
  487. if (class_exists($sClassName))
  488. return;
  489. if ($aModule) {
  490. $a = (true === $aModule) ? $GLOABLS['aModule'] : $aModule;
  491. if (class_exists($a['class_prefix'] . $sClassName))
  492. return;
  493. require_once (BX_DIRECTORY_PATH_MODULES . $a['path'] . 'classes/' . $a['class_prefix'] . $sClassName . '.php');
  494. }
  495. if (0 == strncmp($sClassName, 'BxDol', 5)) {
  496. if (0 == strncmp($sClassName, 'BxDolStudio', 11))
  497. require_once(BX_DOL_DIR_STUDIO_CLASSES . $sClassName . '.php');
  498. else
  499. require_once(BX_DIRECTORY_PATH_CLASSES . $sClassName . '.php');
  500. return;
  501. }
  502. if (0 == strncmp($sClassName, 'BxBase', 6)) {
  503. if(0 == strncmp($sClassName, 'BxBaseStudio', 12))
  504. require_once(BX_DOL_DIR_STUDIO_BASE . 'scripts/' . $sClassName . '.php');
  505. else
  506. require_once(BX_DIRECTORY_PATH_BASE . 'scripts/' . $sClassName . '.php');
  507. return;
  508. }
  509. if (0 == strncmp($sClassName, 'BxTempl', 7) && !class_exists($sClassName)) {
  510. if(0 == strncmp($sClassName, 'BxTemplStudio', 13)) {
  511. bx_import('BxDolStudioTemplate');
  512. $sPath = BX_DIRECTORY_PATH_MODULES . BxDolStudioTemplate::getInstance()->getPath() . 'data/template/studio/scripts/' . $sClassName . '.php';
  513. }
  514. else {
  515. bx_import('BxDolTemplate');
  516. $sPath = BX_DIRECTORY_PATH_MODULES . BxDolTemplate::getInstance()->getPath() . 'data/template/system/scripts/' . $sClassName . '.php';
  517. }
  518. if(file_exists($sPath)) {
  519. require_once($sPath);
  520. return;
  521. }
  522. echo "<b>Fatal error:</b> Class (" . $sClassName . ") not found.";
  523. exit;
  524. }
  525. }
  526. /**
  527. * Gets an instance of class pathing necessary parameters if it's necessary.
  528. *
  529. * @param string $sClassName class name.
  530. * @param array $aParams an array of parameters to be pathed to the constructor of the class.
  531. * @param array $aModule an array with module description. Is used when the requested class is located in some module.
  532. * @return unknown
  533. */
  534. function bx_instance($sClassName, $aParams = array(), $aModule = array()) {
  535. if(isset($GLOBALS['bxDolClasses'][$sClassName]))
  536. return $GLOBALS['bxDolClasses'][$sClassName];
  537. else {
  538. bx_import((empty($aModule) ? $sClassName : str_replace($aModule['class_prefix'], '', $sClassName)), $aModule);
  539. if(empty($aParams))
  540. $GLOBALS['bxDolClasses'][$sClassName] = new $sClassName();
  541. else {
  542. $sParams = "";
  543. foreach($aParams as $mixedKey => $mixedValue)
  544. $sParams .= "\$aParams[" . $mixedKey . "], ";
  545. $sParams = substr($sParams, 0, -2);
  546. $GLOBALS['bxDolClasses'][$sClassName] = eval("return new " . $sClassName . "(" . $sParams . ");"); // TODO: remake without eval
  547. }
  548. return $GLOBALS['bxDolClasses'][$sClassName];
  549. }
  550. }
  551. /**
  552. * Escapes string/array ready to pass to js script with filtered symbols like ', " etc
  553. *
  554. * @param $mixedInput - string/array which should be filtered
  555. * @param $iQuoteType - string escaping method: BX_ESCAPE_STR_AUTO(default), BX_ESCAPE_STR_APOS or BX_ESCAPE_STR_QUOTE
  556. * @return converted string / array
  557. */
  558. function bx_js_string ($mixedInput, $iQuoteType = BX_ESCAPE_STR_AUTO) {
  559. $aUnits = array(
  560. "\n" => "\\n",
  561. "\r" => "",
  562. );
  563. if (BX_ESCAPE_STR_APOS == $iQuoteType) {
  564. $aUnits["'"] = "\\'";
  565. $aUnits['<script'] = "<scr' + 'ipt";
  566. $aUnits['</script>'] = "</scr' + 'ipt>";
  567. } elseif (BX_ESCAPE_STR_QUOTE == $iQuoteType) {
  568. $aUnits['"'] = '\\"';
  569. $aUnits['<script'] = '<scr" + "ipt';
  570. $aUnits['</script>'] = '</scr" + "ipt>';
  571. } else {
  572. $aUnits['"'] = '&quote;';
  573. $aUnits["'"] = '&apos;';
  574. $aUnits["<"] = '&lt;';
  575. $aUnits[">"] = '&gt;';
  576. }
  577. return str_replace(array_keys($aUnits), array_values($aUnits), $mixedInput);
  578. }
  579. /**
  580. * Return input string/array ready to pass to html attribute with filtered symbols like ', " etc
  581. *
  582. * @param mixed $mixedInput - string/array which should be filtered
  583. * @return converted string / array
  584. */
  585. function bx_html_attribute ($mixedInput, $iQuoteType = BX_ESCAPE_STR_AUTO) {
  586. $aUnits = array ();
  587. if (BX_ESCAPE_STR_APOS == $iQuoteType)
  588. $aUnits["'"] = "\\'";
  589. elseif (BX_ESCAPE_STR_QUOTE == $iQuoteType)
  590. $aUnits['"'] = '\\"';
  591. else
  592. $aUnits = array("\"" => "&quot;", "'" => "&apos;");
  593. return str_replace(array_keys($aUnits), array_values($aUnits), $mixedInput);
  594. }
  595. /**
  596. * Escapes string/array ready to pass to php script with filtered symbols like ', " etc
  597. *
  598. * @param mixed $mixedInput - string/array which should be filtered
  599. * @return converted string / array
  600. */
  601. function bx_php_string_apos ($mixedInput) {
  602. return str_replace("'", "\\'", $mixedInput);
  603. }
  604. function bx_php_string_quot ($mixedInput) {
  605. return str_replace('"', '\\"', $mixedInput);
  606. }
  607. /**
  608. * Gets file contents by URL.
  609. *
  610. * @param string $sFileUrl - file URL to be read.
  611. * @param array $aParams - an array of parameters to be pathed with URL.
  612. * @return string the file's contents.
  613. */
  614. function bx_file_get_contents($sFileUrl, $aParams = array(), $bChangeTimeout = false) {
  615. if ($aParams)
  616. $sFileUrl = bx_append_url_params($sFileUrl, $aParams);
  617. $sResult = '';
  618. if(function_exists('curl_init')) {
  619. $rConnect = curl_init();
  620. curl_setopt($rConnect, CURLOPT_URL, $sFileUrl);
  621. curl_setopt($rConnect, CURLOPT_HEADER, 0);
  622. curl_setopt($rConnect, CURLOPT_RETURNTRANSFER, 1);
  623. curl_setopt($rConnect, CURLOPT_FOLLOWLOCATION, 1);
  624. if ($bChangeTimeout) {
  625. curl_setopt($rConnect, CURLOPT_CONNECTTIMEOUT, 3);
  626. curl_setopt($rConnect, CURLOPT_TIMEOUT, 3);
  627. }
  628. $sAllCookies = '';
  629. foreach($_COOKIE as $sKey=>$sValue){
  630. $sAllCookies .= $sKey."=".$sValue.";";
  631. }
  632. curl_setopt($rConnect, CURLOPT_COOKIE, $sAllCookies);
  633. $sResult = curl_exec($rConnect);
  634. curl_close($rConnect);
  635. } else {
  636. $iSaveTimeout = false;
  637. if ($bChangeTimeout) {
  638. $iSaveTimeout = ini_get('default_socket_timeout');
  639. ini_set('default_socket_timeout', 3);
  640. }
  641. $sResult = @file_get_contents($sFileUrl);
  642. if ($bChangeTimeout && false !== $iSaveTimeout) {
  643. ini_set('default_socket_timeout', $iSaveTimeout);
  644. }
  645. }
  646. return $sResult;
  647. }
  648. // calculation ini_get('upload_max_filesize') in bytes as example
  649. function return_bytes($val) {
  650. $val = trim($val);
  651. $last = strtolower($val{strlen($val)-1});
  652. $val = (int)$val;
  653. switch($last) {
  654. // The 'G' modifier is available since PHP 5.1.0
  655. case 'k':
  656. $val *= 1024;
  657. break;
  658. case 'm':
  659. $val *= 1024 * 1024;
  660. break;
  661. case 'g':
  662. $val *= 1024 * 1024 * 1024;
  663. break;
  664. }
  665. return $val;
  666. }
  667. // Generate Random Password
  668. function genRndPwd($iLength = 8, $bSpecialCharacters = true) {
  669. $sPassword = '';
  670. $sChars = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
  671. if($bSpecialCharacters === true)
  672. $sChars .= "!?=/&+,.";
  673. srand((double)microtime()*1000000);
  674. for($i = 0; $i < $iLength; $i++) {
  675. $x = mt_rand(0, strlen($sChars) -1);
  676. $sPassword .= $sChars{$x};
  677. }
  678. return $sPassword;
  679. }
  680. // Generate Random Salt for Password encryption
  681. function genRndSalt() {
  682. return genRndPwd(8, true);
  683. }
  684. // Encrypt User Password
  685. function encryptUserPwd($sPwd, $sSalt) {
  686. return sha1(md5($sPwd) . $sSalt);
  687. }
  688. function bx_get ($sName) {
  689. if (isset($_GET[$sName]))
  690. return $_GET[$sName];
  691. elseif (isset($_POST[$sName]))
  692. return $_POST[$sName];
  693. else
  694. return false;
  695. }
  696. function bx_encode_url_params ($a, $aExcludeKeys = array (), $aOnlyKeys = false) {
  697. $s = '';
  698. foreach ($a as $sKey => $sVal) {
  699. if (in_array($sKey, $aExcludeKeys))
  700. continue;
  701. if (false !== $aOnlyKeys && !in_array($sKey, $aOnlyKeys))
  702. continue;
  703. if (is_array($sVal)) {
  704. foreach ($sVal as $sSubVal) {
  705. $s .= rawurlencode($sKey) . '[]=' . rawurlencode(is_array($sSubVal) ? 'array' : $sSubVal) . '&';
  706. }
  707. } else {
  708. $s .= rawurlencode($sKey) . '=' . rawurlencode($sVal) . '&';
  709. }
  710. }
  711. return $s;
  712. }
  713. function bx_append_url_params ($sUrl, $mixedParams) {
  714. if (!$mixedParams)
  715. return $sUrl;
  716. $sParams = false == strpos($sUrl, '?') ? '?' : '&';
  717. if (is_array($mixedParams)) {
  718. foreach($mixedParams as $sKey => $sValue)
  719. $sParams .= $sKey . '=' . $sValue . '&';
  720. $sParams = substr($sParams, 0, -1);
  721. } else {
  722. $sParams .= $mixedParams;
  723. }
  724. return $sUrl . $sParams;
  725. }
  726. function bx_rrmdir($directory) {
  727. if (substr($directory,-1) == "/")
  728. $directory = substr($directory,0,-1);
  729. if (!file_exists($directory) || !is_dir($directory))
  730. return false;
  731. elseif (!is_readable($directory))
  732. return false;
  733. if (!($directoryHandle = opendir($directory)))
  734. return false;
  735. while ($contents = readdir($directoryHandle)) {
  736. if ($contents != '.' && $contents != '..') {
  737. $path = $directory . "/" . $contents;
  738. if (is_dir($path))
  739. bx_rrmdir($path);
  740. else
  741. unlink($path);
  742. }
  743. }
  744. closedir($directoryHandle);
  745. if (!rmdir($directory))
  746. return false;
  747. return true;
  748. }
  749. function bx_clear_folder ($sPath, $aExts = array ()) {
  750. if (substr($$sPath,-1) == "/")
  751. $sPath = substr($sPath,0,-1);
  752. if (!file_exists($sPath) || !is_dir($sPath))
  753. return false;
  754. elseif (!is_readable($sPath))
  755. return false;
  756. if (!($h = opendir($sPath)))
  757. return false;
  758. while ($sFile = readdir($h)) {
  759. if ('.' == $sFile || '..' == $sFile)
  760. continue;
  761. $sFullPath = $sPath . '/' . $sFile;
  762. if (is_dir($sFullPath))
  763. continue;
  764. if (!$aExts || (($sExt = pathinfo($sFullPath, PATHINFO_EXTENSION)) && in_array($sExt, $aExts)))
  765. @unlink($sFullPath);
  766. }
  767. closedir($h);
  768. return true;
  769. }
  770. function bx_ltrim_str ($sString, $sPrefix, $sReplace = '') {
  771. if ($sReplace && substr($sString, 0, strlen($sReplace)) == $sReplace)
  772. return $sString;
  773. if (substr($sString, 0, strlen($sPrefix)) == $sPrefix)
  774. return $sReplace . substr($sString, strlen($sPrefix));
  775. return $sString;
  776. }
  777. /**
  778. * Convert array to attributes string
  779. *
  780. * Example:
  781. * @code
  782. * $a = array('name' => 'test', 'value' => 5);
  783. * $s = bx_convert_array2attrs($a);
  784. * echo $s; // outputs: name="test" value="5"
  785. * @endcode
  786. *
  787. * @param $a - array of attributes
  788. * @param $sClasses - classes to merge with 'class' attribute
  789. * @param $sStyles - styles to merge with 'style' attribute
  790. * @return string
  791. */
  792. function bx_convert_array2attrs ($a, $sClasses = false, $sStyles = false) {
  793. $sRet = '';
  794. if (!$a || !is_array($a))
  795. $a = array();
  796. if ($sClasses) {
  797. $sClasses = trim($sClasses);
  798. $a['class'] = $sClasses . (!empty($a['class']) ? ' ' . $a['class'] : '');
  799. }
  800. if ($sStyles) {
  801. $sStyles = trim($sStyles);
  802. if (';' != $sStyles[strlen($sStyles)-1])
  803. $sStyles .= ';';
  804. $a['style'] = $sStyles . (!empty($a['style']) ? ' ' . $a['style'] : '');
  805. }
  806. foreach ($a as $sKey => $sValue) {
  807. if(is_null($sValue)) // pass NULL values
  808. continue;
  809. $sValueC = bx_html_attribute($sValue, BX_ESCAPE_STR_QUOTE);
  810. $sRet .= " $sKey=\"$sValueC\"";
  811. }
  812. return $sRet;
  813. }
  814. function bx_unicode_urldecode($s) {
  815. preg_match_all('/%u([[:alnum:]]{4})/', $s, $a);
  816. foreach ($a[1] as $uniord)
  817. {
  818. $dec = hexdec($uniord);
  819. $utf = '';
  820. if ($dec < 128)
  821. {
  822. $utf = chr($dec);
  823. }
  824. else if ($dec < 2048)
  825. {
  826. $utf = chr(192 + (($dec - ($dec % 64)) / 64));
  827. $utf .= chr(128 + ($dec % 64));
  828. }
  829. else
  830. {
  831. $utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
  832. $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
  833. $utf .= chr(128 + ($dec % 64));
  834. }
  835. $s = str_replace('%u'.$uniord, $utf, $s);
  836. }
  837. return urldecode($s);
  838. }
  839. /**
  840. * Raise an alert
  841. * @param string $sType - system type
  842. * @param string $sAction - system action
  843. * @param int $iObjectId - object id
  844. * @param int $iSenderId - sender (action's author) profile id, if it is false - then currectly logged in profile id is used
  845. */
  846. function bx_alert($sUnit, $sAction, $iObjectId, $iSender = false, $aExtras = array()) {
  847. $o = new BxDolAlerts($sUnit, $sAction, $iObjectId, $iSender, $aExtras);
  848. $o->alert();
  849. }
  850. function bx_replace_markers($mixed, $aMarkers) {
  851. if (empty($aMarkers))
  852. return $mixed;
  853. if (is_array($mixed)) {
  854. foreach ($mixed as $sKey => $sValue)
  855. $mixed[$sKey] = bx_replace_markers ($sValue, $aMarkers);
  856. } else {
  857. foreach ($aMarkers as $sKey => $sValue)
  858. $mixed = str_replace('{' . $sKey . '}', $sValue, $mixed);
  859. }
  860. return $mixed;
  861. }
  862. function bx_site_hash($sSalt = '', $isSkipVersion = false) {
  863. return md5($sSalt . ($isSkipVersion ? '' : getParam('sys_version')) . BX_DOL_SECRET . BX_DOL_URL_ROOT);
  864. }
  865. /**
  866. * Transform string to method name string, for example it changes 'some_method' string to 'SomeMethod' string
  867. * @param string where words are separated with underscore
  868. * @return string where every word begins with capital letter
  869. */
  870. function bx_gen_method_name ($s, $sWordsDelimiter = '_') {
  871. return str_replace(' ', '', ucwords(str_replace($sWordsDelimiter, ' ', $s)));
  872. }
  873. /** @} */