utils.inc.php 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051
  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 = '', $sFileName = 'debug.log')
  484. {
  485. $sCont =
  486. '--- ' . date('r') . ' (' . BX_DOL_START . ") ---\n" .
  487. $sDesc . "\n" .
  488. print_r($mWhat, true) . "\n\n\n";
  489. $rFile = fopen(BX_DIRECTORY_PATH_LOGS . $sFileName, 'a');
  490. fwrite($rFile, $sCont);
  491. fclose($rFile);
  492. }
  493. function dbgTiming($sStartMicrotime)
  494. {
  495. $i1 = explode(' ', microtime ());
  496. $i2 = explode(' ', $sStartMicrotime);
  497. $iTime = ($i1[0]+$i1[1]) - ($i2[0]+$i2[1]);
  498. return round($iTime, 6) . ' sec';
  499. }
  500. function echoJson($a)
  501. {
  502. header('Content-type: text/html; charset=utf-8');
  503. echo json_encode($a);
  504. }
  505. function clear_xss($val)
  506. {
  507. // HTML Purifier plugin
  508. global $oHtmlPurifier;
  509. if (!isset($oHtmlPurifier) && !$GLOBALS['logged']['admin']) {
  510. require_once( BX_DIRECTORY_PATH_PLUGINS . 'htmlpurifier/HTMLPurifier.standalone.php' );
  511. HTMLPurifier_Bootstrap::registerAutoload();
  512. $oConfig = HTMLPurifier_Config::createDefault();
  513. $oConfig->set('Cache.SerializerPath', rtrim(BX_DIRECTORY_PATH_CACHE, '/'));
  514. $oConfig->set('Cache.SerializerPermissions', BX_DOL_DIR_RIGHTS);
  515. $oConfig->set('HTML.SafeObject', 'true');
  516. $oConfig->set('Output.FlashCompat', 'true');
  517. $oConfig->set('HTML.FlashAllowFullScreen', 'true');
  518. $oConfig->set('Attr.AllowedFrameTargets', array('_blank', '_self', '_parent', '_top'));
  519. if (getParam('sys_add_nofollow')) {
  520. $sHost = parse_url(BX_DOL_URL_ROOT, PHP_URL_HOST);
  521. $oConfig->set('URI.Host', $sHost);
  522. $oConfig->set('HTML.Nofollow', 'true');
  523. }
  524. $oConfig->set('Filter.Custom', array (new HTMLPurifier_Filter_YouTube(), new HTMLPurifier_Filter_YoutubeIframe(), new HTMLPurifier_Filter_AddBxLinksClass(), new HTMLPurifier_Filter_LocalIframe()));
  525. $oConfig->set('HTML.DefinitionID', 'html5-definitions');
  526. $oConfig->set('HTML.DefinitionRev', 1);
  527. if ($def = $oConfig->maybeGetRawHTMLDefinition()) {
  528. $def->addElement('section', 'Block', 'Flow', 'Common');
  529. $def->addElement('nav', 'Block', 'Flow', 'Common');
  530. $def->addElement('article', 'Block', 'Flow', 'Common');
  531. $def->addElement('aside', 'Block', 'Flow', 'Common');
  532. $def->addElement('header', 'Block', 'Flow', 'Common');
  533. $def->addElement('footer', 'Block', 'Flow', 'Common');
  534. $def->addElement('video', 'Block', 'Optional: (source, Flow) | (Flow, source) | Flow', 'Common', array(
  535. 'src' => 'URI',
  536. 'type' => 'Text',
  537. 'width' => 'Length',
  538. 'height' => 'Length',
  539. 'poster' => 'URI',
  540. 'preload' => 'Enum#auto,metadata,none',
  541. 'controls' => 'Bool',
  542. ));
  543. $def->addElement('source', 'Block', 'Flow', 'Common', array(
  544. 'src' => 'URI',
  545. 'type' => 'Text',
  546. ));
  547. $def->addAttribute('a', 'data-profile-id', 'Number');
  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 ($s, $sTable, $sField, $sEmpty = '-', $sDivider = '-')
  559. {
  560. $s = uriFilter($s, $sEmpty, $sDivider);
  561. if(uriCheckUniq($s, $sTable, $sField))
  562. return $s;
  563. // cut off redundant part
  564. if(get_mb_len($s) > 240)
  565. $s = get_mb_substr($s, 0, 240);
  566. // try to add date
  567. $s .= $sDivider . date('Y-m-d');
  568. if(uriCheckUniq($s, $sTable, $sField))
  569. return $s;
  570. // try to add number
  571. for($i = 0 ; $i < 999 ; ++$i)
  572. if(uriCheckUniq($s . $sDivider . $i, $sTable, $sField))
  573. return ($s . $sDivider . $i);
  574. return rand(0, 999999999);
  575. }
  576. function uriFilter ($s, $sEmpty = '-', $sDivider = '-')
  577. {
  578. if (BxTemplConfig::getInstance()->bAllowUnicodeInPreg)
  579. $s = get_mb_replace ('/[^\pL^\pN]+/u', $sDivider, $s); // unicode characters
  580. else
  581. $s = get_mb_replace ('/([^\d^\w]+)/u', $sDivider, $s); // latin characters only
  582. $s = get_mb_replace ('/([' . $sDivider . '^]+)/', $sDivider, $s);
  583. $s = get_mb_replace ('/([' . $sDivider . ']+)$/', '', $s); // remove trailing dash
  584. if (!$s) $s = $sEmpty;
  585. return $s;
  586. }
  587. function uriCheckUniq ($s, $sTable, $sField)
  588. {
  589. $oDb = BxDolDb::getInstance();
  590. $sSql = $oDb->prepare("SELECT 1 FROM `$sTable` WHERE `$sField`=? LIMIT 1", $s);
  591. return !$oDb->query($sSql);
  592. }
  593. function get_mb_replace ($sPattern, $sReplace, $s)
  594. {
  595. return preg_replace ($sPattern, $sReplace, $s);
  596. }
  597. function get_mb_len ($s)
  598. {
  599. return (function_exists('mb_strlen')) ? mb_strlen($s) : strlen($s);
  600. }
  601. function get_mb_substr ($s, $iStart, $iLen)
  602. {
  603. return (function_exists('mb_substr')) ? mb_substr ($s, $iStart, $iLen) : substr ($s, $iStart, $iLen);
  604. }
  605. function bx_mb_substr_replace($s, $sReplace, $iPosStart, $iLength)
  606. {
  607. return mb_substr($s, 0, $iPosStart) . $sReplace . mb_substr($s, $iPosStart + $iLength);
  608. }
  609. function bx_mb_strpos ($s, $sReplacement, $iStart = 0)
  610. {
  611. return mb_strpos($s, $sReplacement, $iStart);
  612. }
  613. /**
  614. * Import class file, it automatically detects class path by its prefix or module array/name
  615. *
  616. * @param $sClassName - full class name or class postfix(withoit prefix) in the case of module class
  617. * @param $mixedModule - module array or module name in the case of module class
  618. */
  619. function bx_import($sClassName, $mixedModule = array())
  620. {
  621. if (class_exists($sClassName, false))
  622. return;
  623. $aModule = false;
  624. if ($mixedModule) {
  625. if (is_array($mixedModule)) {
  626. $aModule = $mixedModule;
  627. } elseif (is_string($mixedModule)) {
  628. $o = BxDolModule::getInstance($mixedModule);
  629. $aModule = $o->_aModule;
  630. } elseif (is_bool($mixedModule) && true === $mixedModule) {
  631. $aModule = $GLOBALS['aModule'];
  632. }
  633. }
  634. if ($aModule) {
  635. if (class_exists($aModule['class_prefix'] . $sClassName, false))
  636. return;
  637. require_once (BX_DIRECTORY_PATH_MODULES . $aModule['path'] . 'classes/' . $aModule['class_prefix'] . $sClassName . '.php');
  638. return;
  639. }
  640. if (0 === strncmp($sClassName, 'BxDol', 5)) {
  641. if (0 === strncmp($sClassName, 'BxDolStudio', 11))
  642. require_once(BX_DOL_DIR_STUDIO_CLASSES . $sClassName . '.php');
  643. else
  644. require_once(BX_DIRECTORY_PATH_CLASSES . $sClassName . '.php');
  645. return;
  646. }
  647. if (0 === strncmp($sClassName, 'BxBase', 6)) {
  648. if (0 === strncmp($sClassName, 'BxBaseMod', 9)) {
  649. $aMatches = array();
  650. if (preg_match('/BxBaseMod([A-Z][a-z]+)/', $sClassName, $aMatches)) {
  651. require_once(BX_DIRECTORY_PATH_MODULES . 'base/' . strtolower($aMatches[1]) . '/classes/' . $sClassName . '.php');
  652. return;
  653. }
  654. } if (0 === strncmp($sClassName, 'BxBaseStudio', 12)) {
  655. require_once(BX_DOL_DIR_STUDIO_BASE . 'scripts/' . $sClassName . '.php');
  656. return;
  657. } else {
  658. require_once(BX_DIRECTORY_PATH_BASE . 'scripts/' . $sClassName . '.php');
  659. return;
  660. }
  661. }
  662. if (0 === strncmp($sClassName, 'BxTempl', 7)) {
  663. if(0 === strncmp($sClassName, 'BxTemplStudio', 13)) {
  664. $sPath = BX_DIRECTORY_PATH_MODULES . BxDolStudioTemplate::getInstance()->getPath() . 'data/template/studio/scripts/' . $sClassName . '.php';
  665. } else {
  666. $sPath = BX_DIRECTORY_PATH_MODULES . BxDolTemplate::getInstance()->getPath() . 'data/template/system/scripts/' . $sClassName . '.php';
  667. }
  668. if (file_exists($sPath)) {
  669. require_once($sPath);
  670. return;
  671. }
  672. trigger_error ("bx_import fatal error: class (" . $sClassName . ") wasn't found", E_USER_ERROR);
  673. }
  674. }
  675. /**
  676. * used in spl_autoload_register() function, so no need to call bx_import for system classes
  677. */
  678. function bx_autoload($sClassName)
  679. {
  680. if (0 === strncmp($sClassName, 'BxDol', 5) || 0 === strncmp($sClassName, 'BxBase', 6) || 0 === strncmp($sClassName, 'BxTempl', 7))
  681. bx_import($sClassName);
  682. }
  683. /**
  684. * Gets an instance of class pathing necessary parameters if it's necessary.
  685. *
  686. * @param string $sClassName class name.
  687. * @param array $aParams an array of parameters to be pathed to the constructor of the class.
  688. * @param array $mixedModule an array with module description. Is used when the requested class is located in some module.
  689. * @return unknown
  690. */
  691. function bx_instance($sClassName, $aParams = array(), $mixedModule = array())
  692. {
  693. if(isset($GLOBALS['bxDolClasses'][$sClassName]))
  694. return $GLOBALS['bxDolClasses'][$sClassName];
  695. if ($mixedModule) {
  696. if (!is_array($mixedModule)) {
  697. $o = BxDolModule::getInstance($mixedModule);
  698. $mixedModule = $o->_aModule;
  699. }
  700. $sClassName = bx_ltrim_str($sClassName, $mixedModule['class_prefix']);
  701. bx_import($sClassName, $mixedModule);
  702. $sClassName = $mixedModule['class_prefix'] . $sClassName;
  703. }
  704. $oClass = new ReflectionClass($sClassName);
  705. $GLOBALS['bxDolClasses'][$sClassName] = empty($aParams) ? $oClass->newInstance() : $oClass->newInstanceArgs($aParams);
  706. return $GLOBALS['bxDolClasses'][$sClassName];
  707. }
  708. /**
  709. * Escapes string/array ready to pass to js script with filtered symbols like ', " etc
  710. *
  711. * @param $mixedInput - string/array which should be filtered
  712. * @param $iQuoteType - string escaping method: BX_ESCAPE_STR_AUTO(default), BX_ESCAPE_STR_APOS or BX_ESCAPE_STR_QUOTE
  713. * @return converted string / array
  714. */
  715. function bx_js_string ($mixedInput, $iQuoteType = BX_ESCAPE_STR_AUTO)
  716. {
  717. $aUnits = array(
  718. "\n" => "\\n",
  719. "\r" => "",
  720. );
  721. if (BX_ESCAPE_STR_APOS == $iQuoteType) {
  722. $aUnits["'"] = "\\'";
  723. $aUnits['<script'] = "<scr' + 'ipt";
  724. $aUnits['</script>'] = "</scr' + 'ipt>";
  725. } elseif (BX_ESCAPE_STR_QUOTE == $iQuoteType) {
  726. $aUnits['"'] = '\\"';
  727. $aUnits['<script'] = '<scr" + "ipt';
  728. $aUnits['</script>'] = '</scr" + "ipt>';
  729. } else {
  730. $aUnits['"'] = '&quot;';
  731. $aUnits["'"] = '&apos;';
  732. $aUnits["<script>"] = '&lt;script&gt;';
  733. $aUnits["</script>"] = '&lt;/script&gt;';
  734. }
  735. return str_replace(array_keys($aUnits), array_values($aUnits), $mixedInput);
  736. }
  737. /**
  738. * Return input string/array ready to pass to html attribute with filtered symbols like ', " etc
  739. *
  740. * @param $mixedInput - string/array which should be filtered
  741. * @param $iQuoteType - string escaping BX_ESCAPE_STR_AUTO, BX_ESCAPE_STR_APOS or BX_ESCAPE_STR_QUOTE
  742. * @return converted string / array
  743. */
  744. function bx_html_attribute ($mixedInput, $iQuoteType = BX_ESCAPE_STR_AUTO)
  745. {
  746. $aUnits = array ();
  747. if (BX_ESCAPE_STR_APOS == $iQuoteType)
  748. $aUnits["'"] = "\\'";
  749. elseif (BX_ESCAPE_STR_QUOTE == $iQuoteType)
  750. $aUnits['"'] = '&quot;';
  751. else
  752. $aUnits = array("\"" => "&quot;", "'" => "&apos;");
  753. return str_replace(array_keys($aUnits), array_values($aUnits), $mixedInput);
  754. }
  755. /**
  756. * Escapes string/array ready to pass to php script with filtered symbols like ', " etc
  757. *
  758. * @param mixed $mixedInput - string/array which should be filtered
  759. * @return converted string / array
  760. */
  761. function bx_php_string_apos ($mixedInput)
  762. {
  763. return str_replace("'", "\\'", $mixedInput);
  764. }
  765. function bx_php_string_quot ($mixedInput)
  766. {
  767. return str_replace('"', '\\"', $mixedInput);
  768. }
  769. /**
  770. * Gets file contents by URL.
  771. *
  772. * @param string $sFileUrl - file URL to be read.
  773. * @param array $aParams - an array of parameters to be pathed with URL.
  774. * @param string $sMethod - post or get.
  775. * @param array $aHeaders - custom headers.
  776. * @param string $sHttpCode - HTTP code to return
  777. * @param array $aBasicAuth - array with 'user' and 'password' for Basic HTTP Auth
  778. * @return string the file's contents.
  779. */
  780. function bx_file_get_contents($sFileUrl, $aParams = array(), $sMethod = 'get', $aHeaders = array(), &$sHttpCode = null, $aBasicAuth = array(), $iTimeout = 0, $aCustomCurlParams = array())
  781. {
  782. if ('post' != $sMethod)
  783. $sFileUrl = bx_append_url_params($sFileUrl, $aParams);
  784. $sResult = '';
  785. if(function_exists('curl_init')) {
  786. $rConnect = curl_init();
  787. curl_setopt($rConnect, CURLOPT_USERAGENT, 'UNA ' . BX_DOL_VERSION);
  788. curl_setopt($rConnect, CURLOPT_TIMEOUT, 10);
  789. curl_setopt($rConnect, CURLOPT_URL, $sFileUrl);
  790. curl_setopt($rConnect, CURLOPT_HEADER, NULL === $sHttpCode ? false : true);
  791. curl_setopt($rConnect, CURLOPT_RETURNTRANSFER, 1);
  792. if (0 !== $iTimeout) {
  793. curl_setopt($rConnect, CURLOPT_CONNECTTIMEOUT, $iTimeout);
  794. curl_setopt($rConnect, CURLOPT_TIMEOUT, $iTimeout);
  795. }
  796. if (!ini_get('open_basedir'))
  797. curl_setopt($rConnect, CURLOPT_FOLLOWLOCATION, 1);
  798. if ($aHeaders)
  799. curl_setopt($rConnect, CURLOPT_HTTPHEADER, $aHeaders);
  800. if ($aBasicAuth)
  801. curl_setopt($rConnect, CURLOPT_USERPWD, $aBasicAuth['user'] . ':' . $aBasicAuth['password']);
  802. if ('post' == $sMethod) {
  803. curl_setopt($rConnect, CURLOPT_POST, true);
  804. curl_setopt($rConnect, CURLOPT_POSTFIELDS, http_build_query($aParams));
  805. }
  806. $sAllCookies = '';
  807. foreach($_COOKIE as $sKey=>$sValue){
  808. $sAllCookies .= $sKey . '=' . $sValue . ';';
  809. }
  810. curl_setopt($rConnect, CURLOPT_COOKIE, $sAllCookies);
  811. if ($aCustomCurlParams)
  812. foreach ($aCustomCurlParams as $sName => $mixedValue)
  813. curl_setopt($rConnect, constant($sName), $mixedValue);
  814. $sResult = curl_exec($rConnect);
  815. if (curl_errno($rConnect) == 60) { // CURLE_SSL_CACERT
  816. curl_setopt($rConnect, CURLOPT_CAINFO, BX_DIRECTORY_PATH_PLUGINS . 'curl/cacert.pem');
  817. $sResult = curl_exec($rConnect);
  818. }
  819. if (NULL !== $sHttpCode)
  820. $sHttpCode = curl_getinfo($rConnect, CURLINFO_HTTP_CODE);
  821. curl_close($rConnect);
  822. }
  823. else {
  824. $iSaveTimeout = false;
  825. if (0 !== $iTimeout) {
  826. $iSaveTimeout = ini_get('default_socket_timeout');
  827. ini_set('default_socket_timeout', $iTimeout);
  828. }
  829. $sResult = @file_get_contents($sFileUrl);
  830. if (0 !== $iTimeout && false !== $iSaveTimeout) {
  831. ini_set('default_socket_timeout', $iSaveTimeout);
  832. }
  833. }
  834. return $sResult;
  835. }
  836. function bx_get_site_info($sSourceUrl, $aProcessAdditionalTags = array())
  837. {
  838. $aResult = array();
  839. $sContent = bx_file_get_contents($sSourceUrl);
  840. if ($sContent) {
  841. $sCharset = '';
  842. preg_match("/<meta.+charset=([A-Za-z0-9-]+).+>/i", $sContent, $aMatch);
  843. if (isset($aMatch[1]))
  844. $sCharset = $aMatch[1];
  845. $sContent = preg_replace("/<script[^>]*>(.*?)<\/script>/i", '', $sContent);
  846. $sContent = preg_replace("/<style[^>]*>(.*?)<\/style>/i", '', $sContent);
  847. if (preg_match("/<title[^>]*>(.*?)<\/title>/i", $sContent, $aMatch))
  848. $aResult['title'] = strip_tags($aMatch[1]);
  849. else
  850. $aResult['title'] = parse_url($sSourceUrl, PHP_URL_HOST);
  851. $aResult['description'] = bx_parse_html_tag($sContent, 'meta', 'name', 'description', 'content', $sCharset);
  852. $aResult['keywords'] = bx_parse_html_tag($sContent, 'meta', 'name', 'keywords', 'content', $sCharset);
  853. if ($aProcessAdditionalTags) {
  854. foreach ($aProcessAdditionalTags as $k => $a) {
  855. $aResult[$k] = bx_parse_html_tag(
  856. $sContent,
  857. isset($a['tag']) ? $a['tag'] : 'meta',
  858. isset($a['name_attr']) ? $a['name_attr'] : 'itemprop',
  859. isset($a['name']) ? $a['name'] : $k,
  860. isset($a['content_attr']) ? $a['content_attr'] : 'content',
  861. $sCharset,
  862. isset($a['specialchars_decode']) ? $a['specialchars_decode'] : true);
  863. if ((isset($a['name']) && 'og:image' == $a['name']) || (isset($a['tag']) && 'link' == $a['tag'])) {
  864. $aResult[$k] = bx_get_site_info_fix_relative_url ($sSourceUrl, $aResult[$k]);
  865. }
  866. }
  867. }
  868. }
  869. return $aResult;
  870. }
  871. /**
  872. * Fix relative URL to make it absolute
  873. * @param $sSourceUrl main URL
  874. * @param $s URL to fix
  875. * @return absolute URL or URL wothout changes
  876. */
  877. function bx_get_site_info_fix_relative_url ($sSourceUrl, $s)
  878. {
  879. if (0 === stripos($s, 'http://') || 0 === stripos($s, 'https://') || 0 === stripos($s, 'ftp://') || !$s)
  880. return $s;
  881. if ('/' == $s[0]) {
  882. $a = parse_url($sSourceUrl);
  883. return $a['scheme'] . '://' . $a['host'] . (empty($a['port']) || 80 == $a['port'] || 443 == $a['port'] ? '' : ':' . $a['port']) . $s;
  884. }
  885. return $sSourceUrl . ('/' === substr($sSourceUrl, -1) ? $s : '/' . $s);
  886. }
  887. function bx_parse_html_tag ($sContent, $sTag, $sAttrNameName, $sAttrNameValue, $sAttrContentName, $sCharset = false, $bSpecialCharsDecode = true)
  888. {
  889. if (!preg_match("/<{$sTag}\s+{$sAttrNameName}[='\" ]+{$sAttrNameValue}['\"]\s+{$sAttrContentName}[='\" ]+([^'>\"]*)['\"][^>]*>/i", $sContent, $aMatch) || !isset($aMatch[1]))
  890. preg_match("/<{$sTag}\s+{$sAttrContentName}[='\" ]+([^'>\"]*)['\"]\s+{$sAttrNameName}[='\" ]+{$sAttrNameValue}['\"][^>]*>/i", $sContent, $aMatch);
  891. $s = isset($aMatch[1]) ? $aMatch[1] : '';
  892. if ($s && $sCharset)
  893. $s = mb_convert_encoding($s, 'UTF-8', $sCharset);
  894. if ($bSpecialCharsDecode)
  895. $s = htmlspecialchars_decode($s);
  896. return $s;
  897. }
  898. // calculation ini_get('upload_max_filesize') in bytes as example
  899. function return_bytes($val)
  900. {
  901. $val = trim($val);
  902. $last = strtolower($val[strlen($val)-1]);
  903. $val = (int)$val;
  904. switch($last) {
  905. // The 'G' modifier is available since PHP 5.1.0
  906. case 'k':
  907. $val *= 1024;
  908. break;
  909. case 'm':
  910. $val *= 1024 * 1024;
  911. break;
  912. case 'g':
  913. $val *= 1024 * 1024 * 1024;
  914. break;
  915. }
  916. return $val;
  917. }
  918. // Generate Random Password
  919. function genRndPwd($iLength = 8, $bSpecialCharacters = true)
  920. {
  921. $sPassword = '';
  922. $sChars = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
  923. if($bSpecialCharacters === true)
  924. $sChars .= "!?=/&+,.";
  925. for($i = 0; $i < $iLength; $i++) {
  926. $x = mt_rand(0, strlen($sChars) -1);
  927. $sPassword .= $sChars[$x];
  928. }
  929. return $sPassword;
  930. }
  931. // Generate Random Salt for Password encryption
  932. function genRndSalt()
  933. {
  934. return genRndPwd(8, true);
  935. }
  936. /**
  937. * Encrypt user password.
  938. * When BX_PWD_ALGO is 'custom', then bx_custom_pwd_encrypt function with custom algorythm must be defined in inc/header.inc.php file.
  939. * @param $sPwd clear password
  940. * @param $sSalt salt
  941. * @return password hash
  942. */
  943. function encryptUserPwd($sPwd, $sSalt)
  944. {
  945. $sAlgo = defined('BX_PWD_ALGO') ? BX_PWD_ALGO : '';
  946. switch ($sAlgo) {
  947. case 'custom':
  948. return bx_custom_pwd_encrypt($sPwd, $sSalt);
  949. case 'crypt':
  950. return crypt($sPwd, BX_PWD_ALGO_SALT);
  951. case 'sha1_crypt_salt':
  952. return sha1(crypt($sPwd, BX_PWD_ALGO_SALT) . $sSalt);
  953. case 'sha1_md5_salt':
  954. default:
  955. return sha1(md5($sPwd) . $sSalt);
  956. }
  957. }
  958. /**
  959. * Hash profile ID
  960. */
  961. function encryptUserId($sId)
  962. {
  963. if (!($oProfile = BxDolProfile::getInstance($sId)))
  964. return false;
  965. if (!($oAccount = $oProfile->getAccountObject()))
  966. return false;
  967. $aAccountInfo = $oAccount->getInfo();
  968. return sha1(md5($sId) . md5($aAccountInfo['salt']) . BX_DOL_SECRET);
  969. }
  970. function bx_get_reset_password_key($sValue, $sField = 'email', $iLifetime = 0)
  971. {
  972. if(empty($iLifetime)) {
  973. $iLifetime = (int)getParam('sys_account_reset_password_key_lifetime');
  974. if(empty($iLifetime))
  975. $iLifetime = 86400;
  976. }
  977. $oKey = BxDolKey::getInstance();
  978. if(!$oKey)
  979. return false;
  980. return $oKey->getNewKey(array($sField => $sValue), $iLifetime);
  981. }
  982. function bx_get_reset_password_link($sValue, $sField = 'email', $iLifetime = 0)
  983. {
  984. $sKey = bx_get_reset_password_key($sValue, $sField, $iLifetime);
  985. if(!$sKey)
  986. return false;
  987. return bx_get_reset_password_link_by_key($sKey);
  988. }
  989. function bx_get_reset_password_link_by_key($sKey)
  990. {
  991. return BX_DOL_URL_ROOT . BxDolPermalinks::getInstance()->permalink('page.php?i=forgot-password', array('key' => $sKey));
  992. }
  993. function bx_get_reset_password_redirect($iAccountId)
  994. {
  995. $sResult = '';
  996. $sRedirect = getParam('sys_account_reset_password_redirect');
  997. switch($sRedirect) {
  998. case 'home':
  999. $sResult = BxDolPermalinks::getInstance()->permalink('page.php?i=home');
  1000. break;
  1001. case 'profile':
  1002. case 'profile_edit':
  1003. if(empty($iAccountId))
  1004. break;
  1005. $oAccount = BxDolAccount::getInstance($iAccountId);
  1006. if(!$oAccount)
  1007. break;
  1008. $aAccountInfo = $oAccount->getInfo();
  1009. if(empty($aAccountInfo) || !is_array($aAccountInfo) || empty($aAccountInfo['profile_id']))
  1010. break;
  1011. $oProfile = BxDolProfile::getInstance((int)$aAccountInfo['profile_id']);
  1012. if(!$oProfile)
  1013. break;
  1014. $sResult = $oProfile->{'get' . ($sRedirect == 'profile_edit' ? 'Edit' : '') . 'Url'}();
  1015. break;
  1016. case 'custom':
  1017. $sResult = getParam('sys_account_reset_password_redirect_custom');
  1018. break;
  1019. }
  1020. if(!empty($sResult) && mb_stripos($sResult, BX_DOL_URL_ROOT) !== 0)
  1021. $sResult = BX_DOL_URL_ROOT . $sResult;
  1022. return $sResult;
  1023. }
  1024. function bx_get ($sName, $sMethod = false)
  1025. {
  1026. if (isset($_GET[$sName]) && ('get' == $sMethod || !$sMethod))
  1027. return $_GET[$sName];
  1028. elseif (isset($_POST[$sName]) && ('post' == $sMethod || !$sMethod))
  1029. return $_POST[$sName];
  1030. else
  1031. return false;
  1032. }
  1033. function bx_set ($sName, $sValue, $sMethod = false)
  1034. {
  1035. if(!$sMethod)
  1036. $sMethod = 'get';
  1037. $bResult = true;
  1038. switch($sMethod) {
  1039. case 'get':
  1040. $_GET[$sName] = $sValue;
  1041. break;
  1042. case 'post':
  1043. $_POST[$sName] = $sValue;
  1044. break;
  1045. default:
  1046. $bResult = false;
  1047. }
  1048. return $bResult;
  1049. }
  1050. function bx_get_with_prefix ($sPrefix, $sMethod = false)
  1051. {
  1052. $aSources = array('get' => &$_GET, 'post' => &$_POST);
  1053. $aFiltered = array();
  1054. foreach($aSources as $sName => $aSource)
  1055. if($sMethod == $sName || !$sMethod)
  1056. $aFiltered = array_merge($aFiltered, array_filter($aSource, function($sKey) use ($sPrefix) {
  1057. return strpos($sKey, $sPrefix) === 0;
  1058. }, ARRAY_FILTER_USE_KEY));
  1059. $aUpdated = array();
  1060. array_walk($aFiltered, function($sValue, $sKey) use ($sPrefix, &$aUpdated) {
  1061. $aUpdated[trim(str_replace($sPrefix, '', $sKey), '_-')] = $sValue;
  1062. });
  1063. return $aUpdated;
  1064. }
  1065. function bx_get_base_url_inline($aParams = array())
  1066. {
  1067. $aBaseLink = parse_url(BX_DOL_URL_ROOT);
  1068. $sPageLink = (!empty($aBaseLink['scheme']) ? $aBaseLink['scheme'] : 'http') . '://' . $aBaseLink['host'] . (!empty($aBaseLink['port']) ? ':' . $aBaseLink['port'] : '') . $_SERVER['REQUEST_URI'];
  1069. list($sPageLink, $aPageParams) = bx_get_base_url($sPageLink);
  1070. if(!empty($_SERVER['QUERY_STRING'])) {
  1071. $aPageParamsAdd = array();
  1072. parse_str($_SERVER['QUERY_STRING'], $aPageParamsAdd);
  1073. if(!empty($aPageParamsAdd) && is_array($aPageParamsAdd))
  1074. $aPageParams = array_merge($aPageParams, $aPageParamsAdd);
  1075. }
  1076. if(!empty($aParams) && is_array($aParams))
  1077. $aPageParams = array_merge($aPageParams, $aParams);
  1078. return array($sPageLink, $aPageParams);
  1079. }
  1080. function bx_get_base_url_popup($aParams = array())
  1081. {
  1082. list($sPageLink, $aPageParams) = bx_get_base_url($_SERVER['HTTP_REFERER']);
  1083. if(!empty($aParams) && is_array($aParams))
  1084. $aPageParams = array_merge($aPageParams, $aParams);
  1085. return array($sPageLink, $aPageParams);
  1086. }
  1087. function bx_get_base_url($sPageLink)
  1088. {
  1089. $sPageLink = BxDolPermalinks::getInstance()->unpermalink($sPageLink, false);
  1090. $sPageParams = '';
  1091. if(strpos($sPageLink, '?') !== false)
  1092. list($sPageLink, $sPageParams) = explode('?', $sPageLink);
  1093. $aPageParams = array();
  1094. if(!empty($sPageParams))
  1095. parse_str($sPageParams, $aPageParams);
  1096. return array($sPageLink, $aPageParams);
  1097. }
  1098. function bx_get_location_bounds_latlng($fLatitude, $fLongitude, $iRadiusInKm)
  1099. {
  1100. $fEquatorLatInKm = 111.321;
  1101. $aRv = array();
  1102. $aRv['max_lat'] = $fLatitude + $iRadiusInKm / $fEquatorLatInKm;
  1103. $aRv['min_lat'] = $fLatitude - ($aRv['max_lat'] - $fLatitude);
  1104. $aRv['max_lng'] = $fLongitude + $iRadiusInKm / (cos($aRv['min_lat'] * M_PI / 180) * $fEquatorLatInKm);
  1105. $aRv['min_lng'] = $fLongitude - ($aRv['max_lng'] - $fLongitude);
  1106. return $aRv;
  1107. }
  1108. function bx_encode_url_params ($a, $aExcludeKeys = array (), $aOnlyKeys = false)
  1109. {
  1110. $s = '';
  1111. foreach ($a as $sKey => $sVal) {
  1112. if (in_array($sKey, $aExcludeKeys))
  1113. continue;
  1114. if (false !== $aOnlyKeys && !in_array($sKey, $aOnlyKeys))
  1115. continue;
  1116. if (is_array($sVal)) {
  1117. foreach ($sVal as $sSubVal) {
  1118. $s .= rawurlencode($sKey) . '[]=' . rawurlencode(is_array($sSubVal) ? 'array' : $sSubVal) . '&';
  1119. }
  1120. } else {
  1121. $s .= rawurlencode($sKey) . '=' . rawurlencode($sVal) . '&';
  1122. }
  1123. }
  1124. return $s;
  1125. }
  1126. function bx_append_url_params ($sUrl, $mixedParams)
  1127. {
  1128. if (!$mixedParams)
  1129. return $sUrl;
  1130. $sParams = false == strpos($sUrl, '?') ? '?' : '&';
  1131. if (is_array($mixedParams)) {
  1132. foreach($mixedParams as $sKey => $sValue) {
  1133. if (!is_array($sValue)) {
  1134. $sParams .= $sKey . '=' . $sValue . '&';
  1135. }
  1136. else {
  1137. foreach($sValue as $sSubValue)
  1138. $sParams .= $sKey . '[]=' . $sSubValue . '&';
  1139. }
  1140. }
  1141. $sParams = substr($sParams, 0, -1);
  1142. } else {
  1143. $sParams .= $mixedParams;
  1144. }
  1145. return $sUrl . $sParams;
  1146. }
  1147. function bx_rrmdir($directory)
  1148. {
  1149. if (substr($directory,-1) == "/")
  1150. $directory = substr($directory,0,-1);
  1151. if (!file_exists($directory) || !is_dir($directory))
  1152. return false;
  1153. elseif (!is_readable($directory))
  1154. return false;
  1155. if (!($directoryHandle = opendir($directory)))
  1156. return false;
  1157. while ($contents = readdir($directoryHandle)) {
  1158. if ($contents != '.' && $contents != '..') {
  1159. $path = $directory . "/" . $contents;
  1160. if (is_dir($path))
  1161. bx_rrmdir($path);
  1162. else
  1163. unlink($path);
  1164. }
  1165. }
  1166. closedir($directoryHandle);
  1167. if (!rmdir($directory))
  1168. return false;
  1169. return true;
  1170. }
  1171. function bx_clear_folder ($sPath, $aExts = array ())
  1172. {
  1173. if (substr($$sPath,-1) == "/")
  1174. $sPath = substr($sPath,0,-1);
  1175. if (!file_exists($sPath) || !is_dir($sPath))
  1176. return false;
  1177. elseif (!is_readable($sPath))
  1178. return false;
  1179. if (!($h = opendir($sPath)))
  1180. return false;
  1181. while ($sFile = readdir($h)) {
  1182. if ('.' == $sFile || '..' == $sFile)
  1183. continue;
  1184. $sFullPath = $sPath . '/' . $sFile;
  1185. if (is_dir($sFullPath))
  1186. continue;
  1187. if (!$aExts || (($sExt = pathinfo($sFullPath, PATHINFO_EXTENSION)) && in_array($sExt, $aExts)))
  1188. @unlink($sFullPath);
  1189. }
  1190. closedir($h);
  1191. return true;
  1192. }
  1193. function bx_ltrim_str ($sString, $sPrefix, $sReplace = '')
  1194. {
  1195. if ($sReplace && substr($sString, 0, strlen($sReplace)) == $sReplace)
  1196. return $sString;
  1197. if (substr($sString, 0, strlen($sPrefix)) == $sPrefix)
  1198. return $sReplace . substr($sString, strlen($sPrefix));
  1199. return $sString;
  1200. }
  1201. function bx_rtrim_str ($sString, $sPrefix, $sReplace = '')
  1202. {
  1203. if ($sReplace && substr($sString, -strlen($sReplace)) == $sReplace)
  1204. return $sString;
  1205. if (substr($sString, -strlen($sPrefix)) == $sPrefix)
  1206. return substr($sString, 0, -strlen($sPrefix)) . $sReplace;
  1207. return $sString;
  1208. }
  1209. /**
  1210. * Strip all lines with no information for example: <p></p>, <br /><br />
  1211. */
  1212. function bx_trim_nl_duplicates($s)
  1213. {
  1214. $sStrip = implode('', array_keys(get_html_translation_table(HTML_ENTITIES)));
  1215. return implode('', array_filter(mb_split("[\n\r]", $s), function($s) use ($sStrip) {
  1216. return trim(strip_tags($s, '<button><canvas><embed><hr><iframe><img><input><object><select><svg><video>'), $sStrip) !== '';
  1217. }));
  1218. }
  1219. /**
  1220. * Convert array to attributes string
  1221. *
  1222. * Example:
  1223. * @code
  1224. * $a = array('name' => 'test', 'value' => 5);
  1225. * $s = bx_convert_array2attrs($a);
  1226. * echo $s; // outputs: name="test" value="5"
  1227. * @endcode
  1228. *
  1229. * @param $a - array of attributes
  1230. * @param $sClasses - classes to merge with 'class' attribute
  1231. * @param $sStyles - styles to merge with 'style' attribute
  1232. * @return string
  1233. */
  1234. function bx_convert_array2attrs ($a, $sClasses = false, $sStyles = false)
  1235. {
  1236. $sRet = '';
  1237. if (!$a || !is_array($a))
  1238. $a = array();
  1239. if ($sClasses) {
  1240. $sClasses = trim($sClasses);
  1241. $a['class'] = $sClasses . (!empty($a['class']) ? ' ' . $a['class'] : '');
  1242. }
  1243. if ($sStyles) {
  1244. $sStyles = trim($sStyles);
  1245. if (';' != $sStyles[strlen($sStyles)-1])
  1246. $sStyles .= ';';
  1247. $a['style'] = $sStyles . (!empty($a['style']) ? ' ' . $a['style'] : '');
  1248. }
  1249. foreach ($a as $sKey => $sValue) {
  1250. if(is_null($sValue)) // pass NULL values
  1251. continue;
  1252. $sValueC = bx_html_attribute($sValue, BX_ESCAPE_STR_QUOTE);
  1253. $sRet .= " $sKey=\"$sValueC\"";
  1254. }
  1255. return $sRet;
  1256. }
  1257. function bx_unicode_urldecode($s)
  1258. {
  1259. preg_match_all('/%u([[:alnum:]]{4})/', $s, $a);
  1260. foreach ($a[1] as $uniord) {
  1261. $dec = hexdec($uniord);
  1262. $utf = '';
  1263. if ($dec < 128) {
  1264. $utf = chr($dec);
  1265. } else if ($dec < 2048) {
  1266. $utf = chr(192 + (($dec - ($dec % 64)) / 64));
  1267. $utf .= chr(128 + ($dec % 64));
  1268. } else {
  1269. $utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
  1270. $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
  1271. $utf .= chr(128 + ($dec % 64));
  1272. }
  1273. $s = str_replace('%u'.$uniord, $utf, $s);
  1274. }
  1275. return urldecode($s);
  1276. }
  1277. /**
  1278. * Raise an audit event
  1279. * @param int $iContentId - content id
  1280. * @param string $sContentModule - module name
  1281. * @param string $sAction - system action key
  1282. * @param array $aParams - array of parameters
  1283. */
  1284. function bx_audit($iContentId, $sContentModule, $sAction, $aParams)
  1285. {
  1286. if (!getParam('sys_audit_enable') || getParam('sys_audit_acl_levels') == '')
  1287. return;
  1288. $iProfileId = bx_get_logged_profile_id();
  1289. if (!BxDolAcl::getInstance()->isMemberLevelInSet(explode(',', getParam('sys_audit_acl_levels')), $iProfileId))
  1290. return;
  1291. $sContentTitle = $sContentInfoObject = $sContextProfileTitle = $sData = $sActionParams = '';
  1292. $iContextProfileId = 0;
  1293. if (isset($aParams['profile_id']))
  1294. $iProfileId = (int)$aParams['profile_id'];
  1295. if (isset($aParams['content_title']))
  1296. $sContentTitle = $aParams['content_title'];
  1297. if (isset($aParams['context_profile_id']))
  1298. $iContextProfileId = (int)$aParams['context_profile_id'];
  1299. if (isset($aParams['context_profile_title']))
  1300. $sContextProfileTitle = $aParams['context_profile_title'];
  1301. if (isset($aParams['action_params']) && is_array($aParams['action_params']) && count($aParams['action_params']))
  1302. $sActionParams = serialize($aParams['action_params']);
  1303. if (isset($aParams['content_info_object']))
  1304. $sContentInfoObject = $aParams['content_info_object'];
  1305. if (isset($aParams['data']) && is_array($aParams['data']) && count($aParams['data']))
  1306. $sData = serialize($aParams['data']);
  1307. $sProfileTitle = BxDolProfile::getInstance($iProfileId)->getDisplayName();
  1308. $oDb = BxDolDb::getInstance();
  1309. $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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
  1310. ,time(), $iProfileId, $sProfileTitle, $iContentId, $sContentTitle, $sContentModule, $iContextProfileId, $sContextProfileTitle, $sAction, $sActionParams ,$sContentInfoObject, $sData);
  1311. return !$oDb->query($sSql);
  1312. }
  1313. /**
  1314. * Raise an alert
  1315. * @param string $sUnit - system type
  1316. * @param string $sAction - system action
  1317. * @param int $iObjectId - object id
  1318. * @param int $iSender - sender (action's author) profile id, if it is false - then currectly logged in profile id is used
  1319. * @param array $aExtras - extra parameters
  1320. */
  1321. function bx_alert($sUnit, $sAction, $iObjectId, $iSender = false, $aExtras = array())
  1322. {
  1323. $o = new BxDolAlerts($sUnit, $sAction, $iObjectId, $iSender, $aExtras);
  1324. $o->alert();
  1325. }
  1326. /**
  1327. * Perform serice call
  1328. * @param $mixed module name or module id
  1329. * @param $sMethod service method name in format 'method_name', corresponding class metod is serviceMethodName
  1330. * @param $aParams params to pass to service method
  1331. * @param $sClass class to search for service method, by default it is main module class
  1332. * @return service call result
  1333. */
  1334. function bx_srv($mixed, $sMethod, $aParams = array(), $sClass = 'Module', $bIgnoreCache = false, $bIgnoreInactive = false)
  1335. {
  1336. return BxDolService::call($mixed, $sMethod, $aParams, $sClass, $bIgnoreCache, $bIgnoreInactive);
  1337. }
  1338. /**
  1339. * Perform serice call in 'Ignore Inactive' mode.
  1340. */
  1341. function bx_srv_ii($mixed, $sMethod, $aParams = array(), $sClass = 'Module', $bIgnoreCache = false)
  1342. {
  1343. return BxDolService::call($mixed, $sMethod, $aParams, $sClass, $bIgnoreCache, true);
  1344. }
  1345. /**
  1346. * Perform serice call in 'Ignore Cache' mode.
  1347. */
  1348. function bx_srv_ic($mixed, $sMethod, $aParams = array(), $sClass = 'Module', $bIgnoreInactive = false)
  1349. {
  1350. return BxDolService::call($mixed, $sMethod, $aParams, $sClass, true, $bIgnoreInactive);
  1351. }
  1352. function bx_replace_markers($mixed, $aMarkers)
  1353. {
  1354. if (empty($aMarkers))
  1355. return $mixed;
  1356. if (is_array($mixed)) {
  1357. foreach ($mixed as $sKey => $sValue)
  1358. $mixed[$sKey] = bx_replace_markers ($sValue, $aMarkers);
  1359. } else {
  1360. foreach ($aMarkers as $sKey => $sValue)
  1361. $mixed = str_replace('{' . $sKey . '}', $sValue, $mixed);
  1362. }
  1363. return $mixed;
  1364. }
  1365. function bx_site_hash($sSalt = '', $isSkipVersion = false)
  1366. {
  1367. return md5($sSalt . ($isSkipVersion ? '' : bx_get_ver() . getParam('sys_revision')) . BX_DOL_SECRET . BX_DOL_URL_ROOT);
  1368. }
  1369. /**
  1370. * Transform string to method name string, for example it changes 'some_method' string to 'SomeMethod' string
  1371. * @param $s string where words are separated with underscore
  1372. * @param $aWordsDelimiter word delimeters
  1373. * @return string where every word begins with capital letter
  1374. */
  1375. function bx_gen_method_name ($s, $aWordsDelimiter = array('_'))
  1376. {
  1377. return str_replace(' ', '', ucwords(str_replace($aWordsDelimiter, ' ', $s)));
  1378. }
  1379. /**
  1380. * Trigger user error
  1381. * @param $sMsg message to display
  1382. * @param $iNumLevelsBack add additional debug backtracing N levels back
  1383. */
  1384. function bx_trigger_error ($sMsg, $iNumLevelsBack = 0)
  1385. {
  1386. $a = debug_backtrace();
  1387. $sMsgAdd = "<br />\n related code in <b>{$a[$iNumLevelsBack]['file']}</b> on line <b>{$a[$iNumLevelsBack]['line']}</b> <br />\n";
  1388. trigger_error ($sMsg . $sMsgAdd, E_USER_ERROR);
  1389. }
  1390. /**
  1391. * Get system DB version, for files version @see BX_DOL_VERSION, these versions must match
  1392. */
  1393. function bx_get_ver ($bInvalidateCache = false)
  1394. {
  1395. $oDb = BxDolDb::getInstance();
  1396. if ($bInvalidateCache)
  1397. $oDb->cleanMemory('sys_version');
  1398. $sQuery = $oDb->prepare("SELECT `version` FROM `sys_modules` WHERE `name` = 'system'");
  1399. return $oDb->fromMemory('sys_version', 'getOne', $sQuery);
  1400. }
  1401. /**
  1402. * Check if site maintetance mode is enabled.
  1403. * Maintetance mode is enabled when '.bx_maintenance' file exists in the script root folder,
  1404. * please note that this is hidden file and some file managers don't show it.
  1405. * @param $bShowHttpError show 503 HTTP error if site is in mainenance mode
  1406. * @return true if site is in maintenance mode, or false otherwise
  1407. */
  1408. function bx_check_maintenance_mode ($bShowHttpError = false)
  1409. {
  1410. $bMaintetance = file_exists(BX_DIRECTORY_PATH_ROOT . BX_MAINTENANCE_FILE) && !defined('BX_DOL_UPGRADING');
  1411. if ($bMaintetance && $bShowHttpError)
  1412. bx_show_service_unavailable_error_and_exit ('Site is temporarily unavailable due to scheduled maintenance, please try again in a minute.', 600);
  1413. return $bMaintetance;
  1414. }
  1415. /**
  1416. * Check for minimal requirements.
  1417. * if BX_DISABLE_REQUIREMENTS_CHECK is defined then this requirements checking is skipped.
  1418. * @param $bShowHttpError show 503 HTTP error if site doesn't meet minimal requirements
  1419. * @return false if requirements are met, or array of errors of requirements aren't met
  1420. */
  1421. function bx_check_minimal_requirements ($bShowHttpError = false)
  1422. {
  1423. if (defined('BX_DISABLE_REQUIREMENTS_CHECK'))
  1424. return false;
  1425. $aErrors = array();
  1426. $aErrors[] = (ini_get('register_globals') == 0) ? '' : '<b>register_globals</b> is on (you need to disable it, or your site will be unsafe)';
  1427. $aErrors[] = (ini_get('safe_mode') == 0) ? '' : '<b>safe_mode</b> is on (you need to disable it)';
  1428. $aErrors[] = (version_compare(PHP_VERSION, '5.3.0', '<')) ? 'PHP version is too old (please update to <b>PHP 5.3.0</b> at least)' : '';
  1429. $aErrors[] = (!extension_loaded( 'mbstring')) ? '<b>mbstring</b> extension not installed (the script cannot work without it)' : '';
  1430. $aErrors[] = (ini_get('allow_url_include') == 0) ? '' : '<b>allow_url_include</b> is on (you need to disable it, or your site will be unsafe)';
  1431. $aErrors = array_diff($aErrors, array('')); // delete empty
  1432. $bFailedMinimalRequirements = !empty($aErrors);
  1433. if ($bFailedMinimalRequirements && $bShowHttpError) {
  1434. $sErrors = implode(" <br /> ", $aErrors);
  1435. bx_show_service_unavailable_error_and_exit($sErrors);
  1436. }
  1437. return $bFailedMinimalRequirements ? $aErrors : false;
  1438. }
  1439. /**
  1440. * Check if redirect to the correct hostname is required, for example redirect from site.com to www.site.com
  1441. * @param $bProcessRedirect process redirect and exit if needed
  1442. */
  1443. function bx_check_redirect_to_correct_hostname ($bProcessRedirect = false)
  1444. {
  1445. $aUrl = parse_url(BX_DOL_URL_ROOT);
  1446. $iPortDefault = 'https' == $aUrl['scheme'] ? '443' : '80';
  1447. $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));
  1448. if ($bRedirectRequired && $bProcessRedirect) {
  1449. $sPort = empty($aUrl['port']) || 80 == $aUrl['port'] || 443 == $aUrl['port'] ? '' : ':' . $aUrl['port'];
  1450. header("Location:{$aUrl['scheme']}://{$aUrl['host']}{$sPort}{$_SERVER['REQUEST_URI']}", true, 301);
  1451. exit;
  1452. }
  1453. return $bRedirectRequired;
  1454. }
  1455. /**
  1456. * Check if redirect to remove install folder.
  1457. * If BX_SKIP_INSTALL_CHECK is defined then this redirect checking is skipped.
  1458. * @param $bProcessRedirect process redirect and exit if needed
  1459. */
  1460. function bx_check_redirect_to_remove_install_folder ($bProcessRedirect = false)
  1461. {
  1462. $bRemoveInstallFolder = !defined ('BX_SKIP_INSTALL_CHECK') && file_exists(BX_DIRECTORY_PATH_ROOT . 'install');
  1463. if ($bRemoveInstallFolder && $bProcessRedirect) {
  1464. header('Location:' . BX_DOL_URL_ROOT . 'install/index.php?action=remove_install');
  1465. exit;
  1466. }
  1467. return $bRemoveInstallFolder;
  1468. }
  1469. /**
  1470. * Show HTTP 503 service unavailable error and exit
  1471. */
  1472. function bx_show_service_unavailable_error_and_exit ($sMsg = false, $iRetryAfter = 86400)
  1473. {
  1474. header('HTTP/1.0 503 Service Unavailable', true, 503);
  1475. header('Retry-After: 600');
  1476. echo $sMsg ? $sMsg : 'Service temporarily unavailable';
  1477. exit;
  1478. }
  1479. /**
  1480. * The function is sumilar to php readfile, but it send all required headers and can send file by chunks and suports file seek
  1481. * @param $sPath path to file to output to the browser
  1482. * @param $sFilename filename without path, ig file is saved from browser, then this name is used, not used(empty) by default
  1483. * @param $sMimeType file mime type, by default 'application/octet-stream'
  1484. * @param $iCacheAge file cache age, by default 0
  1485. * @param $sCachePrivacy cache privacy 'public' (default value) or 'private'
  1486. * @return true on success or false on error
  1487. */
  1488. function bx_smart_readfile($sPath, $sFilename = '', $sMimeType = 'application/octet-stream', $iCacheAge = 0, $sCachePrivacy = 'public')
  1489. {
  1490. if (!file_exists($sPath))
  1491. return false;
  1492. $fp = @fopen($sPath, 'rb');
  1493. $size = filesize($sPath);
  1494. $length = $size;
  1495. $start = 0;
  1496. $end = $size - 1;
  1497. header('Content-type: ' . $sMimeType);
  1498. header('Cache-Control: ' . $sCachePrivacy . ', must-revalidate, max-age=' . $iCacheAge);
  1499. header("Accept-Ranges: 0-$length");
  1500. if ($sFilename)
  1501. header('Content-Disposition: inline; filename="' . $sFilename . '"');
  1502. if (isset($_SERVER['HTTP_RANGE'])) {
  1503. $c_start = $start;
  1504. $c_end = $end;
  1505. list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
  1506. if (strpos($range, ',') !== false) {
  1507. header('HTTP/1.1 416 Requested Range Not Satisfiable');
  1508. header("Content-Range: bytes $start-$end/$size");
  1509. return false;
  1510. }
  1511. if ($range == '-') {
  1512. $c_start = $size - substr($range, 1);
  1513. }else{
  1514. $range = explode('-', $range);
  1515. $c_start = $range[0];
  1516. $c_end = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $size;
  1517. }
  1518. $c_end = ($c_end > $end) ? $end : $c_end;
  1519. if ($c_start > $c_end || $c_start > $size - 1 || $c_end >= $size) {
  1520. header('HTTP/1.1 416 Requested Range Not Satisfiable');
  1521. header("Content-Range: bytes $start-$end/$size");
  1522. return false;
  1523. }
  1524. $start = $c_start;
  1525. $end = $c_end;
  1526. $length = $end - $start + 1;
  1527. fseek($fp, $start);
  1528. header('HTTP/1.1 206 Partial Content');
  1529. }
  1530. header("Content-Range: bytes $start-$end/$size");
  1531. header("Content-Length: ".$length);
  1532. $buffer = 1024 * 8;
  1533. while(!feof($fp) && ($p = ftell($fp)) <= $end) {
  1534. if ($p + $buffer > $end) {
  1535. $buffer = $end - $p + 1;
  1536. }
  1537. set_time_limit(0);
  1538. echo fread($fp, $buffer);
  1539. flush();
  1540. }
  1541. fclose($fp);
  1542. return true;
  1543. }
  1544. /**
  1545. * Wrap in A tag links in TEXT string
  1546. * @param $text - text string without tags
  1547. * @param $sAttrs - attributes string to add to the added A tag
  1548. * @param $bHtmlSpecialChars - apply htmlspecialchars before processing
  1549. * @return string where all links are wrapped in A tag
  1550. */
  1551. function bx_linkify($text, $sAttrs = '', $bHtmlSpecialChars = false)
  1552. {
  1553. if ($bHtmlSpecialChars)
  1554. $text = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8');
  1555. $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_!~*'().;?:\@&=+$,%#-]+)*/?)@";
  1556. preg_match_all($re, $text, $matches, PREG_OFFSET_CAPTURE);
  1557. $matches = $matches[0];
  1558. if ($i = count($matches))
  1559. $bAddNofollow = getParam('sys_add_nofollow') == 'on';
  1560. while ($i--)
  1561. {
  1562. $sAttrsLocal = $sAttrs;
  1563. $url = $matches[$i][0];
  1564. if (!preg_match('@^https?://@', $url))
  1565. $url = 'http://'.$url;
  1566. if (strncmp(BX_DOL_URL_ROOT, $url, strlen(BX_DOL_URL_ROOT)) !== 0) {
  1567. $sAttrsLocal .= ' target="_blank" ';
  1568. if ($bAddNofollow)
  1569. $sAttrsLocal .= ' rel="nofollow" ';
  1570. }
  1571. $text = substr_replace($text, '<a ' . $sAttrsLocal . ' href="'.$url.'">'.$matches[$i][0].'</a>', $matches[$i][1], strlen($matches[$i][0]));
  1572. }
  1573. // email pattern
  1574. $mail_pattern = "/([A-z0-9\._-]+\@[A-z0-9_-]+\.)([A-z0-9\_\-\.]{1,}[A-z])/";
  1575. $text = preg_replace($mail_pattern, '<a href="mailto:$1$2">$1$2</a>', $text);
  1576. return $text;
  1577. }
  1578. /**
  1579. * Wrap in A tag links in HTML string, which aren't wrapped in A tag yet
  1580. * @param $sHtmlOrig - HTML string
  1581. * @param $sAttrs - attributes string to add to the added A tag
  1582. * @return modified HTML string, in case of errror original string is returned
  1583. */
  1584. function bx_linkify_html($sHtmlOrig, $sAttrs = '')
  1585. {
  1586. if (!trim($sHtmlOrig))
  1587. return $sHtmlOrig;
  1588. $sId = 'bx-linkify-' . md5(microtime());
  1589. $dom = new DOMDocument();
  1590. @$dom->loadHTML('<?xml encoding="UTF-8"><div id="' . $sId . '">' . $sHtmlOrig . '</div>');
  1591. $xpath = new DOMXpath($dom);
  1592. foreach ($xpath->query('//text()') as $text) {
  1593. if (!empty($text->parentNode) && !empty($text->parentNode->tagName) && 'a' == $text->parentNode->tagName)
  1594. continue;
  1595. $frag = $dom->createDocumentFragment();
  1596. @$frag->appendXML(bx_linkify($text->nodeValue, $sAttrs, true));
  1597. $text->parentNode->replaceChild($frag, $text);
  1598. }
  1599. if (version_compare(PHP_VERSION, '5.3.6') >= 0)
  1600. $s = $dom->saveHTML($dom->getElementById($sId));
  1601. else
  1602. $s = $dom->saveXML($dom->getElementById($sId), LIBXML_NOEMPTYTAG);
  1603. if (false === $s) // in case of error return original string
  1604. return $sHtmlOrig;
  1605. if (false !== ($iPos = mb_strpos($s, '<html><body>')) && $iPos < mb_strpos($s, $sId))
  1606. $s = mb_substr($s, $iPos + 12, -15); // strip <html><body> tags and everything before them
  1607. return mb_substr($s, 54, -6); // strip added tags
  1608. }
  1609. /**
  1610. * Returns current site protocol http:// or https://
  1611. */
  1612. function bx_proto()
  1613. {
  1614. return 0 === strncmp('https', BX_DOL_URL_ROOT, 5) ? 'https' : 'http';
  1615. }
  1616. /**
  1617. * Checks protocol in the link
  1618. */
  1619. function bx_has_proto($sLink)
  1620. {
  1621. return preg_match('@^https?://@', $sLink);
  1622. }
  1623. function bx_is_empty_array ($a)
  1624. {
  1625. if (!is_array($a))
  1626. return true;
  1627. if (empty($a))
  1628. return true;
  1629. foreach ($a as $k => $v)
  1630. if ($v)
  1631. return false;
  1632. return true;
  1633. }
  1634. function bx_is_full_array ($a)
  1635. {
  1636. if (!is_array($a))
  1637. return false;
  1638. if (empty($a))
  1639. return false;
  1640. foreach ($a as $k => $v)
  1641. if (empty($v))
  1642. return false;
  1643. return true;
  1644. }
  1645. function bx_is_url_in_content ($sContent)
  1646. {
  1647. $a = array(
  1648. 'http://',
  1649. 'https://',
  1650. 'https/',
  1651. 'http/',
  1652. 'www.',
  1653. '.com'
  1654. );
  1655. foreach ($a as $s)
  1656. if (false !== strpos($sContent, $s))
  1657. return true;
  1658. return false;
  1659. }
  1660. function bx_is_dynamic_request ()
  1661. {
  1662. return bx_get('dynamic') || (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && 'XMLHttpRequest' == $_SERVER['HTTP_X_REQUESTED_WITH']);
  1663. }
  1664. function bx_idn_to_utf8($sUrl, $bReturnDomain = false)
  1665. {
  1666. return bx_idn_to('idn_to_utf8', $sUrl, $bReturnDomain);
  1667. }
  1668. function bx_idn_to_ascii($sUrl, $bReturnDomain = false)
  1669. {
  1670. return bx_idn_to('idn_to_ascii', $sUrl, $bReturnDomain);
  1671. }
  1672. function bx_idn_to($sMethod, $sUrl, $bReturnDomain = false)
  1673. {
  1674. $aUrl = parse_url($sUrl);
  1675. if($aUrl === false)
  1676. return $sUrl;
  1677. $sResult = $aUrl['host'];
  1678. if(function_exists($sMethod))
  1679. $sResult = $sMethod($sResult, IDNA_DEFAULT, (defined('INTL_IDNA_VARIANT_UTS46') ? INTL_IDNA_VARIANT_UTS46 : INTL_IDNA_VARIANT_2003));
  1680. if($bReturnDomain)
  1681. return $sResult;
  1682. $sResult = (!empty($aUrl['scheme']) ? $aUrl['scheme'] . '://' : '' ) . $sResult;
  1683. $sResult = $sResult . (!empty($aUrl['path']) ? $aUrl['path'] : '');
  1684. $sResult = $sResult . (!empty($aUrl['query']) ? '?' . $aUrl['query'] : '');
  1685. return $sResult;
  1686. }
  1687. function bx_is_mobile()
  1688. {
  1689. if(!isset($_SERVER['HTTP_USER_AGENT']))
  1690. return false;
  1691. $s = $_SERVER['HTTP_USER_AGENT'];
  1692. 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));
  1693. }
  1694. function bx_get_device_pixel_ratio()
  1695. {
  1696. $iRatio = 1;
  1697. if(!isset($_COOKIE['devicePixelRatio']))
  1698. return $iRatio;
  1699. $iDevicePixelRatio = intval($_COOKIE['devicePixelRatio']);
  1700. if($iDevicePixelRatio >= 2)
  1701. $iRatio = 2;
  1702. return $iRatio;
  1703. }
  1704. /**
  1705. * Log to logs object
  1706. * @param $sObject - logs object
  1707. * @param $mixed - string or array to log
  1708. */
  1709. function bx_log($sObject, $mixed)
  1710. {
  1711. if ($o = BxDolLogs::getObjectInstance($sObject))
  1712. return $o->add($mixed);
  1713. else
  1714. return false;
  1715. }
  1716. /** @} */