utils.inc.php 102 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940
  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 = $this->_str2px($aAttributes['WIDTH']);
  570. if(!$iHeight && isset($aAttributes['HEIGHT']))
  571. $iHeight = $this->_str2px($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. curl_close($rConnect);
  1001. }
  1002. else {
  1003. $iSaveTimeout = false;
  1004. if (0 !== $iTimeout) {
  1005. $iSaveTimeout = ini_get('default_socket_timeout');
  1006. ini_set('default_socket_timeout', $iTimeout);
  1007. }
  1008. $sResult = @file_get_contents($sFileUrl);
  1009. if (0 !== $iTimeout && false !== $iSaveTimeout) {
  1010. ini_set('default_socket_timeout', $iSaveTimeout);
  1011. }
  1012. }
  1013. return $sResult;
  1014. }
  1015. function bx_make_utf8($s)
  1016. {
  1017. // Test it and see if it is UTF-8 or not
  1018. if (false !== mb_detect_encoding($s, ["UTF-8"], true))
  1019. return $s;
  1020. $sEncoding = mb_detect_encoding($s, ['ASCII', 'BASE64', 'HTML-ENTITIES', 'Windows-1251', 'KOI8-R'], true);
  1021. if ($sEncoding === false)
  1022. return $s;
  1023. return mb_convert_encoding($s, "UTF-8", $sEncoding);
  1024. }
  1025. function bx_get_site_info($sSourceUrl, $aProcessAdditionalTags = array())
  1026. {
  1027. $aResult = array();
  1028. $sContent = bx_file_get_contents($sSourceUrl);
  1029. if ($sContent) {
  1030. $sCharset = '';
  1031. preg_match("/<meta.+charset=([A-Za-z0-9-]+).+>/i", $sContent, $aMatch);
  1032. if (isset($aMatch[1]))
  1033. $sCharset = $aMatch[1];
  1034. $sContent = preg_replace("/<script[^>]*>(.*?)<\/script>/i", '', $sContent);
  1035. $sContent = preg_replace("/<style[^>]*>(.*?)<\/style>/i", '', $sContent);
  1036. if (preg_match("/<title[^>]*>(.*?)<\/title>/i", $sContent, $aMatch))
  1037. $aResult['title'] = bx_make_utf8(strip_tags($aMatch[1]), $sCharset);
  1038. else
  1039. $aResult['title'] = parse_url($sSourceUrl, PHP_URL_HOST);
  1040. $aResult['description'] = bx_make_utf8(bx_parse_html_tag($sContent, 'meta', 'name', 'description', 'content', $sCharset), $sCharset);
  1041. $aResult['keywords'] = bx_make_utf8(bx_parse_html_tag($sContent, 'meta', 'name', 'keywords', 'content', $sCharset), $sCharset);
  1042. if ($aProcessAdditionalTags) {
  1043. foreach ($aProcessAdditionalTags as $k => $a) {
  1044. $aResult[$k] = bx_parse_html_tag(
  1045. $sContent,
  1046. isset($a['tag']) ? $a['tag'] : 'meta',
  1047. isset($a['name_attr']) ? $a['name_attr'] : 'itemprop',
  1048. isset($a['name']) ? $a['name'] : $k,
  1049. isset($a['content_attr']) ? $a['content_attr'] : 'content',
  1050. $sCharset,
  1051. isset($a['specialchars_decode']) ? $a['specialchars_decode'] : true);
  1052. if ((isset($a['name']) && 'og:image' == $a['name']) || (isset($a['tag']) && 'link' == $a['tag'])) {
  1053. $aResult[$k] = bx_get_site_info_fix_relative_url ($sSourceUrl, $aResult[$k]);
  1054. }
  1055. }
  1056. }
  1057. }
  1058. return $aResult;
  1059. }
  1060. /**
  1061. * Fix relative URL to make it absolute
  1062. * @param $sSourceUrl main URL
  1063. * @param $s URL to fix
  1064. * @return absolute URL or URL wothout changes
  1065. */
  1066. function bx_get_site_info_fix_relative_url ($sSourceUrl, $s)
  1067. {
  1068. if (0 === stripos($s, 'http://') || 0 === stripos($s, 'https://') || 0 === stripos($s, 'ftp://') || !$s)
  1069. return $s;
  1070. if ('/' == $s[0]) {
  1071. $a = parse_url($sSourceUrl);
  1072. return $a['scheme'] . '://' . $a['host'] . (empty($a['port']) || 80 == $a['port'] || 443 == $a['port'] ? '' : ':' . $a['port']) . $s;
  1073. }
  1074. return $sSourceUrl . ('/' === substr($sSourceUrl, -1) ? $s : '/' . $s);
  1075. }
  1076. function bx_parse_html_tag ($sContent, $sTag, $sAttrNameName, $sAttrNameValue, $sAttrContentName, $sCharset = false, $bSpecialCharsDecode = true)
  1077. {
  1078. // This regex is designed to be more flexible with attribute orders and spacing
  1079. $regex = "/<{$sTag}\s+(?:[^>]*?\s+)?{$sAttrNameName}\s*=\s*['\"]?{$sAttrNameValue}['\"]?\s+[^>]*{$sAttrContentName}\s*=\s*['\"]([^'\"]*)['\"][^>]*>/i";
  1080. if (!preg_match($regex, $sContent, $aMatch)) {
  1081. // Try reversing the attribute order in case the first regex fails
  1082. $regex = "/<{$sTag}\s+(?:[^>]*?\s+)?{$sAttrContentName}\s*=\s*['\"]([^'\"]*)['\"]\s+[^>]*{$sAttrNameName}\s*=\s*['\"]?{$sAttrNameValue}['\"]?[^>]*>/i";
  1083. preg_match($regex, $sContent, $aMatch);
  1084. }
  1085. // Extract the attribute content if available
  1086. $s = isset($aMatch[1]) ? $aMatch[1] : '';
  1087. // Optionally convert character encoding
  1088. if ($s && $sCharset) {
  1089. $s = mb_convert_encoding($s, 'UTF-8', $sCharset);
  1090. }
  1091. // Optionally decode special HTML characters
  1092. if ($bSpecialCharsDecode) {
  1093. $s = htmlspecialchars_decode($s);
  1094. }
  1095. return $s;
  1096. }
  1097. // calculation ini_get('upload_max_filesize') in bytes as example
  1098. function return_bytes($val)
  1099. {
  1100. $val = trim($val);
  1101. $last = strtolower($val[strlen($val)-1]);
  1102. $val = (int)$val;
  1103. switch($last) {
  1104. // The 'G' modifier is available since PHP 5.1.0
  1105. case 'k':
  1106. $val *= 1024;
  1107. break;
  1108. case 'm':
  1109. $val *= 1024 * 1024;
  1110. break;
  1111. case 'g':
  1112. $val *= 1024 * 1024 * 1024;
  1113. break;
  1114. }
  1115. return $val;
  1116. }
  1117. /**
  1118. * Format bytes to human-readable format
  1119. * @param $iBytes - number of bytes
  1120. * @param $iPrecision - decimal places (default 1)
  1121. * @return formatted string like "2.5M", "512K", "1024B"
  1122. */
  1123. function bx_format_bytes($iBytes)
  1124. {
  1125. return _t_format_size($iBytes);
  1126. }
  1127. // Generate Random Password
  1128. function genRndPwd($iLength = 8, $bSpecialCharacters = true)
  1129. {
  1130. $sPassword = '';
  1131. $sChars = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
  1132. if($bSpecialCharacters === true)
  1133. $sChars .= "!?=/&+,.";
  1134. for($i = 0; $i < $iLength; $i++) {
  1135. $x = mt_rand(0, strlen($sChars) -1);
  1136. $sPassword .= $sChars[$x];
  1137. }
  1138. return $sPassword;
  1139. }
  1140. // Generate Random Salt for Password encryption
  1141. function genRndSalt()
  1142. {
  1143. return genRndPwd(8, true);
  1144. }
  1145. /**
  1146. * Encrypt user password.
  1147. * When BX_PWD_ALGO is 'custom', then bx_custom_pwd_encrypt function with custom algorythm must be defined in inc/header.inc.php file.
  1148. * @param $sPwd clear password
  1149. * @param $sSalt salt
  1150. * @return password hash
  1151. */
  1152. function encryptUserPwd($sPwd, $sSalt)
  1153. {
  1154. $sAlgo = defined('BX_PWD_ALGO') ? BX_PWD_ALGO : '';
  1155. switch ($sAlgo) {
  1156. case 'custom':
  1157. return bx_custom_pwd_encrypt($sPwd, $sSalt);
  1158. case 'crypt':
  1159. return crypt($sPwd, BX_PWD_ALGO_SALT);
  1160. case 'sha1_crypt_salt':
  1161. return sha1(crypt($sPwd, BX_PWD_ALGO_SALT) . $sSalt);
  1162. case 'sha1_md5_salt':
  1163. default:
  1164. return sha1(md5($sPwd) . $sSalt);
  1165. }
  1166. }
  1167. /**
  1168. * Hash profile ID
  1169. */
  1170. function encryptUserId($sId)
  1171. {
  1172. if (!($oProfile = BxDolProfile::getInstance($sId)))
  1173. return false;
  1174. if (!($oAccount = $oProfile->getAccountObject()))
  1175. return false;
  1176. $aAccountInfo = $oAccount->getInfo();
  1177. return sha1(md5($sId) . md5($aAccountInfo['salt']) . BX_DOL_SECRET);
  1178. }
  1179. function bx_get_reset_password_key($sValue, $sField = 'email', $iLifetime = 0)
  1180. {
  1181. if(empty($iLifetime)) {
  1182. $iLifetime = (int)getParam('sys_account_reset_password_key_lifetime');
  1183. if(empty($iLifetime))
  1184. $iLifetime = 86400;
  1185. }
  1186. $oKey = BxDolKey::getInstance();
  1187. if(!$oKey)
  1188. return false;
  1189. return $oKey->getNewKey(array($sField => $sValue), $iLifetime);
  1190. }
  1191. function bx_get_reset_password_link($sValue, $sField = 'email', $iLifetime = 0)
  1192. {
  1193. $sKey = bx_get_reset_password_key($sValue, $sField, $iLifetime);
  1194. if(!$sKey)
  1195. return false;
  1196. return bx_get_reset_password_link_by_key($sKey);
  1197. }
  1198. function bx_get_reset_password_link_by_key($sKey)
  1199. {
  1200. return bx_absolute_url(BxDolPermalinks::getInstance()->permalink('page.php?i=forgot-password', array('key' => $sKey)));
  1201. }
  1202. function bx_get_reset_password_redirect($iAccountId)
  1203. {
  1204. $sResult = '';
  1205. $sRedirect = getParam('sys_account_reset_password_redirect');
  1206. switch($sRedirect) {
  1207. case 'home':
  1208. $sResult = BxDolPermalinks::getInstance()->permalink('page.php?i=home');
  1209. break;
  1210. case 'profile':
  1211. case 'profile_edit':
  1212. if(empty($iAccountId))
  1213. break;
  1214. $oAccount = BxDolAccount::getInstance($iAccountId);
  1215. if(!$oAccount)
  1216. break;
  1217. $aAccountInfo = $oAccount->getInfo();
  1218. if(empty($aAccountInfo) || !is_array($aAccountInfo) || empty($aAccountInfo['profile_id']))
  1219. break;
  1220. $oProfile = BxDolProfile::getInstance((int)$aAccountInfo['profile_id']);
  1221. if(!$oProfile)
  1222. break;
  1223. $sResult = $oProfile->{'get' . ($sRedirect == 'profile_edit' ? 'Edit' : '') . 'Url'}();
  1224. break;
  1225. case 'custom':
  1226. $sResult = getParam('sys_account_reset_password_redirect_custom');
  1227. break;
  1228. }
  1229. if(!empty($sResult))
  1230. $sResult = bx_absolute_url($sResult);
  1231. return $sResult;
  1232. }
  1233. function bx_get ($sName, $sMethod = false)
  1234. {
  1235. if (isset($_GET[$sName]) && ('get' == $sMethod || !$sMethod))
  1236. return $_GET[$sName];
  1237. elseif (isset($_POST[$sName]) && ('post' == $sMethod || !$sMethod))
  1238. return $_POST[$sName];
  1239. else
  1240. return false;
  1241. }
  1242. function bx_set ($sName, $sValue, $sMethod = false)
  1243. {
  1244. if(!$sMethod)
  1245. $sMethod = 'get';
  1246. $bResult = true;
  1247. switch($sMethod) {
  1248. case 'get':
  1249. $_GET[$sName] = $sValue;
  1250. break;
  1251. case 'post':
  1252. $_POST[$sName] = $sValue;
  1253. break;
  1254. default:
  1255. $bResult = false;
  1256. }
  1257. return $bResult;
  1258. }
  1259. function bx_get_with_prefix ($sPrefix, $sMethod = false)
  1260. {
  1261. $aSources = array('get' => &$_GET, 'post' => &$_POST);
  1262. $aFiltered = array();
  1263. foreach($aSources as $sName => $aSource)
  1264. if($sMethod == $sName || !$sMethod)
  1265. $aFiltered = array_merge($aFiltered, array_filter($aSource, function($sKey) use ($sPrefix) {
  1266. return strpos($sKey, $sPrefix) === 0;
  1267. }, ARRAY_FILTER_USE_KEY));
  1268. $aUpdated = array();
  1269. array_walk($aFiltered, function($sValue, $sKey) use ($sPrefix, &$aUpdated) {
  1270. $aUpdated[trim(str_replace($sPrefix, '', $sKey), '_-')] = $sValue;
  1271. });
  1272. return $aUpdated;
  1273. }
  1274. function bx_get_base_url_inline($aParams = array())
  1275. {
  1276. $aBaseLink = parse_url(BX_DOL_URL_ROOT);
  1277. $sPageLink = (!empty($aBaseLink['scheme']) ? $aBaseLink['scheme'] : 'http') . '://' . $aBaseLink['host'] . (!empty($aBaseLink['port']) ? ':' . $aBaseLink['port'] : '');
  1278. if(!empty($_SERVER['REQUEST_URI']))
  1279. $sPageLink .= $_SERVER['REQUEST_URI'];
  1280. list($sPageLink, $aPageParams) = bx_get_base_url($sPageLink);
  1281. if(!empty($_SERVER['QUERY_STRING'])) {
  1282. $aPageParamsAdd = array();
  1283. parse_str($_SERVER['QUERY_STRING'], $aPageParamsAdd);
  1284. if(!empty($aPageParamsAdd) && is_array($aPageParamsAdd))
  1285. $aPageParams = array_merge($aPageParams, $aPageParamsAdd);
  1286. }
  1287. if(!empty($aParams) && is_array($aParams))
  1288. $aPageParams = array_merge($aPageParams, $aParams);
  1289. return array($sPageLink, $aPageParams);
  1290. }
  1291. function bx_get_base_url_popup($aParams = array())
  1292. {
  1293. list($sPageLink, $aPageParams) = bx_get_base_url($_SERVER['HTTP_REFERER']);
  1294. if(!empty($aParams) && is_array($aParams))
  1295. $aPageParams = array_merge($aPageParams, $aParams);
  1296. return array($sPageLink, $aPageParams);
  1297. }
  1298. function bx_get_base_url($sPageLink)
  1299. {
  1300. $sPageLink = BxDolPermalinks::getInstance()->unpermalink($sPageLink, false);
  1301. $sPageParams = '';
  1302. if(strpos($sPageLink, '?') !== false)
  1303. list($sPageLink, $sPageParams) = explode('?', $sPageLink);
  1304. $aPageParams = array();
  1305. if(!empty($sPageParams))
  1306. parse_str($sPageParams, $aPageParams);
  1307. return array($sPageLink, $aPageParams);
  1308. }
  1309. function bx_get_page_info()
  1310. {
  1311. list($sPageLink, $aPageParams) = bx_get_base_url_inline();
  1312. if(isset($aPageParams['i'], $aPageParams['id']) && ($oPage = BxDolPage::getObjectInstanceByURI($aPageParams['i'])) !== false) {
  1313. $sPageModule = $oPage->getModule();
  1314. if(bx_srv('system', 'is_module_context', [$sPageModule]) && ($oProfile = BxDolProfile::getInstanceByContentAndType($aPageParams['id'], $sPageModule)) !== false)
  1315. return [
  1316. 'context_module' => $sPageModule,
  1317. 'context_id' => $aPageParams['id'],
  1318. 'context_profile_id' => $oProfile->id()
  1319. ];
  1320. }
  1321. if(isset($aPageParams['profile_id']) && ($oProfile = BxDolProfile::getInstance($aPageParams['profile_id'])) !== false) {
  1322. $sProfileModule = $oProfile->getModule();
  1323. if(bx_srv('system', 'is_module_context', [$sProfileModule]))
  1324. return [
  1325. 'context_module' => $sProfileModule,
  1326. 'context_id' => $oProfile->getContentId(),
  1327. 'context_profile_id' => $aPageParams['profile_id']
  1328. ];
  1329. }
  1330. return false;
  1331. }
  1332. function bx_get_location_bounds_latlng($fLatitude, $fLongitude, $iRadiusInKm)
  1333. {
  1334. $fEquatorLatInKm = 111.321;
  1335. $aRv = array();
  1336. $aRv['max_lat'] = $fLatitude + $iRadiusInKm / $fEquatorLatInKm;
  1337. $aRv['min_lat'] = $fLatitude - ($aRv['max_lat'] - $fLatitude);
  1338. $aRv['max_lng'] = $fLongitude + $iRadiusInKm / (cos($aRv['min_lat'] * M_PI / 180) * $fEquatorLatInKm);
  1339. $aRv['min_lng'] = $fLongitude - ($aRv['max_lng'] - $fLongitude);
  1340. return $aRv;
  1341. }
  1342. function bx_encode_url_params ($a, $aExcludeKeys = array (), $aOnlyKeys = false)
  1343. {
  1344. $s = '';
  1345. foreach ($a as $sKey => $sVal) {
  1346. if (in_array($sKey, $aExcludeKeys))
  1347. continue;
  1348. if (false !== $aOnlyKeys && !in_array($sKey, $aOnlyKeys))
  1349. continue;
  1350. if (is_array($sVal)) {
  1351. foreach ($sVal as $sSubVal) {
  1352. $s .= rawurlencode($sKey) . '[]=' . rawurlencode(is_array($sSubVal) ? 'array' : $sSubVal) . '&';
  1353. }
  1354. } else {
  1355. $s .= rawurlencode($sKey) . '=' . rawurlencode($sVal) . '&';
  1356. }
  1357. }
  1358. return $s;
  1359. }
  1360. /**
  1361. * It works similar to `parse_str` php function, but it doesn't decode URL params
  1362. */
  1363. function bx_parse_str($s)
  1364. {
  1365. $a = [];
  1366. $aPairs = explode('&', $s);
  1367. foreach ($aPairs as $i) {
  1368. list($sName, $mixedValue) = explode('=', $i, 2);
  1369. $sName = rtrim($sName, '[]');
  1370. if (isset($a[$sName])) {
  1371. if (is_array($a[$sName]))
  1372. $a[$sName][] = $mixedValue;
  1373. else
  1374. $a[$sName] = [$a[$sName], $mixedValue];
  1375. }
  1376. else {
  1377. $a[$sName] = $mixedValue;
  1378. }
  1379. }
  1380. return $a;
  1381. }
  1382. function bx_append_url_params ($sUrl, $mixedParams, $bEncodeParams = true, $aIgnoreParams = [])
  1383. {
  1384. if (!$mixedParams)
  1385. return $sUrl;
  1386. $sParams = false === strpos($sUrl, '?') ? '?' : '&';
  1387. if (is_array($mixedParams)) {
  1388. foreach($mixedParams as $sKey => $sValue) {
  1389. if (!is_array($sValue)) {
  1390. if ($bEncodeParams) {
  1391. if ($sKey && !in_array($sKey, $aIgnoreParams))
  1392. $sKey = rawurlencode($sKey);
  1393. if ($sValue && !in_array($sValue, $aIgnoreParams))
  1394. $sValue = rawurlencode($sValue);
  1395. }
  1396. $sParams .= $sKey . '=' . $sValue . '&';
  1397. }
  1398. else {
  1399. foreach($sValue as $sSubValue) {
  1400. if ($bEncodeParams) {
  1401. if ($sKey && !in_array($sKey, $aIgnoreParams))
  1402. $sKey = rawurlencode($sKey);
  1403. if ($sSubValue && !in_array($sSubValue, $aIgnoreParams))
  1404. $sSubValue = rawurlencode($sSubValue);
  1405. }
  1406. $sParams .= $sKey . '[]=' . $sSubValue . '&';
  1407. }
  1408. }
  1409. }
  1410. $sParams = substr($sParams, 0, -1);
  1411. } else {
  1412. $sParams .= $mixedParams;
  1413. }
  1414. return $sUrl . $sParams;
  1415. }
  1416. function bx_process_url_param($sValue, $sPattern = "/^[\d\w_-]+$/")
  1417. {
  1418. $mixedValue = bx_process_input($sValue);
  1419. return $mixedValue !== false && preg_match($sPattern, $mixedValue) ? $mixedValue : '';
  1420. }
  1421. function bx_rrmdir($directory)
  1422. {
  1423. if (substr($directory,-1) == "/")
  1424. $directory = substr($directory,0,-1);
  1425. if (!file_exists($directory) || !is_dir($directory))
  1426. return false;
  1427. elseif (!is_readable($directory))
  1428. return false;
  1429. if (!($directoryHandle = opendir($directory)))
  1430. return false;
  1431. while ($contents = readdir($directoryHandle)) {
  1432. if ($contents != '.' && $contents != '..') {
  1433. $path = $directory . "/" . $contents;
  1434. if (is_dir($path))
  1435. bx_rrmdir($path);
  1436. else
  1437. unlink($path);
  1438. }
  1439. }
  1440. closedir($directoryHandle);
  1441. if (!rmdir($directory))
  1442. return false;
  1443. return true;
  1444. }
  1445. function bx_clear_folder ($sPath, $aExts = array ())
  1446. {
  1447. if (substr($$sPath,-1) == "/")
  1448. $sPath = substr($sPath,0,-1);
  1449. if (!file_exists($sPath) || !is_dir($sPath))
  1450. return false;
  1451. elseif (!is_readable($sPath))
  1452. return false;
  1453. if (!($h = opendir($sPath)))
  1454. return false;
  1455. while ($sFile = readdir($h)) {
  1456. if ('.' == $sFile || '..' == $sFile)
  1457. continue;
  1458. $sFullPath = $sPath . '/' . $sFile;
  1459. if (is_dir($sFullPath))
  1460. continue;
  1461. if (!$aExts || (($sExt = pathinfo($sFullPath, PATHINFO_EXTENSION)) && in_array($sExt, $aExts)))
  1462. @unlink($sFullPath);
  1463. }
  1464. closedir($h);
  1465. return true;
  1466. }
  1467. function bx_ltrim_str ($sString, $sPrefix, $sReplace = '')
  1468. {
  1469. if ($sReplace && substr($sString, 0, strlen($sReplace)) == $sReplace)
  1470. return $sString;
  1471. if (substr($sString, 0, strlen($sPrefix)) == $sPrefix)
  1472. return $sReplace . substr($sString, strlen($sPrefix));
  1473. return $sString;
  1474. }
  1475. function bx_rtrim_str ($sString, $sPrefix, $sReplace = '')
  1476. {
  1477. if ($sReplace && substr($sString, -strlen($sReplace)) == $sReplace)
  1478. return $sString;
  1479. if (substr($sString, -strlen($sPrefix)) == $sPrefix)
  1480. return substr($sString, 0, -strlen($sPrefix)) . $sReplace;
  1481. return $sString;
  1482. }
  1483. /**
  1484. * Strip all lines with no information for example: <p></p>, <br /><br />
  1485. */
  1486. function bx_trim_nl_duplicates($s)
  1487. {
  1488. $sStrip = implode('', array_keys(get_html_translation_table(HTML_ENTITIES)));
  1489. return implode('', array_filter(mb_split("[\n\r]", $s), function($s) use ($sStrip) {
  1490. return trim(strip_tags($s, '<button><canvas><embed><hr><iframe><img><input><object><select><svg><video>'), $sStrip) !== '';
  1491. }));
  1492. }
  1493. /**
  1494. * Convert array to attributes string
  1495. *
  1496. * Example:
  1497. * @code
  1498. * $a = array('name' => 'test', 'value' => 5);
  1499. * $s = bx_convert_array2attrs($a);
  1500. * echo $s; // outputs: name="test" value="5"
  1501. * @endcode
  1502. *
  1503. * @param $a - array of attributes
  1504. * @param $sClasses - classes to merge with 'class' attribute
  1505. * @param $sStyles - styles to merge with 'style' attribute
  1506. * @return string
  1507. */
  1508. function bx_convert_array2attrs ($a, $sClasses = false, $sStyles = false)
  1509. {
  1510. $sRet = '';
  1511. if (!$a || !is_array($a))
  1512. $a = array();
  1513. if ($sClasses) {
  1514. $sClasses = trim($sClasses);
  1515. $a['class'] = $sClasses . (!empty($a['class']) ? ' ' . $a['class'] : '');
  1516. }
  1517. if ($sStyles) {
  1518. $sStyles = trim($sStyles);
  1519. if (';' != $sStyles[strlen($sStyles)-1])
  1520. $sStyles .= ';';
  1521. $a['style'] = $sStyles . (!empty($a['style']) ? ' ' . $a['style'] : '');
  1522. }
  1523. foreach ($a as $sKey => $sValue) {
  1524. if(is_null($sValue)) // pass NULL values
  1525. continue;
  1526. $sValueC = bx_html_attribute($sValue, BX_ESCAPE_STR_QUOTE);
  1527. $sRet .= " $sKey=\"$sValueC\"";
  1528. }
  1529. return $sRet;
  1530. }
  1531. function bx_unicode_urldecode($s)
  1532. {
  1533. preg_match_all('/%u([[:alnum:]]{4})/', $s, $a);
  1534. foreach ($a[1] as $uniord) {
  1535. $dec = hexdec($uniord);
  1536. $utf = '';
  1537. if ($dec < 128) {
  1538. $utf = chr($dec);
  1539. } else if ($dec < 2048) {
  1540. $utf = chr(192 + (($dec - ($dec % 64)) / 64));
  1541. $utf .= chr(128 + ($dec % 64));
  1542. } else {
  1543. $utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
  1544. $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
  1545. $utf .= chr(128 + ($dec % 64));
  1546. }
  1547. $s = str_replace('%u'.$uniord, $utf, $s);
  1548. }
  1549. return urldecode($s);
  1550. }
  1551. /**
  1552. * Raise an audit event
  1553. * @param int $iContentId - content id
  1554. * @param string $sContentModule - module name
  1555. * @param string $sAction - system action key
  1556. * @param array $aParams - array of parameters
  1557. */
  1558. function bx_audit($iContentId, $sContentModule, $sAction, $aParams, $iProfileId = 0)
  1559. {
  1560. if (!getParam('sys_audit_enable') || getParam('sys_audit_acl_levels') == '')
  1561. return;
  1562. if ($iProfileId == 0)
  1563. $iProfileId = bx_get_logged_profile_id();
  1564. if (!BxDolAcl::getInstance()->isMemberLevelInSet(explode(',', getParam('sys_audit_acl_levels')), $iProfileId))
  1565. return;
  1566. $sContentTitle = $sContentInfoObject = $sContextProfileTitle = $sData = $sActionParams = '';
  1567. $iContextProfileId = 0;
  1568. if (isset($aParams['profile_id']))
  1569. $iProfileId = (int)$aParams['profile_id'];
  1570. if (isset($aParams['content_title']))
  1571. $sContentTitle = $aParams['content_title'];
  1572. if (isset($aParams['context_profile_id']))
  1573. $iContextProfileId = (int)$aParams['context_profile_id'];
  1574. if (isset($aParams['context_profile_title']))
  1575. $sContextProfileTitle = $aParams['context_profile_title'];
  1576. if (isset($aParams['action_params']) && is_array($aParams['action_params']) && count($aParams['action_params']))
  1577. $sActionParams = serialize($aParams['action_params']);
  1578. if (isset($aParams['content_info_object']))
  1579. $sContentInfoObject = $aParams['content_info_object'];
  1580. if (isset($aParams['data']) && is_array($aParams['data']) && count($aParams['data']))
  1581. $sData = serialize($aParams['data']);
  1582. $sProfileTitle = BxDolProfile::getInstance($iProfileId)->getDisplayName();
  1583. $oDb = BxDolDb::getInstance();
  1584. $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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
  1585. ,time(), $iProfileId, $sProfileTitle, $iContentId, $sContentTitle, $sContentModule, $iContextProfileId, $sContextProfileTitle, $sAction, $sActionParams ,$sContentInfoObject, $sData);
  1586. return !$oDb->query($sSql);
  1587. }
  1588. /**
  1589. * Raise an alert
  1590. * @param string $sUnit - system type
  1591. * @param string $sAction - system action
  1592. * @param int $iObjectId - object id
  1593. * @param int $iSender - sender (action's author) profile id, if it is false - then currectly logged in profile id is used
  1594. * @param array $aExtras - extra parameters
  1595. */
  1596. function bx_alert($sUnit, $sAction, $iObjectId, $iSender = false, $aExtras = array())
  1597. {
  1598. $o = new BxDolAlerts($sUnit, $sAction, $iObjectId, $iSender, $aExtras);
  1599. $o->alert();
  1600. }
  1601. /**
  1602. * Check whether serice method exists or not
  1603. * @param $mixed module name or module id
  1604. * @param $sMethod service method name in format 'method_name', corresponding class metod is serviceMethodName
  1605. * @param $sClass class to search for service method, by default it is main module class
  1606. * @return boolean check result
  1607. */
  1608. function bx_is_srv($mixedModule, $sMethod, $sClass = "Module", $bIgnoreInactive = false)
  1609. {
  1610. return BxDolRequest::serviceExists($mixedModule, $sMethod, $sClass, $bIgnoreInactive);
  1611. }
  1612. /**
  1613. * Check whether serice method exists or not in 'Ignore Inactive' mode.
  1614. */
  1615. function bx_is_srv_ii($mixedModule, $sMethod, $sClass = "Module")
  1616. {
  1617. return BxDolRequest::serviceExists($mixedModule, $sMethod, $sClass, true);
  1618. }
  1619. /**
  1620. * Perform serice call
  1621. * @param $mixed module name or module id
  1622. * @param $sMethod service method name in format 'method_name', corresponding class metod is serviceMethodName
  1623. * @param $aParams params to pass to service method
  1624. * @param $sClass class to search for service method, by default it is main module class
  1625. * @return service call result
  1626. */
  1627. function bx_srv($mixed, $sMethod, $aParams = array(), $sClass = 'Module', $bIgnoreCache = false, $bIgnoreInactive = false)
  1628. {
  1629. return BxDolService::call($mixed, $sMethod, $aParams, $sClass, $bIgnoreCache, $bIgnoreInactive);
  1630. }
  1631. /**
  1632. * Perform serice call in 'Ignore Inactive' mode.
  1633. */
  1634. function bx_srv_ii($mixed, $sMethod, $aParams = array(), $sClass = 'Module', $bIgnoreCache = false)
  1635. {
  1636. return BxDolService::call($mixed, $sMethod, $aParams, $sClass, $bIgnoreCache, true);
  1637. }
  1638. /**
  1639. * Perform serice call in 'Ignore Cache' mode.
  1640. */
  1641. function bx_srv_ic($mixed, $sMethod, $aParams = array(), $sClass = 'Module', $bIgnoreInactive = false)
  1642. {
  1643. return BxDolService::call($mixed, $sMethod, $aParams, $sClass, true, $bIgnoreInactive);
  1644. }
  1645. function bx_replace_markers($mixed, $aMarkers)
  1646. {
  1647. if (empty($mixed) || empty($aMarkers))
  1648. return $mixed;
  1649. if (is_array($mixed)) {
  1650. foreach ($mixed as $sKey => $sValue)
  1651. $mixed[$sKey] = bx_replace_markers ($sValue, $aMarkers);
  1652. } else {
  1653. foreach ($aMarkers as $sKey => $sValue)
  1654. $mixed = str_replace('{' . $sKey . '}', is_null($sValue) ? '' : $sValue, $mixed);
  1655. }
  1656. return $mixed;
  1657. }
  1658. function bx_site_hash($sSalt = '', $isSkipVersion = false)
  1659. {
  1660. return md5($sSalt . ($isSkipVersion ? '' : bx_get_ver() . getParam('sys_revision')) . BX_DOL_SECRET . BX_DOL_URL_ROOT);
  1661. }
  1662. /**
  1663. * Transform string to method name string, for example it changes 'some_method' string to 'SomeMethod' string
  1664. * @param $s string where words are separated with underscore
  1665. * @param $aWordsDelimiter word delimeters
  1666. * @return string where every word begins with capital letter
  1667. */
  1668. function bx_gen_method_name ($s, $aWordsDelimiter = array('_'))
  1669. {
  1670. return str_replace(' ', '', ucwords(str_replace($aWordsDelimiter, ' ', $s)));
  1671. }
  1672. /**
  1673. * Trigger user error
  1674. * @param $sMsg message to display
  1675. * @param $iNumLevelsBack add additional debug backtracing N levels back
  1676. */
  1677. function bx_trigger_error ($sMsg, $iNumLevelsBack = 0)
  1678. {
  1679. $a = debug_backtrace();
  1680. $sMsgAdd = "<br />\n related code in <b>{$a[$iNumLevelsBack]['file']}</b> on line <b>{$a[$iNumLevelsBack]['line']}</b> <br />\n";
  1681. trigger_error ($sMsg . $sMsgAdd, E_USER_ERROR);
  1682. }
  1683. /**
  1684. * Get system DB version, for files version @see BX_DOL_VERSION, these versions must match
  1685. */
  1686. function bx_get_ver ($bInvalidateCache = false)
  1687. {
  1688. $oDb = BxDolDb::getInstance();
  1689. if ($bInvalidateCache)
  1690. $oDb->cleanMemory('sys_version');
  1691. $sQuery = $oDb->prepare("SELECT `version` FROM `sys_modules` WHERE `name` = 'system'");
  1692. return $oDb->fromMemory('sys_version', 'getOne', $sQuery);
  1693. }
  1694. function bx_check_debug_mode()
  1695. {
  1696. if(!bx_is_dbg())
  1697. return;
  1698. ini_set('display_errors', 'On');
  1699. error_reporting(E_ALL);
  1700. }
  1701. /**
  1702. * Check if site maintetance mode is enabled.
  1703. * Maintetance mode is enabled when '.bx_maintenance' file exists in the script root folder,
  1704. * please note that this is hidden file and some file managers don't show it.
  1705. * @param $bShowHttpError show 503 HTTP error if site is in mainenance mode
  1706. * @return true if site is in maintenance mode, or false otherwise
  1707. */
  1708. function bx_check_maintenance_mode ($bShowHttpError = false)
  1709. {
  1710. $bMaintetance = file_exists(BX_DIRECTORY_PATH_ROOT . BX_MAINTENANCE_FILE) && !defined('BX_DOL_UPGRADING');
  1711. if ($bMaintetance && $bShowHttpError)
  1712. bx_show_service_unavailable_error_and_exit ('Site is temporarily unavailable due to scheduled maintenance, please try again in a minute.', 600);
  1713. return $bMaintetance;
  1714. }
  1715. /**
  1716. * Check if site soft maintetance mode is enabled.
  1717. * Soft maintetance mode is enabled when maintenance mode is enabled via studio setting.
  1718. */
  1719. function bx_check_maintenance_mode_soft ()
  1720. {
  1721. if (isset($_SERVER['HTTP_HOST'])) {
  1722. $sUrl = bx_proto() . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
  1723. if (0 === strpos($sUrl, BX_DOL_URL_STUDIO)) // allow to view studio
  1724. return;
  1725. if (0 === strpos($sUrl, BX_DOL_URL_ROOT . 'member.php') && $_SERVER['REQUEST_METHOD'] === 'POST') // make studio login form to always work
  1726. return;
  1727. }
  1728. if (defined('BX_DOL_UPGRADING')) // allow upgrade
  1729. return;
  1730. if (!getParam('sys_maintenance_mode')) // check mainenance mode switcher
  1731. return;
  1732. if (isAdmin()) // always allow studio operators
  1733. return;
  1734. $sHtml = getParam('sys_maintenance_mode_html');
  1735. 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);
  1736. }
  1737. /**
  1738. * Check for minimal requirements.
  1739. * if BX_DISABLE_REQUIREMENTS_CHECK is defined then this requirements checking is skipped.
  1740. * @param $bShowHttpError show 503 HTTP error if site doesn't meet minimal requirements
  1741. * @return false if requirements are met, or array of errors of requirements aren't met
  1742. */
  1743. function bx_check_minimal_requirements ($bShowHttpError = false)
  1744. {
  1745. if (defined('BX_DISABLE_REQUIREMENTS_CHECK'))
  1746. return false;
  1747. $aErrors = array();
  1748. $aErrors[] = (ini_get('register_globals') == 0) ? '' : '<b>register_globals</b> is on (you need to disable it, or your site will be unsafe)';
  1749. $aErrors[] = (ini_get('safe_mode') == 0) ? '' : '<b>safe_mode</b> is on (you need to disable it)';
  1750. $aErrors[] = (version_compare(PHP_VERSION, '5.3.0', '<')) ? 'PHP version is too old (please update to <b>PHP 5.3.0</b> at least)' : '';
  1751. $aErrors[] = (!extension_loaded( 'mbstring')) ? '<b>mbstring</b> extension not installed (the script cannot work without it)' : '';
  1752. $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)';
  1753. $aErrors = array_diff($aErrors, array('')); // delete empty
  1754. $bFailedMinimalRequirements = !empty($aErrors);
  1755. if ($bFailedMinimalRequirements && $bShowHttpError) {
  1756. $sErrors = implode(" <br /> ", $aErrors);
  1757. bx_show_service_unavailable_error_and_exit($sErrors);
  1758. }
  1759. return $bFailedMinimalRequirements ? $aErrors : false;
  1760. }
  1761. /**
  1762. * Check if redirect to the correct hostname is required, for example redirect from site.com to www.site.com
  1763. * @param $bProcessRedirect process redirect and exit if needed
  1764. */
  1765. function bx_check_redirect_to_correct_hostname ($bProcessRedirect = false)
  1766. {
  1767. $aUrl = parse_url(BX_DOL_URL_ROOT);
  1768. $iPortDefault = 'https' == $aUrl['scheme'] ? '443' : '80';
  1769. $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));
  1770. if ($bRedirectRequired && $bProcessRedirect) {
  1771. header("Location:" . bx_get_self_url(), true, 301);
  1772. exit;
  1773. }
  1774. return $bRedirectRequired;
  1775. }
  1776. /**
  1777. * Get URL of current page
  1778. */
  1779. function bx_get_self_url ()
  1780. {
  1781. $aUrl = parse_url(BX_DOL_URL_ROOT);
  1782. $sPort = empty($aUrl['port']) || 80 == $aUrl['port'] || 443 == $aUrl['port'] ? '' : ':' . $aUrl['port'];
  1783. return "{$aUrl['scheme']}://{$aUrl['host']}{$sPort}{$_SERVER['REQUEST_URI']}";
  1784. }
  1785. /**
  1786. * Check if redirect to remove install folder.
  1787. * If BX_SKIP_INSTALL_CHECK is defined then this redirect checking is skipped.
  1788. * @param $bProcessRedirect process redirect and exit if needed
  1789. */
  1790. function bx_check_redirect_to_remove_install_folder ($bProcessRedirect = false)
  1791. {
  1792. $bRemoveInstallFolder = !defined ('BX_SKIP_INSTALL_CHECK') && file_exists(BX_DIRECTORY_PATH_ROOT . 'install');
  1793. if ($bRemoveInstallFolder && $bProcessRedirect) {
  1794. header('Location:' . BX_DOL_URL_ROOT . 'install/index.php?action=remove_install');
  1795. exit;
  1796. }
  1797. return $bRemoveInstallFolder;
  1798. }
  1799. /**
  1800. * Show HTTP 503 service unavailable error and exit
  1801. */
  1802. function bx_show_service_unavailable_error_and_exit ($sMsg = false, $iRetryAfter = 86400)
  1803. {
  1804. if (defined('BX_DOL_HEALTHCHECK') && BX_DOL_HEALTHCHECK) {
  1805. echo 'OK';
  1806. exit;
  1807. }
  1808. header('HTTP/1.0 503 Service Unavailable', true, 503);
  1809. header('Retry-After: 600');
  1810. echo $sMsg ? $sMsg : 'Service temporarily unavailable';
  1811. exit;
  1812. }
  1813. /**
  1814. * The function is sumilar to php readfile, but it send all required headers and can send file by chunks and suports file seek
  1815. * @param $sPath path to file to output to the browser
  1816. * @param $sFilename filename without path, ig file is saved from browser, then this name is used, not used(empty) by default
  1817. * @param $sMimeType file mime type, by default 'application/octet-stream'
  1818. * @param $iCacheAge file cache age, by default 0
  1819. * @param $sCachePrivacy cache privacy 'public' (default value) or 'private'
  1820. * @param $sContentDisposition content disposition header ('inline' or 'attachment' usually
  1821. * @return true on success or false on error
  1822. */
  1823. function bx_smart_readfile($sPath, $sFilename = '', $sMimeType = 'application/octet-stream', $iCacheAge = 0, $sCachePrivacy = 'public', $sContentDisposition = 'inline')
  1824. {
  1825. if (!file_exists($sPath))
  1826. return false;
  1827. $fp = @fopen($sPath, 'rb');
  1828. $size = filesize($sPath);
  1829. $length = $size;
  1830. $start = 0;
  1831. $end = $size - 1;
  1832. header('Content-Type: ' . $sMimeType);
  1833. header('Cache-Control: ' . $sCachePrivacy . ', must-revalidate, max-age=' . $iCacheAge);
  1834. header("Expires: " . gmdate('D, d M Y H:i:s', time() + $iCacheAge) . ' GMT');
  1835. header("Last-Modified: " . gmdate('D, d M Y H:i:s', @filemtime($sPath)) . ' GMT');
  1836. header("Accept-Ranges: bytes");
  1837. if ($sFilename)
  1838. header('Content-Disposition: ' . $sContentDisposition . '; filename="' . $sFilename . '"');
  1839. if (isset($_SERVER['HTTP_RANGE'])) {
  1840. $c_start = $start;
  1841. $c_end = $end;
  1842. list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
  1843. if (strpos($range, ',') !== false) {
  1844. header('HTTP/1.1 416 Requested Range Not Satisfiable');
  1845. header("Content-Range: bytes $start-$end/$size");
  1846. return false;
  1847. }
  1848. if ($range == '-') {
  1849. $c_start = $size - substr($range, 1);
  1850. }else{
  1851. $range = explode('-', $range);
  1852. $c_start = $range[0];
  1853. $c_end = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $size;
  1854. }
  1855. $c_end = ($c_end > $end) ? $end : $c_end;
  1856. if ($c_start > $c_end || $c_start > $size - 1 || $c_end >= $size) {
  1857. header('HTTP/1.1 416 Requested Range Not Satisfiable');
  1858. header("Content-Range: bytes $start-$end/$size");
  1859. return false;
  1860. }
  1861. $start = $c_start;
  1862. $end = $c_end;
  1863. $length = $end - $start + 1;
  1864. fseek($fp, $start);
  1865. header('HTTP/1.1 206 Partial Content');
  1866. }
  1867. header("Content-Range: bytes $start-$end/$size");
  1868. header("Content-Length: ".$length);
  1869. set_time_limit(0);
  1870. $buffer = 1024 * 8;
  1871. while(!feof($fp) && ($p = ftell($fp)) <= $end) {
  1872. if ($p + $buffer > $end) {
  1873. $buffer = $end - $p + 1;
  1874. }
  1875. echo fread($fp, $buffer);
  1876. flush();
  1877. }
  1878. fclose($fp);
  1879. return true;
  1880. }
  1881. /**
  1882. * Wrap in A tag links in TEXT string
  1883. * @param $text - text string without tags
  1884. * @param $sAttrs - attributes string to add to the added A tag
  1885. * @param $bHtmlSpecialChars - apply htmlspecialchars before processing
  1886. * @return string where all links are wrapped in A tag
  1887. */
  1888. function bx_linkify($text, $sAttrs = '', $bHtmlSpecialChars = false)
  1889. {
  1890. if ($bHtmlSpecialChars)
  1891. $text = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8');
  1892. $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_!~*'().;?:\@&=+$,%#-]+)*/?)@";
  1893. preg_match_all($re, $text, $matches, PREG_OFFSET_CAPTURE);
  1894. $matches = $matches[0];
  1895. if ($i = count($matches))
  1896. $bAddNofollow = getParam('sys_add_nofollow') == 'on';
  1897. while ($i--)
  1898. {
  1899. $sAttrsLocal = $sAttrs;
  1900. $url = $matches[$i][0];
  1901. if (!preg_match('@^https?://@', $url))
  1902. $url = 'http://'.$url;
  1903. if (strncmp(BX_DOL_URL_ROOT, $url, strlen(BX_DOL_URL_ROOT)) !== 0) {
  1904. $sAttrsLocal .= ' target="_blank" ';
  1905. if ($bAddNofollow)
  1906. $sAttrsLocal .= ' rel="nofollow" ';
  1907. }
  1908. $text = substr_replace($text, '<a ' . $sAttrsLocal . ' href="'.$url.'">'.$matches[$i][0].'</a>', $matches[$i][1], strlen($matches[$i][0]));
  1909. }
  1910. // email pattern
  1911. $mail_pattern = "/([A-z0-9\._-]+\@[A-z0-9_-]+\.)([A-z0-9\_\-\.]{1,}[A-z])/";
  1912. $text = preg_replace($mail_pattern, '<a href="mailto:$1$2">$1$2</a>', $text);
  1913. return $text;
  1914. }
  1915. function bx_linkify_embeded($sText)
  1916. {
  1917. $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_!~*\'().;?:@&=+$,%#-]*)*))/';
  1918. $aMatches = [];
  1919. preg_match_all($sRegex, $sText, $aMatches, PREG_SET_ORDER);
  1920. // Reverse the matches to mimic JavaScript's reverse order processing
  1921. $aMatches = array_reverse($aMatches);
  1922. $sUrlRoot = BX_DOL_URL_ROOT;
  1923. $sUrlRootApi = bx_api_get_base_url();
  1924. $sLink = '';
  1925. foreach($aMatches as $aMatch) {
  1926. if(!strstr($aMatch[0], $sUrlRoot) && ($sUrlRootApi === false || !strstr($aMatch[0], $sUrlRootApi))) {
  1927. $sLink = $aMatch[0]; // Returns the first URL that doesn't include the restricted domains
  1928. }
  1929. }
  1930. $sResult = '';
  1931. if($sLink) {
  1932. bx_import('BxDolEmbed');
  1933. if(($oEmbed = BxDolEmbed::getObjectInstance('sys_system')) !== false)
  1934. $sResult = $oEmbed->getLinkHTML($sLink);
  1935. }
  1936. return $sResult;
  1937. }
  1938. /**
  1939. * Wrap in A tag links in HTML string, which aren't wrapped in A tag yet
  1940. * @param $sHtmlOrig - HTML string
  1941. * @param $sAttrs - attributes string to add to the added A tag
  1942. * @return modified HTML string, in case of errror original string is returned
  1943. */
  1944. function bx_linkify_html($sHtmlOrig, $sAttrs = '')
  1945. {
  1946. if (!trim($sHtmlOrig))
  1947. return $sHtmlOrig;
  1948. $sId = 'bx-linkify-' . md5(microtime());
  1949. $dom = new DOMDocument();
  1950. @$dom->loadHTML('<?xml encoding="UTF-8"><div id="' . $sId . '">' . $sHtmlOrig . '</div>');
  1951. $xpath = new DOMXpath($dom);
  1952. foreach ($xpath->query('//text()') as $text) {
  1953. if (!empty($text->parentNode) && !empty($text->parentNode->tagName) && 'a' == $text->parentNode->tagName)
  1954. continue;
  1955. $frag = $dom->createDocumentFragment();
  1956. @$frag->appendXML(bx_linkify($text->nodeValue, $sAttrs, true));
  1957. $text->parentNode->replaceChild($frag, $text);
  1958. }
  1959. if (version_compare(PHP_VERSION, '5.3.6') >= 0)
  1960. $s = $dom->saveHTML($dom->getElementById($sId));
  1961. else
  1962. $s = $dom->saveXML($dom->getElementById($sId), LIBXML_NOEMPTYTAG);
  1963. if (false === $s) // in case of error return original string
  1964. return $sHtmlOrig;
  1965. if (false !== ($iPos = mb_strpos($s, '<html><body>')) && $iPos < mb_strpos($s, $sId))
  1966. $s = mb_substr($s, $iPos + 12, -15); // strip <html><body> tags and everything before them
  1967. return mb_substr($s, 54, -6); // strip added tags
  1968. }
  1969. /**
  1970. * Returns current site protocol http:// or https://
  1971. */
  1972. function bx_proto()
  1973. {
  1974. return 0 === strncmp('https', BX_DOL_URL_ROOT, 5) ? 'https' : 'http';
  1975. }
  1976. /**
  1977. * Checks protocol in the link
  1978. */
  1979. function bx_has_proto($sLink)
  1980. {
  1981. return preg_match('@^https?://@', $sLink);
  1982. }
  1983. function bx_is_empty_array ($a)
  1984. {
  1985. if (!is_array($a))
  1986. return true;
  1987. if (empty($a))
  1988. return true;
  1989. foreach ($a as $k => $v)
  1990. if ($v)
  1991. return false;
  1992. return true;
  1993. }
  1994. function bx_is_full_array ($a)
  1995. {
  1996. if (!is_array($a))
  1997. return false;
  1998. if (empty($a))
  1999. return false;
  2000. foreach ($a as $k => $v)
  2001. if (empty($v))
  2002. return false;
  2003. return true;
  2004. }
  2005. function bx_is_url_in_content ($sContent, $bSkipLocalUrls = false)
  2006. {
  2007. if ($bSkipLocalUrls)
  2008. $sContent = str_replace(BX_DOL_URL_ROOT, '', $sContent);
  2009. $a = array(
  2010. 'http://',
  2011. 'https://',
  2012. 'https/',
  2013. 'http/',
  2014. 'www.',
  2015. '.com'
  2016. );
  2017. foreach ($a as $s)
  2018. if (false !== strpos($sContent, $s))
  2019. return true;
  2020. return false;
  2021. }
  2022. function bx_is_dynamic_request ()
  2023. {
  2024. return bx_get('dynamic') || (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && 'XMLHttpRequest' == $_SERVER['HTTP_X_REQUESTED_WITH']);
  2025. }
  2026. function bx_is_htmx_request ()
  2027. {
  2028. return !empty($_SERVER['HTTP_HX_REQUEST']);
  2029. }
  2030. function bx_get_htmx_target ()
  2031. {
  2032. if(!bx_is_htmx_request())
  2033. return false;
  2034. return isset($_SERVER['HTTP_HX_TARGET']) ? $_SERVER['HTTP_HX_TARGET'] : false;
  2035. }
  2036. function bx_get_htmx_attrs ($aAttrs, $mPreload = false)
  2037. {
  2038. if(!$aAttrs)
  2039. return '';
  2040. if($mPreload === true)
  2041. $mPreload = 'mousedown';
  2042. $aHxAttrs = [];
  2043. array_walk($aAttrs, function($mixedValue, $sIndex) use (&$aHxAttrs) {
  2044. $aHxAttrs['hx-' . $sIndex] = $mixedValue;
  2045. });
  2046. return bx_convert_array2attrs($aHxAttrs) . ($mPreload ? ' preload="' . $mPreload . '"' : '');
  2047. }
  2048. function bx_idn_to_utf8($sUrl, $bReturnDomain = false)
  2049. {
  2050. return bx_idn_to('idn_to_utf8', $sUrl, $bReturnDomain);
  2051. }
  2052. function bx_idn_to_ascii($sUrl, $bReturnDomain = false)
  2053. {
  2054. return bx_idn_to('idn_to_ascii', $sUrl, $bReturnDomain);
  2055. }
  2056. function bx_idn_to($sMethod, $sUrl, $bReturnDomain = false)
  2057. {
  2058. $aUrl = parse_url($sUrl);
  2059. if($aUrl === false)
  2060. return $sUrl;
  2061. $sResult = $aUrl['host'];
  2062. if(function_exists($sMethod))
  2063. $sResult = $sMethod($sResult, IDNA_DEFAULT, (defined('INTL_IDNA_VARIANT_UTS46') ? INTL_IDNA_VARIANT_UTS46 : INTL_IDNA_VARIANT_2003));
  2064. if($bReturnDomain)
  2065. return $sResult;
  2066. $sResult = (!empty($aUrl['scheme']) ? $aUrl['scheme'] . '://' : '' ) . $sResult;
  2067. $sResult = $sResult . (!empty($aUrl['path']) ? $aUrl['path'] : '');
  2068. $sResult = $sResult . (!empty($aUrl['query']) ? '?' . $aUrl['query'] : '');
  2069. return $sResult;
  2070. }
  2071. function bx_is_mobile()
  2072. {
  2073. if(!isset($_SERVER['HTTP_USER_AGENT']))
  2074. return false;
  2075. $s = $_SERVER['HTTP_USER_AGENT'];
  2076. 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));
  2077. }
  2078. function bx_get_device_pixel_ratio()
  2079. {
  2080. $iRatio = 1;
  2081. if(!isset($_COOKIE['devicePixelRatio']))
  2082. return $iRatio;
  2083. $iDevicePixelRatio = intval($_COOKIE['devicePixelRatio']);
  2084. if($iDevicePixelRatio >= 2)
  2085. $iRatio = 2;
  2086. return $iRatio;
  2087. }
  2088. /**
  2089. * Log to logs object
  2090. * @param $sObject - logs object
  2091. * @param $mixed - string or array to log
  2092. */
  2093. function bx_log($sObject, $mixed, $iLevel = BX_LOG_DEBUG)
  2094. {
  2095. if (class_exists('BxDolLogs', true) && $o = BxDolLogs::getObjectInstance($sObject))
  2096. return $o->add($mixed, $iLevel);
  2097. else
  2098. return false;
  2099. }
  2100. function bx_birthday2age($sBirthday)
  2101. {
  2102. if(!$sBirthday)
  2103. return 0;
  2104. $iPosSpace = strpos($sBirthday, ' ');
  2105. if($iPosSpace !== false)
  2106. $sBirthday = trim(substr($sBirthday, 0, $iPosSpace));
  2107. $aDate = explode('-', $sBirthday);
  2108. $iCdYear = (int)date('Y');
  2109. $iCdMonth = (int)date('n');
  2110. $iCdDay = (int)date('j');
  2111. $iResult = 0;
  2112. if(isset($aDate[0]))
  2113. $iResult = $iCdYear - (int)$aDate[0];
  2114. if((isset($aDate[1]) && $iCdMonth < (int)$aDate[1]) || (isset($aDate[1], $aDate[2]) && $iCdMonth == (int)$aDate[1] && $iCdDay < (int)$aDate[2]))
  2115. $iResult -= 1;
  2116. return $iResult;
  2117. }
  2118. function bx_setcookie($sName, $sValue = "", $oExpiresOrOptions = 0, $sPath = 'auto', $sDomain = '', $bSecure = 'auto', $bHttpOnly = false)
  2119. {
  2120. $aUrl = 'auto' === $sPath || 'auto' === $bSecure ? parse_url(BX_DOL_URL_ROOT) : [];
  2121. if (defined('BX_MULTISITE_URL_COOKIE')) {
  2122. $aUrl = parse_url(BX_MULTISITE_URL_COOKIE);
  2123. $sDomain = $aUrl['host'];
  2124. }
  2125. if (bx_is_api())
  2126. $sPath = trim(getParam('sys_api_cookie_path'));
  2127. elseif ('auto' === $sPath)
  2128. $sPath = isset($aUrl['path']) && !empty($aUrl['path']) ? $aUrl['path'] : '/';
  2129. if (bx_is_api())
  2130. $bSecure = !!getParam('sys_api_cookie_secure');
  2131. elseif ('auto' === $bSecure)
  2132. $bSecure = 0 === strcasecmp('https', $aUrl['scheme']);
  2133. if (PHP_VERSION_ID < 70300) {
  2134. if (!defined('BX_MULTISITE_URL_COOKIE') && ('memberPassword' == $sName || 'memberSession' == $sName))
  2135. $sPath .= '; SameSite=' . (bx_is_api() ? getParam('sys_api_cookie_samesite') : getParam('sys_samesite_cookies'));
  2136. return setcookie($sName, $sValue, $oExpiresOrOptions, $sPath, $sDomain, $bSecure, $bHttpOnly);
  2137. }
  2138. else {
  2139. $aOptions = is_array($oExpiresOrOptions) ? $oExpiresOrOptions : [
  2140. 'expires' => $oExpiresOrOptions,
  2141. 'path' => $sPath,
  2142. 'domain' => $sDomain,
  2143. 'secure' => $bSecure,
  2144. 'httponly' => $bHttpOnly,
  2145. ];
  2146. if (!defined('BX_MULTISITE_URL_COOKIE') && !isset($aOptions['samesite']) && ('memberPassword' == $sName || 'memberSession' == $sName))
  2147. $aOptions['samesite'] = bx_is_api() ? getParam('sys_api_cookie_samesite') : getParam('sys_samesite_cookies');
  2148. return setcookie($sName, $sValue, $aOptions);
  2149. }
  2150. }
  2151. function bx_get_ip_hash($sIp)
  2152. {
  2153. return sprintf("%u", crc32(crc32($sIp) + crc32(BX_DOL_SECRET)));
  2154. }
  2155. function is_private_ip ($sIp)
  2156. {
  2157. if (filter_var($sIp, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6) !== $sIp)
  2158. return false;
  2159. return filter_var($sIp, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== $sIp;
  2160. }
  2161. function bx_absolute_url($sUrl, $sPrefix = BX_DOL_URL_ROOT)
  2162. {
  2163. if (!preg_match('/^https?:\/\//', $sUrl))
  2164. $sUrl = $sPrefix . $sUrl;
  2165. return $sUrl;
  2166. }
  2167. function bx_is_api()
  2168. {
  2169. return defined('BX_API') || bx_get('api') ? true : false;
  2170. }
  2171. function bx_api_get_sql($q)
  2172. {
  2173. $sql = false;
  2174. $t = false;
  2175. if ($q == 'accounts_count'){
  2176. $sql = 'SELECT Count(*) FROM sys_accounts';
  2177. $t = 'One';
  2178. }
  2179. if ($sql){
  2180. $oDb = BxDolDb::getInstance();
  2181. if ($t == 'One')
  2182. echo json_encode($oDb->getOne($sql));
  2183. else
  2184. echo json_encode($oDb->getAll($sql));
  2185. exit;
  2186. }
  2187. }
  2188. function bx_api_check_access()
  2189. {
  2190. if (!getParam('sys_api_enable')) {
  2191. header('HTTP/1.0 403 Forbidden');
  2192. BxDolLanguages::getInstance();
  2193. echo json_encode(['status' => 403, 'error' => _t("_Access denied")]);
  2194. exit;
  2195. }
  2196. $aHeaders = function_exists('getallheaders') ? getallheaders() : false;
  2197. if ($aHeaders) {
  2198. $sOriginHeader = isset($aHeaders['Origin']) ? $aHeaders['Origin'] : (isset($aHeaders['origin']) ? $aHeaders['origin'] : false);
  2199. $sAuthHeader = isset($aHeaders['Authorization']) ? $aHeaders['Authorization'] : (isset($aHeaders['authorization']) ? $aHeaders['authorization'] : false);
  2200. }
  2201. else {
  2202. $sOriginHeader = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : false;
  2203. $sAuthHeader = isset($_SERVER['HTTP_AUTHORIZATION']) ? $_SERVER['HTTP_AUTHORIZATION'] : false;
  2204. }
  2205. if ($sAuthHeader && getParam('sys_api_access_by_key')) {
  2206. if (!BxDolApiQuery::getInstance()->getKey(str_replace('Bearer ', '', $sAuthHeader))) {
  2207. header('HTTP/1.0 403 Forbidden');
  2208. BxDolLanguages::getInstance();
  2209. echo json_encode(['status' => 403, 'error' => _t("_Access denied")]);
  2210. exit;
  2211. }
  2212. if(bx_get('r') == 'q' && getParam('sys_api_access_unsafe_services')){
  2213. bx_api_get_sql(bx_get('q'));
  2214. }
  2215. }
  2216. elseif (getParam('sys_api_access_by_origin') && $sOriginHeader) {
  2217. if (parse_url($sOriginHeader, PHP_URL_HOST) != parse_url(BX_DOL_URL_ROOT, PHP_URL_HOST)) {
  2218. if (!BxDolApiQuery::getInstance()->getOrigin($sOriginHeader)) {
  2219. header('HTTP/1.0 403 Forbidden');
  2220. BxDolLanguages::getInstance();
  2221. echo json_encode(['status' => 403, 'error' => _t("_Access denied")]);
  2222. exit;
  2223. }
  2224. header('Access-Control-Allow-Origin: ' . $sOriginHeader);
  2225. header('Access-Control-Allow-Credentials: true');
  2226. // with acces by origin this block has to be disabled!!!
  2227. // if(bx_get('r') == 'q'){
  2228. // bx_api_get_sql(bx_get('q'));
  2229. // }
  2230. if ('OPTIONS' == $_SERVER['REQUEST_METHOD']) {
  2231. header('Access-Control-Allow-Methods: POST, GET');
  2232. header('Access-Control-Allow-Headers: Accept-Encoding, Authorization, Cache-Control, Connection, Host, Origin, Pragma, Referer, User-Agent, X-Custom-Header, X-Requested-With');
  2233. exit;
  2234. }
  2235. }
  2236. }
  2237. else {
  2238. header('HTTP/1.0 403 Forbidden');
  2239. BxDolLanguages::getInstance();
  2240. echo json_encode(['status' => 403, 'error' => _t("_Access denied")]);
  2241. exit;
  2242. }
  2243. // TODO: Temporarily to use logged state
  2244. // bx_login(1);
  2245. // check_logged();
  2246. }
  2247. function bx_api_get_base_url()
  2248. {
  2249. if(($sResult = getParam('sys_api_url_root_email')) != '')
  2250. return $sResult;
  2251. if(($sResult = getParam('sys_api_url_root_push')) != '')
  2252. return $sResult;
  2253. return false;
  2254. }
  2255. function bx_api_get_relative_url($sUrl, $sPrefix = BX_DOL_URL_ROOT)
  2256. {
  2257. $a = '/' . bx_ltrim_str($sUrl, $sPrefix);
  2258. if ($a == '/studio/')
  2259. return BX_DOL_URL_ROOT . 'studio/';
  2260. return $a;
  2261. }
  2262. function bx_api_get_block($sType, $sData, $aParams = [])
  2263. { $aData = ['id' => isset($aParams['id']) ? $aParams['id'] : 1 , 'type' => $sType, 'data' => $sData];
  2264. if (isset($aParams['ext']))
  2265. $aData = array_merge($aData, $aParams['ext']);
  2266. return $aData;
  2267. }
  2268. function bx_api_get_msg($sMessage, $aParams = [])
  2269. {
  2270. return bx_api_get_block('msg', $sMessage != '' ? _t($sMessage) : '', $aParams);
  2271. }
  2272. function bx_api_get_image($mixedStorage, $iId)
  2273. {
  2274. $sStorage = $sTranscoder = '';
  2275. if(is_array($mixedStorage))
  2276. list($sStorage, $sTranscoder) = $mixedStorage;
  2277. else
  2278. $sStorage = $mixedStorage;
  2279. $sUrl = '';
  2280. $iWidth = $iHeight = 0;
  2281. if($sTranscoder && ($oTranscoder = BxDolTranscoder::getObjectInstance($sTranscoder))) {
  2282. $sUrl = $oTranscoder->getFileUrl($iId);
  2283. if(($aSize = $oTranscoder->getSize($sUrl)) !== false) {
  2284. $iWidth = (int)$aSize['w'];
  2285. $iHeight = (int)$aSize['h'];
  2286. }
  2287. }
  2288. if(!$sUrl && ($oS = BxDolStorage::getObjectInstance($sStorage))) {
  2289. $sUrl = $oS->getFileUrlById($iId);
  2290. if(($aFile = $oS->getFile($iId)) && !empty($aFile['dimensions'])) {
  2291. $aTmp = explode('x', $aFile['dimensions']);
  2292. $iWidth = (int)$aTmp[0];
  2293. $iHeight = (int)$aTmp[1];
  2294. }
  2295. }
  2296. if(!$iWidth && !$iHeight && $sUrl) {
  2297. $aSize = BxDolImageResize::getInstance()->getImageSize($sUrl);
  2298. $iWidth = (int)$aSize['w'];
  2299. $iHeight = (int)$aSize['h'];
  2300. }
  2301. if(!$iWidth && !$iHeight) {
  2302. $iWidth = 500;
  2303. $iHeight = 500;
  2304. }
  2305. return !empty($sUrl) ? [
  2306. 'storage' => $sStorage,
  2307. 'src' => $sUrl,
  2308. 'width' => $iWidth,
  2309. 'height' => $iHeight,
  2310. ] : false;
  2311. }
  2312. function bx_api_get_browse_params($sParams, $bParamsOnly = false)
  2313. {
  2314. if(!$sParams || !is_string($sParams))
  2315. return [];
  2316. $aParams = json_decode($sParams, true);
  2317. if(!$bParamsOnly)
  2318. return $aParams;
  2319. if(!isset($aParams['params']))
  2320. return [];
  2321. return $aParams['params'];
  2322. }
  2323. function bx_api_get_location_string($mixedValue)
  2324. {
  2325. if(!is_array($mixedValue))
  2326. $aValue = bx_is_serialized($mixedValue) ? @unserialize($mixedValue) : json_decode($mixedValue, true);
  2327. else
  2328. $aValue = $mixedValue;
  2329. if(empty($aValue) || !is_array($aValue) || empty($aValue['country']))
  2330. return '';
  2331. $aCountries = BxDolFormQuery::getDataItems('Country');
  2332. $sResult = '';
  2333. $sResult .= $aValue['street_number'] ? $aValue['street_number'] . ', ' : '';
  2334. $sResult .= $aValue['street'] ? $aValue['street'] . ', ' : '';
  2335. $sResult .= $aValue['city'] ? $aValue['city'] . ', ' : '';
  2336. $sResult .= $aValue['state'] ? $aValue['state'] . ', ' : '';
  2337. $sResult .= $aCountries[$aValue['country']];
  2338. return $sResult;
  2339. }
  2340. function bx_is_serialized($string)
  2341. {
  2342. if (!is_string($string))
  2343. return false;
  2344. $string = trim($string);
  2345. // base types
  2346. if ($string === 'N;') return true; // null
  2347. if ($string === 'b:0;' || $string === 'b:1;') return true; // boolean
  2348. // other types
  2349. return preg_match('/^([adObis]):[0-9]+:/', $string) === 1;
  2350. }
  2351. function bx_get_context_workspace($bFromCache = true)
  2352. {
  2353. if ($bFromCache && !empty($GLOBALS['bxWorkspaceContext']))
  2354. return $GLOBALS['bxWorkspaceContext'];
  2355. $o = BxDolProfile::getInstance();
  2356. if (!$o) {
  2357. return ($GLOBALS['bxWorkspaceContext'] = false);
  2358. }
  2359. $sModule = $o->getModule();
  2360. if ($sModule !== 'bx_workspaces') {
  2361. return ($GLOBALS['bxWorkspaceContext'] = false);
  2362. }
  2363. $sModuleContext = getParam('bx_workspaces_context_module');
  2364. if (!$sModuleContext) {
  2365. return ($GLOBALS['bxWorkspaceContext'] = false);
  2366. }
  2367. $oModuleContext = BxDolModule::getInstance($sModuleContext);
  2368. if (!$oModuleContext) {
  2369. return ($GLOBALS['bxWorkspaceContext'] = false);
  2370. }
  2371. $CNF = $oModuleContext->_oConfig->CNF;
  2372. $oConnection = BxDolConnection::getObjectInstance($CNF['OBJECT_CONNECTIONS']);
  2373. if (!$oConnection) {
  2374. return ($GLOBALS['bxWorkspaceContext'] = false);
  2375. }
  2376. $a = $oConnection->getConnectedContent ($o->id(), true, 0, 1);
  2377. if (!$a) {
  2378. return ($GLOBALS['bxWorkspaceContext'] = false);
  2379. }
  2380. return ($GLOBALS['bxWorkspaceContext'] = array_pop($a));
  2381. }
  2382. function bx_content_cache_get(string $sKey, int|false $iTTL = false): mixed
  2383. {
  2384. if (!getParam('sys_content_cache_enable'))
  2385. return null;
  2386. $oCache = bx_content_cache_obj();
  2387. return $oCache->getData(bx_content_cache_key($sKey), $iTTL);
  2388. }
  2389. function bx_content_cache_set(string $sKey, mixed $mixedData, int|false $iTTL = false): bool
  2390. {
  2391. if (!getParam('sys_content_cache_enable'))
  2392. return false;
  2393. $oCache = bx_content_cache_obj();
  2394. return (bool)$oCache->setData(bx_content_cache_key($sKey), $mixedData, $iTTL);
  2395. }
  2396. function bx_content_cache_del(string $sKey): bool
  2397. {
  2398. $oCache = bx_content_cache_obj();
  2399. return (bool)$oCache->delData(bx_content_cache_key($sKey));
  2400. }
  2401. function bx_content_cache_del_by_prefix(string $sPrefix): bool
  2402. {
  2403. $oCache = bx_content_cache_obj();
  2404. return (bool)$oCache->removeAllByPrefix(bx_content_cache_key($sPrefix, true));
  2405. }
  2406. function bx_content_cache_key(string $sKey, bool $bPrefixOnly = false): string
  2407. {
  2408. if ($bPrefixOnly)
  2409. return 'content_' . $sKey;
  2410. return 'content_' . $sKey . '_' . bx_lang_name() . '_' . BxDolTemplate::getInstance()->getCode() . '_' . bx_site_hash() . '.php';
  2411. }
  2412. function bx_content_cache_obj(): object
  2413. {
  2414. if (isset($GLOBALS['bxCacheContentObj']))
  2415. return $GLOBALS['bxCacheContentObj'];
  2416. $sEngine = getParam('sys_content_cache_engine');
  2417. $oCacheObject = bx_instance('BxDolCache' . $sEngine);
  2418. if(!$oCacheObject->isAvailable())
  2419. $oCacheObject = bx_instance('BxDolCacheFile');
  2420. return $GLOBALS['bxCacheContentObj'] = $oCacheObject;
  2421. }
  2422. function bx_mem_cache_get(string $sKey): mixed
  2423. {
  2424. if(isset($GLOBALS['glMemCache']) && array_key_exists($sKey, $GLOBALS['glMemCache']) && !defined('BX_DOL_INSTALL') && !defined('BX_DOL_CRON_EXECUTE'))
  2425. return $GLOBALS['glMemCache'][$sKey];
  2426. return null;
  2427. }
  2428. function bx_mem_cache_set(string $sKey, mixed $mixedData): mixed
  2429. {
  2430. if(!isset($GLOBALS['glMemCache']))
  2431. $GLOBALS['glMemCache'] = [];
  2432. return $GLOBALS['glMemCache'][$sKey] = $mixedData;
  2433. }
  2434. function bx_ai_process_agents_call_queue($bFinishRequest = true, $bExit = true)
  2435. {
  2436. if ($bFinishRequest) {
  2437. if (function_exists('fastcgi_finish_request')) {
  2438. fastcgi_finish_request();
  2439. } else {
  2440. @ob_end_flush();
  2441. @flush();
  2442. }
  2443. }
  2444. if (!empty($GLOBALS['glAgentsCallQueue']))
  2445. {
  2446. $oAi = BxDolAI::getInstance();
  2447. foreach ($GLOBALS['glAgentsCallQueue'] as $r)
  2448. {
  2449. $sMessage = $oAi->callAgent($r['type'], $r['agent'], $r['params']);
  2450. $oParsedown = new Parsedown();
  2451. $oParsedown->setSafeMode(true);
  2452. $sMessageHtml = $oParsedown->text($sMessage);
  2453. $oAi->sendMessengerMessage($r['agent']['profile_id'], $r['params']['sender_profile_id'], str_replace('\n', '', $sMessageHtml));
  2454. }
  2455. }
  2456. if ($bExit) {
  2457. exit(0);
  2458. }
  2459. }
  2460. /** @} */