utils.inc.php 96 KB

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