utils.inc.php 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187
  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:s", $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']))) {
  357. $ip = $_SERVER['REMOTE_ADDR'];
  358. }
  359. }
  360. return $ip;
  361. }
  362. function genFlag( $country ) {
  363. return '<img src="' . genFlagUrl($country) . '" />';
  364. }
  365. function genFlagUrl($country) {
  366. bx_import('BxDolTemplate');
  367. return BxDolTemplate::getInstance()->getIconUrl('sys_fl_' . strtolower($country) . '.gif');
  368. }
  369. // print debug information ( e.g. arrays )
  370. function echoDbg( $what, $desc = '' ) {
  371. if ( $desc )
  372. echo "<b>$desc:</b> ";
  373. echo "<pre>";
  374. print_r( $what );
  375. echo "</pre>\n";
  376. }
  377. function echoDbgLog($mWhat, $sDesc = '', $sFileName = 'debug.log') {
  378. $sCont =
  379. '--- ' . date('r') . ' (' . BX_DOL_START_TIME . ") ---\n" .
  380. $sDesc . "\n" .
  381. print_r($mWhat, true) . "\n\n\n";
  382. $rFile = fopen(BxDolConfig::getInstance()->get('path_dynamic', 'tmp') . $sFileName, 'a');
  383. fwrite($rFile, $sCont);
  384. fclose($rFile);
  385. }
  386. function clear_xss($val) {
  387. if ($GLOBALS['logged']['admin'])
  388. return $val;
  389. // HTML Purifier plugin
  390. global $oHtmlPurifier;
  391. require_once( BX_DIRECTORY_PATH_PLUGINS . 'htmlpurifier/HTMLPurifier.standalone.php' );
  392. if (!isset($oHtmlPurifier)) {
  393. HTMLPurifier_Bootstrap::registerAutoload();
  394. $oConfig = HTMLPurifier_Config::createDefault();
  395. $oConfig->set('Cache.SerializerPath', rtrim(BX_DIRECTORY_PATH_CACHE, '/'));
  396. $oConfig->set('HTML.SafeObject', 'true');
  397. $oConfig->set('Output.FlashCompat', 'true');
  398. $oConfig->set('HTML.FlashAllowFullScreen', 'true');
  399. $oConfig->set('Filter.Custom', array (new HTMLPurifier_Filter_YouTube(), new HTMLPurifier_Filter_YoutubeIframe()));
  400. $oDef = $oConfig->getHTMLDefinition(true);
  401. $oDef->addAttribute('a', 'target', 'Enum#_blank,_self,_target,_top');
  402. $oHtmlPurifier = new HTMLPurifier($oConfig);
  403. }
  404. return $oHtmlPurifier->purify($val);
  405. }
  406. //--------------------------------------- friendly permalinks --------------------------------------//
  407. //------------------------------------------- main functions ---------------------------------------//
  408. function uriGenerate ($s, $sTable, $sField, $sEmpty = '-') {
  409. $s = uriFilter($s, $sEmpty);
  410. if(uriCheckUniq($s, $sTable, $sField))
  411. return $s;
  412. // cut off redundant part
  413. if(get_mb_len($s) > 240)
  414. $s = get_mb_substr($s, 0, 240);
  415. // try to add date
  416. $s .= '-' . date('Y-m-d');
  417. if(uriCheckUniq($s, $sTable, $sField))
  418. return $s;
  419. // try to add number
  420. for($i = 0 ; $i < 999 ; ++$i)
  421. if(uriCheckUniq($s . '-' . $i, $sTable, $sField))
  422. return ($s . '-' . $i);
  423. return rand(0, 999999999);
  424. }
  425. function uriFilter ($s, $sEmpty = '-') {
  426. bx_import('BxTemplConfig');
  427. if (BxTemplConfig::getInstance()->bAllowUnicodeInPreg)
  428. $s = get_mb_replace ('/[^\pL^\pN]+/u', '-', $s); // unicode characters
  429. else
  430. $s = get_mb_replace ('/([^\d^\w]+)/u', '-', $s); // latin characters only
  431. $s = get_mb_replace ('/([-^]+)/', '-', $s);
  432. $s = get_mb_replace ('/([-]+)$/', '', $s); // remove trailing dash
  433. if (!$s) $s = '-';
  434. return $s;
  435. }
  436. function uriCheckUniq ($s, $sTable, $sField) {
  437. bx_import('BxDolDb');
  438. $oDb = BxDolDb::getInstance();
  439. $sSql = $oDb->prepare("SELECT 1 FROM `$sTable` WHERE `$sField`=? LIMIT 1", $s);
  440. return !$oDb->query($sSql);
  441. }
  442. function get_mb_replace ($sPattern, $sReplace, $s) {
  443. return preg_replace ($sPattern, $sReplace, $s);
  444. }
  445. function get_mb_len ($s) {
  446. return (function_exists('mb_strlen')) ? mb_strlen($s) : strlen($s);
  447. }
  448. function get_mb_substr ($s, $iStart, $iLen) {
  449. return (function_exists('mb_substr')) ? mb_substr ($s, $iStart, $iLen) : substr ($s, $iStart, $iLen);
  450. }
  451. function bx_mb_substr_replace($s, $sReplace, $iPosStart, $iLength) {
  452. return mb_substr($s, 0, $iPosStart) . $sReplace . mb_substr($s, $iPosStart + $iLength);
  453. }
  454. function bx_mb_strpos ($s, $sReplacement, $iStart = 0) {
  455. return mb_strpos($s, $sReplacement, $iStart);
  456. }
  457. /**
  458. * Block user IP
  459. *
  460. * @param $sIP mixed
  461. * @param $iExpirationInSec integer
  462. * @param $sComment string
  463. * @return void
  464. */
  465. function bx_block_ip($mixedIP, $iExpirationInSec = 86400, $sComment = '') {
  466. if (preg_match('/^[0-9]+$/', $mixedIP))
  467. $iIP = $mixedIP;
  468. else
  469. $iIP = sprintf("%u", ip2long($sIP));
  470. $iExpirationInSec = time() + (int)$iExpirationInSec;
  471. $oDb = BxDolDb::getInstance();
  472. $sQuery = $oDb->prepare("SELECT ID FROM `sys_ip_list` WHERE `From` = ? AND `To` = ? LIMIT 1", $iIP, $iIP);
  473. if (!$oDb->getOne($sQuery)) {
  474. $sQuery = $oDb->prepare("INSERT INTO `sys_ip_list` SET `From` = ?, `To` = ?, `Type` = 'deny', `LastDT` = ?, `Desc` = ?", $iIP, $iIP, $iExpirationInSec, $sComment);
  475. return $oDb->res($sQuery);
  476. }
  477. return false;
  478. }
  479. function bx_is_ip_dns_blacklisted($sCurIP = '', $sType = '') {
  480. if (defined('BX_DOL_CRON_EXECUTE'))
  481. return false;
  482. if (!$sCurIP)
  483. $sCurIP = getVisitorIP();
  484. if (bx_is_ip_whitelisted($sCurIP))
  485. return false;
  486. $o = bx_instance('BxDolDNSBlacklists');
  487. if (BX_DOL_DNSBL_POSITIVE == $o->dnsbl_lookup_ip(BX_DOL_DNSBL_CHAIN_SPAMMERS, $sCurIP) && BX_DOL_DNSBL_POSITIVE != $o->dnsbl_lookup_ip(BX_DOL_DNSBL_CHAIN_WHITELIST, $sCurIP))
  488. {
  489. $o->onPositiveDetection ($sCurIP, $sType);
  490. return true;
  491. }
  492. return false;
  493. }
  494. function bx_is_ip_whitelisted($sCurIP = '') {
  495. if (defined('BX_DOL_CRON_EXECUTE'))
  496. return true;
  497. $iIPGlobalType = (int)getParam('ipListGlobalType');
  498. if ($iIPGlobalType != 1 && $iIPGlobalType != 2) // 0 - disabled
  499. return false;
  500. if (!$sCurIP)
  501. $sCurIP = getVisitorIP();
  502. $iCurIP = sprintf("%u", ip2long($sCurIP));
  503. $iCurrTume = time();
  504. return db_value("SELECT `ID` FROM `sys_ip_list` WHERE `Type` = 'allow' AND `LastDT` > $iCurrTume AND `From` <= '$iCurIP' AND `To` >= '$iCurIP' LIMIT 1") ? true : false;
  505. }
  506. function bx_is_ip_blocked($sCurIP = '') {
  507. if (defined('BX_DOL_CRON_EXECUTE'))
  508. return false;
  509. $iIPGlobalType = (int)getParam('ipListGlobalType');
  510. if ($iIPGlobalType != 1 && $iIPGlobalType != 2) // 0 - disabled
  511. return false;
  512. if (!$sCurIP)
  513. $sCurIP = getVisitorIP();
  514. $iCurIP = sprintf("%u", ip2long($sCurIP));
  515. $iCurrTume = time();
  516. if (bx_is_ip_whitelisted($sCurIP))
  517. return false;
  518. $isBlocked = db_value("SELECT `ID` FROM `sys_ip_list` WHERE `Type` = 'deny' AND `LastDT` > $iCurrTume AND `From` <= '$iCurIP' AND `To` >= '$iCurIP' LIMIT 1");
  519. if ($isBlocked)
  520. return true;
  521. // 1 - all allowed except listed
  522. // 2 - all blocked except listed
  523. return $iIPGlobalType == 2 ? true : false;
  524. }
  525. /**
  526. * spam checking function
  527. * @param $s content to check for spam
  528. * @param $isStripSlashes slashes parameter:
  529. * BX_SLASHES_AUTO - automatically detect magic_quotes_gpc setting
  530. * BX_SLASHES_NO_ACTION - do not perform any action with slashes
  531. * @return true if spam detected
  532. */
  533. function bx_is_spam ($val, $isStripSlashes = BX_SLASHES_AUTO) {
  534. if (defined('BX_DOL_CRON_EXECUTE'))
  535. return false;
  536. if (isAdmin())
  537. return false;
  538. if (bx_is_ip_whitelisted())
  539. return false;
  540. if (get_magic_quotes_gpc() && $isStripSlashes == BX_SLASHES_AUTO)
  541. $val = stripslashes($val);
  542. $bRet = false;
  543. if ('on' == getParam('sys_uridnsbl_enable')) {
  544. $oBxDolDNSURIBlacklists = bx_instance('BxDolDNSURIBlacklists');
  545. if ($oBxDolDNSURIBlacklists->isSpam($val)) {
  546. $oBxDolDNSURIBlacklists->onPositiveDetection($val);
  547. $bRet = true;
  548. }
  549. }
  550. if ('on' == getParam('sys_akismet_enable')) {
  551. $oBxDolAkismet = bx_instance('BxDolAkismet');
  552. if ($oBxDolAkismet->isSpam($val)) {
  553. $oBxDolAkismet->onPositiveDetection($val);
  554. $bRet = true;
  555. }
  556. }
  557. if ($bRet && 'on' == getParam('sys_antispam_report')) {
  558. $iProfileId = getLoggedId();
  559. $aPlus = array(
  560. 'SpammerUrl' => getProfileLink($iProfileId),
  561. 'SpammerNickName' => getNickName($iProfileId),
  562. 'Page' => htmlspecialchars_adv($_SERVER['PHP_SELF']),
  563. 'Get' => print_r($_GET, true),
  564. 'SpamContent' => htmlspecialchars_adv($val),
  565. );
  566. bx_import('BxDolEmailTemplates');
  567. $aTemplate = BxDolEmailTemplates::getInstance()->parseTemplate('t_SpamReportAuto', $aPlus);
  568. if (!$aTemplate)
  569. trigger_error('Email template or translation missing: t_SpamReportAuto', E_USER_ERROR);
  570. sendMail(getParam('site_email'), $aTemplate['Subject'], $aTemplate['Body']);
  571. }
  572. if ($bRet && 'on' == getParam('sys_antispam_block'))
  573. return true;
  574. return false;
  575. }
  576. /**
  577. ** @description : function will create cache file with all SQL queries ;
  578. ** @return :
  579. */
  580. function genSiteStatCache() {
  581. $sqlQuery = "SELECT `Name` as `name`,
  582. `Title` as `capt`,
  583. `UserQuery` as `query`,
  584. `UserLink` as `link`,
  585. `IconName` as `icon`,
  586. `AdminQuery` as `adm_query`,
  587. `AdminLink` as `adm_link`
  588. FROM `sys_stat_site`
  589. ORDER BY `StatOrder` ASC, `ID` ASC";
  590. $rData = db_res($sqlQuery);
  591. $sLine = "return array( \n";
  592. while ($aVal = mysql_fetch_assoc($rData)) {
  593. $sLine .= genSiteStatFile($aVal);
  594. }
  595. $sLine = rtrim($sLine, ",\n")."\n);";
  596. $aResult = eval($sLine);
  597. $oCache = BxDolDb::getInstance()->getDbCacheObject();
  598. return $oCache->setData (BxDolDb::getInstance()->genDbCacheKey('sys_stat_site'), $aResult);
  599. }
  600. /**
  601. * import class file, it detect class path by its prefix or module array
  602. *
  603. * @param $sClassName - full class name or class postfix in a case of module class
  604. * @param $aModule - module array or true to get module array from global variable
  605. */
  606. function bx_import($sClassName, $aModule = array()) {
  607. if (class_exists($sClassName))
  608. return;
  609. if ($aModule) {
  610. $a = (true === $aModule) ? $GLOABLS['aModule'] : $aModule;
  611. if (class_exists($a['class_prefix'] . $sClassName))
  612. return;
  613. require_once (BX_DIRECTORY_PATH_MODULES . $a['path'] . 'classes/' . $a['class_prefix'] . $sClassName . '.php');
  614. }
  615. if (0 == strncmp($sClassName, 'BxDol', 5)) {
  616. if (0 == strncmp($sClassName, 'BxDolStudio', 11))
  617. require_once(BX_DOL_DIR_STUDIO_CLASSES . $sClassName . '.php');
  618. else
  619. require_once(BX_DIRECTORY_PATH_CLASSES . $sClassName . '.php');
  620. return;
  621. }
  622. if (0 == strncmp($sClassName, 'BxBase', 6)) {
  623. if(0 == strncmp($sClassName, 'BxBaseStudio', 12))
  624. require_once(BX_DOL_DIR_STUDIO_BASE . 'scripts/' . $sClassName . '.php');
  625. else
  626. require_once(BX_DIRECTORY_PATH_BASE . 'scripts/' . $sClassName . '.php');
  627. return;
  628. }
  629. if (0 == strncmp($sClassName, 'BxTempl', 7) && !class_exists($sClassName)) {
  630. if(0 == strncmp($sClassName, 'BxTemplStudio', 13)) {
  631. bx_import('BxDolStudioTemplate');
  632. $sPath = BX_DIRECTORY_PATH_MODULES . BxDolStudioTemplate::getInstance()->getPath() . 'data/template/studio/scripts/' . $sClassName . '.php';
  633. }
  634. else {
  635. bx_import('BxDolTemplate');
  636. $sPath = BX_DIRECTORY_PATH_MODULES . BxDolTemplate::getInstance()->getPath() . 'data/template/system/scripts/' . $sClassName . '.php';
  637. }
  638. if(file_exists($sPath)) {
  639. require_once($sPath);
  640. return;
  641. }
  642. echo "<b>Fatal error:</b> Class (" . $sClassName . ") not found.";
  643. exit;
  644. }
  645. }
  646. /**
  647. * Gets an instance of class pathing necessary parameters if it's necessary.
  648. *
  649. * @param string $sClassName class name.
  650. * @param array $aParams an array of parameters to be pathed to the constructor of the class.
  651. * @param array $aModule an array with module description. Is used when the requested class is located in some module.
  652. * @return unknown
  653. */
  654. function bx_instance($sClassName, $aParams = array(), $aModule = array()) {
  655. if(isset($GLOBALS['bxDolClasses'][$sClassName]))
  656. return $GLOBALS['bxDolClasses'][$sClassName];
  657. else {
  658. bx_import((empty($aModule) ? $sClassName : str_replace($aModule['class_prefix'], '', $sClassName)), $aModule);
  659. if(empty($aParams))
  660. $GLOBALS['bxDolClasses'][$sClassName] = new $sClassName();
  661. else {
  662. $sParams = "";
  663. foreach($aParams as $mixedKey => $mixedValue)
  664. $sParams .= "\$aParams[" . $mixedKey . "], ";
  665. $sParams = substr($sParams, 0, -2);
  666. $GLOBALS['bxDolClasses'][$sClassName] = eval("return new " . $sClassName . "(" . $sParams . ");"); // TODO: remake without eval
  667. }
  668. return $GLOBALS['bxDolClasses'][$sClassName];
  669. }
  670. }
  671. /**
  672. * Escapes string/array ready to pass to js script with filtered symbols like ', " etc
  673. *
  674. * @param $mixedInput - string/array which should be filtered
  675. * @param $iQuoteType - string escaping method: BX_ESCAPE_STR_AUTO(default), BX_ESCAPE_STR_APOS or BX_ESCAPE_STR_QUOTE
  676. * @return converted string / array
  677. */
  678. function bx_js_string ($mixedInput, $iQuoteType = BX_ESCAPE_STR_AUTO) {
  679. $aUnits = array(
  680. "\n" => "\\n",
  681. "\r" => "",
  682. );
  683. if (BX_ESCAPE_STR_APOS == $iQuoteType) {
  684. $aUnits["'"] = "\\'";
  685. $aUnits['<script'] = "<scr' + 'ipt";
  686. $aUnits['</script>'] = "</scr' + 'ipt>";
  687. } elseif (BX_ESCAPE_STR_QUOTE == $iQuoteType) {
  688. $aUnits['"'] = '\\"';
  689. $aUnits['<script'] = '<scr" + "ipt';
  690. $aUnits['</script>'] = '</scr" + "ipt>';
  691. } else {
  692. $aUnits['"'] = '&quote;';
  693. $aUnits["'"] = '&apos;';
  694. $aUnits["<"] = '&lt;';
  695. $aUnits[">"] = '&gt;';
  696. }
  697. return str_replace(array_keys($aUnits), array_values($aUnits), $mixedInput);
  698. }
  699. /**
  700. * Return input string/array ready to pass to html attribute with filtered symbols like ', " etc
  701. *
  702. * @param mixed $mixedInput - string/array which should be filtered
  703. * @return converted string / array
  704. */
  705. function bx_html_attribute ($mixedInput, $iQuoteType = BX_ESCAPE_STR_AUTO) {
  706. $aUnits = array ();
  707. if (BX_ESCAPE_STR_APOS == $iQuoteType)
  708. $aUnits["'"] = "\\'";
  709. elseif (BX_ESCAPE_STR_QUOTE == $iQuoteType)
  710. $aUnits['"'] = '\\"';
  711. else
  712. $aUnits = array("\"" => "&quot;", "'" => "&apos;");
  713. return str_replace(array_keys($aUnits), array_values($aUnits), $mixedInput);
  714. }
  715. /**
  716. * Escapes string/array ready to pass to php script with filtered symbols like ', " etc
  717. *
  718. * @param mixed $mixedInput - string/array which should be filtered
  719. * @return converted string / array
  720. */
  721. function bx_php_string_apos ($mixedInput) {
  722. return str_replace("'", "\\'", $mixedInput);
  723. }
  724. function bx_php_string_quot ($mixedInput) {
  725. return str_replace('"', '\\"', $mixedInput);
  726. }
  727. /**
  728. * Gets file contents by URL.
  729. *
  730. * @param string $sFileUrl - file URL to be read.
  731. * @param array $aParams - an array of parameters to be pathed with URL.
  732. * @return string the file's contents.
  733. */
  734. function bx_file_get_contents($sFileUrl, $aParams = array(), $bChangeTimeout = false) {
  735. if ($aParams)
  736. $sFileUrl = bx_append_url_params($sFileUrl, $aParams);
  737. $sResult = '';
  738. if(function_exists('curl_init')) {
  739. $rConnect = curl_init();
  740. curl_setopt($rConnect, CURLOPT_URL, $sFileUrl);
  741. curl_setopt($rConnect, CURLOPT_HEADER, 0);
  742. curl_setopt($rConnect, CURLOPT_RETURNTRANSFER, 1);
  743. curl_setopt($rConnect, CURLOPT_FOLLOWLOCATION, 1);
  744. if ($bChangeTimeout) {
  745. curl_setopt($rConnect, CURLOPT_CONNECTTIMEOUT, 3);
  746. curl_setopt($rConnect, CURLOPT_TIMEOUT, 3);
  747. }
  748. $sAllCookies = '';
  749. foreach($_COOKIE as $sKey=>$sValue){
  750. $sAllCookies .= $sKey."=".$sValue.";";
  751. }
  752. curl_setopt($rConnect, CURLOPT_COOKIE, $sAllCookies);
  753. $sResult = curl_exec($rConnect);
  754. curl_close($rConnect);
  755. } else {
  756. $iSaveTimeout = false;
  757. if ($bChangeTimeout) {
  758. $iSaveTimeout = ini_get('default_socket_timeout');
  759. ini_set('default_socket_timeout', 3);
  760. }
  761. $sResult = @file_get_contents($sFileUrl);
  762. if ($bChangeTimeout && false !== $iSaveTimeout) {
  763. ini_set('default_socket_timeout', $iSaveTimeout);
  764. }
  765. }
  766. return $sResult;
  767. }
  768. // calculation ini_get('upload_max_filesize') in bytes as example
  769. function return_bytes($val) {
  770. $val = trim($val);
  771. $last = strtolower($val{strlen($val)-1});
  772. $val = (int)$val;
  773. switch($last) {
  774. // The 'G' modifier is available since PHP 5.1.0
  775. case 'k':
  776. $val *= 1024;
  777. break;
  778. case 'm':
  779. $val *= 1024 * 1024;
  780. break;
  781. case 'g':
  782. $val *= 1024 * 1024 * 1024;
  783. break;
  784. }
  785. return $val;
  786. }
  787. // Generate Random Password
  788. function genRndPwd($iLength = 8, $bSpecialCharacters = true) {
  789. $sPassword = '';
  790. $sChars = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
  791. if($bSpecialCharacters === true)
  792. $sChars .= "!?=/&+,.";
  793. srand((double)microtime()*1000000);
  794. for($i = 0; $i < $iLength; $i++) {
  795. $x = mt_rand(0, strlen($sChars) -1);
  796. $sPassword .= $sChars{$x};
  797. }
  798. return $sPassword;
  799. }
  800. // Generate Random Salt for Password encryption
  801. function genRndSalt() {
  802. return genRndPwd(8, true);
  803. }
  804. // Encrypt User Password
  805. function encryptUserPwd($sPwd, $sSalt) {
  806. return sha1(md5($sPwd) . $sSalt);
  807. }
  808. function bx_get ($sName) {
  809. if (isset($_GET[$sName]))
  810. return $_GET[$sName];
  811. elseif (isset($_POST[$sName]))
  812. return $_POST[$sName];
  813. else
  814. return false;
  815. }
  816. function bx_encode_url_params ($a, $aExcludeKeys = array (), $aOnlyKeys = false) {
  817. $s = '';
  818. foreach ($a as $sKey => $sVal) {
  819. if (in_array($sKey, $aExcludeKeys))
  820. continue;
  821. if (false !== $aOnlyKeys && !in_array($sKey, $aOnlyKeys))
  822. continue;
  823. if (is_array($sVal)) {
  824. foreach ($sVal as $sSubVal) {
  825. $s .= rawurlencode($sKey) . '[]=' . rawurlencode(is_array($sSubVal) ? 'array' : $sSubVal) . '&';
  826. }
  827. } else {
  828. $s .= rawurlencode($sKey) . '=' . rawurlencode($sVal) . '&';
  829. }
  830. }
  831. return $s;
  832. }
  833. function bx_append_url_params ($sUrl, $mixedParams) {
  834. if (!$mixedParams)
  835. return $sUrl;
  836. $sParams = false == strpos($sUrl, '?') ? '?' : '&';
  837. if (is_array($mixedParams)) {
  838. foreach($mixedParams as $sKey => $sValue)
  839. $sParams .= $sKey . '=' . $sValue . '&';
  840. $sParams = substr($sParams, 0, -1);
  841. } else {
  842. $sParams .= $mixedParams;
  843. }
  844. return $sUrl . $sParams;
  845. }
  846. function bx_rrmdir($directory) {
  847. if (substr($directory,-1) == "/")
  848. $directory = substr($directory,0,-1);
  849. if (!file_exists($directory) || !is_dir($directory))
  850. return false;
  851. elseif (!is_readable($directory))
  852. return false;
  853. if (!($directoryHandle = opendir($directory)))
  854. return false;
  855. while ($contents = readdir($directoryHandle)) {
  856. if ($contents != '.' && $contents != '..') {
  857. $path = $directory . "/" . $contents;
  858. if (is_dir($path))
  859. bx_rrmdir($path);
  860. else
  861. unlink($path);
  862. }
  863. }
  864. closedir($directoryHandle);
  865. if (!rmdir($directory))
  866. return false;
  867. return true;
  868. }
  869. function bx_clear_folder ($sPath, $aExts = array ()) {
  870. if (substr($$sPath,-1) == "/")
  871. $sPath = substr($sPath,0,-1);
  872. if (!file_exists($sPath) || !is_dir($sPath))
  873. return false;
  874. elseif (!is_readable($sPath))
  875. return false;
  876. if (!($h = opendir($sPath)))
  877. return false;
  878. while ($sFile = readdir($h)) {
  879. if ('.' == $sFile || '..' == $sFile)
  880. continue;
  881. $sFullPath = $sPath . '/' . $sFile;
  882. if (is_dir($sFullPath))
  883. continue;
  884. if (!$aExts || (($sExt = pathinfo($sFullPath, PATHINFO_EXTENSION)) && in_array($sExt, $aExts)))
  885. @unlink($sFullPath);
  886. }
  887. closedir($h);
  888. return true;
  889. }
  890. function bx_ltrim_str ($sString, $sPrefix, $sReplace = '') {
  891. if ($sReplace && substr($sString, 0, strlen($sReplace)) == $sReplace)
  892. return $sString;
  893. if (substr($sString, 0, strlen($sPrefix)) == $sPrefix)
  894. return $sReplace . substr($sString, strlen($sPrefix));
  895. return $sString;
  896. }
  897. /**
  898. * Convert array to attributes string
  899. *
  900. * Example:
  901. * @code
  902. * $a = array('name' => 'test', 'value' => 5);
  903. * $s = bx_convert_array2attrs($a);
  904. * echo $s; // outputs: name="test" value="5"
  905. * @endcode
  906. *
  907. * @param $a - array of attributes
  908. * @param $sClasses - classes to merge with 'class' attribute
  909. * @param $sStyles - styles to merge with 'style' attribute
  910. * @return string
  911. */
  912. function bx_convert_array2attrs ($a, $sClasses = false, $sStyles = false) {
  913. $sRet = '';
  914. if (!$a || !is_array($a))
  915. $a = array();
  916. if ($sClasses) {
  917. $sClasses = trim($sClasses);
  918. $a['class'] = $sClasses . (!empty($a['class']) ? ' ' . $a['class'] : '');
  919. }
  920. if ($sStyles) {
  921. $sStyles = trim($sStyles);
  922. if (';' != $sStyles[strlen($sStyles)-1])
  923. $sStyles .= ';';
  924. $a['style'] = $sStyles . (!empty($a['style']) ? ' ' . $a['style'] : '');
  925. }
  926. foreach ($a as $sKey => $sValue) {
  927. if(is_null($sValue)) // pass NULL values
  928. continue;
  929. $sValueC = bx_html_attribute($sValue, BX_ESCAPE_STR_QUOTE);
  930. $sRet .= " $sKey=\"$sValueC\"";
  931. }
  932. return $sRet;
  933. }
  934. function bx_unicode_urldecode($s) {
  935. preg_match_all('/%u([[:alnum:]]{4})/', $s, $a);
  936. foreach ($a[1] as $uniord)
  937. {
  938. $dec = hexdec($uniord);
  939. $utf = '';
  940. if ($dec < 128)
  941. {
  942. $utf = chr($dec);
  943. }
  944. else if ($dec < 2048)
  945. {
  946. $utf = chr(192 + (($dec - ($dec % 64)) / 64));
  947. $utf .= chr(128 + ($dec % 64));
  948. }
  949. else
  950. {
  951. $utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
  952. $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
  953. $utf .= chr(128 + ($dec % 64));
  954. }
  955. $s = str_replace('%u'.$uniord, $utf, $s);
  956. }
  957. return urldecode($s);
  958. }
  959. /**
  960. * Raise an alert
  961. * @param string $sType - system type
  962. * @param string $sAction - system action
  963. * @param int $iObjectId - object id
  964. * @param int $iSenderId - sender (action's author) profile id, if it is false - then currectly logged in profile id is used
  965. */
  966. function bx_alert($sUnit, $sAction, $iObjectId, $iSender = false, $aExtras = array()) {
  967. $o = new BxDolAlerts($sUnit, $sAction, $iObjectId, $iSender, $aExtras);
  968. $o->alert();
  969. }
  970. function bx_replace_markers($mixed, $aMarkers) {
  971. if (empty($aMarkers))
  972. return $mixed;
  973. if (is_array($mixed)) {
  974. foreach ($mixed as $sKey => $sValue)
  975. $mixed[$sKey] = bx_replace_markers ($sValue, $aMarkers);
  976. } else {
  977. foreach ($aMarkers as $sKey => $sValue)
  978. $mixed = str_replace('{' . $sKey . '}', $sValue, $mixed);
  979. }
  980. return $mixed;
  981. }
  982. function bx_site_hash($sSalt = '', $isSkipVersion = false) {
  983. return md5($sSalt . ($isSkipVersion ? '' : getParam('sys_version')) . BX_DOL_SECRET . BX_DOL_URL_ROOT);
  984. }
  985. /** @} */