utils.inc.php 35 KB

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