utils.inc.php 73 KB

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