utils.inc.php 94 KB

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