1
0

utils.inc.php 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498
  1. <?php defined('BX_DOL') 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_DOL_LOCALE_TIME', 2);
  10. define('BX_DOL_LOCALE_DATE_SHORT', 4);
  11. define('BX_DOL_LOCALE_DATE', 5);
  12. define('BX_DOL_LOCALE_PHP', 1);
  13. define('BX_DOL_LOCALE_DB', 2);
  14. define('BX_DATA_TEXT', 1); ///< regular text data type
  15. define('BX_DATA_TEXT_MULTILINE', 2); ///< regular multiline text data type
  16. define('BX_DATA_INT', 3); ///< integer data type
  17. define('BX_DATA_FLOAT', 4); ///< float data type
  18. define('BX_DATA_CHECKBOX', 5); ///< checkbox data type, 'on' or empty value
  19. define('BX_DATA_HTML', 6); ///< HTML data type
  20. define('BX_DATA_DATE', 7); ///< date data type stored as yyyy-mm-dd
  21. define('BX_DATA_DATE_TS', 8); ///< date data type stored as unixtimestamp
  22. define('BX_DATA_DATETIME_TS', 9); ///< date/time data type stored as unixtimestamp
  23. define('BX_SLASHES_AUTO', 0);
  24. define('BX_SLASHES_ADD', 1);
  25. define('BX_SLASHES_STRIP', 2);
  26. define('BX_SLASHES_NO_ACTION', 3);
  27. 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
  28. 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
  29. 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
  30. define('BX_EMAIL_SYSTEM', 0); ///< system email without unsubscribe link, like forgot password or email verification
  31. define('BX_EMAIL_NOTIFY', 1); ///< notification message, with unsubscribe link
  32. define('BX_EMAIL_MASS', 2); ///< mass email, one mesage send to manu users, with unsubscribe link
  33. /**
  34. * The following two functions are needed to convert title to uri and back.
  35. * It usefull when titles are used in URLs, like in Categories and Tags.
  36. */
  37. function title2uri($sValue) {
  38. return str_replace(
  39. array('&', '/', '\\', '"', '+'),
  40. array('[and]', '[slash]', '[backslash]', '[quote]', '[plus]'),
  41. $sValue
  42. );
  43. }
  44. function uri2title($sValue) {
  45. return str_replace(
  46. array('[and]', '[slash]', '[backslash]', '[quote]', '[plus]'),
  47. array('&', '/', '\\', '"', '+'),
  48. $sValue
  49. );
  50. }
  51. /**
  52. * Convert date(timestamp) in accordance with requested format code.
  53. *
  54. * @param string $sTimestamp - timestamp
  55. * @param integer $iCode - format code
  56. * 1(4) - short date format. @see sys_options -> short_date_format_php
  57. * 2 - time format. @see sys_options -> time_format_php
  58. * 3(5) - long date format. @see sys_options -> date_format_php
  59. * 6 - RFC 2822 date format.
  60. */
  61. function getLocaleDate($sTimestamp = '', $iCode = BX_DOL_LOCALE_DATE_SHORT) {
  62. $sFormat = (int)$iCode == 6 ? 'r' : getLocaleFormat($iCode);
  63. return date($sFormat, $sTimestamp);
  64. }
  65. /**
  66. * Get data format in accordance with requested format code and format type.
  67. *
  68. * @param integer $iCode - format code
  69. * 1(4) - short date format. @see sys_options -> short_date_format_php
  70. * 2 - time format. @see sys_options -> time_format_php
  71. * 3(5) - long date format. @see sys_options -> date_format_php
  72. * 6 - RFC 2822 date format.
  73. * @param integer $iType - format type
  74. * 1 - for PHP code.
  75. * 2 - for database.
  76. */
  77. function getLocaleFormat($iCode = BX_DOL_LOCALE_DATE_SHORT, $iType = BX_DOL_LOCALE_PHP) {
  78. $sPostfix = (int)$iType == BX_DOL_LOCALE_PHP ? '_php' : '';
  79. $sResult = '';
  80. switch ($iCode) {
  81. case 2:
  82. $sResult = getParam('time_format' . $sPostfix);
  83. break;
  84. case 1:
  85. case 4:
  86. $sResult = getParam('short_date_format' . $sPostfix);
  87. break;
  88. case 3:
  89. case 5:
  90. $sResult = getParam('date_format' . $sPostfix);
  91. break;
  92. }
  93. return $sResult;
  94. }
  95. /*
  96. * functions for limiting maximal word length
  97. */
  98. function strmaxwordlen($input, $len = 100) {
  99. return $input;
  100. }
  101. /*
  102. * functions for limiting maximal text length
  103. */
  104. function strmaxtextlen($sInput, $iMaxLen = 60) {
  105. $sTail = '';
  106. $s = trim(strip_tags($sInput));
  107. if (mb_strlen($s) > $iMaxLen) {
  108. $s = mb_substr($s, 0, $iMaxLen);
  109. $sTail = '&#8230;';
  110. }
  111. return htmlspecialchars_adv($s) . $sTail;
  112. }
  113. function html2txt($content, $tags = "") {
  114. while($content != strip_tags($content, $tags)) {
  115. $content = strip_tags($content, $tags);
  116. }
  117. return $content;
  118. }
  119. function html_encode($text) {
  120. $searcharray = array(
  121. "'([-_\w\d.]+@[-_\w\d.]+)'",
  122. "'((?:(?!://).{3}|^.{0,2}))(www\.[-\d\w\.\/]+)'",
  123. "'(http[s]?:\/\/[-_~\w\d\.\/]+)'");
  124. $replacearray = array(
  125. "<a href=\"mailto:\\1\">\\1</a>",
  126. "\\1http://\\2",
  127. "<a href=\"\\1\" target=_blank>\\1</a>");
  128. return preg_replace($searcharray, $replacearray, stripslashes($text));
  129. }
  130. /**
  131. * Functions to process user input.
  132. * DON'T use to process data before passing to SQL query - use db prepare instead @see BxDolDb::prepare.
  133. * It is ok to use bx_process_input and then db prepare.
  134. * @param $mixedData data to process
  135. * @param $iDataType how to handle data, possible valies:
  136. * BX_DATA_INT - integer value
  137. * BX_DATA_FLOAT - float values
  138. * BX_DATA_CHECKBOX - 'on' or empty string
  139. * BX_DATA_TEXT - text data, single line (default)
  140. * BX_DATA_TEXT_MULTILINE - text data, multiple lines
  141. * BX_DATA_HTML - HTML data
  142. * BX_DATA_DATE - date data type stored as yyyy-mm-dd
  143. * BX_DATA_DATE_TS' - date data type stored as unixtimestamp
  144. * BX_DATA_DATETIME_TS - date/time data type stored as unixtimestamp
  145. * @param $mixedParams optional parameters to pass for validation
  146. * @return the filtered data, or FALSE if the filter fails.
  147. */
  148. function bx_process_input ($mixedData, $iDataType = BX_DATA_TEXT, $mixedParams = false, $isCheckMagicQuotes = true) {
  149. if (is_array($mixedData)) {
  150. foreach ($mixedData as $k => $v)
  151. $mixedData[$k] = bx_process_input($v, $iDataType, $mixedParams);
  152. return $mixedData;
  153. }
  154. if (get_magic_quotes_gpc() && $isCheckMagicQuotes)
  155. $mixedData = stripslashes($mixedData);
  156. switch ($iDataType) {
  157. case BX_DATA_INT:
  158. return filter_var(trim($mixedData), FILTER_VALIDATE_INT);
  159. case BX_DATA_FLOAT:
  160. return filter_var(trim($mixedData), FILTER_VALIDATE_FLOAT);
  161. case BX_DATA_CHECKBOX:
  162. return 'on' == trim($mixedData) ? 'on' : '';
  163. case BX_DATA_DATE:
  164. // maybe consider using strtotime
  165. $mixedData = trim($mixedData);
  166. if (!preg_match('/^\d{4}-\d{1,2}-\d{1,2}$/', $mixedData))
  167. return false;
  168. list($iYear, $iMonth, $iDay) = explode('-', $mixedData); // 1985-10-28
  169. $iDay = intval($iDay);
  170. $iMonth = intval($iMonth);
  171. $iYear = intval($iYear);
  172. return sprintf("%04d-%02d-%02d", $iYear, $iMonth, $iDay);
  173. case BX_DATA_DATE_TS:
  174. $mixedData = trim($mixedData);
  175. if (!preg_match('/^\d{4}-\d{1,2}-\d{1,2}$/', $mixedData))
  176. return false;
  177. list($iYear, $iMonth, $iDay) = explode('-', $mixedData);
  178. $iDay = intval($iDay);
  179. $iMonth = intval($iMonth);
  180. $iYear = intval($iYear);
  181. $iRet = mktime (0, 0, 0, $iMonth, $iDay, $iYear);
  182. return $iRet > 0 ? $iRet : false;
  183. case BX_DATA_DATETIME_TS:
  184. if (!preg_match('#(\d+)\-(\d+)\-(\d+)[\sT]{1}(\d+):(\d+):(\d+)#', $mixedData, $m) && !preg_match('#(\d+)\-(\d+)\-(\d+)[\sT]{1}(\d+):(\d+)#', $mixedData, $m))
  185. return bx_process_input ($mixedData, BX_DATA_DATE_TS, $mixedParams, $isCheckMagicQuotes);
  186. $iDay = $m[3];
  187. $iMonth = $m[2];
  188. $iYear = $m[1];
  189. $iH = $m[4];
  190. $iM = $m[5];
  191. $iS = isset($m[6]) ? $m[6] : 0;
  192. $iRet = mktime ($iH, $iM, $iS, $iMonth, $iDay, $iYear);
  193. return $iRet > 0 ? $iRet : false;
  194. case BX_DATA_HTML:
  195. return clear_xss($mixedData);
  196. case BX_DATA_TEXT_MULTILINE:
  197. return nl2br(strip_tags($mixedData));
  198. case BX_DATA_TEXT:
  199. default:
  200. return $mixedData;
  201. }
  202. }
  203. /*
  204. * Functions to process user output.
  205. * Always use this function before output data which was entered by user before.
  206. * @param $mixedData string to process
  207. * @param $iDataType how to handle data, possible valies the same as in bx_process_input function, see bx_process_input.
  208. * @param $mixedParams optional parameters to pass for validation
  209. * @return the filtered data, or FALSE if the filter fails.
  210. */
  211. function bx_process_output ($mixedData, $iDataType = BX_DATA_TEXT, $mixedParams = false) {
  212. if (is_array($mixedData)) {
  213. foreach ($mixedData as $k => $v)
  214. $mixedData[$k] = bx_process_output($v, $iDataType, $mixedParams);
  215. return $mixedData;
  216. }
  217. switch ($iDataType) {
  218. case BX_DATA_INT:
  219. return filter_var($mixedData, FILTER_VALIDATE_INT);
  220. case BX_DATA_FLOAT:
  221. return filter_var($mixedData, FILTER_VALIDATE_FLOAT);
  222. case BX_DATA_CHECKBOX:
  223. return 'on' == trim($mixedData) ? 'on' : '';
  224. case BX_DATA_DATE:
  225. return $mixedData;
  226. case BX_DATA_DATE_TS:
  227. return empty($mixedData) ? '' : date("Y-m-d", $mixedData);
  228. case BX_DATA_DATETIME_TS:
  229. return empty($mixedData) ? '' : date("Y-m-d H:i:s", $mixedData);
  230. case BX_DATA_HTML:
  231. return $mixedData;
  232. case BX_DATA_TEXT_MULTILINE:
  233. return $mixedData;
  234. case BX_DATA_TEXT:
  235. default:
  236. return htmlspecialchars_adv($mixedData);
  237. }
  238. }
  239. /*
  240. * This function apply bx_process_input and then bx_process_output.
  241. * Use this function to output data immediately after receiving, without saving to database.
  242. * Patams are the same as bx_process_input function - @see bx_process_input
  243. */
  244. function bx_process_pass ($mixedData, $iDataType = BX_DATA_TEXT, $mixedParams = false, $isCheckMagicQuotes = true) {
  245. return bx_process_output(bx_process_input ($mixedData, $iDataType, $mixedParams, $isCheckMagicQuotes), $iDataType, $mixedParams);
  246. }
  247. /**
  248. * DEPRECATED
  249. * use bx_process_input + bx_process_output instead
  250. * --------
  251. * function for processing pass data
  252. *
  253. * This function cleans the GET/POST/COOKIE data if magic_quotes_gpc() is on
  254. * for data which should be outputed immediately after submit
  255. */
  256. /*
  257. function process_pass_data( $text, $strip_tags = 0 ) {
  258. if ( $strip_tags )
  259. $text = strip_tags($text);
  260. if ( !get_magic_quotes_gpc() )
  261. return $text;
  262. else
  263. return stripslashes($text);
  264. }
  265. */
  266. /*
  267. * function for output data from database into html
  268. */
  269. function htmlspecialchars_adv( $string ) {
  270. return htmlspecialchars($string, ENT_COMPAT, 'UTF-8');
  271. }
  272. function process_text_output( $text, $maxwordlen = 100 ) {
  273. return ( htmlspecialchars_adv( strmaxwordlen( $text, $maxwordlen ) ) );
  274. }
  275. function process_text_withlinks_output( $text, $maxwordlen = 100 ) {
  276. return nl2br( html_encode( htmlspecialchars_adv( strmaxwordlen( $text, $maxwordlen ) ) ) );
  277. }
  278. function process_line_output( $text, $maxwordlen = 100 ) {
  279. return htmlspecialchars_adv( strmaxwordlen( $text, $maxwordlen ) );
  280. }
  281. function process_html_output( $text, $maxwordlen = 100 ) {
  282. return strmaxwordlen( $text, $maxwordlen );
  283. }
  284. /**
  285. * Used to construct sturctured arrays in GET or POST data. Supports multidimensional arrays.
  286. *
  287. * @param array $Values Specifies values and values names, that should be submitted. Can be multidimensional.
  288. *
  289. * @return string HTML code, which contains <input type="hidden"...> tags with names and values, specified in $Values array.
  290. */
  291. function ConstructHiddenValues($Values) {
  292. /**
  293. * Recursive function, processes multidimensional arrays
  294. *
  295. * @param string $Name Full name of array, including all subarrays' names
  296. *
  297. * @param array $Value Array of values, can be multidimensional
  298. *
  299. * @return string Properly consctructed <input type="hidden"...> tags
  300. */
  301. function ConstructHiddenSubValues($Name, $Value) {
  302. if (is_array($Value)) {
  303. $Result = "";
  304. foreach ($Value as $KeyName => $SubValue) {
  305. $Result .= ConstructHiddenSubValues("{$Name}[{$KeyName}]", $SubValue);
  306. }
  307. } else
  308. // Exit recurse
  309. $Result = "<input type=\"hidden\" name=\"".htmlspecialchars($Name)."\" value=\"".htmlspecialchars($Value)."\" />\n";
  310. return $Result;
  311. }
  312. /* End of ConstructHiddenSubValues function */
  313. $Result = '';
  314. if (is_array($Values)) {
  315. foreach ($Values as $KeyName => $Value) {
  316. $Result .= ConstructHiddenSubValues($KeyName, $Value);
  317. }
  318. }
  319. return $Result;
  320. }
  321. /**
  322. * Returns HTML/javascript code, which redirects to another URL with passing specified data (through specified method)
  323. *
  324. * @param string $ActionURL destination URL
  325. *
  326. * @param array $Params Parameters to be passed (through GET or POST)
  327. *
  328. * @param string $Method Submit mode. Only two values are valid: 'get' and 'post'
  329. *
  330. * @return mixed Correspondent HTML/javascript code or false, if input data is wrong
  331. */
  332. function RedirectCode($ActionURL, $Params = NULL, $Method = "get", $Title = 'Redirect') {
  333. if ((strcasecmp(trim($Method), "get") && strcasecmp(trim($Method), "post")) || (trim($ActionURL) == ""))
  334. return false;
  335. ob_start();
  336. ?>
  337. <html>
  338. <head>
  339. <title><?= $Title ?></title>
  340. </head>
  341. <body>
  342. <form name="RedirectForm" action="<?= htmlspecialchars($ActionURL) ?>" method="<?= $Method ?>">
  343. <?= ConstructHiddenValues($Params) ?>
  344. </form>
  345. <script type="text/javascript">
  346. <!--
  347. document.forms['RedirectForm'].submit();
  348. -->
  349. </script>
  350. </body>
  351. </html>
  352. <?
  353. $Result = ob_get_contents();
  354. ob_end_clean();
  355. return $Result;
  356. }
  357. /**
  358. * Redirects browser to another URL, passing parameters through POST or GET
  359. * Actually just prints code, returned by RedirectCode (see RedirectCode)
  360. */
  361. function Redirect($ActionURL, $Params = NULL, $Method = "get", $Title = 'Redirect') {
  362. $RedirectCodeValue = RedirectCode($ActionURL, $Params, $Method, $Title);
  363. if ($RedirectCodeValue !== false)
  364. echo $RedirectCodeValue;
  365. }
  366. function isRWAccessible($sFileName) {
  367. clearstatcache();
  368. $perms = fileperms($sFileName);
  369. return ( $perms & 0x0004 && $perms & 0x0002 ) ? true : false;
  370. }
  371. /**
  372. * Send email function
  373. *
  374. * @param $sRecipientEmail - Email where email should be send
  375. * @param $sMailSubject - subject of the message
  376. * @param $sMailBody - Body of the message
  377. * @param $iRecipientID - ID of recipient profile
  378. * @param $aPlus - Array of additional information
  379. * @param $iEmailType - email message type: BX_EMAIL_SYSTEM, BX_EMAIL_NOTIFY or BX_EMAIL_MASS
  380. * @return true if message was send or false otherwise
  381. */
  382. function sendMail($sRecipientEmail, $sMailSubject, $sMailBody, $iRecipientID = 0, $aPlus = array(), $iEmailType = BX_EMAIL_NOTIFY, $sEmailFlag = 'html', $isDisableAlert = false) {
  383. // make sure that recipient's email is valid and message isn't empty
  384. if (!$sMailBody || !$sRecipientEmail || preg_match('/\(2\)$/', $sRecipientEmail))
  385. return false;
  386. // get recipient account
  387. bx_import('BxDolAccount');
  388. $oAccount = BxDolAccount::getInstance($sRecipientEmail);
  389. $aAccountInfo = $oAccount ? $oAccount->getInfo() : false;
  390. // don't send bulk emails if user didn't subscribed to site news or email is unconfirmed
  391. if ($aAccountInfo && BX_EMAIL_MASS == $iEmailType && (!$aAccountInfo['email_confirmed'] || !$aAccountInfo['receive_news']))
  392. return false;
  393. // don't send email notifications if user didn't subscribed to notifications or email is unconfirmed
  394. if ($aAccountInfo && BX_EMAIL_NOTIFY == $iEmailType && (!$aAccountInfo['email_confirmed'] || !$aAccountInfo['receive_updates']))
  395. return false;
  396. // if profile id is provided - get profile's info
  397. $aRecipientInfo = false;
  398. if ($iRecipientID) {
  399. bx_import('BxDolProfile');
  400. $oProfile = BxDolProfile::getInstance($iRecipientID);
  401. if ($oProfile)
  402. $aRecipientInfo = $oProfile->getInfo();
  403. }
  404. // get site vars
  405. $sEmailNotify = getParam('site_email_notify');
  406. $sSiteTitle = getParam('site_title');
  407. // add unsubscribe link
  408. if (empty($aPlus['unsubscribe'])) {
  409. $aPlus['unsubscribe'] = '';
  410. if ($oAccount && (BX_EMAIL_MASS == $iEmailType || BX_EMAIL_NOTIFY == $iEmailType))
  411. $aPlus['unsubscribe'] = ($sLink = $oAccount->getUnsubscribeLink($iEmailType)) ? '<a href="' . BX_DOL_URL_ROOT . $sLink . '">' . _t('_sys_et_txt_unsubscribe') . '</a>' : '';
  412. }
  413. // parse template
  414. if ($aPlus || $iRecipientID) {
  415. if(!is_array($aPlus))
  416. $aPlus = array();
  417. bx_import('BxDolEmailTemplates');
  418. $oEmailTemplates = BxDolEmailTemplates::getInstance();
  419. $sMailSubject = $oEmailTemplates->parseContent($sMailSubject, $aPlus, $iRecipientID);
  420. $sMailBody = $oEmailTemplates->parseContent($sMailBody, $aPlus, $iRecipientID);
  421. }
  422. // email message headers
  423. $sMailHeader = "From: =?UTF-8?B?" . base64_encode( $sSiteTitle ) . "?= <{$sEmailNotify}>";
  424. $sMailParameters = "-f{$sEmailNotify}";
  425. $sMailSubject = '=?UTF-8?B?' . base64_encode( $sMailSubject ) . '?=';
  426. $sMailHeader = "MIME-Version: 1.0\r\n" . $sMailHeader;
  427. // if SMPT mailer is installed and enabled - send mail throught it
  428. if (!$isDisableAlert && 'on' == getParam('bx_smtp_on')) { // TODO: remake to use alert: before_send_mail
  429. return BxDolService::call('bx_smtp', 'send', array($sRecipientEmail, $sMailSubject, $sMailBody, $sMailHeader, $sMailParameters, 'html' == $sEmailFlag, $aRecipientInfo));
  430. }
  431. // send mail
  432. if( 'html' == $sEmailFlag) {
  433. $sMailHeader = "Content-type: text/html; charset=UTF-8\r\n" . $sMailHeader;
  434. $iSendingResult = mail( $sRecipientEmail, $sMailSubject, $sMailBody, $sMailHeader, $sMailParameters );
  435. } else {
  436. $sMailHeader = "Content-type: text/plain; charset=UTF-8\r\n" . $sMailHeader;
  437. $sMailBody = html2txt($sMailBody);
  438. $iSendingResult = mail( $sRecipientEmail, $sMailSubject, html2txt($sMailBody), $sMailHeader, $sMailParameters );
  439. }
  440. // system alert
  441. if (!$isDisableAlert) {
  442. bx_alert('profile', 'send_mail', (isset($aRecipientInfo['ID']) ? $aRecipientInfo['ID'] : 0), '', array(
  443. 'email' => $sRecipientEmail,
  444. 'subject' => $sMailSubject,
  445. 'body' => $sMailBody,
  446. 'header' => $sMailHeader,
  447. 'params' => $sMailParameters,
  448. 'html' => 'html' == $sEmailFlag ? true : false,
  449. ));
  450. }
  451. return $iSendingResult;
  452. }
  453. /*
  454. * Getting an array with Templates' Names
  455. */
  456. function get_templates_array($bEnabledOnly = true) {
  457. bx_import('BxDolDb');
  458. return BxDolDb::getInstance()->getPairs("SELECT `uri`, `title` FROM `sys_modules` WHERE 1 AND `type`='" . BX_DOL_MODULE_TYPE_TEMPLATE . "'" . ($bEnabledOnly ? " AND `enabled`='1'" : ""), "uri", "title");
  459. }
  460. /*
  461. * The Function Show a Line with Templates Names
  462. */
  463. function templates_select_txt() {
  464. $templ_choices = get_templates_array();
  465. $current_template = ( strlen( $_GET['skin'] ) ) ? $_GET['skin'] : $_COOKIE['skin'];
  466. foreach ($templ_choices as $tmpl_key => $tmpl_value) {
  467. if ($current_template == $tmpl_key) {
  468. $ReturnResult .= $tmpl_value . ' | ';
  469. } else {
  470. $sGetTransfer = bx_encode_url_params($_GET, array('skin'));
  471. $ReturnResult .= '<a href="' . bx_html_attribute($_SERVER['PHP_SELF']) . '?' . $sGetTransfer . 'skin=' . $tmpl_key . '">' . $tmpl_value . '</a> | ';
  472. }
  473. }
  474. return $ReturnResult;
  475. }
  476. function extFileExists( $sFileSrc ) {
  477. return (file_exists( $sFileSrc ) && is_file( $sFileSrc )) ? true : false;
  478. }
  479. function getVisitorIP() {
  480. $ip = "0.0.0.0";
  481. if( ( isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) && ( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) ) {
  482. $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
  483. } elseif( ( isset( $_SERVER['HTTP_CLIENT_IP'])) && (!empty($_SERVER['HTTP_CLIENT_IP'] ) ) ) {
  484. $ip = explode(".",$_SERVER['HTTP_CLIENT_IP']);
  485. $ip = $ip[3].".".$ip[2].".".$ip[1].".".$ip[0];
  486. } elseif((!isset( $_SERVER['HTTP_X_FORWARDED_FOR'])) || (empty($_SERVER['HTTP_X_FORWARDED_FOR']))) {
  487. if ((!isset( $_SERVER['HTTP_CLIENT_IP'])) && (empty($_SERVER['HTTP_CLIENT_IP']))) {
  488. $ip = $_SERVER['REMOTE_ADDR'];
  489. }
  490. }
  491. return $ip;
  492. }
  493. function genFlag( $country ) {
  494. return '<img src="' . genFlagUrl($country) . '" />';
  495. }
  496. function genFlagUrl($country) {
  497. bx_import('BxDolTemplate');
  498. return BxDolTemplate::getInstance()->getIconUrl('sys_fl_' . strtolower($country) . '.gif');
  499. }
  500. // print debug information ( e.g. arrays )
  501. function echoDbg( $what, $desc = '' ) {
  502. if ( $desc )
  503. echo "<b>$desc:</b> ";
  504. echo "<pre>";
  505. print_r( $what );
  506. echo "</pre>\n";
  507. }
  508. function echoDbgLog($mWhat, $sDesc = '', $sFileName = 'debug.log') {
  509. $sCont =
  510. '--- ' . date('r') . ' (' . BX_DOL_START_TIME . ") ---\n" .
  511. $sDesc . "\n" .
  512. print_r($mWhat, true) . "\n\n\n";
  513. $rFile = fopen(BxDolConfig::getInstance()->get('path_dynamic', 'tmp') . $sFileName, 'a');
  514. fwrite($rFile, $sCont);
  515. fclose($rFile);
  516. }
  517. function clear_xss($val) {
  518. if ($GLOBALS['logged']['admin'])
  519. return $val;
  520. // HTML Purifier plugin
  521. global $oHtmlPurifier;
  522. require_once( BX_DIRECTORY_PATH_PLUGINS . 'htmlpurifier/HTMLPurifier.standalone.php' );
  523. if (!isset($oHtmlPurifier)) {
  524. HTMLPurifier_Bootstrap::registerAutoload();
  525. $oConfig = HTMLPurifier_Config::createDefault();
  526. $oConfig->set('HTML.SafeObject', 'true');
  527. $oConfig->set('Output.FlashCompat', 'true');
  528. $oConfig->set('HTML.FlashAllowFullScreen', 'true');
  529. $oConfig->set('Filter.Custom', array (new HTMLPurifier_Filter_YouTube(), new HTMLPurifier_Filter_YoutubeIframe()));
  530. $oDef = $oConfig->getHTMLDefinition(true);
  531. $oDef->addAttribute('a', 'target', 'Enum#_blank,_self,_target,_top');
  532. $oHtmlPurifier = new HTMLPurifier($oConfig);
  533. }
  534. return $oHtmlPurifier->purify($val);
  535. }
  536. function _format_when ($iSec) {
  537. $s = '';
  538. if ($iSec>0) {
  539. if ($iSec < 3600) {
  540. $i = round($iSec/60);
  541. $s .= (0 == $i || 1 == $i) ? _t('_1_minute_ago') : _t('_x_minute_ago', $i, 's');
  542. } else if ($iSec < 86400) {
  543. $i = round($iSec/60/60);
  544. $s .= (0 == $i || 1 == $i) ? _t('_x_hour_ago', '1', '') : _t('_x_hour_ago', $i, 's');
  545. } else {
  546. $i = round($iSec/60/60/24);
  547. $s .= (0 == $i || 1 == $i) ? _t('_1_day_ago') : _t('_x_day_ago', $i, 's');
  548. }
  549. } else {
  550. if ($iSec > -3600) {
  551. $i = round($iSec/60);
  552. $s .= (0 == $i || 1 == $i) ? _t('_in_1_minute') : _t('_in_x_minute', -$i, 's');
  553. } else if ($iSec > -86400) {
  554. $i = round($iSec/60/60);
  555. $s .= (0 == $i || 1 == $i) ? _t('_in_x_hour', '1', '') : _t('_in_x_hour', -$i, 's');
  556. } elseif ($iSec < -86400) {
  557. $i = round($iSec/60/60/24);
  558. $s .= (0 == $i || 1 == $i) ? _t('_in_1_day') : _t('_in_x_day', -$i, 's');
  559. }
  560. }
  561. return $s;
  562. }
  563. function _format_time($iSec, $aParams = array()) {
  564. $sDivider = isset($aParams['divider']) ? $aParams['divider'] : ':';
  565. $iSec = (int)$iSec;
  566. $sFormat = $iSec > 3600 ? 'H' . $sDivider . 'i' . $sDivider . 's' : 'i' . $sDivider . 's';
  567. return gmdate($sFormat, $iSec);
  568. }
  569. function defineTimeInterval($iTime) {
  570. $iTime = time() - (int)$iTime;
  571. $sCode = _format_when($iTime);
  572. return $sCode;
  573. }
  574. function execSqlFile($sFileName) {
  575. if (! $f = fopen($sFileName, "r"))
  576. return false;
  577. db_res( "SET NAMES 'utf8'" );
  578. $s_sql = "";
  579. while ( $s = fgets ( $f, 10240) ) {
  580. $s = trim( $s ); //Utf with BOM only
  581. if( !strlen( $s ) ) continue;
  582. if ( mb_substr( $s, 0, 1 ) == '#' ) continue; //pass comments
  583. if ( mb_substr( $s, 0, 2 ) == '--' ) continue;
  584. $s_sql .= $s;
  585. if ( mb_substr( $s, -1 ) != ';' ) continue;
  586. db_res( $s_sql );
  587. $s_sql = "";
  588. }
  589. fclose($f);
  590. return true;
  591. }
  592. function replace_full_uris( $text ) {
  593. $text = preg_replace_callback( '/([\s\n\r]src\=")([^"]+)(")/', 'replace_full_uri', $text );
  594. return $text;
  595. }
  596. function replace_full_uri( $matches ) {
  597. if( substr( $matches[2], 0, 7 ) != 'http://' and substr( $matches[2], 0, 6 ) != 'ftp://' )
  598. $matches[2] = BX_DOL_URL_ROOT . $matches[2];
  599. return $matches[1] . $matches[2] . $matches[3];
  600. }
  601. //--------------------------------------- friendly permalinks --------------------------------------//
  602. //------------------------------------------- main functions ---------------------------------------//
  603. function uriGenerate ($s, $sTable, $sField, $sEmpty = '-') {
  604. $s = uriFilter($s, $sEmpty);
  605. if(uriCheckUniq($s, $sTable, $sField))
  606. return $s;
  607. // cut off redundant part
  608. if(get_mb_len($s) > 240)
  609. $s = get_mb_substr($s, 0, 240);
  610. // try to add date
  611. $s .= '-' . date('Y-m-d');
  612. if(uriCheckUniq($s, $sTable, $sField))
  613. return $s;
  614. // try to add number
  615. for($i = 0 ; $i < 999 ; ++$i)
  616. if(uriCheckUniq($s . '-' . $i, $sTable, $sField))
  617. return ($s . '-' . $i);
  618. return rand(0, 999999999);
  619. }
  620. function uriFilter ($s, $sEmpty = '-') {
  621. bx_import('BxTemplConfig');
  622. if (BxTemplConfig::getInstance()->bAllowUnicodeInPreg)
  623. $s = get_mb_replace ('/[^\pL^\pN]+/u', '-', $s); // unicode characters
  624. else
  625. $s = get_mb_replace ('/([^\d^\w]+)/u', '-', $s); // latin characters only
  626. $s = get_mb_replace ('/([-^]+)/', '-', $s);
  627. $s = get_mb_replace ('/([-]+)$/', '', $s); // remove trailing dash
  628. if (!$s) $s = '-';
  629. return $s;
  630. }
  631. function uriCheckUniq ($s, $sTable, $sField) {
  632. bx_import('BxDolDb');
  633. $oDb = BxDolDb::getInstance();
  634. $sSql = $oDb->prepare("SELECT 1 FROM `$sTable` WHERE `$sField`=? LIMIT 1", $s);
  635. return !$oDb->query($sSql);
  636. }
  637. function get_mb_replace ($sPattern, $sReplace, $s) {
  638. return preg_replace ($sPattern, $sReplace, $s);
  639. }
  640. function get_mb_len ($s) {
  641. return (function_exists('mb_strlen')) ? mb_strlen($s) : strlen($s);
  642. }
  643. function get_mb_substr ($s, $iStart, $iLen) {
  644. return (function_exists('mb_substr')) ? mb_substr ($s, $iStart, $iLen) : substr ($s, $iStart, $iLen);
  645. }
  646. function bx_mb_substr_replace($s, $sReplace, $iPosStart, $iLength) {
  647. return mb_substr($s, 0, $iPosStart) . $sReplace . mb_substr($s, $iPosStart + $iLength);
  648. }
  649. function bx_mb_strpos ($s, $sReplacement, $iStart = 0) {
  650. return mb_strpos($s, $sReplacement, $iStart);
  651. }
  652. /**
  653. * Block user IP
  654. *
  655. * @param $sIP mixed
  656. * @param $iExpirationInSec integer
  657. * @param $sComment string
  658. * @return void
  659. */
  660. function bx_block_ip($mixedIP, $iExpirationInSec = 86400, $sComment = '') {
  661. if (preg_match('/^[0-9]+$/', $mixedIP))
  662. $iIP = $mixedIP;
  663. else
  664. $iIP = sprintf("%u", ip2long($sIP));
  665. $iExpirationInSec = time() + (int)$iExpirationInSec;
  666. $oDb = BxDolDb::getInstance();
  667. $sQuery = $oDb->prepare("SELECT ID FROM `sys_ip_list` WHERE `From` = ? AND `To` = ? LIMIT 1", $iIP, $iIP);
  668. if (!$oDb->getOne($sQuery)) {
  669. $sQuery = $oDb->prepare("INSERT INTO `sys_ip_list` SET `From` = ?, `To` = ?, `Type` = 'deny', `LastDT` = ?, `Desc` = ?", $iIP, $iIP, $iExpirationInSec, $sComment);
  670. return $oDb->res($sQuery);
  671. }
  672. return false;
  673. }
  674. function bx_is_ip_dns_blacklisted($sCurIP = '', $sType = '') {
  675. if (defined('BX_DOL_CRON_EXECUTE'))
  676. return false;
  677. if (!$sCurIP)
  678. $sCurIP = getVisitorIP();
  679. if (bx_is_ip_whitelisted($sCurIP))
  680. return false;
  681. $o = bx_instance('BxDolDNSBlacklists');
  682. 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))
  683. {
  684. $o->onPositiveDetection ($sCurIP, $sType);
  685. return true;
  686. }
  687. return false;
  688. }
  689. function bx_is_ip_whitelisted($sCurIP = '') {
  690. if (defined('BX_DOL_CRON_EXECUTE'))
  691. return true;
  692. $iIPGlobalType = (int)getParam('ipListGlobalType');
  693. if ($iIPGlobalType != 1 && $iIPGlobalType != 2) // 0 - disabled
  694. return false;
  695. if (!$sCurIP)
  696. $sCurIP = getVisitorIP();
  697. $iCurIP = sprintf("%u", ip2long($sCurIP));
  698. $iCurrTume = time();
  699. 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;
  700. }
  701. function bx_is_ip_blocked($sCurIP = '') {
  702. if (defined('BX_DOL_CRON_EXECUTE'))
  703. return false;
  704. $iIPGlobalType = (int)getParam('ipListGlobalType');
  705. if ($iIPGlobalType != 1 && $iIPGlobalType != 2) // 0 - disabled
  706. return false;
  707. if (!$sCurIP)
  708. $sCurIP = getVisitorIP();
  709. $iCurIP = sprintf("%u", ip2long($sCurIP));
  710. $iCurrTume = time();
  711. if (bx_is_ip_whitelisted($sCurIP))
  712. return false;
  713. $isBlocked = db_value("SELECT `ID` FROM `sys_ip_list` WHERE `Type` = 'deny' AND `LastDT` > $iCurrTume AND `From` <= '$iCurIP' AND `To` >= '$iCurIP' LIMIT 1");
  714. if ($isBlocked)
  715. return true;
  716. // 1 - all allowed except listed
  717. // 2 - all blocked except listed
  718. return $iIPGlobalType == 2 ? true : false;
  719. }
  720. /**
  721. * spam checking function
  722. * @param $s content to check for spam
  723. * @param $isStripSlashes slashes parameter:
  724. * BX_SLASHES_AUTO - automatically detect magic_quotes_gpc setting
  725. * BX_SLASHES_NO_ACTION - do not perform any action with slashes
  726. * @return true if spam detected
  727. */
  728. function bx_is_spam ($val, $isStripSlashes = BX_SLASHES_AUTO) {
  729. if (defined('BX_DOL_CRON_EXECUTE'))
  730. return false;
  731. if (isAdmin())
  732. return false;
  733. if (bx_is_ip_whitelisted())
  734. return false;
  735. if (get_magic_quotes_gpc() && $isStripSlashes == BX_SLASHES_AUTO)
  736. $val = stripslashes($val);
  737. $bRet = false;
  738. if ('on' == getParam('sys_uridnsbl_enable')) {
  739. $oBxDolDNSURIBlacklists = bx_instance('BxDolDNSURIBlacklists');
  740. if ($oBxDolDNSURIBlacklists->isSpam($val)) {
  741. $oBxDolDNSURIBlacklists->onPositiveDetection($val);
  742. $bRet = true;
  743. }
  744. }
  745. if ('on' == getParam('sys_akismet_enable')) {
  746. $oBxDolAkismet = bx_instance('BxDolAkismet');
  747. if ($oBxDolAkismet->isSpam($val)) {
  748. $oBxDolAkismet->onPositiveDetection($val);
  749. $bRet = true;
  750. }
  751. }
  752. if ($bRet && 'on' == getParam('sys_antispam_report')) {
  753. $iProfileId = getLoggedId();
  754. $aPlus = array(
  755. 'SpammerUrl' => getProfileLink($iProfileId),
  756. 'SpammerNickName' => getNickName($iProfileId),
  757. 'Page' => htmlspecialchars_adv($_SERVER['PHP_SELF']),
  758. 'Get' => print_r($_GET, true),
  759. 'SpamContent' => htmlspecialchars_adv($val),
  760. );
  761. bx_import('BxDolEmailTemplates');
  762. $aTemplate = BxDolEmailTemplates::getInstance()->parseTemplate('t_SpamReportAuto', $aPlus);
  763. if (!$aTemplate)
  764. trigger_error('Email template or translation missing: t_SpamReportAuto', E_USER_ERROR);
  765. sendMail(getParam('site_email'), $aTemplate['Subject'], $aTemplate['Body']);
  766. }
  767. if ($bRet && 'on' == getParam('sys_antispam_block'))
  768. return true;
  769. return false;
  770. }
  771. function getmicrotime() {
  772. list($usec, $sec) = explode(" ", microtime());
  773. return ((float)$usec + (float)$sec);
  774. }
  775. /**
  776. ** @description : function will create cache file with all SQL queries ;
  777. ** @return :
  778. */
  779. function genSiteStatCache() {
  780. $sqlQuery = "SELECT `Name` as `name`,
  781. `Title` as `capt`,
  782. `UserQuery` as `query`,
  783. `UserLink` as `link`,
  784. `IconName` as `icon`,
  785. `AdminQuery` as `adm_query`,
  786. `AdminLink` as `adm_link`
  787. FROM `sys_stat_site`
  788. ORDER BY `StatOrder` ASC, `ID` ASC";
  789. $rData = db_res($sqlQuery);
  790. $sLine = "return array( \n";
  791. while ($aVal = mysql_fetch_assoc($rData)) {
  792. $sLine .= genSiteStatFile($aVal);
  793. }
  794. $sLine = rtrim($sLine, ",\n")."\n);";
  795. $aResult = eval($sLine);
  796. $oCache = BxDolDb::getInstance()->getDbCacheObject();
  797. return $oCache->setData (BxDolDb::getInstance()->genDbCacheKey('sys_stat_site'), $aResult);
  798. }
  799. /**
  800. * Function will cute the parameter from received string;
  801. * remove received parameter from 'GET' query ;
  802. *
  803. * @param : $aExceptNames (string) - name of unnecessary parameter;
  804. * @return : cleared string;
  805. */
  806. function getClearedParam( $sExceptParam, $sString ) {
  807. return preg_replace( "/(&amp;|&){$sExceptParam}=([a-z0-9\_\-]{1,})/i",'', $sString);
  808. }
  809. /**
  810. * import class file, it detect class path by its prefix or module array
  811. *
  812. * @param $sClassName - full class name or class postfix in a case of module class
  813. * @param $aModule - module array or true to get module array from global variable
  814. */
  815. function bx_import($sClassName, $aModule = array()) {
  816. if (class_exists($sClassName))
  817. return;
  818. if ($aModule) {
  819. $a = (true === $aModule) ? $GLOABLS['aModule'] : $aModule;
  820. if (class_exists($a['class_prefix'] . $sClassName))
  821. return;
  822. require_once (BX_DIRECTORY_PATH_MODULES . $a['path'] . 'classes/' . $a['class_prefix'] . $sClassName . '.php');
  823. }
  824. if (0 == strncmp($sClassName, 'BxDol', 5)) {
  825. if (0 == strncmp($sClassName, 'BxDolStudio', 11))
  826. require_once(BX_DOL_DIR_STUDIO_CLASSES . $sClassName . '.php');
  827. else
  828. require_once(BX_DIRECTORY_PATH_CLASSES . $sClassName . '.php');
  829. return;
  830. }
  831. if (0 == strncmp($sClassName, 'BxBase', 6)) {
  832. if(0 == strncmp($sClassName, 'BxBaseStudio', 12))
  833. require_once(BX_DOL_DIR_STUDIO_BASE . 'scripts/' . $sClassName . '.php');
  834. else
  835. require_once(BX_DIRECTORY_PATH_BASE . 'scripts/' . $sClassName . '.php');
  836. return;
  837. }
  838. if (0 == strncmp($sClassName, 'BxTempl', 7) && !class_exists($sClassName)) {
  839. if(0 == strncmp($sClassName, 'BxTemplStudio', 13)) {
  840. bx_import('BxDolStudioTemplate');
  841. $sPath = BX_DIRECTORY_PATH_MODULES . BxDolStudioTemplate::getInstance()->getPath() . 'data/template/studio/scripts/' . $sClassName . '.php';
  842. }
  843. else {
  844. bx_import('BxDolTemplate');
  845. $sPath = BX_DIRECTORY_PATH_MODULES . BxDolTemplate::getInstance()->getPath() . 'data/template/system/scripts/' . $sClassName . '.php';
  846. }
  847. if(file_exists($sPath)) {
  848. require_once($sPath);
  849. return;
  850. }
  851. echo "<b>Fatal error:</b> Class (" . $sClassName . ") not found.";
  852. exit;
  853. }
  854. }
  855. /**
  856. * Gets an instance of class pathing necessary parameters if it's necessary.
  857. *
  858. * @param string $sClassName class name.
  859. * @param array $aParams an array of parameters to be pathed to the constructor of the class.
  860. * @param array $aModule an array with module description. Is used when the requested class is located in some module.
  861. * @return unknown
  862. */
  863. function bx_instance($sClassName, $aParams = array(), $aModule = array()) {
  864. if(isset($GLOBALS['bxDolClasses'][$sClassName]))
  865. return $GLOBALS['bxDolClasses'][$sClassName];
  866. else {
  867. bx_import((empty($aModule) ? $sClassName : str_replace($aModule['class_prefix'], '', $sClassName)), $aModule);
  868. if(empty($aParams))
  869. $GLOBALS['bxDolClasses'][$sClassName] = new $sClassName();
  870. else {
  871. $sParams = "";
  872. foreach($aParams as $mixedKey => $mixedValue)
  873. $sParams .= "\$aParams[" . $mixedKey . "], ";
  874. $sParams = substr($sParams, 0, -2);
  875. $GLOBALS['bxDolClasses'][$sClassName] = eval("return new " . $sClassName . "(" . $sParams . ");"); // TODO: remake without eval
  876. }
  877. return $GLOBALS['bxDolClasses'][$sClassName];
  878. }
  879. }
  880. /**
  881. * Escapes string/array ready to pass to js script with filtered symbols like ', " etc
  882. *
  883. * @param $mixedInput - string/array which should be filtered
  884. * @param $iQuoteType - string escaping method: BX_ESCAPE_STR_AUTO(default), BX_ESCAPE_STR_APOS or BX_ESCAPE_STR_QUOTE
  885. * @return converted string / array
  886. */
  887. function bx_js_string ($mixedInput, $iQuoteType = BX_ESCAPE_STR_AUTO) {
  888. $aUnits = array(
  889. "\n" => "\\n",
  890. "\r" => "",
  891. );
  892. if (BX_ESCAPE_STR_APOS == $iQuoteType) {
  893. $aUnits["'"] = "\\'";
  894. $aUnits['<script'] = "<scr' + 'ipt";
  895. $aUnits['</script>'] = "</scr' + 'ipt>";
  896. } elseif (BX_ESCAPE_STR_QUOTE == $iQuoteType) {
  897. $aUnits['"'] = '\\"';
  898. $aUnits['<script'] = '<scr" + "ipt';
  899. $aUnits['</script>'] = '</scr" + "ipt>';
  900. } else {
  901. $aUnits['"'] = '&quote;';
  902. $aUnits["'"] = '&apos;';
  903. $aUnits["<"] = '&lt;';
  904. $aUnits[">"] = '&gt;';
  905. }
  906. return str_replace(array_keys($aUnits), array_values($aUnits), $mixedInput);
  907. }
  908. /**
  909. * Return input string/array ready to pass to html attribute with filtered symbols like ', " etc
  910. *
  911. * @param mixed $mixedInput - string/array which should be filtered
  912. * @return converted string / array
  913. */
  914. function bx_html_attribute ($mixedInput, $iQuoteType = BX_ESCAPE_STR_AUTO) {
  915. $aUnits = array ();
  916. if (BX_ESCAPE_STR_APOS == $iQuoteType)
  917. $aUnits["'"] = "\\'";
  918. elseif (BX_ESCAPE_STR_QUOTE == $iQuoteType)
  919. $aUnits['"'] = '\\"';
  920. else
  921. $aUnits = array("\"" => "&quot;", "'" => "&apos;");
  922. return str_replace(array_keys($aUnits), array_values($aUnits), $mixedInput);
  923. }
  924. /**
  925. * Escapes string/array ready to pass to php script with filtered symbols like ', " etc
  926. *
  927. * @param mixed $mixedInput - string/array which should be filtered
  928. * @return converted string / array
  929. */
  930. function bx_php_string_apos ($mixedInput) {
  931. return str_replace("'", "\\'", $mixedInput);
  932. }
  933. function bx_php_string_quot ($mixedInput) {
  934. return str_replace('"', '\\"', $mixedInput);
  935. }
  936. /**
  937. * Gets file contents by URL.
  938. *
  939. * @param string $sFileUrl - file URL to be read.
  940. * @param array $aParams - an array of parameters to be pathed with URL.
  941. * @return string the file's contents.
  942. */
  943. function bx_file_get_contents($sFileUrl, $aParams = array(), $bChangeTimeout = false) {
  944. if ($aParams)
  945. $sFileUrl = bx_append_url_params($sFileUrl, $aParams);
  946. $sResult = '';
  947. if(function_exists('curl_init')) {
  948. $rConnect = curl_init();
  949. curl_setopt($rConnect, CURLOPT_URL, $sFileUrl);
  950. curl_setopt($rConnect, CURLOPT_HEADER, 0);
  951. curl_setopt($rConnect, CURLOPT_RETURNTRANSFER, 1);
  952. curl_setopt($rConnect, CURLOPT_FOLLOWLOCATION, 1);
  953. if ($bChangeTimeout) {
  954. curl_setopt($rConnect, CURLOPT_CONNECTTIMEOUT, 3);
  955. curl_setopt($rConnect, CURLOPT_TIMEOUT, 3);
  956. }
  957. $sAllCookies = '';
  958. foreach($_COOKIE as $sKey=>$sValue){
  959. $sAllCookies .= $sKey."=".$sValue.";";
  960. }
  961. curl_setopt($rConnect, CURLOPT_COOKIE, $sAllCookies);
  962. $sResult = curl_exec($rConnect);
  963. curl_close($rConnect);
  964. } else {
  965. $iSaveTimeout = false;
  966. if ($bChangeTimeout) {
  967. $iSaveTimeout = ini_get('default_socket_timeout');
  968. ini_set('default_socket_timeout', 3);
  969. }
  970. $sResult = @file_get_contents($sFileUrl);
  971. if ($bChangeTimeout && false !== $iSaveTimeout) {
  972. ini_set('default_socket_timeout', $iSaveTimeout);
  973. }
  974. }
  975. return $sResult;
  976. }
  977. /**
  978. * perform write log into 'tmp/log.txt' (for any debug development)
  979. *
  980. * @param $sNewLineText - New line debug text
  981. */
  982. function writeLog($sNewLineText = 'test') {
  983. $sFileName = BX_DIRECTORY_PATH_ROOT . 'tmp/log.txt';
  984. if (is_writable($sFileName)) {
  985. if (! $vHandle = fopen($sFileName, 'a')) {
  986. echo "Unable to open ({$sFileName})";
  987. }
  988. if (fwrite($vHandle, $sNewLineText . "\r\n") === FALSE) {
  989. echo "Unable write to ({$sFileName})";
  990. }
  991. fclose($vHandle);
  992. } else {
  993. echo "{$sFileName} is not writeable";
  994. }
  995. }
  996. function getLinkSet ($sLinkString, $sUrlPrefix, $sDivider = ';,', $bUriConvert = false) {
  997. $aSet = preg_split( '/['.$sDivider.']/', $sLinkString, 0, PREG_SPLIT_NO_EMPTY);
  998. $sFinalSet = '';
  999. foreach ($aSet as $sKey) {
  1000. $sLink = $sUrlPrefix . urlencode($bUriConvert ? title2uri($sKey) : $sKey);
  1001. $sFinalSet .= '<a href="' . $sUrlPrefix . urlencode(title2uri($sKey)) . '">' . $sKey . '</a> ';
  1002. }
  1003. return trim($sFinalSet, ' ');
  1004. }
  1005. // TODO: move to files modules - it is used only there
  1006. function getRelatedWords (&$aInfo) {
  1007. $sString = implode(' ', $aInfo);
  1008. $aRes = array_unique(explode(' ', $sString));
  1009. $sString = implode(' ', $aRes);
  1010. return addslashes($sString);
  1011. }
  1012. // TODO: move to sites module - it is used only there
  1013. function getSiteInfo($sSourceUrl)
  1014. {
  1015. $aResult = array();
  1016. $sContent = bx_file_get_contents($sSourceUrl);
  1017. if (strlen($sContent))
  1018. {
  1019. preg_match("/<title>(.*)<\/title>/", $sContent, $aMatch);
  1020. $aResult['title'] = $aMatch[1];
  1021. preg_match("/<meta.*name[='\" ]+description['\"].*content[='\" ]+(.*)['\"].*><\/meta>/", $sContent, $aMatch);
  1022. $aResult['description'] = $aMatch[1];
  1023. }
  1024. return $aResult;
  1025. }
  1026. // calculation ini_get('upload_max_filesize') in bytes as example
  1027. function return_bytes($val) {
  1028. $val = trim($val);
  1029. $last = strtolower($val{strlen($val)-1});
  1030. $val = (int)$val;
  1031. switch($last) {
  1032. // The 'G' modifier is available since PHP 5.1.0
  1033. case 'k':
  1034. $val *= 1024;
  1035. break;
  1036. case 'm':
  1037. $val *= 1024 * 1024;
  1038. break;
  1039. case 'g':
  1040. $val *= 1024 * 1024 * 1024;
  1041. break;
  1042. }
  1043. return $val;
  1044. }
  1045. // Generate Random Password
  1046. function genRndPwd($iLength = 8, $bSpecialCharacters = true) {
  1047. $sPassword = '';
  1048. $sChars = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
  1049. if($bSpecialCharacters === true)
  1050. $sChars .= "!?=/&+,.";
  1051. srand((double)microtime()*1000000);
  1052. for($i = 0; $i < $iLength; $i++) {
  1053. $x = mt_rand(0, strlen($sChars) -1);
  1054. $sPassword .= $sChars{$x};
  1055. }
  1056. return $sPassword;
  1057. }
  1058. // Generate Random Salt for Password encryption
  1059. function genRndSalt() {
  1060. return genRndPwd(8, true);
  1061. }
  1062. // Encrypt User Password
  1063. function encryptUserPwd($sPwd, $sSalt) {
  1064. return sha1(md5($sPwd) . $sSalt);
  1065. }
  1066. // Advanced stripslashes. Strips strings and arrays
  1067. function stripslashes_adv($s) {
  1068. if (is_string($s))
  1069. return stripslashes($s);
  1070. elseif (is_array($s)) {
  1071. foreach ($s as $k => $v) {
  1072. $s[$k] = stripslashes($v);
  1073. }
  1074. return $s;
  1075. } else
  1076. return $s;
  1077. }
  1078. function bx_get ($sName) {
  1079. if (isset($_GET[$sName]))
  1080. return $_GET[$sName];
  1081. elseif (isset($_POST[$sName]))
  1082. return $_POST[$sName];
  1083. else
  1084. return false;
  1085. }
  1086. function bx_encode_url_params ($a, $aExcludeKeys = array (), $aOnlyKeys = false) {
  1087. $s = '';
  1088. foreach ($a as $sKey => $sVal) {
  1089. if (in_array($sKey, $aExcludeKeys))
  1090. continue;
  1091. if (false !== $aOnlyKeys && !in_array($sKey, $aOnlyKeys))
  1092. continue;
  1093. if (is_array($sVal)) {
  1094. foreach ($sVal as $sSubVal) {
  1095. $s .= rawurlencode($sKey) . '[]=' . rawurlencode(is_array($sSubVal) ? 'array' : $sSubVal) . '&';
  1096. }
  1097. } else {
  1098. $s .= rawurlencode($sKey) . '=' . rawurlencode($sVal) . '&';
  1099. }
  1100. }
  1101. return $s;
  1102. }
  1103. function bx_append_url_params ($sUrl, $mixedParams) {
  1104. if (!$mixedParams)
  1105. return $sUrl;
  1106. $sParams = false == strpos($sUrl, '?') ? '?' : '&';
  1107. if (is_array($mixedParams)) {
  1108. foreach($mixedParams as $sKey => $sValue)
  1109. $sParams .= $sKey . '=' . $sValue . '&';
  1110. $sParams = substr($sParams, 0, -1);
  1111. } else {
  1112. $sParams .= $mixedParams;
  1113. }
  1114. return $sUrl . $sParams;
  1115. }
  1116. function bx_rrmdir($directory) {
  1117. if (substr($directory,-1) == "/")
  1118. $directory = substr($directory,0,-1);
  1119. if (!file_exists($directory) || !is_dir($directory))
  1120. return false;
  1121. elseif (!is_readable($directory))
  1122. return false;
  1123. if (!($directoryHandle = opendir($directory)))
  1124. return false;
  1125. while ($contents = readdir($directoryHandle)) {
  1126. if ($contents != '.' && $contents != '..') {
  1127. $path = $directory . "/" . $contents;
  1128. if (is_dir($path))
  1129. bx_rrmdir($path);
  1130. else
  1131. unlink($path);
  1132. }
  1133. }
  1134. closedir($directoryHandle);
  1135. if (!rmdir($directory))
  1136. return false;
  1137. return true;
  1138. }
  1139. function bx_clear_folder ($sPath, $aExts = array ()) {
  1140. if (substr($$sPath,-1) == "/")
  1141. $sPath = substr($sPath,0,-1);
  1142. if (!file_exists($sPath) || !is_dir($sPath))
  1143. return false;
  1144. elseif (!is_readable($sPath))
  1145. return false;
  1146. if (!($h = opendir($sPath)))
  1147. return false;
  1148. while ($sFile = readdir($h)) {
  1149. if ('.' == $sFile || '..' == $sFile)
  1150. continue;
  1151. $sFullPath = $sPath . '/' . $sFile;
  1152. if (is_dir($sFullPath))
  1153. continue;
  1154. if (!$aExts || (($sExt = pathinfo($sFullPath, PATHINFO_EXTENSION)) && in_array($sExt, $aExts)))
  1155. @unlink($sFullPath);
  1156. }
  1157. closedir($h);
  1158. return true;
  1159. }
  1160. function bx_ltrim_str ($sString, $sPrefix, $sReplace = '') {
  1161. if ($sReplace && substr($sString, 0, strlen($sReplace)) == $sReplace)
  1162. return $sString;
  1163. if (substr($sString, 0, strlen($sPrefix)) == $sPrefix)
  1164. return $sReplace . substr($sString, strlen($sPrefix));
  1165. return $sString;
  1166. }
  1167. /**
  1168. * Convert array to attributes string
  1169. *
  1170. * Example:
  1171. * @code
  1172. * $a = array('name' => 'test', 'value' => 5);
  1173. * $s = bx_convert_array2attrs($a);
  1174. * echo $s; // outputs: name="test" value="5"
  1175. * @endcode
  1176. *
  1177. * @param $a - array of attributes
  1178. * @param $sClasses - classes to merge with 'class' attribute
  1179. * @param $sStyles - styles to merge with 'style' attribute
  1180. * @return string
  1181. */
  1182. function bx_convert_array2attrs ($a, $sClasses = false, $sStyles = false) {
  1183. $sRet = '';
  1184. if (!$a || !is_array($a))
  1185. $a = array();
  1186. if ($sClasses) {
  1187. $sClasses = trim($sClasses);
  1188. $a['class'] = $sClasses . (!empty($a['class']) ? ' ' . $a['class'] : '');
  1189. }
  1190. if ($sStyles) {
  1191. $sStyles = trim($sStyles);
  1192. if (';' != $sStyles[strlen($sStyles)-1])
  1193. $sStyles .= ';';
  1194. $a['style'] = $sStyles . (!empty($a['style']) ? ' ' . $a['style'] : '');
  1195. }
  1196. foreach ($a as $sKey => $sValue) {
  1197. if(is_null($sValue)) // pass NULL values
  1198. continue;
  1199. $sValueC = bx_html_attribute($sValue, BX_ESCAPE_STR_QUOTE);
  1200. $sRet .= " $sKey=\"$sValueC\"";
  1201. }
  1202. return $sRet;
  1203. }
  1204. function bx_unicode_urldecode($s) {
  1205. preg_match_all('/%u([[:alnum:]]{4})/', $s, $a);
  1206. foreach ($a[1] as $uniord)
  1207. {
  1208. $dec = hexdec($uniord);
  1209. $utf = '';
  1210. if ($dec < 128)
  1211. {
  1212. $utf = chr($dec);
  1213. }
  1214. else if ($dec < 2048)
  1215. {
  1216. $utf = chr(192 + (($dec - ($dec % 64)) / 64));
  1217. $utf .= chr(128 + ($dec % 64));
  1218. }
  1219. else
  1220. {
  1221. $utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
  1222. $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
  1223. $utf .= chr(128 + ($dec % 64));
  1224. }
  1225. $s = str_replace('%u'.$uniord, $utf, $s);
  1226. }
  1227. return urldecode($s);
  1228. }
  1229. /**
  1230. * Raise an alert
  1231. * @param string $sType - system type
  1232. * @param string $sAction - system action
  1233. * @param int $iObjectId - object id
  1234. * @param int $iSenderId - sender (action's author) profile id, if it is false - then currectly logged in profile id is used
  1235. */
  1236. function bx_alert($sUnit, $sAction, $iObjectId, $iSender = false, $aExtras = array()) {
  1237. $o = new BxDolAlerts($sUnit, $sAction, $iObjectId, $iSender, $aExtras);
  1238. $o->alert();
  1239. }
  1240. function getSitesArray ($sLink) {
  1241. $aSites = $GLOBALS['MySQL']->fromCache ('sys_shared_sites', 'getAllWithKey', "SELECT `ID` as `id`, `URL` as `url`, `Icon` as `icon`, `Name` FROM `sys_shared_sites`", 'Name');
  1242. $sLink = htmlentities(($sLink));
  1243. foreach ($aSites as $sKey => $aValue)
  1244. $aSites[$sKey]['url'] .= $sLink;
  1245. return $aSites;
  1246. }
  1247. /** @} */