utils.inc.php 49 KB

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