utils.inc.php 77 KB

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