utils.inc.php 89 KB

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