utils.inc.php 98 KB

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