utils.inc.php 83 KB

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