utils.inc.php 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084
  1. <?php defined('BX_DOL') or defined('BX_DOL_INSTALL') or die('hack attempt');
  2. /**
  3. * Copyright (c) UNA, Inc - https://una.io
  4. * MIT License - https://opensource.org/licenses/MIT
  5. *
  6. * @defgroup UnaCore UNA Core
  7. * @{
  8. */
  9. define('BX_DOL_LINK_CLASS', 'bx-link'); ///< class to add to every link in user content
  10. define('BX_DATA_TEXT', 1); ///< regular text data type
  11. define('BX_DATA_TEXT_MULTILINE', 2); ///< regular multiline text data type
  12. define('BX_DATA_INT', 3); ///< integer data type
  13. define('BX_DATA_FLOAT', 4); ///< float data type
  14. define('BX_DATA_CHECKBOX', 5); ///< checkbox data type, 'on' or empty value
  15. define('BX_DATA_HTML', 6); ///< HTML data type
  16. define('BX_DATA_DATE', 7); ///< date data type stored as yyyy-mm-dd
  17. define('BX_DATA_DATETIME', 12); ///< date/time data type stored as yyyy-mm-dd hh:mm:ss
  18. define('BX_DATA_DATE_TS', 8); ///< date data type stored as unixtimestamp
  19. define('BX_DATA_DATETIME_TS', 9); ///< date/time data type stored as unixtimestamp
  20. define('BX_DATA_DATE_TS_UTC', 10); ///< date data type stored as unixtimestamp from UTC time
  21. define('BX_DATA_DATETIME_TS_UTC', 11); ///< date/time data type stored as unixtimestamp from UTC time
  22. define('BX_SLASHES_AUTO', 0);
  23. define('BX_SLASHES_ADD', 1);
  24. define('BX_SLASHES_STRIP', 2);
  25. define('BX_SLASHES_NO_ACTION', 3);
  26. 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
  27. 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
  28. 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
  29. define('BX_EMAIL_SYSTEM', 0); ///< system email without unsubscribe link, like forgot password or email verification
  30. define('BX_EMAIL_NOTIFY', 1); ///< notification message, with unsubscribe link
  31. define('BX_EMAIL_MASS', 2); ///< mass email, one mesage send to manu users, with unsubscribe link
  32. define('BX_MAINTENANCE_FILE', '.bx_maintenance'); ///< file name to use as mantenance mode indicator
  33. /**
  34. * The following two functions are needed to convert title to uri and back.
  35. * It usefull when titles are used in URLs, like in Categories and Tags.
  36. */
  37. function title2uri($sValue)
  38. {
  39. return str_replace(
  40. array('&', '/', '\\', '"', '+'),
  41. array('[and]', '[slash]', '[backslash]', '[quote]', '[plus]'),
  42. $sValue
  43. );
  44. }
  45. function uri2title($sValue)
  46. {
  47. return str_replace(
  48. array('[and]', '[slash]', '[backslash]', '[quote]', '[plus]'),
  49. array('&', '/', '\\', '"', '+'),
  50. $sValue
  51. );
  52. }
  53. /*
  54. * functions for limiting maximal text length
  55. */
  56. function strmaxtextlen($sInput, $iMaxLen = 60, $sEllipsisSign = '&#8230;')
  57. {
  58. $sTail = '';
  59. $s = trim(strip_tags($sInput));
  60. if (mb_strlen($s) > $iMaxLen) {
  61. $s = mb_substr($s, 0, $iMaxLen);
  62. $sTail = $sEllipsisSign;
  63. }
  64. return htmlspecialchars_adv($s) . $sTail;
  65. }
  66. function html2txt($content, $tags = "")
  67. {
  68. while($content != strip_tags($content, $tags)) {
  69. $content = strip_tags($content, $tags);
  70. }
  71. return $content;
  72. }
  73. /**
  74. * Functions to process user input.
  75. * DON'T use to process data before passing to SQL query - use db prepare instead @see BxDolDb::prepare.
  76. * It is ok to use bx_process_input and then db prepare.
  77. * @param $mixedData data to process
  78. * @param $iDataType how to handle data, possible valies:
  79. * @code
  80. * BX_DATA_INT - integer value
  81. * BX_DATA_FLOAT - float values
  82. * BX_DATA_CHECKBOX - 'on' or empty string
  83. * BX_DATA_TEXT - text data, single line (default)
  84. * BX_DATA_TEXT_MULTILINE - text data, multiple lines
  85. * BX_DATA_HTML - HTML data
  86. * BX_DATA_DATE - date data type stored as yyyy-mm-dd
  87. * BX_DATA_DATETIME - date/time data type stored as yyyy-mm-dd hh:mm:ss
  88. * BX_DATA_DATE_TS' - date data type stored as unixtimestamp
  89. * BX_DATA_DATETIME_TS - date/time data type stored as unixtimestamp
  90. * BX_DATA_DATE_TS_UTC - date data type stored as unixtimestamp from UTC time
  91. * BX_DATA_DATETIME_TS_UTC - date/time data type stored as unixtimestamp from UTC time
  92. * @endcode
  93. * @param $mixedParams optional parameters to pass for validation
  94. * @param $isCheckMagicQuotes deprecated
  95. * @return the filtered data, or FALSE if the filter fails.
  96. */
  97. function bx_process_input ($mixedData, $iDataType = BX_DATA_TEXT, $mixedParams = false, $isCheckMagicQuotes = true)
  98. {
  99. if (is_array($mixedData)) {
  100. foreach ($mixedData as $k => $v)
  101. $mixedData[$k] = bx_process_input($v, $iDataType, $mixedParams);
  102. return $mixedData;
  103. }
  104. switch ($iDataType) {
  105. case BX_DATA_INT:
  106. return filter_var(trim($mixedData), FILTER_VALIDATE_INT);
  107. case BX_DATA_FLOAT:
  108. return filter_var(trim($mixedData), FILTER_VALIDATE_FLOAT);
  109. case BX_DATA_CHECKBOX:
  110. return 'on' == trim($mixedData) ? 'on' : '';
  111. case BX_DATA_DATE:
  112. // maybe consider using strtotime
  113. $mixedData = trim($mixedData);
  114. if (!preg_match('/^\d{4}-\d{1,2}-\d{1,2}$/', $mixedData))
  115. return false;
  116. list($iYear, $iMonth, $iDay) = explode('-', $mixedData); // 1985-10-28
  117. $iDay = intval($iDay);
  118. $iMonth = intval($iMonth);
  119. $iYear = intval($iYear);
  120. return sprintf("%04d-%02d-%02d", $iYear, $iMonth, $iDay);
  121. case BX_DATA_DATETIME:
  122. // maybe consider using strtotime
  123. $mixedData = trim($mixedData);
  124. if (!preg_match('#(\d+)\-(\d+)\-(\d+)[\sT]{1}(\d+):(\d+):(\d+)#', $mixedData, $m) && !preg_match('#(\d+)\-(\d+)\-(\d+)[\sT]{1}(\d+):(\d+)#', $mixedData, $m))
  125. return bx_process_input ($mixedData, BX_DATA_DATE, $mixedParams, $isCheckMagicQuotes);
  126. $iDay = intval($m[3]);
  127. $iMonth = intval($m[2]);
  128. $iYear = intval($m[1]);
  129. $iH = intval($m[4]);
  130. $iM = intval($m[5]);
  131. $iS = isset($m[6]) ? intval($m[6]) : 0;
  132. return sprintf("%04d-%02d-%02d %02d:%02d:%02d", $iYear, $iMonth, $iDay, $iH, $iM, $iS); // 1985-10-28 00:59:35
  133. case BX_DATA_DATE_TS:
  134. case BX_DATA_DATE_TS_UTC:
  135. $mixedData = trim($mixedData);
  136. if (!preg_match('/^\d{4}-\d{1,2}-\d{1,2}$/', $mixedData))
  137. return false;
  138. list($iYear, $iMonth, $iDay) = explode('-', $mixedData);
  139. $iDay = intval($iDay);
  140. $iMonth = intval($iMonth);
  141. $iYear = intval($iYear);
  142. $sFunc = BX_DATA_DATE_TS_UTC == $iDataType ? 'gmmktime' : 'mktime';
  143. $iRet = $sFunc (0, 0, 0, $iMonth, $iDay, $iYear);
  144. return $iRet > 0 ? $iRet : false;
  145. case BX_DATA_DATETIME_TS:
  146. case BX_DATA_DATETIME_TS_UTC:
  147. if (!preg_match('#(\d+)\-(\d+)\-(\d+)[\s]{1}(\d+):(\d+):(\d+)[\s]{1}([+\-\d:Z]+)#', $mixedData, $m) && !preg_match('#(\d+)\-(\d+)\-(\d+)[\sT]{1}(\d+):(\d+):(\d+)#', $mixedData, $m) && !preg_match('#(\d+)\-(\d+)\-(\d+)[\sT]{1}(\d+):(\d+)#', $mixedData, $m))
  148. return bx_process_input ($mixedData, BX_DATA_DATETIME_TS == $iDataType ? BX_DATA_DATE_TS : BX_DATA_DATE_TS_UTC, $mixedParams, $isCheckMagicQuotes);
  149. $iDay = $m[3];
  150. $iMonth = $m[2];
  151. $iYear = $m[1];
  152. $iH = $m[4];
  153. $iM = $m[5];
  154. $iS = isset($m[6]) ? $m[6] : 0;
  155. $iTimezoneOffset = 0;
  156. if (isset($m[7])) {
  157. $oTz = new DateTimeZone($m[7]);
  158. $oUtc = new DateTime(str_replace($m[7], '', $mixedData), new DateTimeZone('UTC'));
  159. if ($oTz && $oUtc)
  160. $iTimezoneOffset = $oTz->getOffset($oUtc);
  161. }
  162. $sFunc = BX_DATA_DATETIME_TS_UTC == $iDataType ? 'gmmktime' : 'mktime';
  163. $iRet = $sFunc ($iH, $iM, $iS, $iMonth, $iDay, $iYear) - $iTimezoneOffset;
  164. return $iRet > 0 ? $iRet : false;
  165. case BX_DATA_HTML:
  166. return clear_xss($mixedData);
  167. case BX_DATA_TEXT_MULTILINE:
  168. return nl2br(htmlspecialchars_adv($mixedData));
  169. case BX_DATA_TEXT:
  170. default:
  171. return $mixedData;
  172. }
  173. }
  174. /*
  175. * Functions to process user output.
  176. * Always use this function before output data which was entered by user before.
  177. * @param $mixedData string to process
  178. * @param $iDataType how to handle data, possible valies the same as in bx_process_input function, see bx_process_input.
  179. * @param $mixedParams optional parameters to pass for validation
  180. * @return the filtered data, or FALSE if the filter fails.
  181. */
  182. function bx_process_output ($mixedData, $iDataType = BX_DATA_TEXT, $mixedParams = false)
  183. {
  184. if (is_array($mixedData)) {
  185. foreach ($mixedData as $k => $v)
  186. $mixedData[$k] = bx_process_output($v, $iDataType, $mixedParams);
  187. return $mixedData;
  188. }
  189. switch ($iDataType) {
  190. case BX_DATA_INT:
  191. return filter_var($mixedData, FILTER_VALIDATE_INT);
  192. case BX_DATA_FLOAT:
  193. return filter_var($mixedData, FILTER_VALIDATE_FLOAT);
  194. case BX_DATA_CHECKBOX:
  195. return 'on' == trim($mixedData) ? 'on' : '';
  196. case BX_DATA_DATE:
  197. case BX_DATA_DATETIME:
  198. return $mixedData;
  199. case BX_DATA_DATE_TS:
  200. return empty($mixedData) ? '' : date("Y-m-d", (int)$mixedData);
  201. case BX_DATA_DATE_TS_UTC:
  202. return empty($mixedData) ? '' : gmdate("Y-m-d", (int)$mixedData);
  203. case BX_DATA_DATETIME_TS:
  204. return empty($mixedData) ? '' : date("Y-m-d H:i", (int)$mixedData);
  205. case BX_DATA_DATETIME_TS_UTC:
  206. return empty($mixedData) ? '' : gmdate("Y-m-d H:i", (int)$mixedData);
  207. case BX_DATA_HTML:
  208. $s = bx_linkify_html($mixedData, 'class="' . BX_DOL_LINK_CLASS . '"');
  209. return $mixedParams && is_array($mixedParams) && in_array('no_process_macro', $mixedParams) ? $s : bx_process_macros($s);
  210. case BX_DATA_TEXT_MULTILINE:
  211. $s = $mixedData;
  212. return $mixedParams && is_array($mixedParams) && in_array('no_process_macros', $mixedParams) ? $s : bx_process_macros($s);
  213. case BX_DATA_TEXT:
  214. default:
  215. $s = htmlspecialchars_adv($mixedData);
  216. return $mixedParams && is_array($mixedParams) && in_array('no_process_macros', $mixedParams) ? $s : bx_process_macros($s);
  217. }
  218. }
  219. function bx_is_macros_in_content (&$s)
  220. {
  221. return false === strpos($s, '{{~') ? false : true;
  222. }
  223. /**
  224. * This function converts macros upon text output.
  225. * Macros represents constructions like this:
  226. * @code
  227. * {{!module_name:function[param1, "param2"]}}
  228. * @endcode
  229. * For example, to display some content from module Posts:
  230. * @code
  231. * {{!bx_posts:get_search_result_unit[3]}}
  232. * @endcode
  233. * Only users which have "use macros" ACL action enabled can use this functionlity.
  234. *
  235. * @param $s text to process
  236. * @return modified or not modified text
  237. */
  238. function bx_process_macros ($s)
  239. {
  240. if (!bx_is_macros_in_content($s))
  241. return $s;
  242. return preg_replace_callback(
  243. "/{{\~(.*?)\~}}/",
  244. function ($aMatches) {
  245. return BxDolService::callMacro($aMatches[1]);
  246. },
  247. $s);
  248. }
  249. /*
  250. * This function apply bx_process_input and then bx_process_output.
  251. * Use this function to output data immediately after receiving, without saving to database.
  252. * Patams are the same as bx_process_input function - @see bx_process_input
  253. */
  254. function bx_process_pass ($mixedData, $iDataType = BX_DATA_TEXT, $mixedParams = false, $isCheckMagicQuotes = true)
  255. {
  256. return bx_process_output(bx_process_input ($mixedData, $iDataType, $mixedParams, $isCheckMagicQuotes), $iDataType, $mixedParams);
  257. }
  258. /**
  259. * DEPRECATED
  260. * use bx_process_input + bx_process_output instead
  261. * --------
  262. * function for processing pass data
  263. *
  264. * This function cleans the GET/POST/COOKIE data if magic_quotes_gpc() is on
  265. * for data which should be outputed immediately after submit
  266. */
  267. /*
  268. function process_pass_data( $text, $strip_tags = 0 )
  269. {
  270. if ( $strip_tags )
  271. $text = strip_tags($text);
  272. if ( !get_magic_quotes_gpc() )
  273. return $text;
  274. else
  275. return stripslashes($text);
  276. }
  277. */
  278. /*
  279. * function for output data from database into html
  280. */
  281. function htmlspecialchars_adv( $string )
  282. {
  283. return htmlspecialchars($string, ENT_COMPAT, 'UTF-8', false);
  284. }
  285. /**
  286. * Send mail to user by parsing email template
  287. */
  288. function sendMailTemplate($sTemplateName, $iAccountId = 0, $iProfileId = 0, $aReplaceVars = array(), $iEmailType = BX_EMAIL_NOTIFY, $bAddToQueue = false)
  289. {
  290. $oProfile = $iProfileId ? BxDolProfile::getInstance($iProfileId) : null;
  291. $oAccount = $iAccountId ? BxDolAccount::getInstance($iAccountId) : ($oProfile ? $oProfile->getAccountObject() : null);
  292. $oEmailTemplates = BxDolEmailTemplates::getInstance();
  293. if (!($oAccount || $oProfile) || !$oEmailTemplates)
  294. return false;
  295. $aTemplate = $oEmailTemplates->parseTemplate($sTemplateName, $aReplaceVars, $oAccount ? $oAccount->id() : 0, (int)$iProfileId);
  296. if (!$aTemplate)
  297. return false;
  298. return sendMail($oAccount->getEmail(), $aTemplate['Subject'], $aTemplate['Body'], 0, array(), $iEmailType, 'html', false, array(), $bAddToQueue);
  299. }
  300. /**
  301. * Send system email
  302. */
  303. function sendMailTemplateSystem($sTemplateName, $aReplaceVars = array(), $iEmailType = BX_EMAIL_SYSTEM, $bAddToQueue = false)
  304. {
  305. $oEmailTemplates = BxDolEmailTemplates::getInstance();
  306. if (!$oEmailTemplates)
  307. return false;
  308. $aTemplate = $oEmailTemplates->parseTemplate($sTemplateName, $aReplaceVars);
  309. if (!$aTemplate)
  310. return false;
  311. return sendMail(getParam('site_email'), $aTemplate['Subject'], $aTemplate['Body'], 0, array(), $iEmailType, 'html', false, array(), $bAddToQueue);
  312. }
  313. /**
  314. * Send email function
  315. *
  316. * @param $sRecipientEmail - Email where email should be send
  317. * @param $sMailSubject - subject of the message
  318. * @param $sMailBody - Body of the message
  319. * @param $iRecipientID - ID of recipient profile
  320. * @param $aPlus - Array of additional information
  321. * @param $iEmailType - email message type: BX_EMAIL_SYSTEM, BX_EMAIL_NOTIFY or BX_EMAIL_MASS
  322. * @param $sEmailFlag - use 'html' for HTML email message
  323. * @param $isDisableAlert - disable alert
  324. * @param $aCustomHeaders - custom email headers
  325. * @param $bAddToQueue - add message to email queue
  326. * @return true if message was send or false otherwise
  327. */
  328. function sendMail($sRecipientEmail, $sMailSubject, $sMailBody, $iRecipientID = 0, $aPlus = array(), $iEmailType = BX_EMAIL_NOTIFY, $sEmailFlag = 'html', $isDisableAlert = false, $aCustomHeaders = array(), $bAddToQueue = false)
  329. {
  330. // make sure that recipient's email is valid and message isn't empty
  331. if (!$sMailBody || !$sRecipientEmail || preg_match('/\(2\)$/', $sRecipientEmail))
  332. return false;
  333. // get recipient account
  334. $oAccount = !$isDisableAlert ? BxDolAccount::getInstance($sRecipientEmail) : null;
  335. $aAccountInfo = $oAccount ? $oAccount->getInfo() : false;
  336. // don't send bulk emails if user didn't subscribed to site news or email is unconfirmed
  337. if ($aAccountInfo && BX_EMAIL_MASS == $iEmailType && (!$aAccountInfo['email_confirmed'] || !$aAccountInfo['receive_news']))
  338. return false;
  339. // don't send email notifications if user didn't subscribed to notifications or email is unconfirmed
  340. if ($aAccountInfo && BX_EMAIL_NOTIFY == $iEmailType && (!$aAccountInfo['email_confirmed'] || !$aAccountInfo['receive_updates']))
  341. return false;
  342. if($bAddToQueue && BxDolQueueEmail::getInstance()->add($sRecipientEmail, $sMailSubject, $sMailBody, $iRecipientID, $aPlus, $iEmailType, $sEmailFlag, $isDisableAlert, $aCustomHeaders))
  343. return true;
  344. // if profile id is provided - get profile's info
  345. $aRecipientInfo = false;
  346. if ($iRecipientID) {
  347. $oProfile = BxDolProfile::getInstance($iRecipientID);
  348. if ($oProfile)
  349. $aRecipientInfo = $oProfile->getInfo();
  350. }
  351. // get site vars
  352. $sEmailNotify = !$isDisableAlert ? getParam('site_email_notify') : $sRecipientEmail;
  353. $sSiteTitle = !$isDisableAlert ? getParam('site_title') : 'UNA ' . BX_DOL_VERSION;
  354. // add unsubscribe link
  355. if (!$isDisableAlert && empty($aPlus['unsubscribe'])) {
  356. $aPlus['unsubscribe'] = '';
  357. if ($oAccount && (BX_EMAIL_MASS == $iEmailType || BX_EMAIL_NOTIFY == $iEmailType))
  358. $aPlus['unsubscribe'] = ($sLink = $oAccount->getUnsubscribeLink($iEmailType)) ? '<a href="' . BX_DOL_URL_ROOT . $sLink . '">' . _t('_sys_et_txt_unsubscribe') . '</a>' : '';
  359. }
  360. // parse template
  361. if ($aPlus || $iRecipientID || $oAccount) {
  362. if(!is_array($aPlus))
  363. $aPlus = array();
  364. $oEmailTemplates = BxDolEmailTemplates::getInstance();
  365. $sMailSubject = $oEmailTemplates->parseContent($sMailSubject, $aPlus, !$iRecipientID && $oAccount ? $oAccount->id() : 0, $iRecipientID);
  366. $sMailBody = $oEmailTemplates->parseContent($sMailBody, $aPlus, !$iRecipientID && $oAccount ? $oAccount->id() : 0, $iRecipientID);
  367. }
  368. // email message headers
  369. $sMailHeader = '';
  370. foreach ($aCustomHeaders as $sHeaderName => $sHeaderValue)
  371. $sMailHeader = "$sHeaderName: $sHeaderValue\r\n" . $sMailHeader;
  372. if (!isset($aCustomHeaders['From']))
  373. $sMailHeader = "From: =?UTF-8?B?" . base64_encode( $sSiteTitle ) . "?= <{$sEmailNotify}>";
  374. if (!isset($aCustomHeaders['MIME-Version']))
  375. $sMailHeader = "MIME-Version: 1.0\r\n" . $sMailHeader;
  376. $sMailParameters = isset($aCustomHeaders['Sender']) ? "-f{$aCustomHeaders['Sender']}" : "-f{$sEmailNotify}";
  377. if (isset($aCustomHeaders['Subject']))
  378. $sMailSubject = $aCustomHeaders['Subject'];
  379. // build data for alert handler
  380. $bResult = null;
  381. $aAlert = array(
  382. 'email' => $sRecipientEmail,
  383. 'subject' => $sMailSubject,
  384. 'body' => $sMailBody,
  385. 'header' => $sMailHeader,
  386. 'params' => $sMailParameters,
  387. 'recipient' => $aRecipientInfo,
  388. 'html' => 'html' == $sEmailFlag ? true : false,
  389. 'custom_headers' => $aCustomHeaders,
  390. 'override_result' => &$bResult,
  391. );
  392. // system alert
  393. if (!$isDisableAlert) {
  394. bx_alert('system', 'before_send_mail', (isset($aRecipientInfo['ID']) ? $aRecipientInfo['ID'] : 0), '', $aAlert);
  395. if ($bResult !== null)
  396. return $bResult;
  397. unset($aAlert['override_result']);
  398. }
  399. // prepare HTML/Plain message
  400. if($sEmailFlag == 'html')
  401. $sMailHeader = "Content-type: text/html; charset=UTF-8\r\n" . $sMailHeader;
  402. else {
  403. $sMailHeader = "Content-type: text/plain; charset=UTF-8\r\n" . $sMailHeader;
  404. $sMailBody = html2txt($sMailBody);
  405. }
  406. // encode subject
  407. if (0 !== strncasecmp($sMailSubject, '=?UTF-8?B?', 10))
  408. $sMailSubject = '=?UTF-8?B?' . base64_encode($sMailSubject) . '?=';
  409. // send mail or put it into queue
  410. $bResult = mail($sRecipientEmail, $sMailSubject, $sMailBody, $sMailHeader, $sMailParameters);
  411. // system alert
  412. if (!$isDisableAlert)
  413. bx_alert('system', 'send_mail', (isset($aRecipientInfo['ID']) ? $aRecipientInfo['ID'] : 0), '', $aAlert);
  414. return $bResult;
  415. }
  416. /*
  417. * Getting an array with Templates' Names
  418. */
  419. function get_templates_array($bEnabledOnly = true, $bShortInfo = true)
  420. {
  421. $oDb = BxDolDb::getInstance();
  422. $sWhereAddon = $bEnabledOnly ? " AND `enabled`='1'" : "";
  423. if($bShortInfo)
  424. return $oDb->getPairs("SELECT `uri`, `title` FROM `sys_modules` WHERE 1 AND `type`='" . BX_DOL_MODULE_TYPE_TEMPLATE . "'" . $sWhereAddon, "uri", "title");
  425. else
  426. return $oDb->getAllWithKey("SELECT * FROM `sys_modules` WHERE 1 AND `type`='" . BX_DOL_MODULE_TYPE_TEMPLATE . "'" . $sWhereAddon, "uri");
  427. }
  428. function bx_get_image_exif_and_size($oStorage, $oTranscoder, $iContentId){
  429. $sData = '';
  430. $sExif = '';
  431. $aExif = false;
  432. $aPhoto = $oStorage->getFile($iContentId);
  433. if ($oTranscoder->isMimeTypeSupported($aPhoto['mime_type'])) {
  434. $oImageReize = BxDolImageResize::getInstance();
  435. $a = $oImageReize->getImageSize($oTranscoder->getFileUrl($iContentId));
  436. $sData = isset($a['w']) && isset($a['h']) ? $a['w'] . 'x' . $a['h'] : '';
  437. if ($aExif = $oImageReize->getExifInfo($oStorage->getFileUrlById($iContentId))) {
  438. $a = array('Make', 'Model', 'FocalLength', 'ShutterSpeedValue', 'ExposureTime', 'ISOSpeedRatings', 'Orientation', 'Artist', 'Copyright', 'Flash', 'WhiteBalance', 'DateTimeOriginal', 'DateTimeDigitized', 'ExifVersion', 'COMPUTED', 'GPSLatitudeRef', 'GPSLatitude', 'GPSLongitudeRef', 'GPSLongitude', 'GPSAltitudeRef', 'GPSAltitude', 'GPSTimeStamp', 'GPSImgDirectionRef', 'GPSImgDirection', 'GPSDateStamp');
  439. $aExifFiltered = array();
  440. foreach ($a as $sIndex)
  441. if (isset($aExif[$sIndex]))
  442. $aExifFiltered[$sIndex] = $aExif[$sIndex];
  443. $sExif = serialize($aExifFiltered);
  444. }
  445. }
  446. return array('exif' => $sExif, 'size' => $sData);
  447. }
  448. function extFileExists( $sFileSrc )
  449. {
  450. return (file_exists( $sFileSrc ) && is_file( $sFileSrc )) ? true : false;
  451. }
  452. function getVisitorIP()
  453. {
  454. $ip = "0.0.0.0";
  455. if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  456. $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
  457. } elseif (isset( $_SERVER['HTTP_CLIENT_IP']) && !empty($_SERVER['HTTP_CLIENT_IP'])) {
  458. $ip = explode(".",$_SERVER['HTTP_CLIENT_IP']);
  459. $ip = $ip[3].".".$ip[2].".".$ip[1].".".$ip[0];
  460. } elseif (!isset( $_SERVER['HTTP_X_FORWARDED_FOR']) || empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  461. if (!isset( $_SERVER['HTTP_CLIENT_IP']) && empty($_SERVER['HTTP_CLIENT_IP']) && isset($_SERVER['REMOTE_ADDR']))
  462. $ip = $_SERVER['REMOTE_ADDR'];
  463. }
  464. return $ip;
  465. }
  466. function genFlag($sLang = '', $oTemplate = null)
  467. {
  468. if (!$oTemplate)
  469. $oTemplate = BxDolTemplate::getInstance();
  470. $oTemplate->addCss(BX_DIRECTORY_PATH_PLUGINS_PUBLIC . 'flag-icon-css/css/|flag-icon.min.css');
  471. $sFlag = BxDolLanguages::getInstance()->getLangFlag($sLang);
  472. return '<span title="' . $sFlag . '" class="flag-icon flag-icon-' . $sFlag . '"></span>';
  473. }
  474. // print debug information ( e.g. arrays )
  475. function echoDbg( $what, $desc = '' )
  476. {
  477. if ( $desc )
  478. echo "<b>$desc:</b> ";
  479. echo "<pre>";
  480. print_r( $what );
  481. echo "</pre>\n";
  482. }
  483. function echoDbgLog($mWhat, $sDesc = 'unused', $sFileName = 'unused')
  484. {
  485. bx_log('sys_debug', $mWhat);
  486. }
  487. function dbgTiming($sStartMicrotime)
  488. {
  489. $i1 = explode(' ', microtime ());
  490. $i2 = explode(' ', $sStartMicrotime);
  491. $iTime = ($i1[0]+$i1[1]) - ($i2[0]+$i2[1]);
  492. return round($iTime, 6) . ' sec';
  493. }
  494. function echoJson($a)
  495. {
  496. header('Content-type: text/html; charset=utf-8');
  497. echo json_encode($a);
  498. }
  499. function clear_xss($val)
  500. {
  501. // HTML Purifier plugin
  502. global $oHtmlPurifier;
  503. if (!isset($oHtmlPurifier) && !$GLOBALS['logged']['admin']) {
  504. HTMLPurifier_Bootstrap::registerAutoload();
  505. $oConfig = HTMLPurifier_Config::createDefault();
  506. $oConfig->set('Cache.SerializerPath', rtrim(BX_DIRECTORY_PATH_CACHE, '/'));
  507. $oConfig->set('Cache.SerializerPermissions', BX_DOL_DIR_RIGHTS);
  508. $oConfig->set('HTML.SafeObject', 'true');
  509. $oConfig->set('Output.FlashCompat', 'true');
  510. $oConfig->set('HTML.FlashAllowFullScreen', 'true');
  511. $oConfig->set('Attr.AllowedFrameTargets', array('_blank', '_self', '_parent', '_top'));
  512. if (getParam('sys_add_nofollow')) {
  513. $sHost = parse_url(BX_DOL_URL_ROOT, PHP_URL_HOST);
  514. $oConfig->set('URI.Host', $sHost);
  515. $oConfig->set('HTML.Nofollow', 'true');
  516. }
  517. $oConfig->set('Filter.Custom', array (
  518. new BxDolHTMLPurifierFilterYouTube(),
  519. new BxDolHTMLPurifierFilterYoutubeIframe(),
  520. new BxDolHTMLPurifierFilterAddBxLinksClass(),
  521. new BxDolHTMLPurifierFilterLocalIframe(),
  522. new BxDolHTMLPurifierFilterEmbed(),
  523. ));
  524. $oConfig->set('HTML.DefinitionID', 'html5-definitions');
  525. $oConfig->set('HTML.DefinitionRev', 1);
  526. if ($def = $oConfig->maybeGetRawHTMLDefinition()) {
  527. $def->addElement('section', 'Block', 'Flow', 'Common');
  528. $def->addElement('nav', 'Block', 'Flow', 'Common');
  529. $def->addElement('article', 'Block', 'Flow', 'Common');
  530. $def->addElement('aside', 'Block', 'Flow', 'Common');
  531. $def->addElement('header', 'Block', 'Flow', 'Common');
  532. $def->addElement('footer', 'Block', 'Flow', 'Common');
  533. $def->addElement('video', 'Block', 'Optional: (source, Flow) | (Flow, source) | Flow', 'Common', array(
  534. 'src' => 'URI',
  535. 'type' => 'Text',
  536. 'width' => 'Length',
  537. 'height' => 'Length',
  538. 'poster' => 'URI',
  539. 'preload' => 'Enum#auto,metadata,none',
  540. 'controls' => 'Bool',
  541. ));
  542. $def->addElement('source', 'Block', 'Flow', 'Common', array(
  543. 'src' => 'URI',
  544. 'type' => 'Text',
  545. ));
  546. $def->addAttribute('a', 'data-profile-id', 'Number');
  547. $def->addAttribute('div', 'source', 'Text');
  548. }
  549. $oHtmlPurifier = new HTMLPurifier($oConfig);
  550. }
  551. if (!$GLOBALS['logged']['admin'])
  552. $val = $oHtmlPurifier->purify($val);
  553. bx_alert('system', 'clear_xss', 0, 0, array('oHtmlPurifier' => $oHtmlPurifier, 'return_data' => &$val));
  554. return $val;
  555. }
  556. //--------------------------------------- friendly permalinks --------------------------------------//
  557. //------------------------------------------- main functions ---------------------------------------//
  558. function uriGenerate ($sValue, $sTable, $sField, $sEmpty = '-', $sDivider = '-', $aCond = [])
  559. {
  560. $sValue = uriFilter($sValue, $sEmpty, $sDivider);
  561. if(uriCheckUniq($sValue, $sTable, $sField, $aCond))
  562. return $sValue;
  563. // cut off redundant part
  564. if(get_mb_len($sValue) > 240)
  565. $sValue = get_mb_substr($sValue, 0, 240);
  566. // try to add number
  567. for($i = 0 ; $i < 999 ; ++$i) {
  568. $iRnd = mt_rand(1000, 9999);
  569. if(uriCheckUniq($sValue . $sDivider . $iRnd, $sTable, $sField, $aCond))
  570. return ($sValue . $sDivider . $iRnd);
  571. }
  572. return rand(0, PHP_INT_MAX);
  573. }
  574. function uriFilter ($s, $sEmpty = '-', $sDivider = '-')
  575. {
  576. if (BxTemplConfig::getInstance()->bAllowUnicodeInPreg)
  577. $s = get_mb_replace ('/[^\pL^\pN]+/u', $sDivider, $s); // unicode characters
  578. else
  579. $s = get_mb_replace ('/([^\d^\w]+)/u', $sDivider, $s); // latin characters only
  580. $s = get_mb_replace ('/([' . $sDivider . '^]+)/', $sDivider, $s);
  581. $s = get_mb_replace ('/([' . $sDivider . ']+)$/', '', $s); // remove trailing dash
  582. if (!$s) $s = $sEmpty;
  583. return mb_strtolower($s);
  584. }
  585. function uriCheckUniq ($sValue, $sTable, $sField, $aCond = [])
  586. {
  587. $oDb = BxDolDb::getInstance();
  588. $sWhere = $aCond ? $oDb->arrayToSQL($aCond, ' AND ') : '1';
  589. $sSql = $oDb->prepare("SELECT 1 FROM `$sTable` WHERE $sWhere AND `$sField`=? LIMIT 1", $sValue);
  590. return !$oDb->query($sSql);
  591. }
  592. function get_mb_replace ($sPattern, $sReplace, $s)
  593. {
  594. return preg_replace ($sPattern, $sReplace, $s);
  595. }
  596. function get_mb_len ($s)
  597. {
  598. return (function_exists('mb_strlen')) ? mb_strlen($s) : strlen($s);
  599. }
  600. function get_mb_substr ($s, $iStart, $iLen)
  601. {
  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. {
  606. return mb_substr($s, 0, $iPosStart) . $sReplace . mb_substr($s, $iPosStart + $iLength);
  607. }
  608. function bx_mb_strpos ($s, $sReplacement, $iStart = 0)
  609. {
  610. return mb_strpos($s, $sReplacement, $iStart);
  611. }
  612. /**
  613. * Import class file, it automatically detects class path by its prefix or module array/name
  614. *
  615. * @param $sClassName - full class name or class postfix(withoit prefix) in the case of module class
  616. * @param $mixedModule - module array or module name in the case of module class
  617. */
  618. function bx_import($sClassName, $mixedModule = array())
  619. {
  620. if (class_exists($sClassName, false))
  621. return;
  622. $aModule = false;
  623. if ($mixedModule) {
  624. if (is_array($mixedModule)) {
  625. $aModule = $mixedModule;
  626. } elseif (is_string($mixedModule)) {
  627. $o = BxDolModule::getInstance($mixedModule);
  628. $aModule = $o->_aModule;
  629. } elseif (is_bool($mixedModule) && true === $mixedModule) {
  630. $aModule = $GLOBALS['aModule'];
  631. }
  632. }
  633. if ($aModule) {
  634. if (class_exists($aModule['class_prefix'] . $sClassName, false))
  635. return;
  636. require_once (BX_DIRECTORY_PATH_MODULES . $aModule['path'] . 'classes/' . $aModule['class_prefix'] . $sClassName . '.php');
  637. return;
  638. }
  639. if (0 === strncmp($sClassName, 'BxDol', 5)) {
  640. if (0 === strncmp($sClassName, 'BxDolStudio', 11))
  641. require_once(BX_DOL_DIR_STUDIO_CLASSES . $sClassName . '.php');
  642. else
  643. require_once(BX_DIRECTORY_PATH_CLASSES . $sClassName . '.php');
  644. return;
  645. }
  646. if (0 === strncmp($sClassName, 'BxBase', 6)) {
  647. if (0 === strncmp($sClassName, 'BxBaseMod', 9)) {
  648. $aMatches = array();
  649. if (preg_match('/BxBaseMod([A-Z][a-z]+)/', $sClassName, $aMatches)) {
  650. require_once(BX_DIRECTORY_PATH_MODULES . 'base/' . strtolower($aMatches[1]) . '/classes/' . $sClassName . '.php');
  651. return;
  652. }
  653. } if (0 === strncmp($sClassName, 'BxBaseStudio', 12)) {
  654. require_once(BX_DOL_DIR_STUDIO_BASE . 'scripts/' . $sClassName . '.php');
  655. return;
  656. } else {
  657. require_once(BX_DIRECTORY_PATH_BASE . 'scripts/' . $sClassName . '.php');
  658. return;
  659. }
  660. }
  661. if (0 === strncmp($sClassName, 'BxTempl', 7)) {
  662. if(0 === strncmp($sClassName, 'BxTemplStudio', 13)) {
  663. $sPath = BX_DIRECTORY_PATH_MODULES . BxDolStudioTemplate::getInstance()->getPath() . 'data/template/studio/scripts/' . $sClassName . '.php';
  664. if (!file_exists($sPath))
  665. $sPath = BX_DOL_DIR_STUDIO_BASE . 'scripts_templ/' . $sClassName . '.php';
  666. } else {
  667. $sPath = BX_DIRECTORY_PATH_MODULES . BxDolTemplate::getInstance()->getPath() . 'data/template/system/scripts/' . $sClassName . '.php';
  668. }
  669. if (file_exists($sPath)) {
  670. require_once($sPath);
  671. return;
  672. }
  673. trigger_error ("bx_import fatal error: class (" . $sClassName . ") wasn't found", E_USER_ERROR);
  674. }
  675. }
  676. /**
  677. * used in spl_autoload_register() function, so no need to call bx_import for system classes
  678. */
  679. function bx_autoload($sClassName)
  680. {
  681. if (0 === strncmp($sClassName, 'BxDol', 5) || 0 === strncmp($sClassName, 'BxBase', 6) || 0 === strncmp($sClassName, 'BxTempl', 7))
  682. bx_import($sClassName);
  683. }
  684. /**
  685. * Gets an instance of class pathing necessary parameters if it's necessary.
  686. *
  687. * @param string $sClassName class name.
  688. * @param array $aParams an array of parameters to be pathed to the constructor of the class.
  689. * @param array $mixedModule an array with module description. Is used when the requested class is located in some module.
  690. * @return unknown
  691. */
  692. function bx_instance($sClassName, $aParams = array(), $mixedModule = array())
  693. {
  694. if(isset($GLOBALS['bxDolClasses'][$sClassName]))
  695. return $GLOBALS['bxDolClasses'][$sClassName];
  696. if ($mixedModule) {
  697. if (!is_array($mixedModule)) {
  698. $o = BxDolModule::getInstance($mixedModule);
  699. $mixedModule = $o->_aModule;
  700. }
  701. $sClassName = bx_ltrim_str($sClassName, $mixedModule['class_prefix']);
  702. bx_import($sClassName, $mixedModule);
  703. $sClassName = $mixedModule['class_prefix'] . $sClassName;
  704. }
  705. $oClass = new ReflectionClass($sClassName);
  706. $GLOBALS['bxDolClasses'][$sClassName] = empty($aParams) ? $oClass->newInstance() : $oClass->newInstanceArgs($aParams);
  707. return $GLOBALS['bxDolClasses'][$sClassName];
  708. }
  709. /**
  710. * Escapes string/array ready to pass to js script with filtered symbols like ', " etc
  711. *
  712. * @param $mixedInput - string/array which should be filtered
  713. * @param $iQuoteType - string escaping method: BX_ESCAPE_STR_AUTO(default), BX_ESCAPE_STR_APOS or BX_ESCAPE_STR_QUOTE
  714. * @return converted string / array
  715. */
  716. function bx_js_string ($mixedInput, $iQuoteType = BX_ESCAPE_STR_AUTO)
  717. {
  718. $aUnits = array(
  719. "\n" => "\\n",
  720. "\r" => "",
  721. );
  722. if (BX_ESCAPE_STR_APOS == $iQuoteType) {
  723. $aUnits["'"] = "\\'";
  724. $aUnits['<script'] = "<scr' + 'ipt";
  725. $aUnits['</script>'] = "</scr' + 'ipt>";
  726. } elseif (BX_ESCAPE_STR_QUOTE == $iQuoteType) {
  727. $aUnits['"'] = '\\"';
  728. $aUnits['<script'] = '<scr" + "ipt';
  729. $aUnits['</script>'] = '</scr" + "ipt>';
  730. } else {
  731. $aUnits['"'] = '&quot;';
  732. $aUnits["'"] = '&apos;';
  733. $aUnits["<script>"] = '&lt;script&gt;';
  734. $aUnits["</script>"] = '&lt;/script&gt;';
  735. }
  736. return str_replace(array_keys($aUnits), array_values($aUnits), $mixedInput);
  737. }
  738. /**
  739. * Return input string/array ready to pass to html attribute with filtered symbols like ', " etc
  740. *
  741. * @param $mixedInput - string/array which should be filtered
  742. * @param $iQuoteType - string escaping BX_ESCAPE_STR_AUTO, BX_ESCAPE_STR_APOS or BX_ESCAPE_STR_QUOTE
  743. * @return converted string / array
  744. */
  745. function bx_html_attribute ($mixedInput, $iQuoteType = BX_ESCAPE_STR_AUTO)
  746. {
  747. $aUnits = array ();
  748. if (BX_ESCAPE_STR_APOS == $iQuoteType)
  749. $aUnits["'"] = "\\'";
  750. elseif (BX_ESCAPE_STR_QUOTE == $iQuoteType)
  751. $aUnits['"'] = '&quot;';
  752. else
  753. $aUnits = array("\"" => "&quot;", "'" => "&apos;");
  754. return str_replace(array_keys($aUnits), array_values($aUnits), $mixedInput);
  755. }
  756. /**
  757. * Escapes string/array ready to pass to php script with filtered symbols like ', " etc
  758. *
  759. * @param mixed $mixedInput - string/array which should be filtered
  760. * @return converted string / array
  761. */
  762. function bx_php_string_apos ($mixedInput)
  763. {
  764. return str_replace("'", "\\'", $mixedInput);
  765. }
  766. function bx_php_string_quot ($mixedInput)
  767. {
  768. return str_replace('"', '\\"', $mixedInput);
  769. }
  770. /**
  771. * Gets file contents by URL.
  772. *
  773. * @param string $sFileUrl - file URL to be read.
  774. * @param array $aParams - an array of parameters to be pathed with URL.
  775. * @param string $sMethod - post or get.
  776. * @param array $aHeaders - custom headers.
  777. * @param string $sHttpCode - HTTP code to return
  778. * @param array $aBasicAuth - array with 'user' and 'password' for Basic HTTP Auth
  779. * @return string the file's contents.
  780. */
  781. function bx_file_get_contents($sFileUrl, $aParams = array(), $sMethod = 'get', $aHeaders = array(), &$sHttpCode = null, $aBasicAuth = array(), $iTimeout = 0, $aCustomCurlParams = array())
  782. {
  783. if ('post' != $sMethod && 'post-json' != $sMethod)
  784. $sFileUrl = bx_append_url_params($sFileUrl, $aParams);
  785. $sResult = '';
  786. if(function_exists('curl_init')) {
  787. $rConnect = curl_init();
  788. curl_setopt($rConnect, CURLOPT_USERAGENT, 'UNA ' . (defined('BX_DOL_VERSION') ? constant('BX_DOL_VERSION') : ''));
  789. curl_setopt($rConnect, CURLOPT_TIMEOUT, BxDolDb::getInstance() ? getParam('sys_default_curl_timeout') : 10);
  790. curl_setopt($rConnect, CURLOPT_URL, $sFileUrl);
  791. curl_setopt($rConnect, CURLOPT_HEADER, NULL === $sHttpCode ? false : true);
  792. curl_setopt($rConnect, CURLOPT_RETURNTRANSFER, 1);
  793. if (0 !== $iTimeout) {
  794. curl_setopt($rConnect, CURLOPT_CONNECTTIMEOUT, $iTimeout);
  795. curl_setopt($rConnect, CURLOPT_TIMEOUT, $iTimeout);
  796. }
  797. if(getParam('curl_ssl_allow_untrusted') == 'on'){
  798. curl_setopt($rConnect, CURLOPT_SSL_VERIFYPEER, false);
  799. curl_setopt($rConnect, CURLOPT_SSL_VERIFYHOST, false);
  800. }
  801. if (!ini_get('open_basedir'))
  802. curl_setopt($rConnect, CURLOPT_FOLLOWLOCATION, 1);
  803. if ($aBasicAuth)
  804. curl_setopt($rConnect, CURLOPT_USERPWD, $aBasicAuth['user'] . ':' . $aBasicAuth['password']);
  805. if ('post' == $sMethod) {
  806. curl_setopt($rConnect, CURLOPT_POST, true);
  807. curl_setopt($rConnect, CURLOPT_POSTFIELDS, http_build_query($aParams));
  808. }
  809. elseif ('post-json' == $sMethod) {
  810. curl_setopt($rConnect, CURLOPT_POST, true);
  811. curl_setopt($rConnect, CURLOPT_POSTFIELDS, json_encode($aParams));
  812. $aHeaders[] = 'Content-Type: application/json';
  813. }
  814. if ($aHeaders)
  815. curl_setopt($rConnect, CURLOPT_HTTPHEADER, $aHeaders);
  816. $sAllCookies = '';
  817. foreach($_COOKIE as $sKey => $mValue){
  818. if(is_array($mValue)){
  819. foreach ($mValue as $k => $v)
  820. $sAllCookies .= "{$sKey}[{$k}]={$v};";
  821. }
  822. else{
  823. $sAllCookies .= $sKey . '=' . $mValue . ';';
  824. }
  825. }
  826. curl_setopt($rConnect, CURLOPT_COOKIE, $sAllCookies);
  827. if ($aCustomCurlParams)
  828. foreach ($aCustomCurlParams as $sName => $mixedValue)
  829. curl_setopt($rConnect, $sName, $mixedValue);
  830. $sResult = curl_exec($rConnect);
  831. if (curl_errno($rConnect) == 60) { // CURLE_SSL_CACERT
  832. curl_setopt($rConnect, CURLOPT_CAINFO, BX_DIRECTORY_PATH_PLUGINS . 'curl/cacert/cacert.pem');
  833. $sResult = curl_exec($rConnect);
  834. }
  835. if (NULL !== $sHttpCode)
  836. $sHttpCode = curl_getinfo($rConnect, CURLINFO_HTTP_CODE);
  837. curl_close($rConnect);
  838. }
  839. else {
  840. $iSaveTimeout = false;
  841. if (0 !== $iTimeout) {
  842. $iSaveTimeout = ini_get('default_socket_timeout');
  843. ini_set('default_socket_timeout', $iTimeout);
  844. }
  845. $sResult = @file_get_contents($sFileUrl);
  846. if (0 !== $iTimeout && false !== $iSaveTimeout) {
  847. ini_set('default_socket_timeout', $iSaveTimeout);
  848. }
  849. }
  850. return $sResult;
  851. }
  852. function bx_get_site_info($sSourceUrl, $aProcessAdditionalTags = array())
  853. {
  854. $aResult = array();
  855. $sContent = bx_file_get_contents($sSourceUrl);
  856. if ($sContent) {
  857. $sCharset = '';
  858. preg_match("/<meta.+charset=([A-Za-z0-9-]+).+>/i", $sContent, $aMatch);
  859. if (isset($aMatch[1]))
  860. $sCharset = $aMatch[1];
  861. $sContent = preg_replace("/<script[^>]*>(.*?)<\/script>/i", '', $sContent);
  862. $sContent = preg_replace("/<style[^>]*>(.*?)<\/style>/i", '', $sContent);
  863. if (preg_match("/<title[^>]*>(.*?)<\/title>/i", $sContent, $aMatch))
  864. $aResult['title'] = strip_tags($aMatch[1]);
  865. else
  866. $aResult['title'] = parse_url($sSourceUrl, PHP_URL_HOST);
  867. $aResult['description'] = bx_parse_html_tag($sContent, 'meta', 'name', 'description', 'content', $sCharset);
  868. $aResult['keywords'] = bx_parse_html_tag($sContent, 'meta', 'name', 'keywords', 'content', $sCharset);
  869. if ($aProcessAdditionalTags) {
  870. foreach ($aProcessAdditionalTags as $k => $a) {
  871. $aResult[$k] = bx_parse_html_tag(
  872. $sContent,
  873. isset($a['tag']) ? $a['tag'] : 'meta',
  874. isset($a['name_attr']) ? $a['name_attr'] : 'itemprop',
  875. isset($a['name']) ? $a['name'] : $k,
  876. isset($a['content_attr']) ? $a['content_attr'] : 'content',
  877. $sCharset,
  878. isset($a['specialchars_decode']) ? $a['specialchars_decode'] : true);
  879. if ((isset($a['name']) && 'og:image' == $a['name']) || (isset($a['tag']) && 'link' == $a['tag'])) {
  880. $aResult[$k] = bx_get_site_info_fix_relative_url ($sSourceUrl, $aResult[$k]);
  881. }
  882. }
  883. }
  884. }
  885. return $aResult;
  886. }
  887. /**
  888. * Fix relative URL to make it absolute
  889. * @param $sSourceUrl main URL
  890. * @param $s URL to fix
  891. * @return absolute URL or URL wothout changes
  892. */
  893. function bx_get_site_info_fix_relative_url ($sSourceUrl, $s)
  894. {
  895. if (0 === stripos($s, 'http://') || 0 === stripos($s, 'https://') || 0 === stripos($s, 'ftp://') || !$s)
  896. return $s;
  897. if ('/' == $s[0]) {
  898. $a = parse_url($sSourceUrl);
  899. return $a['scheme'] . '://' . $a['host'] . (empty($a['port']) || 80 == $a['port'] || 443 == $a['port'] ? '' : ':' . $a['port']) . $s;
  900. }
  901. return $sSourceUrl . ('/' === substr($sSourceUrl, -1) ? $s : '/' . $s);
  902. }
  903. function bx_parse_html_tag ($sContent, $sTag, $sAttrNameName, $sAttrNameValue, $sAttrContentName, $sCharset = false, $bSpecialCharsDecode = true)
  904. {
  905. if (!preg_match("/<{$sTag}\s+{$sAttrNameName}[='\" ]+{$sAttrNameValue}['\"]\s+{$sAttrContentName}[='\" ]+([^'>\"]*)['\"][^>]*>/i", $sContent, $aMatch) || !isset($aMatch[1]))
  906. preg_match("/<{$sTag}\s+{$sAttrContentName}[='\" ]+([^'>\"]*)['\"]\s+{$sAttrNameName}[='\" ]+{$sAttrNameValue}['\"][^>]*>/i", $sContent, $aMatch);
  907. $s = isset($aMatch[1]) ? $aMatch[1] : '';
  908. if ($s && $sCharset)
  909. $s = mb_convert_encoding($s, 'UTF-8', $sCharset);
  910. if ($bSpecialCharsDecode)
  911. $s = htmlspecialchars_decode($s);
  912. return $s;
  913. }
  914. // calculation ini_get('upload_max_filesize') in bytes as example
  915. function return_bytes($val)
  916. {
  917. $val = trim($val);
  918. $last = strtolower($val[strlen($val)-1]);
  919. $val = (int)$val;
  920. switch($last) {
  921. // The 'G' modifier is available since PHP 5.1.0
  922. case 'k':
  923. $val *= 1024;
  924. break;
  925. case 'm':
  926. $val *= 1024 * 1024;
  927. break;
  928. case 'g':
  929. $val *= 1024 * 1024 * 1024;
  930. break;
  931. }
  932. return $val;
  933. }
  934. // Generate Random Password
  935. function genRndPwd($iLength = 8, $bSpecialCharacters = true)
  936. {
  937. $sPassword = '';
  938. $sChars = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
  939. if($bSpecialCharacters === true)
  940. $sChars .= "!?=/&+,.";
  941. for($i = 0; $i < $iLength; $i++) {
  942. $x = mt_rand(0, strlen($sChars) -1);
  943. $sPassword .= $sChars[$x];
  944. }
  945. return $sPassword;
  946. }
  947. // Generate Random Salt for Password encryption
  948. function genRndSalt()
  949. {
  950. return genRndPwd(8, true);
  951. }
  952. /**
  953. * Encrypt user password.
  954. * When BX_PWD_ALGO is 'custom', then bx_custom_pwd_encrypt function with custom algorythm must be defined in inc/header.inc.php file.
  955. * @param $sPwd clear password
  956. * @param $sSalt salt
  957. * @return password hash
  958. */
  959. function encryptUserPwd($sPwd, $sSalt)
  960. {
  961. $sAlgo = defined('BX_PWD_ALGO') ? BX_PWD_ALGO : '';
  962. switch ($sAlgo) {
  963. case 'custom':
  964. return bx_custom_pwd_encrypt($sPwd, $sSalt);
  965. case 'crypt':
  966. return crypt($sPwd, BX_PWD_ALGO_SALT);
  967. case 'sha1_crypt_salt':
  968. return sha1(crypt($sPwd, BX_PWD_ALGO_SALT) . $sSalt);
  969. case 'sha1_md5_salt':
  970. default:
  971. return sha1(md5($sPwd) . $sSalt);
  972. }
  973. }
  974. /**
  975. * Hash profile ID
  976. */
  977. function encryptUserId($sId)
  978. {
  979. if (!($oProfile = BxDolProfile::getInstance($sId)))
  980. return false;
  981. if (!($oAccount = $oProfile->getAccountObject()))
  982. return false;
  983. $aAccountInfo = $oAccount->getInfo();
  984. return sha1(md5($sId) . md5($aAccountInfo['salt']) . BX_DOL_SECRET);
  985. }
  986. function bx_get_reset_password_key($sValue, $sField = 'email', $iLifetime = 0)
  987. {
  988. if(empty($iLifetime)) {
  989. $iLifetime = (int)getParam('sys_account_reset_password_key_lifetime');
  990. if(empty($iLifetime))
  991. $iLifetime = 86400;
  992. }
  993. $oKey = BxDolKey::getInstance();
  994. if(!$oKey)
  995. return false;
  996. return $oKey->getNewKey(array($sField => $sValue), $iLifetime);
  997. }
  998. function bx_get_reset_password_link($sValue, $sField = 'email', $iLifetime = 0)
  999. {
  1000. $sKey = bx_get_reset_password_key($sValue, $sField, $iLifetime);
  1001. if(!$sKey)
  1002. return false;
  1003. return bx_get_reset_password_link_by_key($sKey);
  1004. }
  1005. function bx_get_reset_password_link_by_key($sKey)
  1006. {
  1007. return BX_DOL_URL_ROOT . BxDolPermalinks::getInstance()->permalink('page.php?i=forgot-password', array('key' => $sKey));
  1008. }
  1009. function bx_get_reset_password_redirect($iAccountId)
  1010. {
  1011. $sResult = '';
  1012. $sRedirect = getParam('sys_account_reset_password_redirect');
  1013. switch($sRedirect) {
  1014. case 'home':
  1015. $sResult = BxDolPermalinks::getInstance()->permalink('page.php?i=home');
  1016. break;
  1017. case 'profile':
  1018. case 'profile_edit':
  1019. if(empty($iAccountId))
  1020. break;
  1021. $oAccount = BxDolAccount::getInstance($iAccountId);
  1022. if(!$oAccount)
  1023. break;
  1024. $aAccountInfo = $oAccount->getInfo();
  1025. if(empty($aAccountInfo) || !is_array($aAccountInfo) || empty($aAccountInfo['profile_id']))
  1026. break;
  1027. $oProfile = BxDolProfile::getInstance((int)$aAccountInfo['profile_id']);
  1028. if(!$oProfile)
  1029. break;
  1030. $sResult = $oProfile->{'get' . ($sRedirect == 'profile_edit' ? 'Edit' : '') . 'Url'}();
  1031. break;
  1032. case 'custom':
  1033. $sResult = getParam('sys_account_reset_password_redirect_custom');
  1034. break;
  1035. }
  1036. if(!empty($sResult) && mb_stripos($sResult, BX_DOL_URL_ROOT) !== 0)
  1037. $sResult = BX_DOL_URL_ROOT . $sResult;
  1038. return $sResult;
  1039. }
  1040. function bx_get ($sName, $sMethod = false)
  1041. {
  1042. if (isset($_GET[$sName]) && ('get' == $sMethod || !$sMethod))
  1043. return $_GET[$sName];
  1044. elseif (isset($_POST[$sName]) && ('post' == $sMethod || !$sMethod))
  1045. return $_POST[$sName];
  1046. else
  1047. return false;
  1048. }
  1049. function bx_set ($sName, $sValue, $sMethod = false)
  1050. {
  1051. if(!$sMethod)
  1052. $sMethod = 'get';
  1053. $bResult = true;
  1054. switch($sMethod) {
  1055. case 'get':
  1056. $_GET[$sName] = $sValue;
  1057. break;
  1058. case 'post':
  1059. $_POST[$sName] = $sValue;
  1060. break;
  1061. default:
  1062. $bResult = false;
  1063. }
  1064. return $bResult;
  1065. }
  1066. function bx_get_with_prefix ($sPrefix, $sMethod = false)
  1067. {
  1068. $aSources = array('get' => &$_GET, 'post' => &$_POST);
  1069. $aFiltered = array();
  1070. foreach($aSources as $sName => $aSource)
  1071. if($sMethod == $sName || !$sMethod)
  1072. $aFiltered = array_merge($aFiltered, array_filter($aSource, function($sKey) use ($sPrefix) {
  1073. return strpos($sKey, $sPrefix) === 0;
  1074. }, ARRAY_FILTER_USE_KEY));
  1075. $aUpdated = array();
  1076. array_walk($aFiltered, function($sValue, $sKey) use ($sPrefix, &$aUpdated) {
  1077. $aUpdated[trim(str_replace($sPrefix, '', $sKey), '_-')] = $sValue;
  1078. });
  1079. return $aUpdated;
  1080. }
  1081. function bx_get_base_url_inline($aParams = array())
  1082. {
  1083. $aBaseLink = parse_url(BX_DOL_URL_ROOT);
  1084. $sPageLink = (!empty($aBaseLink['scheme']) ? $aBaseLink['scheme'] : 'http') . '://' . $aBaseLink['host'] . (!empty($aBaseLink['port']) ? ':' . $aBaseLink['port'] : '');
  1085. if(!empty($_SERVER['REQUEST_URI']))
  1086. $sPageLink .= $_SERVER['REQUEST_URI'];
  1087. list($sPageLink, $aPageParams) = bx_get_base_url($sPageLink);
  1088. if(!empty($_SERVER['QUERY_STRING'])) {
  1089. $aPageParamsAdd = array();
  1090. parse_str($_SERVER['QUERY_STRING'], $aPageParamsAdd);
  1091. if(!empty($aPageParamsAdd) && is_array($aPageParamsAdd))
  1092. $aPageParams = array_merge($aPageParams, $aPageParamsAdd);
  1093. }
  1094. if(!empty($aParams) && is_array($aParams))
  1095. $aPageParams = array_merge($aPageParams, $aParams);
  1096. return array($sPageLink, $aPageParams);
  1097. }
  1098. function bx_get_base_url_popup($aParams = array())
  1099. {
  1100. list($sPageLink, $aPageParams) = bx_get_base_url($_SERVER['HTTP_REFERER']);
  1101. if(!empty($aParams) && is_array($aParams))
  1102. $aPageParams = array_merge($aPageParams, $aParams);
  1103. return array($sPageLink, $aPageParams);
  1104. }
  1105. function bx_get_base_url($sPageLink)
  1106. {
  1107. $sPageLink = BxDolPermalinks::getInstance()->unpermalink($sPageLink, false);
  1108. $sPageParams = '';
  1109. if(strpos($sPageLink, '?') !== false)
  1110. list($sPageLink, $sPageParams) = explode('?', $sPageLink);
  1111. $aPageParams = array();
  1112. if(!empty($sPageParams))
  1113. parse_str($sPageParams, $aPageParams);
  1114. return array($sPageLink, $aPageParams);
  1115. }
  1116. function bx_get_location_bounds_latlng($fLatitude, $fLongitude, $iRadiusInKm)
  1117. {
  1118. $fEquatorLatInKm = 111.321;
  1119. $aRv = array();
  1120. $aRv['max_lat'] = $fLatitude + $iRadiusInKm / $fEquatorLatInKm;
  1121. $aRv['min_lat'] = $fLatitude - ($aRv['max_lat'] - $fLatitude);
  1122. $aRv['max_lng'] = $fLongitude + $iRadiusInKm / (cos($aRv['min_lat'] * M_PI / 180) * $fEquatorLatInKm);
  1123. $aRv['min_lng'] = $fLongitude - ($aRv['max_lng'] - $fLongitude);
  1124. return $aRv;
  1125. }
  1126. function bx_encode_url_params ($a, $aExcludeKeys = array (), $aOnlyKeys = false)
  1127. {
  1128. $s = '';
  1129. foreach ($a as $sKey => $sVal) {
  1130. if (in_array($sKey, $aExcludeKeys))
  1131. continue;
  1132. if (false !== $aOnlyKeys && !in_array($sKey, $aOnlyKeys))
  1133. continue;
  1134. if (is_array($sVal)) {
  1135. foreach ($sVal as $sSubVal) {
  1136. $s .= rawurlencode($sKey) . '[]=' . rawurlencode(is_array($sSubVal) ? 'array' : $sSubVal) . '&';
  1137. }
  1138. } else {
  1139. $s .= rawurlencode($sKey) . '=' . rawurlencode($sVal) . '&';
  1140. }
  1141. }
  1142. return $s;
  1143. }
  1144. function bx_append_url_params ($sUrl, $mixedParams)
  1145. {
  1146. if (!$mixedParams)
  1147. return $sUrl;
  1148. $sParams = false === strpos($sUrl, '?') ? '?' : '&';
  1149. if (is_array($mixedParams)) {
  1150. foreach($mixedParams as $sKey => $sValue) {
  1151. if (!is_array($sValue)) {
  1152. $sParams .= $sKey . '=' . $sValue . '&';
  1153. }
  1154. else {
  1155. foreach($sValue as $sSubValue)
  1156. $sParams .= $sKey . '[]=' . $sSubValue . '&';
  1157. }
  1158. }
  1159. $sParams = substr($sParams, 0, -1);
  1160. } else {
  1161. $sParams .= $mixedParams;
  1162. }
  1163. return $sUrl . $sParams;
  1164. }
  1165. function bx_rrmdir($directory)
  1166. {
  1167. if (substr($directory,-1) == "/")
  1168. $directory = substr($directory,0,-1);
  1169. if (!file_exists($directory) || !is_dir($directory))
  1170. return false;
  1171. elseif (!is_readable($directory))
  1172. return false;
  1173. if (!($directoryHandle = opendir($directory)))
  1174. return false;
  1175. while ($contents = readdir($directoryHandle)) {
  1176. if ($contents != '.' && $contents != '..') {
  1177. $path = $directory . "/" . $contents;
  1178. if (is_dir($path))
  1179. bx_rrmdir($path);
  1180. else
  1181. unlink($path);
  1182. }
  1183. }
  1184. closedir($directoryHandle);
  1185. if (!rmdir($directory))
  1186. return false;
  1187. return true;
  1188. }
  1189. function bx_clear_folder ($sPath, $aExts = array ())
  1190. {
  1191. if (substr($$sPath,-1) == "/")
  1192. $sPath = substr($sPath,0,-1);
  1193. if (!file_exists($sPath) || !is_dir($sPath))
  1194. return false;
  1195. elseif (!is_readable($sPath))
  1196. return false;
  1197. if (!($h = opendir($sPath)))
  1198. return false;
  1199. while ($sFile = readdir($h)) {
  1200. if ('.' == $sFile || '..' == $sFile)
  1201. continue;
  1202. $sFullPath = $sPath . '/' . $sFile;
  1203. if (is_dir($sFullPath))
  1204. continue;
  1205. if (!$aExts || (($sExt = pathinfo($sFullPath, PATHINFO_EXTENSION)) && in_array($sExt, $aExts)))
  1206. @unlink($sFullPath);
  1207. }
  1208. closedir($h);
  1209. return true;
  1210. }
  1211. function bx_ltrim_str ($sString, $sPrefix, $sReplace = '')
  1212. {
  1213. if ($sReplace && substr($sString, 0, strlen($sReplace)) == $sReplace)
  1214. return $sString;
  1215. if (substr($sString, 0, strlen($sPrefix)) == $sPrefix)
  1216. return $sReplace . substr($sString, strlen($sPrefix));
  1217. return $sString;
  1218. }
  1219. function bx_rtrim_str ($sString, $sPrefix, $sReplace = '')
  1220. {
  1221. if ($sReplace && substr($sString, -strlen($sReplace)) == $sReplace)
  1222. return $sString;
  1223. if (substr($sString, -strlen($sPrefix)) == $sPrefix)
  1224. return substr($sString, 0, -strlen($sPrefix)) . $sReplace;
  1225. return $sString;
  1226. }
  1227. /**
  1228. * Strip all lines with no information for example: <p></p>, <br /><br />
  1229. */
  1230. function bx_trim_nl_duplicates($s)
  1231. {
  1232. $sStrip = implode('', array_keys(get_html_translation_table(HTML_ENTITIES)));
  1233. return implode('', array_filter(mb_split("[\n\r]", $s), function($s) use ($sStrip) {
  1234. return trim(strip_tags($s, '<button><canvas><embed><hr><iframe><img><input><object><select><svg><video>'), $sStrip) !== '';
  1235. }));
  1236. }
  1237. /**
  1238. * Convert array to attributes string
  1239. *
  1240. * Example:
  1241. * @code
  1242. * $a = array('name' => 'test', 'value' => 5);
  1243. * $s = bx_convert_array2attrs($a);
  1244. * echo $s; // outputs: name="test" value="5"
  1245. * @endcode
  1246. *
  1247. * @param $a - array of attributes
  1248. * @param $sClasses - classes to merge with 'class' attribute
  1249. * @param $sStyles - styles to merge with 'style' attribute
  1250. * @return string
  1251. */
  1252. function bx_convert_array2attrs ($a, $sClasses = false, $sStyles = false)
  1253. {
  1254. $sRet = '';
  1255. if (!$a || !is_array($a))
  1256. $a = array();
  1257. if ($sClasses) {
  1258. $sClasses = trim($sClasses);
  1259. $a['class'] = $sClasses . (!empty($a['class']) ? ' ' . $a['class'] : '');
  1260. }
  1261. if ($sStyles) {
  1262. $sStyles = trim($sStyles);
  1263. if (';' != $sStyles[strlen($sStyles)-1])
  1264. $sStyles .= ';';
  1265. $a['style'] = $sStyles . (!empty($a['style']) ? ' ' . $a['style'] : '');
  1266. }
  1267. foreach ($a as $sKey => $sValue) {
  1268. if(is_null($sValue)) // pass NULL values
  1269. continue;
  1270. $sValueC = bx_html_attribute($sValue, BX_ESCAPE_STR_QUOTE);
  1271. $sRet .= " $sKey=\"$sValueC\"";
  1272. }
  1273. return $sRet;
  1274. }
  1275. function bx_unicode_urldecode($s)
  1276. {
  1277. preg_match_all('/%u([[:alnum:]]{4})/', $s, $a);
  1278. foreach ($a[1] as $uniord) {
  1279. $dec = hexdec($uniord);
  1280. $utf = '';
  1281. if ($dec < 128) {
  1282. $utf = chr($dec);
  1283. } else if ($dec < 2048) {
  1284. $utf = chr(192 + (($dec - ($dec % 64)) / 64));
  1285. $utf .= chr(128 + ($dec % 64));
  1286. } else {
  1287. $utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
  1288. $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
  1289. $utf .= chr(128 + ($dec % 64));
  1290. }
  1291. $s = str_replace('%u'.$uniord, $utf, $s);
  1292. }
  1293. return urldecode($s);
  1294. }
  1295. /**
  1296. * Raise an audit event
  1297. * @param int $iContentId - content id
  1298. * @param string $sContentModule - module name
  1299. * @param string $sAction - system action key
  1300. * @param array $aParams - array of parameters
  1301. */
  1302. function bx_audit($iContentId, $sContentModule, $sAction, $aParams)
  1303. {
  1304. if (!getParam('sys_audit_enable') || getParam('sys_audit_acl_levels') == '')
  1305. return;
  1306. $iProfileId = bx_get_logged_profile_id();
  1307. if (!BxDolAcl::getInstance()->isMemberLevelInSet(explode(',', getParam('sys_audit_acl_levels')), $iProfileId))
  1308. return;
  1309. $sContentTitle = $sContentInfoObject = $sContextProfileTitle = $sData = $sActionParams = '';
  1310. $iContextProfileId = 0;
  1311. if (isset($aParams['profile_id']))
  1312. $iProfileId = (int)$aParams['profile_id'];
  1313. if (isset($aParams['content_title']))
  1314. $sContentTitle = $aParams['content_title'];
  1315. if (isset($aParams['context_profile_id']))
  1316. $iContextProfileId = (int)$aParams['context_profile_id'];
  1317. if (isset($aParams['context_profile_title']))
  1318. $sContextProfileTitle = $aParams['context_profile_title'];
  1319. if (isset($aParams['action_params']) && is_array($aParams['action_params']) && count($aParams['action_params']))
  1320. $sActionParams = serialize($aParams['action_params']);
  1321. if (isset($aParams['content_info_object']))
  1322. $sContentInfoObject = $aParams['content_info_object'];
  1323. if (isset($aParams['data']) && is_array($aParams['data']) && count($aParams['data']))
  1324. $sData = serialize($aParams['data']);
  1325. $sProfileTitle = BxDolProfile::getInstance($iProfileId)->getDisplayName();
  1326. $oDb = BxDolDb::getInstance();
  1327. $sSql = $oDb->prepare("INSERT INTO `sys_audit`(`added`, `profile_id`, `profile_title`, `content_id`, `content_title`, `content_module`, `context_profile_id`, `context_profile_title`, `action_lang_key`, `action_lang_key_params`, `content_info_object`, `extras`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
  1328. ,time(), $iProfileId, $sProfileTitle, $iContentId, $sContentTitle, $sContentModule, $iContextProfileId, $sContextProfileTitle, $sAction, $sActionParams ,$sContentInfoObject, $sData);
  1329. return !$oDb->query($sSql);
  1330. }
  1331. /**
  1332. * Raise an alert
  1333. * @param string $sUnit - system type
  1334. * @param string $sAction - system action
  1335. * @param int $iObjectId - object id
  1336. * @param int $iSender - sender (action's author) profile id, if it is false - then currectly logged in profile id is used
  1337. * @param array $aExtras - extra parameters
  1338. */
  1339. function bx_alert($sUnit, $sAction, $iObjectId, $iSender = false, $aExtras = array())
  1340. {
  1341. $o = new BxDolAlerts($sUnit, $sAction, $iObjectId, $iSender, $aExtras);
  1342. $o->alert();
  1343. }
  1344. /**
  1345. * Check whether serice method exists or not
  1346. * @param $mixed module name or module id
  1347. * @param $sMethod service method name in format 'method_name', corresponding class metod is serviceMethodName
  1348. * @param $sClass class to search for service method, by default it is main module class
  1349. * @return boolean check result
  1350. */
  1351. function bx_is_srv($mixedModule, $sMethod, $sClass = "Module")
  1352. {
  1353. return BxDolRequest::serviceExists($mixedModule, $sMethod, $sClass);
  1354. }
  1355. /**
  1356. * Perform serice call
  1357. * @param $mixed module name or module id
  1358. * @param $sMethod service method name in format 'method_name', corresponding class metod is serviceMethodName
  1359. * @param $aParams params to pass to service method
  1360. * @param $sClass class to search for service method, by default it is main module class
  1361. * @return service call result
  1362. */
  1363. function bx_srv($mixed, $sMethod, $aParams = array(), $sClass = 'Module', $bIgnoreCache = false, $bIgnoreInactive = false)
  1364. {
  1365. return BxDolService::call($mixed, $sMethod, $aParams, $sClass, $bIgnoreCache, $bIgnoreInactive);
  1366. }
  1367. /**
  1368. * Perform serice call in 'Ignore Inactive' mode.
  1369. */
  1370. function bx_srv_ii($mixed, $sMethod, $aParams = array(), $sClass = 'Module', $bIgnoreCache = false)
  1371. {
  1372. return BxDolService::call($mixed, $sMethod, $aParams, $sClass, $bIgnoreCache, true);
  1373. }
  1374. /**
  1375. * Perform serice call in 'Ignore Cache' mode.
  1376. */
  1377. function bx_srv_ic($mixed, $sMethod, $aParams = array(), $sClass = 'Module', $bIgnoreInactive = false)
  1378. {
  1379. return BxDolService::call($mixed, $sMethod, $aParams, $sClass, true, $bIgnoreInactive);
  1380. }
  1381. function bx_replace_markers($mixed, $aMarkers)
  1382. {
  1383. if (empty($aMarkers))
  1384. return $mixed;
  1385. if (is_array($mixed)) {
  1386. foreach ($mixed as $sKey => $sValue)
  1387. $mixed[$sKey] = bx_replace_markers ($sValue, $aMarkers);
  1388. } else {
  1389. foreach ($aMarkers as $sKey => $sValue)
  1390. $mixed = str_replace('{' . $sKey . '}', $sValue, $mixed);
  1391. }
  1392. return $mixed;
  1393. }
  1394. function bx_site_hash($sSalt = '', $isSkipVersion = false)
  1395. {
  1396. return md5($sSalt . ($isSkipVersion ? '' : bx_get_ver() . getParam('sys_revision')) . BX_DOL_SECRET . BX_DOL_URL_ROOT);
  1397. }
  1398. /**
  1399. * Transform string to method name string, for example it changes 'some_method' string to 'SomeMethod' string
  1400. * @param $s string where words are separated with underscore
  1401. * @param $aWordsDelimiter word delimeters
  1402. * @return string where every word begins with capital letter
  1403. */
  1404. function bx_gen_method_name ($s, $aWordsDelimiter = array('_'))
  1405. {
  1406. return str_replace(' ', '', ucwords(str_replace($aWordsDelimiter, ' ', $s)));
  1407. }
  1408. /**
  1409. * Trigger user error
  1410. * @param $sMsg message to display
  1411. * @param $iNumLevelsBack add additional debug backtracing N levels back
  1412. */
  1413. function bx_trigger_error ($sMsg, $iNumLevelsBack = 0)
  1414. {
  1415. $a = debug_backtrace();
  1416. $sMsgAdd = "<br />\n related code in <b>{$a[$iNumLevelsBack]['file']}</b> on line <b>{$a[$iNumLevelsBack]['line']}</b> <br />\n";
  1417. trigger_error ($sMsg . $sMsgAdd, E_USER_ERROR);
  1418. }
  1419. /**
  1420. * Get system DB version, for files version @see BX_DOL_VERSION, these versions must match
  1421. */
  1422. function bx_get_ver ($bInvalidateCache = false)
  1423. {
  1424. $oDb = BxDolDb::getInstance();
  1425. if ($bInvalidateCache)
  1426. $oDb->cleanMemory('sys_version');
  1427. $sQuery = $oDb->prepare("SELECT `version` FROM `sys_modules` WHERE `name` = 'system'");
  1428. return $oDb->fromMemory('sys_version', 'getOne', $sQuery);
  1429. }
  1430. /**
  1431. * Check if site maintetance mode is enabled.
  1432. * Maintetance mode is enabled when '.bx_maintenance' file exists in the script root folder,
  1433. * please note that this is hidden file and some file managers don't show it.
  1434. * @param $bShowHttpError show 503 HTTP error if site is in mainenance mode
  1435. * @return true if site is in maintenance mode, or false otherwise
  1436. */
  1437. function bx_check_maintenance_mode ($bShowHttpError = false)
  1438. {
  1439. $bMaintetance = file_exists(BX_DIRECTORY_PATH_ROOT . BX_MAINTENANCE_FILE) && !defined('BX_DOL_UPGRADING');
  1440. if ($bMaintetance && $bShowHttpError)
  1441. bx_show_service_unavailable_error_and_exit ('Site is temporarily unavailable due to scheduled maintenance, please try again in a minute.', 600);
  1442. return $bMaintetance;
  1443. }
  1444. /**
  1445. * Check for minimal requirements.
  1446. * if BX_DISABLE_REQUIREMENTS_CHECK is defined then this requirements checking is skipped.
  1447. * @param $bShowHttpError show 503 HTTP error if site doesn't meet minimal requirements
  1448. * @return false if requirements are met, or array of errors of requirements aren't met
  1449. */
  1450. function bx_check_minimal_requirements ($bShowHttpError = false)
  1451. {
  1452. if (defined('BX_DISABLE_REQUIREMENTS_CHECK'))
  1453. return false;
  1454. $aErrors = array();
  1455. $aErrors[] = (ini_get('register_globals') == 0) ? '' : '<b>register_globals</b> is on (you need to disable it, or your site will be unsafe)';
  1456. $aErrors[] = (ini_get('safe_mode') == 0) ? '' : '<b>safe_mode</b> is on (you need to disable it)';
  1457. $aErrors[] = (version_compare(PHP_VERSION, '5.3.0', '<')) ? 'PHP version is too old (please update to <b>PHP 5.3.0</b> at least)' : '';
  1458. $aErrors[] = (!extension_loaded( 'mbstring')) ? '<b>mbstring</b> extension not installed (the script cannot work without it)' : '';
  1459. $aErrors[] = (ini_get('allow_url_include') == 0 || version_compare(PHP_VERSION, '8.0.0', '>=')) ? '' : '<b>allow_url_include</b> is on (you need to disable it, or your site will be unsafe)';
  1460. $aErrors = array_diff($aErrors, array('')); // delete empty
  1461. $bFailedMinimalRequirements = !empty($aErrors);
  1462. if ($bFailedMinimalRequirements && $bShowHttpError) {
  1463. $sErrors = implode(" <br /> ", $aErrors);
  1464. bx_show_service_unavailable_error_and_exit($sErrors);
  1465. }
  1466. return $bFailedMinimalRequirements ? $aErrors : false;
  1467. }
  1468. /**
  1469. * Check if redirect to the correct hostname is required, for example redirect from site.com to www.site.com
  1470. * @param $bProcessRedirect process redirect and exit if needed
  1471. */
  1472. function bx_check_redirect_to_correct_hostname ($bProcessRedirect = false)
  1473. {
  1474. $aUrl = parse_url(BX_DOL_URL_ROOT);
  1475. $iPortDefault = 'https' == $aUrl['scheme'] ? '443' : '80';
  1476. $bRedirectRequired = isset($_SERVER['HTTP_HOST']) && 0 !== strcasecmp($_SERVER['HTTP_HOST'], $aUrl['host']) && 0 !== strcasecmp($_SERVER['HTTP_HOST'], $aUrl['host'] . ':' . (!empty($aUrl['port']) ? $aUrl['port'] : $iPortDefault));
  1477. if ($bRedirectRequired && $bProcessRedirect) {
  1478. $sPort = empty($aUrl['port']) || 80 == $aUrl['port'] || 443 == $aUrl['port'] ? '' : ':' . $aUrl['port'];
  1479. header("Location:{$aUrl['scheme']}://{$aUrl['host']}{$sPort}{$_SERVER['REQUEST_URI']}", true, 301);
  1480. exit;
  1481. }
  1482. return $bRedirectRequired;
  1483. }
  1484. /**
  1485. * Check if redirect to remove install folder.
  1486. * If BX_SKIP_INSTALL_CHECK is defined then this redirect checking is skipped.
  1487. * @param $bProcessRedirect process redirect and exit if needed
  1488. */
  1489. function bx_check_redirect_to_remove_install_folder ($bProcessRedirect = false)
  1490. {
  1491. $bRemoveInstallFolder = !defined ('BX_SKIP_INSTALL_CHECK') && file_exists(BX_DIRECTORY_PATH_ROOT . 'install');
  1492. if ($bRemoveInstallFolder && $bProcessRedirect) {
  1493. header('Location:' . BX_DOL_URL_ROOT . 'install/index.php?action=remove_install');
  1494. exit;
  1495. }
  1496. return $bRemoveInstallFolder;
  1497. }
  1498. /**
  1499. * Show HTTP 503 service unavailable error and exit
  1500. */
  1501. function bx_show_service_unavailable_error_and_exit ($sMsg = false, $iRetryAfter = 86400)
  1502. {
  1503. header('HTTP/1.0 503 Service Unavailable', true, 503);
  1504. header('Retry-After: 600');
  1505. echo $sMsg ? $sMsg : 'Service temporarily unavailable';
  1506. exit;
  1507. }
  1508. /**
  1509. * The function is sumilar to php readfile, but it send all required headers and can send file by chunks and suports file seek
  1510. * @param $sPath path to file to output to the browser
  1511. * @param $sFilename filename without path, ig file is saved from browser, then this name is used, not used(empty) by default
  1512. * @param $sMimeType file mime type, by default 'application/octet-stream'
  1513. * @param $iCacheAge file cache age, by default 0
  1514. * @param $sCachePrivacy cache privacy 'public' (default value) or 'private'
  1515. * @param $sContentDisposition content disposition header ('inline' or 'attachment' usually
  1516. * @return true on success or false on error
  1517. */
  1518. function bx_smart_readfile($sPath, $sFilename = '', $sMimeType = 'application/octet-stream', $iCacheAge = 0, $sCachePrivacy = 'public', $sContentDisposition = 'inline')
  1519. {
  1520. if (!file_exists($sPath))
  1521. return false;
  1522. $fp = @fopen($sPath, 'rb');
  1523. $size = filesize($sPath);
  1524. $length = $size;
  1525. $start = 0;
  1526. $end = $size - 1;
  1527. header('Content-Type: ' . $sMimeType);
  1528. header('Cache-Control: ' . $sCachePrivacy . ', must-revalidate, max-age=' . $iCacheAge);
  1529. header("Expires: " . gmdate('D, d M Y H:i:s', time() + $iCacheAge) . ' GMT');
  1530. header("Last-Modified: " . gmdate('D, d M Y H:i:s', @filemtime($sPath)) . ' GMT');
  1531. header("Accept-Ranges: bytes");
  1532. if ($sFilename)
  1533. header('Content-Disposition: ' . $sContentDisposition . '; filename="' . $sFilename . '"');
  1534. if (isset($_SERVER['HTTP_RANGE'])) {
  1535. $c_start = $start;
  1536. $c_end = $end;
  1537. list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
  1538. if (strpos($range, ',') !== false) {
  1539. header('HTTP/1.1 416 Requested Range Not Satisfiable');
  1540. header("Content-Range: bytes $start-$end/$size");
  1541. return false;
  1542. }
  1543. if ($range == '-') {
  1544. $c_start = $size - substr($range, 1);
  1545. }else{
  1546. $range = explode('-', $range);
  1547. $c_start = $range[0];
  1548. $c_end = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $size;
  1549. }
  1550. $c_end = ($c_end > $end) ? $end : $c_end;
  1551. if ($c_start > $c_end || $c_start > $size - 1 || $c_end >= $size) {
  1552. header('HTTP/1.1 416 Requested Range Not Satisfiable');
  1553. header("Content-Range: bytes $start-$end/$size");
  1554. return false;
  1555. }
  1556. $start = $c_start;
  1557. $end = $c_end;
  1558. $length = $end - $start + 1;
  1559. fseek($fp, $start);
  1560. header('HTTP/1.1 206 Partial Content');
  1561. }
  1562. header("Content-Range: bytes $start-$end/$size");
  1563. header("Content-Length: ".$length);
  1564. set_time_limit(0);
  1565. $buffer = 1024 * 8;
  1566. while(!feof($fp) && ($p = ftell($fp)) <= $end) {
  1567. if ($p + $buffer > $end) {
  1568. $buffer = $end - $p + 1;
  1569. }
  1570. echo fread($fp, $buffer);
  1571. flush();
  1572. }
  1573. fclose($fp);
  1574. return true;
  1575. }
  1576. /**
  1577. * Wrap in A tag links in TEXT string
  1578. * @param $text - text string without tags
  1579. * @param $sAttrs - attributes string to add to the added A tag
  1580. * @param $bHtmlSpecialChars - apply htmlspecialchars before processing
  1581. * @return string where all links are wrapped in A tag
  1582. */
  1583. function bx_linkify($text, $sAttrs = '', $bHtmlSpecialChars = false)
  1584. {
  1585. if ($bHtmlSpecialChars)
  1586. $text = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8');
  1587. $re = "@\b((https?://)|(www\.))(([0-9a-zA-Z_!~*'().&=+$%-]+:)?[0-9a-zA-Z_!~*'().&=+$%-]+\@)?(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-zA-Z_!~*'()-]+\.)*([0-9a-zA-Z][0-9a-zA-Z-]{0,61})?[0-9a-zA-Z]\.[a-zA-Z]{2,16})(:[0-9]{1,4})?((/[0-9a-zA-Z_!~*'().;?:\@&=+$,%#-]+)*/?)@";
  1588. preg_match_all($re, $text, $matches, PREG_OFFSET_CAPTURE);
  1589. $matches = $matches[0];
  1590. if ($i = count($matches))
  1591. $bAddNofollow = getParam('sys_add_nofollow') == 'on';
  1592. while ($i--)
  1593. {
  1594. $sAttrsLocal = $sAttrs;
  1595. $url = $matches[$i][0];
  1596. if (!preg_match('@^https?://@', $url))
  1597. $url = 'http://'.$url;
  1598. if (strncmp(BX_DOL_URL_ROOT, $url, strlen(BX_DOL_URL_ROOT)) !== 0) {
  1599. $sAttrsLocal .= ' target="_blank" ';
  1600. if ($bAddNofollow)
  1601. $sAttrsLocal .= ' rel="nofollow" ';
  1602. }
  1603. $text = substr_replace($text, '<a ' . $sAttrsLocal . ' href="'.$url.'">'.$matches[$i][0].'</a>', $matches[$i][1], strlen($matches[$i][0]));
  1604. }
  1605. // email pattern
  1606. $mail_pattern = "/([A-z0-9\._-]+\@[A-z0-9_-]+\.)([A-z0-9\_\-\.]{1,}[A-z])/";
  1607. $text = preg_replace($mail_pattern, '<a href="mailto:$1$2">$1$2</a>', $text);
  1608. return $text;
  1609. }
  1610. /**
  1611. * Wrap in A tag links in HTML string, which aren't wrapped in A tag yet
  1612. * @param $sHtmlOrig - HTML string
  1613. * @param $sAttrs - attributes string to add to the added A tag
  1614. * @return modified HTML string, in case of errror original string is returned
  1615. */
  1616. function bx_linkify_html($sHtmlOrig, $sAttrs = '')
  1617. {
  1618. if (!trim($sHtmlOrig))
  1619. return $sHtmlOrig;
  1620. $sId = 'bx-linkify-' . md5(microtime());
  1621. $dom = new DOMDocument();
  1622. @$dom->loadHTML('<?xml encoding="UTF-8"><div id="' . $sId . '">' . $sHtmlOrig . '</div>');
  1623. $xpath = new DOMXpath($dom);
  1624. foreach ($xpath->query('//text()') as $text) {
  1625. if (!empty($text->parentNode) && !empty($text->parentNode->tagName) && 'a' == $text->parentNode->tagName)
  1626. continue;
  1627. $frag = $dom->createDocumentFragment();
  1628. @$frag->appendXML(bx_linkify($text->nodeValue, $sAttrs, true));
  1629. $text->parentNode->replaceChild($frag, $text);
  1630. }
  1631. if (version_compare(PHP_VERSION, '5.3.6') >= 0)
  1632. $s = $dom->saveHTML($dom->getElementById($sId));
  1633. else
  1634. $s = $dom->saveXML($dom->getElementById($sId), LIBXML_NOEMPTYTAG);
  1635. if (false === $s) // in case of error return original string
  1636. return $sHtmlOrig;
  1637. if (false !== ($iPos = mb_strpos($s, '<html><body>')) && $iPos < mb_strpos($s, $sId))
  1638. $s = mb_substr($s, $iPos + 12, -15); // strip <html><body> tags and everything before them
  1639. return mb_substr($s, 54, -6); // strip added tags
  1640. }
  1641. /**
  1642. * Returns current site protocol http:// or https://
  1643. */
  1644. function bx_proto()
  1645. {
  1646. return 0 === strncmp('https', BX_DOL_URL_ROOT, 5) ? 'https' : 'http';
  1647. }
  1648. /**
  1649. * Checks protocol in the link
  1650. */
  1651. function bx_has_proto($sLink)
  1652. {
  1653. return preg_match('@^https?://@', $sLink);
  1654. }
  1655. function bx_is_empty_array ($a)
  1656. {
  1657. if (!is_array($a))
  1658. return true;
  1659. if (empty($a))
  1660. return true;
  1661. foreach ($a as $k => $v)
  1662. if ($v)
  1663. return false;
  1664. return true;
  1665. }
  1666. function bx_is_full_array ($a)
  1667. {
  1668. if (!is_array($a))
  1669. return false;
  1670. if (empty($a))
  1671. return false;
  1672. foreach ($a as $k => $v)
  1673. if (empty($v))
  1674. return false;
  1675. return true;
  1676. }
  1677. function bx_is_url_in_content ($sContent, $bSkipLocalUrls = false)
  1678. {
  1679. if ($bSkipLocalUrls)
  1680. $sContent = str_replace(BX_DOL_URL_ROOT, '', $sContent);
  1681. $a = array(
  1682. 'http://',
  1683. 'https://',
  1684. 'https/',
  1685. 'http/',
  1686. 'www.',
  1687. '.com'
  1688. );
  1689. foreach ($a as $s)
  1690. if (false !== strpos($sContent, $s))
  1691. return true;
  1692. return false;
  1693. }
  1694. function bx_is_dynamic_request ()
  1695. {
  1696. return bx_get('dynamic') || (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && 'XMLHttpRequest' == $_SERVER['HTTP_X_REQUESTED_WITH']);
  1697. }
  1698. function bx_idn_to_utf8($sUrl, $bReturnDomain = false)
  1699. {
  1700. return bx_idn_to('idn_to_utf8', $sUrl, $bReturnDomain);
  1701. }
  1702. function bx_idn_to_ascii($sUrl, $bReturnDomain = false)
  1703. {
  1704. return bx_idn_to('idn_to_ascii', $sUrl, $bReturnDomain);
  1705. }
  1706. function bx_idn_to($sMethod, $sUrl, $bReturnDomain = false)
  1707. {
  1708. $aUrl = parse_url($sUrl);
  1709. if($aUrl === false)
  1710. return $sUrl;
  1711. $sResult = $aUrl['host'];
  1712. if(function_exists($sMethod))
  1713. $sResult = $sMethod($sResult, IDNA_DEFAULT, (defined('INTL_IDNA_VARIANT_UTS46') ? INTL_IDNA_VARIANT_UTS46 : INTL_IDNA_VARIANT_2003));
  1714. if($bReturnDomain)
  1715. return $sResult;
  1716. $sResult = (!empty($aUrl['scheme']) ? $aUrl['scheme'] . '://' : '' ) . $sResult;
  1717. $sResult = $sResult . (!empty($aUrl['path']) ? $aUrl['path'] : '');
  1718. $sResult = $sResult . (!empty($aUrl['query']) ? '?' . $aUrl['query'] : '');
  1719. return $sResult;
  1720. }
  1721. function bx_is_mobile()
  1722. {
  1723. if(!isset($_SERVER['HTTP_USER_AGENT']))
  1724. return false;
  1725. $s = $_SERVER['HTTP_USER_AGENT'];
  1726. return preg_match('/(android|bb\d+|meego|una).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i', $s) || preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i', substr($s, 0, 4));
  1727. }
  1728. function bx_get_device_pixel_ratio()
  1729. {
  1730. $iRatio = 1;
  1731. if(!isset($_COOKIE['devicePixelRatio']))
  1732. return $iRatio;
  1733. $iDevicePixelRatio = intval($_COOKIE['devicePixelRatio']);
  1734. if($iDevicePixelRatio >= 2)
  1735. $iRatio = 2;
  1736. return $iRatio;
  1737. }
  1738. /**
  1739. * Log to logs object
  1740. * @param $sObject - logs object
  1741. * @param $mixed - string or array to log
  1742. */
  1743. function bx_log($sObject, $mixed)
  1744. {
  1745. if ($o = BxDolLogs::getObjectInstance($sObject))
  1746. return $o->add($mixed);
  1747. else
  1748. return false;
  1749. }
  1750. /** @} */