utils.inc.php 86 KB

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