utils.inc.php 47 KB

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