utils.inc.php 101 KB

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