utils.inc.php 49 KB

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