utils.inc.php 93 KB

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