utils.inc.php 103 KB

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