utils.inc.php 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741
  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_SLASHES_AUTO', 0);
  23. define('BX_SLASHES_ADD', 1);
  24. define('BX_SLASHES_STRIP', 2);
  25. define('BX_SLASHES_NO_ACTION', 3);
  26. 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
  27. 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
  28. 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
  29. define('BX_EMAIL_SYSTEM', 0); ///< system email without unsubscribe link, like forgot password or email verification
  30. define('BX_EMAIL_NOTIFY', 1); ///< notification message, with unsubscribe link
  31. define('BX_EMAIL_MASS', 2); ///< mass email, one mesage send to manu users, with unsubscribe link
  32. define('BX_MAINTENANCE_FILE', '.bx_maintenance'); ///< file name to use as mantenance mode indicator
  33. /**
  34. * The following two functions are needed to convert title to uri and back.
  35. * It usefull when titles are used in URLs, like in Categories and Tags.
  36. */
  37. function title2uri($sValue)
  38. {
  39. return str_replace(
  40. array('&', '/', '\\', '"', '+'),
  41. array('[and]', '[slash]', '[backslash]', '[quote]', '[plus]'),
  42. $sValue
  43. );
  44. }
  45. function uri2title($sValue)
  46. {
  47. return str_replace(
  48. array('[and]', '[slash]', '[backslash]', '[quote]', '[plus]'),
  49. array('&', '/', '\\', '"', '+'),
  50. $sValue
  51. );
  52. }
  53. /*
  54. * functions for limiting maximal text length
  55. */
  56. function strmaxtextlen($sInput, $iMaxLen = 60, $sEllipsisSign = '&#8230;')
  57. {
  58. $sTail = '';
  59. $s = trim(strip_tags($sInput));
  60. if (mb_strlen($s) > $iMaxLen) {
  61. $s = mb_substr($s, 0, $iMaxLen);
  62. $sTail = $sEllipsisSign;
  63. }
  64. return htmlspecialchars_adv($s) . $sTail;
  65. }
  66. function html2txt($content, $tags = "")
  67. {
  68. while($content != strip_tags($content, $tags)) {
  69. $content = strip_tags($content, $tags);
  70. }
  71. return $content;
  72. }
  73. /**
  74. * Functions to process user input.
  75. * DON'T use to process data before passing to SQL query - use db prepare instead @see BxDolDb::prepare.
  76. * It is ok to use bx_process_input and then db prepare.
  77. * @param $mixedData data to process
  78. * @param $iDataType how to handle data, possible valies:
  79. * @code
  80. * BX_DATA_INT - integer value
  81. * BX_DATA_FLOAT - float values
  82. * BX_DATA_CHECKBOX - 'on' or empty string
  83. * BX_DATA_TEXT - text data, single line (default)
  84. * BX_DATA_TEXT_MULTILINE - text data, multiple lines
  85. * BX_DATA_HTML - HTML data
  86. * BX_DATA_DATE - date data type stored as yyyy-mm-dd
  87. * BX_DATA_DATETIME - date/time data type stored as yyyy-mm-dd hh:mm:ss
  88. * BX_DATA_DATE_TS' - date data type stored as unixtimestamp
  89. * BX_DATA_DATETIME_TS - date/time data type stored as unixtimestamp
  90. * BX_DATA_DATE_TS_UTC - date data type stored as unixtimestamp from UTC time
  91. * BX_DATA_DATETIME_TS_UTC - date/time data type stored as unixtimestamp from UTC time
  92. * @endcode
  93. * @param $mixedParams optional parameters to pass for validation
  94. * @param $isCheckMagicQuotes deprecated
  95. * @return the filtered data, or FALSE if the filter fails.
  96. */
  97. function bx_process_input ($mixedData, $iDataType = BX_DATA_TEXT, $mixedParams = false, $isCheckMagicQuotes = true)
  98. {
  99. if (is_array($mixedData)) {
  100. foreach ($mixedData as $k => $v)
  101. $mixedData[$k] = bx_process_input($v, $iDataType, $mixedParams);
  102. return $mixedData;
  103. }
  104. if (get_magic_quotes_gpc() && $isCheckMagicQuotes)
  105. $mixedData = stripslashes($mixedData);
  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_TS:
  202. return empty($mixedData) ? '' : date("Y-m-d", (int)$mixedData);
  203. case BX_DATA_DATE_TS_UTC:
  204. return empty($mixedData) ? '' : gmdate("Y-m-d", (int)$mixedData);
  205. case BX_DATA_DATETIME_TS:
  206. return empty($mixedData) ? '' : date("Y-m-d H:i", (int)$mixedData);
  207. case BX_DATA_DATETIME_TS_UTC:
  208. return empty($mixedData) ? '' : gmdate("Y-m-d H:i", (int)$mixedData);
  209. case BX_DATA_HTML:
  210. return bx_linkify_html($mixedData, 'class="' . BX_DOL_LINK_CLASS . '"');
  211. case BX_DATA_TEXT_MULTILINE:
  212. return $mixedData;
  213. case BX_DATA_TEXT:
  214. default:
  215. return htmlspecialchars_adv($mixedData);
  216. }
  217. }
  218. /*
  219. * This function apply bx_process_input and then bx_process_output.
  220. * Use this function to output data immediately after receiving, without saving to database.
  221. * Patams are the same as bx_process_input function - @see bx_process_input
  222. */
  223. function bx_process_pass ($mixedData, $iDataType = BX_DATA_TEXT, $mixedParams = false, $isCheckMagicQuotes = true)
  224. {
  225. return bx_process_output(bx_process_input ($mixedData, $iDataType, $mixedParams, $isCheckMagicQuotes), $iDataType, $mixedParams);
  226. }
  227. /**
  228. * DEPRECATED
  229. * use bx_process_input + bx_process_output instead
  230. * --------
  231. * function for processing pass data
  232. *
  233. * This function cleans the GET/POST/COOKIE data if magic_quotes_gpc() is on
  234. * for data which should be outputed immediately after submit
  235. */
  236. /*
  237. function process_pass_data( $text, $strip_tags = 0 )
  238. {
  239. if ( $strip_tags )
  240. $text = strip_tags($text);
  241. if ( !get_magic_quotes_gpc() )
  242. return $text;
  243. else
  244. return stripslashes($text);
  245. }
  246. */
  247. /*
  248. * function for output data from database into html
  249. */
  250. function htmlspecialchars_adv( $string )
  251. {
  252. return htmlspecialchars($string, ENT_COMPAT, 'UTF-8', false);
  253. }
  254. /**
  255. * Send mail to user by parsing email template
  256. */
  257. function sendMailTemplate($sTemplateName, $iAccountId = 0, $iProfileId = 0, $aReplaceVars = array(), $iEmailType = BX_EMAIL_NOTIFY, $bAddToQueue = false)
  258. {
  259. $oProfile = BxDolProfile::getInstance($iProfileId);
  260. $oAccount = $iAccountId ? BxDolAccount::getInstance($iAccountId) : ($oProfile ? $oProfile->getAccountObject() : null);
  261. $oEmailTemplates = BxDolEmailTemplates::getInstance();
  262. if (!$oAccount || !$oProfile || !$oEmailTemplates)
  263. return false;
  264. $aTemplate = $oEmailTemplates->parseTemplate($sTemplateName, $aReplaceVars, $oAccount ? $oAccount->id() : 0, (int)$iProfileId);
  265. if (!$aTemplate)
  266. return false;
  267. return sendMail($oAccount->getEmail(), $aTemplate['Subject'], $aTemplate['Body'], 0, array(), $iEmailType, 'html', false, array(), $bAddToQueue);
  268. }
  269. /**
  270. * Send system email
  271. */
  272. function sendMailTemplateSystem($sTemplateName, $aReplaceVars = array(), $iEmailType = BX_EMAIL_SYSTEM, $bAddToQueue = false)
  273. {
  274. $oEmailTemplates = BxDolEmailTemplates::getInstance();
  275. if (!$oEmailTemplates)
  276. return false;
  277. $aTemplate = $oEmailTemplates->parseTemplate($sTemplateName, $aReplaceVars);
  278. if (!$aTemplate)
  279. return false;
  280. return sendMail(getParam('site_email'), $aTemplate['Subject'], $aTemplate['Body'], 0, array(), $iEmailType, 'html', false, array(), $bAddToQueue);
  281. }
  282. /**
  283. * Send email function
  284. *
  285. * @param $sRecipientEmail - Email where email should be send
  286. * @param $sMailSubject - subject of the message
  287. * @param $sMailBody - Body of the message
  288. * @param $iRecipientID - ID of recipient profile
  289. * @param $aPlus - Array of additional information
  290. * @param $iEmailType - email message type: BX_EMAIL_SYSTEM, BX_EMAIL_NOTIFY or BX_EMAIL_MASS
  291. * @param $sEmailFlag - use 'html' for HTML email message
  292. * @param $isDisableAlert - disable alert
  293. * @param $aCustomHeaders - custom email headers
  294. * @param $bAddToQueue - add message to email queue
  295. * @return true if message was send or false otherwise
  296. */
  297. function sendMail($sRecipientEmail, $sMailSubject, $sMailBody, $iRecipientID = 0, $aPlus = array(), $iEmailType = BX_EMAIL_NOTIFY, $sEmailFlag = 'html', $isDisableAlert = false, $aCustomHeaders = array(), $bAddToQueue = false)
  298. {
  299. // make sure that recipient's email is valid and message isn't empty
  300. if (!$sMailBody || !$sRecipientEmail || preg_match('/\(2\)$/', $sRecipientEmail))
  301. return false;
  302. // get recipient account
  303. $oAccount = !$isDisableAlert ? BxDolAccount::getInstance($sRecipientEmail) : null;
  304. $aAccountInfo = $oAccount ? $oAccount->getInfo() : false;
  305. // don't send bulk emails if user didn't subscribed to site news or email is unconfirmed
  306. if ($aAccountInfo && BX_EMAIL_MASS == $iEmailType && (!$aAccountInfo['email_confirmed'] || !$aAccountInfo['receive_news']))
  307. return false;
  308. // don't send email notifications if user didn't subscribed to notifications or email is unconfirmed
  309. if ($aAccountInfo && BX_EMAIL_NOTIFY == $iEmailType && (!$aAccountInfo['email_confirmed'] || !$aAccountInfo['receive_updates']))
  310. return false;
  311. if($bAddToQueue && BxDolQueueEmail::getInstance()->add($sRecipientEmail, $sMailSubject, $sMailBody, $iRecipientID, $aPlus, $iEmailType, $sEmailFlag, $isDisableAlert, $aCustomHeaders))
  312. return true;
  313. // if profile id is provided - get profile's info
  314. $aRecipientInfo = false;
  315. if ($iRecipientID) {
  316. $oProfile = BxDolProfile::getInstance($iRecipientID);
  317. if ($oProfile)
  318. $aRecipientInfo = $oProfile->getInfo();
  319. }
  320. // get site vars
  321. $sEmailNotify = !$isDisableAlert ? getParam('site_email_notify') : $sRecipientEmail;
  322. $sSiteTitle = !$isDisableAlert ? getParam('site_title') : 'UNA ' . BX_DOL_VERSION;
  323. // add unsubscribe link
  324. if (!$isDisableAlert && empty($aPlus['unsubscribe'])) {
  325. $aPlus['unsubscribe'] = '';
  326. if ($oAccount && (BX_EMAIL_MASS == $iEmailType || BX_EMAIL_NOTIFY == $iEmailType))
  327. $aPlus['unsubscribe'] = ($sLink = $oAccount->getUnsubscribeLink($iEmailType)) ? '<a href="' . BX_DOL_URL_ROOT . $sLink . '">' . _t('_sys_et_txt_unsubscribe') . '</a>' : '';
  328. }
  329. // parse template
  330. if ($aPlus || $iRecipientID || $oAccount) {
  331. if(!is_array($aPlus))
  332. $aPlus = array();
  333. $oEmailTemplates = BxDolEmailTemplates::getInstance();
  334. $sMailSubject = $oEmailTemplates->parseContent($sMailSubject, $aPlus, !$iRecipientID && $oAccount ? $oAccount->id() : 0, $iRecipientID);
  335. $sMailBody = $oEmailTemplates->parseContent($sMailBody, $aPlus, !$iRecipientID && $oAccount ? $oAccount->id() : 0, $iRecipientID);
  336. }
  337. // email message headers
  338. $sMailHeader = '';
  339. foreach ($aCustomHeaders as $sHeaderName => $sHeaderValue)
  340. $sMailHeader = "$sHeaderName: $sHeaderValue\r\n" . $sMailHeader;
  341. if (!isset($aCustomHeaders['From']))
  342. $sMailHeader = "From: =?UTF-8?B?" . base64_encode( $sSiteTitle ) . "?= <{$sEmailNotify}>";
  343. if (!isset($aCustomHeaders['MIME-Version']))
  344. $sMailHeader = "MIME-Version: 1.0\r\n" . $sMailHeader;
  345. $sMailParameters = isset($aCustomHeaders['Sender']) ? "-f{$aCustomHeaders['Sender']}" : "-f{$sEmailNotify}";
  346. if (isset($aCustomHeaders['Subject']))
  347. $sMailSubject = $aCustomHeaders['Subject'];
  348. // build data for alert handler
  349. $bResult = null;
  350. $aAlert = array(
  351. 'email' => $sRecipientEmail,
  352. 'subject' => $sMailSubject,
  353. 'body' => $sMailBody,
  354. 'header' => $sMailHeader,
  355. 'params' => $sMailParameters,
  356. 'recipient' => $aRecipientInfo,
  357. 'html' => 'html' == $sEmailFlag ? true : false,
  358. 'custom_headers' => $aCustomHeaders,
  359. 'override_result' => &$bResult,
  360. );
  361. // system alert
  362. if (!$isDisableAlert) {
  363. bx_alert('system', 'before_send_mail', (isset($aRecipientInfo['ID']) ? $aRecipientInfo['ID'] : 0), '', $aAlert);
  364. if ($bResult !== null)
  365. return $bResult;
  366. unset($aAlert['override_result']);
  367. }
  368. // prepare HTML/Plain message
  369. if($sEmailFlag == 'html')
  370. $sMailHeader = "Content-type: text/html; charset=UTF-8\r\n" . $sMailHeader;
  371. else {
  372. $sMailHeader = "Content-type: text/plain; charset=UTF-8\r\n" . $sMailHeader;
  373. $sMailBody = html2txt($sMailBody);
  374. }
  375. // encode subject
  376. if (0 !== strncasecmp($sMailSubject, '=?UTF-8?B?', 10))
  377. $sMailSubject = '=?UTF-8?B?' . base64_encode($sMailSubject) . '?=';
  378. // send mail or put it into queue
  379. $bResult = mail($sRecipientEmail, $sMailSubject, $sMailBody, $sMailHeader, $sMailParameters);
  380. // system alert
  381. if (!$isDisableAlert)
  382. bx_alert('system', 'send_mail', (isset($aRecipientInfo['ID']) ? $aRecipientInfo['ID'] : 0), '', $aAlert);
  383. return $bResult;
  384. }
  385. /*
  386. * Getting an array with Templates' Names
  387. */
  388. function get_templates_array($bEnabledOnly = true, $bShortInfo = true)
  389. {
  390. $oDb = BxDolDb::getInstance();
  391. $sWhereAddon = $bEnabledOnly ? " AND `enabled`='1'" : "";
  392. if($bShortInfo)
  393. return $oDb->getPairs("SELECT `uri`, `title` FROM `sys_modules` WHERE 1 AND `type`='" . BX_DOL_MODULE_TYPE_TEMPLATE . "'" . $sWhereAddon, "uri", "title");
  394. else
  395. return $oDb->getAllWithKey("SELECT * FROM `sys_modules` WHERE 1 AND `type`='" . BX_DOL_MODULE_TYPE_TEMPLATE . "'" . $sWhereAddon, "uri");
  396. }
  397. function extFileExists( $sFileSrc )
  398. {
  399. return (file_exists( $sFileSrc ) && is_file( $sFileSrc )) ? true : false;
  400. }
  401. function getVisitorIP()
  402. {
  403. $ip = "0.0.0.0";
  404. if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  405. $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
  406. } elseif (isset( $_SERVER['HTTP_CLIENT_IP']) && !empty($_SERVER['HTTP_CLIENT_IP'])) {
  407. $ip = explode(".",$_SERVER['HTTP_CLIENT_IP']);
  408. $ip = $ip[3].".".$ip[2].".".$ip[1].".".$ip[0];
  409. } elseif (!isset( $_SERVER['HTTP_X_FORWARDED_FOR']) || empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  410. if (!isset( $_SERVER['HTTP_CLIENT_IP']) && empty($_SERVER['HTTP_CLIENT_IP']) && isset($_SERVER['REMOTE_ADDR']))
  411. $ip = $_SERVER['REMOTE_ADDR'];
  412. }
  413. return $ip;
  414. }
  415. function genFlag($sLang = '', $oTemplate = null)
  416. {
  417. if (!$oTemplate)
  418. $oTemplate = BxDolTemplate::getInstance();
  419. $oTemplate->addCss(BX_DIRECTORY_PATH_PLUGINS_PUBLIC . 'flag-icon-css/css/|flag-icon.min.css');
  420. $sFlag = BxDolLanguages::getInstance()->getLangFlag($sLang);
  421. return '<span title="' . $sFlag . '" class="flag-icon flag-icon-' . $sFlag . '"></span>';
  422. }
  423. // print debug information ( e.g. arrays )
  424. function echoDbg( $what, $desc = '' )
  425. {
  426. if ( $desc )
  427. echo "<b>$desc:</b> ";
  428. echo "<pre>";
  429. print_r( $what );
  430. echo "</pre>\n";
  431. }
  432. function echoDbgLog($mWhat, $sDesc = '', $sFileName = 'debug.log')
  433. {
  434. $sCont =
  435. '--- ' . date('r') . ' (' . BX_DOL_START . ") ---\n" .
  436. $sDesc . "\n" .
  437. print_r($mWhat, true) . "\n\n\n";
  438. $rFile = fopen(BX_DIRECTORY_PATH_LOGS . $sFileName, 'a');
  439. fwrite($rFile, $sCont);
  440. fclose($rFile);
  441. }
  442. function dbgTiming($sStartMicrotime)
  443. {
  444. $i1 = explode(' ', microtime ());
  445. $i2 = explode(' ', $sStartMicrotime);
  446. $iTime = ($i1[0]+$i1[1]) - ($i2[0]+$i2[1]);
  447. return round($iTime, 3) . ' sec';
  448. }
  449. function echoJson($a)
  450. {
  451. header('Content-type: text/html; charset=utf-8');
  452. echo json_encode($a);
  453. }
  454. function clear_xss($val)
  455. {
  456. // HTML Purifier plugin
  457. global $oHtmlPurifier;
  458. if (!isset($oHtmlPurifier) && !$GLOBALS['logged']['admin']) {
  459. require_once( BX_DIRECTORY_PATH_PLUGINS . 'htmlpurifier/HTMLPurifier.standalone.php' );
  460. HTMLPurifier_Bootstrap::registerAutoload();
  461. $oConfig = HTMLPurifier_Config::createDefault();
  462. $oConfig->set('Cache.SerializerPath', rtrim(BX_DIRECTORY_PATH_CACHE, '/'));
  463. $oConfig->set('Cache.SerializerPermissions', BX_DOL_DIR_RIGHTS);
  464. $oConfig->set('HTML.SafeObject', 'true');
  465. $oConfig->set('Output.FlashCompat', 'true');
  466. $oConfig->set('HTML.FlashAllowFullScreen', 'true');
  467. $oConfig->set('Attr.AllowedFrameTargets', array('_blank', '_self', '_parent', '_top'));
  468. if (getParam('sys_add_nofollow')) {
  469. $sHost = parse_url(BX_DOL_URL_ROOT, PHP_URL_HOST);
  470. $oConfig->set('URI.Host', $sHost);
  471. $oConfig->set('HTML.Nofollow', 'true');
  472. }
  473. $oConfig->set('Filter.Custom', array (new HTMLPurifier_Filter_YouTube(), new HTMLPurifier_Filter_YoutubeIframe(), new HTMLPurifier_Filter_AddBxLinksClass(), new HTMLPurifier_Filter_LocalIframe()));
  474. $oConfig->set('HTML.DefinitionID', 'html5-definitions');
  475. $oConfig->set('HTML.DefinitionRev', 1);
  476. if ($def = $oConfig->maybeGetRawHTMLDefinition()) {
  477. $def->addElement('section', 'Block', 'Flow', 'Common');
  478. $def->addElement('nav', 'Block', 'Flow', 'Common');
  479. $def->addElement('article', 'Block', 'Flow', 'Common');
  480. $def->addElement('aside', 'Block', 'Flow', 'Common');
  481. $def->addElement('header', 'Block', 'Flow', 'Common');
  482. $def->addElement('footer', 'Block', 'Flow', 'Common');
  483. $def->addElement('video', 'Block', 'Optional: (source, Flow) | (Flow, source) | Flow', 'Common', array(
  484. 'src' => 'URI',
  485. 'type' => 'Text',
  486. 'width' => 'Length',
  487. 'height' => 'Length',
  488. 'poster' => 'URI',
  489. 'preload' => 'Enum#auto,metadata,none',
  490. 'controls' => 'Bool',
  491. ));
  492. $def->addElement('source', 'Block', 'Flow', 'Common', array(
  493. 'src' => 'URI',
  494. 'type' => 'Text',
  495. ));
  496. $def->addAttribute('a', 'data-profile-id', 'Number');
  497. }
  498. $oHtmlPurifier = new HTMLPurifier($oConfig);
  499. }
  500. if (!$GLOBALS['logged']['admin'])
  501. $val = $oHtmlPurifier->purify($val);
  502. bx_alert('system', 'clear_xss', 0, 0, array('oHtmlPurifier' => $oHtmlPurifier, 'return_data' => &$val));
  503. return $val;
  504. }
  505. //--------------------------------------- friendly permalinks --------------------------------------//
  506. //------------------------------------------- main functions ---------------------------------------//
  507. function uriGenerate ($s, $sTable, $sField, $sEmpty = '-', $sDivider = '-')
  508. {
  509. $s = uriFilter($s, $sEmpty, $sDivider);
  510. if(uriCheckUniq($s, $sTable, $sField))
  511. return $s;
  512. // cut off redundant part
  513. if(get_mb_len($s) > 240)
  514. $s = get_mb_substr($s, 0, 240);
  515. // try to add date
  516. $s .= $sDivider . date('Y-m-d');
  517. if(uriCheckUniq($s, $sTable, $sField))
  518. return $s;
  519. // try to add number
  520. for($i = 0 ; $i < 999 ; ++$i)
  521. if(uriCheckUniq($s . $sDivider . $i, $sTable, $sField))
  522. return ($s . $sDivider . $i);
  523. return rand(0, 999999999);
  524. }
  525. function uriFilter ($s, $sEmpty = '-', $sDivider = '-')
  526. {
  527. if (BxTemplConfig::getInstance()->bAllowUnicodeInPreg)
  528. $s = get_mb_replace ('/[^\pL^\pN]+/u', $sDivider, $s); // unicode characters
  529. else
  530. $s = get_mb_replace ('/([^\d^\w]+)/u', $sDivider, $s); // latin characters only
  531. $s = get_mb_replace ('/([' . $sDivider . '^]+)/', $sDivider, $s);
  532. $s = get_mb_replace ('/([' . $sDivider . ']+)$/', '', $s); // remove trailing dash
  533. if (!$s) $s = $sEmpty;
  534. return $s;
  535. }
  536. function uriCheckUniq ($s, $sTable, $sField)
  537. {
  538. $oDb = BxDolDb::getInstance();
  539. $sSql = $oDb->prepare("SELECT 1 FROM `$sTable` WHERE `$sField`=? LIMIT 1", $s);
  540. return !$oDb->query($sSql);
  541. }
  542. function get_mb_replace ($sPattern, $sReplace, $s)
  543. {
  544. return preg_replace ($sPattern, $sReplace, $s);
  545. }
  546. function get_mb_len ($s)
  547. {
  548. return (function_exists('mb_strlen')) ? mb_strlen($s) : strlen($s);
  549. }
  550. function get_mb_substr ($s, $iStart, $iLen)
  551. {
  552. return (function_exists('mb_substr')) ? mb_substr ($s, $iStart, $iLen) : substr ($s, $iStart, $iLen);
  553. }
  554. function bx_mb_substr_replace($s, $sReplace, $iPosStart, $iLength)
  555. {
  556. return mb_substr($s, 0, $iPosStart) . $sReplace . mb_substr($s, $iPosStart + $iLength);
  557. }
  558. function bx_mb_strpos ($s, $sReplacement, $iStart = 0)
  559. {
  560. return mb_strpos($s, $sReplacement, $iStart);
  561. }
  562. /**
  563. * Import class file, it automatically detects class path by its prefix or module array/name
  564. *
  565. * @param $sClassName - full class name or class postfix(withoit prefix) in the case of module class
  566. * @param $mixedModule - module array or module name in the case of module class
  567. */
  568. function bx_import($sClassName, $mixedModule = array())
  569. {
  570. if (class_exists($sClassName, false))
  571. return;
  572. $aModule = false;
  573. if ($mixedModule) {
  574. if (is_array($mixedModule)) {
  575. $aModule = $mixedModule;
  576. } elseif (is_string($mixedModule)) {
  577. $o = BxDolModule::getInstance($mixedModule);
  578. $aModule = $o->_aModule;
  579. } elseif (is_bool($mixedModule) && true === $mixedModule) {
  580. $aModule = $GLOBALS['aModule'];
  581. }
  582. }
  583. if ($aModule) {
  584. if (class_exists($aModule['class_prefix'] . $sClassName, false))
  585. return;
  586. require_once (BX_DIRECTORY_PATH_MODULES . $aModule['path'] . 'classes/' . $aModule['class_prefix'] . $sClassName . '.php');
  587. return;
  588. }
  589. if (0 === strncmp($sClassName, 'BxDol', 5)) {
  590. if (0 === strncmp($sClassName, 'BxDolStudio', 11))
  591. require_once(BX_DOL_DIR_STUDIO_CLASSES . $sClassName . '.php');
  592. else
  593. require_once(BX_DIRECTORY_PATH_CLASSES . $sClassName . '.php');
  594. return;
  595. }
  596. if (0 === strncmp($sClassName, 'BxBase', 6)) {
  597. if (0 === strncmp($sClassName, 'BxBaseMod', 9)) {
  598. $aMatches = array();
  599. if (preg_match('/BxBaseMod([A-Z][a-z]+)/', $sClassName, $aMatches)) {
  600. require_once(BX_DIRECTORY_PATH_MODULES . 'base/' . strtolower($aMatches[1]) . '/classes/' . $sClassName . '.php');
  601. return;
  602. }
  603. } if (0 === strncmp($sClassName, 'BxBaseStudio', 12)) {
  604. require_once(BX_DOL_DIR_STUDIO_BASE . 'scripts/' . $sClassName . '.php');
  605. return;
  606. } else {
  607. require_once(BX_DIRECTORY_PATH_BASE . 'scripts/' . $sClassName . '.php');
  608. return;
  609. }
  610. }
  611. if (0 === strncmp($sClassName, 'BxTempl', 7)) {
  612. if(0 === strncmp($sClassName, 'BxTemplStudio', 13)) {
  613. $sPath = BX_DIRECTORY_PATH_MODULES . BxDolStudioTemplate::getInstance()->getPath() . 'data/template/studio/scripts/' . $sClassName . '.php';
  614. } else {
  615. $sPath = BX_DIRECTORY_PATH_MODULES . BxDolTemplate::getInstance()->getPath() . 'data/template/system/scripts/' . $sClassName . '.php';
  616. }
  617. if (file_exists($sPath)) {
  618. require_once($sPath);
  619. return;
  620. }
  621. trigger_error ("bx_import fatal error: class (" . $sClassName . ") wasn't found", E_USER_ERROR);
  622. }
  623. }
  624. /**
  625. * used in spl_autoload_register() function, so no need to call bx_import for system classes
  626. */
  627. function bx_autoload($sClassName)
  628. {
  629. if (0 === strncmp($sClassName, 'BxDol', 5) || 0 === strncmp($sClassName, 'BxBase', 6) || 0 === strncmp($sClassName, 'BxTempl', 7))
  630. bx_import($sClassName);
  631. }
  632. /**
  633. * Gets an instance of class pathing necessary parameters if it's necessary.
  634. *
  635. * @param string $sClassName class name.
  636. * @param array $aParams an array of parameters to be pathed to the constructor of the class.
  637. * @param array $mixedModule an array with module description. Is used when the requested class is located in some module.
  638. * @return unknown
  639. */
  640. function bx_instance($sClassName, $aParams = array(), $mixedModule = array())
  641. {
  642. if(isset($GLOBALS['bxDolClasses'][$sClassName]))
  643. return $GLOBALS['bxDolClasses'][$sClassName];
  644. if ($mixedModule) {
  645. if (!is_array($mixedModule)) {
  646. $o = BxDolModule::getInstance($mixedModule);
  647. $mixedModule = $o->_aModule;
  648. }
  649. $sClassName = bx_ltrim_str($sClassName, $mixedModule['class_prefix']);
  650. bx_import($sClassName, $mixedModule);
  651. $sClassName = $mixedModule['class_prefix'] . $sClassName;
  652. }
  653. $oClass = new ReflectionClass($sClassName);
  654. $GLOBALS['bxDolClasses'][$sClassName] = empty($aParams) ? $oClass->newInstance() : $oClass->newInstanceArgs($aParams);
  655. return $GLOBALS['bxDolClasses'][$sClassName];
  656. }
  657. /**
  658. * Escapes string/array ready to pass to js script with filtered symbols like ', " etc
  659. *
  660. * @param $mixedInput - string/array which should be filtered
  661. * @param $iQuoteType - string escaping method: BX_ESCAPE_STR_AUTO(default), BX_ESCAPE_STR_APOS or BX_ESCAPE_STR_QUOTE
  662. * @return converted string / array
  663. */
  664. function bx_js_string ($mixedInput, $iQuoteType = BX_ESCAPE_STR_AUTO)
  665. {
  666. $aUnits = array(
  667. "\n" => "\\n",
  668. "\r" => "",
  669. );
  670. if (BX_ESCAPE_STR_APOS == $iQuoteType) {
  671. $aUnits["'"] = "\\'";
  672. $aUnits['<script'] = "<scr' + 'ipt";
  673. $aUnits['</script>'] = "</scr' + 'ipt>";
  674. } elseif (BX_ESCAPE_STR_QUOTE == $iQuoteType) {
  675. $aUnits['"'] = '\\"';
  676. $aUnits['<script'] = '<scr" + "ipt';
  677. $aUnits['</script>'] = '</scr" + "ipt>';
  678. } else {
  679. $aUnits['"'] = '&quot;';
  680. $aUnits["'"] = '&apos;';
  681. $aUnits["<script>"] = '&lt;script&gt;';
  682. $aUnits["</script>"] = '&lt;/script&gt;';
  683. }
  684. return str_replace(array_keys($aUnits), array_values($aUnits), $mixedInput);
  685. }
  686. /**
  687. * Return input string/array ready to pass to html attribute with filtered symbols like ', " etc
  688. *
  689. * @param $mixedInput - string/array which should be filtered
  690. * @param $iQuoteType - string escaping BX_ESCAPE_STR_AUTO, BX_ESCAPE_STR_APOS or BX_ESCAPE_STR_QUOTE
  691. * @return converted string / array
  692. */
  693. function bx_html_attribute ($mixedInput, $iQuoteType = BX_ESCAPE_STR_AUTO)
  694. {
  695. $aUnits = array ();
  696. if (BX_ESCAPE_STR_APOS == $iQuoteType)
  697. $aUnits["'"] = "\\'";
  698. elseif (BX_ESCAPE_STR_QUOTE == $iQuoteType)
  699. $aUnits['"'] = '&quot;';
  700. else
  701. $aUnits = array("\"" => "&quot;", "'" => "&apos;");
  702. return str_replace(array_keys($aUnits), array_values($aUnits), $mixedInput);
  703. }
  704. /**
  705. * Escapes string/array ready to pass to php script with filtered symbols like ', " etc
  706. *
  707. * @param mixed $mixedInput - string/array which should be filtered
  708. * @return converted string / array
  709. */
  710. function bx_php_string_apos ($mixedInput)
  711. {
  712. return str_replace("'", "\\'", $mixedInput);
  713. }
  714. function bx_php_string_quot ($mixedInput)
  715. {
  716. return str_replace('"', '\\"', $mixedInput);
  717. }
  718. /**
  719. * Gets file contents by URL.
  720. *
  721. * @param string $sFileUrl - file URL to be read.
  722. * @param array $aParams - an array of parameters to be pathed with URL.
  723. * @param string $sMethod - post or get.
  724. * @param array $aHeaders - custom headers.
  725. * @param string $sHttpCode - HTTP code to return
  726. * @param array $aBasicAuth - array with 'user' and 'password' for Basic HTTP Auth
  727. * @return string the file's contents.
  728. */
  729. function bx_file_get_contents($sFileUrl, $aParams = array(), $sMethod = 'get', $aHeaders = array(), &$sHttpCode = null, $aBasicAuth = array(), $iTimeout = 0, $aCustomCurlParams = array())
  730. {
  731. if ('post' != $sMethod)
  732. $sFileUrl = bx_append_url_params($sFileUrl, $aParams);
  733. $sResult = '';
  734. if(function_exists('curl_init')) {
  735. $rConnect = curl_init();
  736. curl_setopt($rConnect, CURLOPT_USERAGENT, 'UNA ' . BX_DOL_VERSION);
  737. curl_setopt($rConnect, CURLOPT_TIMEOUT, 10);
  738. curl_setopt($rConnect, CURLOPT_URL, $sFileUrl);
  739. curl_setopt($rConnect, CURLOPT_HEADER, NULL === $sHttpCode ? false : true);
  740. curl_setopt($rConnect, CURLOPT_RETURNTRANSFER, 1);
  741. if (0 !== $iTimeout) {
  742. curl_setopt($rConnect, CURLOPT_CONNECTTIMEOUT, $iTimeout);
  743. curl_setopt($rConnect, CURLOPT_TIMEOUT, $iTimeout);
  744. }
  745. if (!ini_get('open_basedir'))
  746. curl_setopt($rConnect, CURLOPT_FOLLOWLOCATION, 1);
  747. if ($aHeaders)
  748. curl_setopt($rConnect, CURLOPT_HTTPHEADER, $aHeaders);
  749. if ($aBasicAuth)
  750. curl_setopt($rConnect, CURLOPT_USERPWD, $aBasicAuth['user'] . ':' . $aBasicAuth['password']);
  751. if ('post' == $sMethod) {
  752. curl_setopt($rConnect, CURLOPT_POST, true);
  753. curl_setopt($rConnect, CURLOPT_POSTFIELDS, http_build_query($aParams));
  754. }
  755. $sAllCookies = '';
  756. foreach($_COOKIE as $sKey=>$sValue){
  757. $sAllCookies .= $sKey . '=' . $sValue . ';';
  758. }
  759. curl_setopt($rConnect, CURLOPT_COOKIE, $sAllCookies);
  760. if ($aCustomCurlParams)
  761. foreach ($aCustomCurlParams as $sName => $mixedValue)
  762. curl_setopt($rConnect, constant($sName), $mixedValue);
  763. $sResult = curl_exec($rConnect);
  764. if (curl_errno($rConnect) == 60) { // CURLE_SSL_CACERT
  765. curl_setopt($rConnect, CURLOPT_CAINFO, BX_DIRECTORY_PATH_PLUGINS . 'curl/cacert.pem');
  766. $sResult = curl_exec($rConnect);
  767. }
  768. if (NULL !== $sHttpCode)
  769. $sHttpCode = curl_getinfo($rConnect, CURLINFO_HTTP_CODE);
  770. curl_close($rConnect);
  771. }
  772. else {
  773. $iSaveTimeout = false;
  774. if (0 !== $iTimeout) {
  775. $iSaveTimeout = ini_get('default_socket_timeout');
  776. ini_set('default_socket_timeout', $iTimeout);
  777. }
  778. $sResult = @file_get_contents($sFileUrl);
  779. if (0 !== $iTimeout && false !== $iSaveTimeout) {
  780. ini_set('default_socket_timeout', $iSaveTimeout);
  781. }
  782. }
  783. return $sResult;
  784. }
  785. function bx_get_site_info($sSourceUrl, $aProcessAdditionalTags = array())
  786. {
  787. $aResult = array();
  788. $sContent = bx_file_get_contents($sSourceUrl);
  789. if ($sContent) {
  790. $sCharset = '';
  791. preg_match("/<meta.+charset=([A-Za-z0-9-]+).+>/i", $sContent, $aMatch);
  792. if (isset($aMatch[1]))
  793. $sCharset = $aMatch[1];
  794. $sContent = preg_replace("/<script[^>]*>(.*?)<\/script>/i", '', $sContent);
  795. $sContent = preg_replace("/<style[^>]*>(.*?)<\/style>/i", '', $sContent);
  796. if (preg_match("/<title[^>]*>(.*?)<\/title>/i", $sContent, $aMatch))
  797. $aResult['title'] = strip_tags($aMatch[1]);
  798. else
  799. $aResult['title'] = parse_url($sSourceUrl, PHP_URL_HOST);
  800. $aResult['description'] = bx_parse_html_tag($sContent, 'meta', 'name', 'description', 'content', $sCharset);
  801. $aResult['keywords'] = bx_parse_html_tag($sContent, 'meta', 'name', 'keywords', 'content', $sCharset);
  802. if ($aProcessAdditionalTags) {
  803. foreach ($aProcessAdditionalTags as $k => $a) {
  804. $aResult[$k] = bx_parse_html_tag(
  805. $sContent,
  806. isset($a['tag']) ? $a['tag'] : 'meta',
  807. isset($a['name_attr']) ? $a['name_attr'] : 'itemprop',
  808. isset($a['name']) ? $a['name'] : $k,
  809. isset($a['content_attr']) ? $a['content_attr'] : 'content',
  810. $sCharset,
  811. isset($a['specialchars_decode']) ? $a['specialchars_decode'] : true);
  812. if ((isset($a['name']) && 'og:image' == $a['name']) || (isset($a['tag']) && 'link' == $a['tag'])) {
  813. $aResult[$k] = bx_get_site_info_fix_relative_url ($sSourceUrl, $aResult[$k]);
  814. }
  815. }
  816. }
  817. }
  818. return $aResult;
  819. }
  820. /**
  821. * Fix relative URL to make it absolute
  822. * @param $sSourceUrl main URL
  823. * @param $s URL to fix
  824. * @return absolute URL or URL wothout changes
  825. */
  826. function bx_get_site_info_fix_relative_url ($sSourceUrl, $s)
  827. {
  828. if (0 === stripos($s, 'http://') || 0 === stripos($s, 'https://') || 0 === stripos($s, 'ftp://') || !$s)
  829. return $s;
  830. if ('/' == $s[0]) {
  831. $a = parse_url($sSourceUrl);
  832. return $a['scheme'] . '://' . $a['host'] . (empty($a['port']) || 80 == $a['port'] || 443 == $a['port'] ? '' : ':' . $a['port']) . $s;
  833. }
  834. return $sSourceUrl . ('/' === substr($sSourceUrl, -1) ? $s : '/' . $s);
  835. }
  836. function bx_parse_html_tag ($sContent, $sTag, $sAttrNameName, $sAttrNameValue, $sAttrContentName, $sCharset = false, $bSpecialCharsDecode = true)
  837. {
  838. if (!preg_match("/<{$sTag}\s+{$sAttrNameName}[='\" ]+{$sAttrNameValue}['\"]\s+{$sAttrContentName}[='\" ]+([^'>\"]*)['\"][^>]*>/i", $sContent, $aMatch) || !isset($aMatch[1]))
  839. preg_match("/<{$sTag}\s+{$sAttrContentName}[='\" ]+([^'>\"]*)['\"]\s+{$sAttrNameName}[='\" ]+{$sAttrNameValue}['\"][^>]*>/i", $sContent, $aMatch);
  840. $s = isset($aMatch[1]) ? $aMatch[1] : '';
  841. if ($s && $sCharset)
  842. $s = mb_convert_encoding($s, 'UTF-8', $sCharset);
  843. if ($bSpecialCharsDecode)
  844. $s = htmlspecialchars_decode($s);
  845. return $s;
  846. }
  847. // calculation ini_get('upload_max_filesize') in bytes as example
  848. function return_bytes($val)
  849. {
  850. $val = trim($val);
  851. $last = strtolower($val{strlen($val)-1});
  852. $val = (int)$val;
  853. switch($last) {
  854. // The 'G' modifier is available since PHP 5.1.0
  855. case 'k':
  856. $val *= 1024;
  857. break;
  858. case 'm':
  859. $val *= 1024 * 1024;
  860. break;
  861. case 'g':
  862. $val *= 1024 * 1024 * 1024;
  863. break;
  864. }
  865. return $val;
  866. }
  867. // Generate Random Password
  868. function genRndPwd($iLength = 8, $bSpecialCharacters = true)
  869. {
  870. $sPassword = '';
  871. $sChars = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
  872. if($bSpecialCharacters === true)
  873. $sChars .= "!?=/&+,.";
  874. for($i = 0; $i < $iLength; $i++) {
  875. $x = mt_rand(0, strlen($sChars) -1);
  876. $sPassword .= $sChars{$x};
  877. }
  878. return $sPassword;
  879. }
  880. // Generate Random Salt for Password encryption
  881. function genRndSalt()
  882. {
  883. return genRndPwd(8, true);
  884. }
  885. /**
  886. * Encrypt user password.
  887. * When BX_PWD_ALGO is 'custom', then bx_custom_pwd_encrypt function with custom algorythm must be defined in inc/header.inc.php file.
  888. * @param $sPwd clear password
  889. * @param $sSalt salt
  890. * @return password hash
  891. */
  892. function encryptUserPwd($sPwd, $sSalt)
  893. {
  894. $sAlgo = defined('BX_PWD_ALGO') ? BX_PWD_ALGO : '';
  895. switch ($sAlgo) {
  896. case 'custom':
  897. return bx_custom_pwd_encrypt($sPwd, $sSalt);
  898. case 'crypt':
  899. return crypt($sPwd, BX_PWD_ALGO_SALT);
  900. case 'sha1_crypt_salt':
  901. return sha1(crypt($sPwd, BX_PWD_ALGO_SALT) . $sSalt);
  902. case 'sha1_md5_salt':
  903. default:
  904. return sha1(md5($sPwd) . $sSalt);
  905. }
  906. }
  907. function bx_get ($sName, $sMethod = false)
  908. {
  909. if (isset($_GET[$sName]) && ('get' == $sMethod || !$sMethod))
  910. return $_GET[$sName];
  911. elseif (isset($_POST[$sName]) && ('post' == $sMethod || !$sMethod))
  912. return $_POST[$sName];
  913. else
  914. return false;
  915. }
  916. function bx_get_base_url_inline($aParams = array())
  917. {
  918. $aBaseLink = parse_url(BX_DOL_URL_ROOT);
  919. $sPageLink = (!empty($aBaseLink['scheme']) ? $aBaseLink['scheme'] : 'http') . '://' . $aBaseLink['host'] . $_SERVER['REQUEST_URI'];
  920. list($sPageLink, $aPageParams) = bx_get_base_url($sPageLink);
  921. if(!empty($_SERVER['QUERY_STRING'])) {
  922. $aPageParamsAdd = array();
  923. parse_str($_SERVER['QUERY_STRING'], $aPageParamsAdd);
  924. if(!empty($aPageParamsAdd) && is_array($aPageParamsAdd))
  925. $aPageParams = array_merge($aPageParams, $aPageParamsAdd);
  926. }
  927. if(!empty($aParams) && is_array($aParams))
  928. $aPageParams = array_merge($aPageParams, $aParams);
  929. return array($sPageLink, $aPageParams);
  930. }
  931. function bx_get_base_url_popup($aParams = array())
  932. {
  933. list($sPageLink, $aPageParams) = bx_get_base_url($_SERVER['HTTP_REFERER']);
  934. if(!empty($aParams) && is_array($aParams))
  935. $aPageParams = array_merge($aPageParams, $aParams);
  936. return array($sPageLink, $aPageParams);
  937. }
  938. function bx_get_base_url($sPageLink)
  939. {
  940. $sPageLink = BxDolPermalinks::getInstance()->unpermalink($sPageLink, false);
  941. $sPageParams = '';
  942. if(strpos($sPageLink, '?') !== false)
  943. list($sPageLink, $sPageParams) = explode('?', $sPageLink);
  944. $aPageParams = array();
  945. if(!empty($sPageParams))
  946. parse_str($sPageParams, $aPageParams);
  947. return array($sPageLink, $aPageParams);
  948. }
  949. function bx_get_location_bounds_latlng($fLatitude, $fLongitude, $iRadiusInKm)
  950. {
  951. $fEquatorLatInKm = 111.321;
  952. $aRv = array();
  953. $aRv['max_lat'] = $fLatitude + $iRadiusInKm / $fEquatorLatInKm;
  954. $aRv['min_lat'] = $fLatitude - ($aRv['max_lat'] - $fLatitude);
  955. $aRv['max_lng'] = $fLongitude + $iRadiusInKm / (cos($aRv['min_lat'] * M_PI / 180) * $fEquatorLatInKm);
  956. $aRv['min_lng'] = $fLongitude - ($aRv['max_lng'] - $fLongitude);
  957. return $aRv;
  958. }
  959. function bx_encode_url_params ($a, $aExcludeKeys = array (), $aOnlyKeys = false)
  960. {
  961. $s = '';
  962. foreach ($a as $sKey => $sVal) {
  963. if (in_array($sKey, $aExcludeKeys))
  964. continue;
  965. if (false !== $aOnlyKeys && !in_array($sKey, $aOnlyKeys))
  966. continue;
  967. if (is_array($sVal)) {
  968. foreach ($sVal as $sSubVal) {
  969. $s .= rawurlencode($sKey) . '[]=' . rawurlencode(is_array($sSubVal) ? 'array' : $sSubVal) . '&';
  970. }
  971. } else {
  972. $s .= rawurlencode($sKey) . '=' . rawurlencode($sVal) . '&';
  973. }
  974. }
  975. return $s;
  976. }
  977. function bx_append_url_params ($sUrl, $mixedParams)
  978. {
  979. if (!$mixedParams)
  980. return $sUrl;
  981. $sParams = false == strpos($sUrl, '?') ? '?' : '&';
  982. if (is_array($mixedParams)) {
  983. foreach($mixedParams as $sKey => $sValue) {
  984. if (!is_array($sValue)) {
  985. $sParams .= $sKey . '=' . $sValue . '&';
  986. }
  987. else {
  988. foreach($sValue as $sSubValue)
  989. $sParams .= $sKey . '[]=' . $sSubValue . '&';
  990. }
  991. }
  992. $sParams = substr($sParams, 0, -1);
  993. } else {
  994. $sParams .= $mixedParams;
  995. }
  996. return $sUrl . $sParams;
  997. }
  998. function bx_rrmdir($directory)
  999. {
  1000. if (substr($directory,-1) == "/")
  1001. $directory = substr($directory,0,-1);
  1002. if (!file_exists($directory) || !is_dir($directory))
  1003. return false;
  1004. elseif (!is_readable($directory))
  1005. return false;
  1006. if (!($directoryHandle = opendir($directory)))
  1007. return false;
  1008. while ($contents = readdir($directoryHandle)) {
  1009. if ($contents != '.' && $contents != '..') {
  1010. $path = $directory . "/" . $contents;
  1011. if (is_dir($path))
  1012. bx_rrmdir($path);
  1013. else
  1014. unlink($path);
  1015. }
  1016. }
  1017. closedir($directoryHandle);
  1018. if (!rmdir($directory))
  1019. return false;
  1020. return true;
  1021. }
  1022. function bx_clear_folder ($sPath, $aExts = array ())
  1023. {
  1024. if (substr($$sPath,-1) == "/")
  1025. $sPath = substr($sPath,0,-1);
  1026. if (!file_exists($sPath) || !is_dir($sPath))
  1027. return false;
  1028. elseif (!is_readable($sPath))
  1029. return false;
  1030. if (!($h = opendir($sPath)))
  1031. return false;
  1032. while ($sFile = readdir($h)) {
  1033. if ('.' == $sFile || '..' == $sFile)
  1034. continue;
  1035. $sFullPath = $sPath . '/' . $sFile;
  1036. if (is_dir($sFullPath))
  1037. continue;
  1038. if (!$aExts || (($sExt = pathinfo($sFullPath, PATHINFO_EXTENSION)) && in_array($sExt, $aExts)))
  1039. @unlink($sFullPath);
  1040. }
  1041. closedir($h);
  1042. return true;
  1043. }
  1044. function bx_ltrim_str ($sString, $sPrefix, $sReplace = '')
  1045. {
  1046. if ($sReplace && substr($sString, 0, strlen($sReplace)) == $sReplace)
  1047. return $sString;
  1048. if (substr($sString, 0, strlen($sPrefix)) == $sPrefix)
  1049. return $sReplace . substr($sString, strlen($sPrefix));
  1050. return $sString;
  1051. }
  1052. function bx_rtrim_str ($sString, $sPrefix, $sReplace = '')
  1053. {
  1054. if ($sReplace && substr($sString, -strlen($sReplace)) == $sReplace)
  1055. return $sString;
  1056. if (substr($sString, -strlen($sPrefix)) == $sPrefix)
  1057. return substr($sString, 0, -strlen($sPrefix)) . $sReplace;
  1058. return $sString;
  1059. }
  1060. /**
  1061. * Strip all lines with no information for example: <p></p>, <br /><br />
  1062. */
  1063. function bx_trim_nl_duplicates($s)
  1064. {
  1065. $sStrip = implode('', array_keys(get_html_translation_table(HTML_ENTITIES)));
  1066. return implode('', array_filter(mb_split("[\n\r]", $s), function($s) use ($sStrip) {
  1067. return trim(strip_tags($s, '<button><canvas><embed><hr><iframe><img><input><object><select><svg><video>'), $sStrip) !== '';
  1068. }));
  1069. }
  1070. /**
  1071. * Convert array to attributes string
  1072. *
  1073. * Example:
  1074. * @code
  1075. * $a = array('name' => 'test', 'value' => 5);
  1076. * $s = bx_convert_array2attrs($a);
  1077. * echo $s; // outputs: name="test" value="5"
  1078. * @endcode
  1079. *
  1080. * @param $a - array of attributes
  1081. * @param $sClasses - classes to merge with 'class' attribute
  1082. * @param $sStyles - styles to merge with 'style' attribute
  1083. * @return string
  1084. */
  1085. function bx_convert_array2attrs ($a, $sClasses = false, $sStyles = false)
  1086. {
  1087. $sRet = '';
  1088. if (!$a || !is_array($a))
  1089. $a = array();
  1090. if ($sClasses) {
  1091. $sClasses = trim($sClasses);
  1092. $a['class'] = $sClasses . (!empty($a['class']) ? ' ' . $a['class'] : '');
  1093. }
  1094. if ($sStyles) {
  1095. $sStyles = trim($sStyles);
  1096. if (';' != $sStyles[strlen($sStyles)-1])
  1097. $sStyles .= ';';
  1098. $a['style'] = $sStyles . (!empty($a['style']) ? ' ' . $a['style'] : '');
  1099. }
  1100. foreach ($a as $sKey => $sValue) {
  1101. if(is_null($sValue)) // pass NULL values
  1102. continue;
  1103. $sValueC = bx_html_attribute($sValue, BX_ESCAPE_STR_QUOTE);
  1104. $sRet .= " $sKey=\"$sValueC\"";
  1105. }
  1106. return $sRet;
  1107. }
  1108. function bx_unicode_urldecode($s)
  1109. {
  1110. preg_match_all('/%u([[:alnum:]]{4})/', $s, $a);
  1111. foreach ($a[1] as $uniord) {
  1112. $dec = hexdec($uniord);
  1113. $utf = '';
  1114. if ($dec < 128) {
  1115. $utf = chr($dec);
  1116. } else if ($dec < 2048) {
  1117. $utf = chr(192 + (($dec - ($dec % 64)) / 64));
  1118. $utf .= chr(128 + ($dec % 64));
  1119. } else {
  1120. $utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
  1121. $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
  1122. $utf .= chr(128 + ($dec % 64));
  1123. }
  1124. $s = str_replace('%u'.$uniord, $utf, $s);
  1125. }
  1126. return urldecode($s);
  1127. }
  1128. /**
  1129. * Raise an alert
  1130. * @param string $sUnit - system type
  1131. * @param string $sAction - system action
  1132. * @param int $iObjectId - object id
  1133. * @param int $iSender - sender (action's author) profile id, if it is false - then currectly logged in profile id is used
  1134. * @param array $aExtras - extra parameters
  1135. */
  1136. function bx_alert($sUnit, $sAction, $iObjectId, $iSender = false, $aExtras = array())
  1137. {
  1138. $o = new BxDolAlerts($sUnit, $sAction, $iObjectId, $iSender, $aExtras);
  1139. $o->alert();
  1140. }
  1141. /**
  1142. * Perform serice call
  1143. * @param $mixed module name or module id
  1144. * @param $sMethod service method name in format 'method_name', corresponding class metod is serviceMethodName
  1145. * @param $aParams params to pass to service method
  1146. * @param $sClass class to search for service method, by default it is main module class
  1147. * @return service call result
  1148. */
  1149. function bx_srv($mixed, $sMethod, $aParams = array(), $sClass = 'Module', $bIgnoreCache = false)
  1150. {
  1151. return BxDolService::call($mixed, $sMethod, $aParams, $sClass, $bIgnoreCache);
  1152. }
  1153. function bx_replace_markers($mixed, $aMarkers)
  1154. {
  1155. if (empty($aMarkers))
  1156. return $mixed;
  1157. if (is_array($mixed)) {
  1158. foreach ($mixed as $sKey => $sValue)
  1159. $mixed[$sKey] = bx_replace_markers ($sValue, $aMarkers);
  1160. } else {
  1161. foreach ($aMarkers as $sKey => $sValue)
  1162. $mixed = str_replace('{' . $sKey . '}', $sValue, $mixed);
  1163. }
  1164. return $mixed;
  1165. }
  1166. function bx_site_hash($sSalt = '', $isSkipVersion = false)
  1167. {
  1168. return md5($sSalt . ($isSkipVersion ? '' : bx_get_ver() . getParam('sys_revision')) . BX_DOL_SECRET . BX_DOL_URL_ROOT);
  1169. }
  1170. /**
  1171. * Transform string to method name string, for example it changes 'some_method' string to 'SomeMethod' string
  1172. * @param $s string where words are separated with underscore
  1173. * @param $aWordsDelimiter word delimeters
  1174. * @return string where every word begins with capital letter
  1175. */
  1176. function bx_gen_method_name ($s, $aWordsDelimiter = array('_'))
  1177. {
  1178. return str_replace(' ', '', ucwords(str_replace($aWordsDelimiter, ' ', $s)));
  1179. }
  1180. /**
  1181. * Trigger user error
  1182. * @param $sMsg message to display
  1183. * @param $iNumLevelsBack add additional debug backtracing N levels back
  1184. */
  1185. function bx_trigger_error ($sMsg, $iNumLevelsBack = 0)
  1186. {
  1187. $a = debug_backtrace();
  1188. $sMsgAdd = "<br />\n related code in <b>{$a[$iNumLevelsBack]['file']}</b> on line <b>{$a[$iNumLevelsBack]['line']}</b> <br />\n";
  1189. trigger_error ($sMsg . $sMsgAdd, E_USER_ERROR);
  1190. }
  1191. /**
  1192. * Get system DB version, for files version @see BX_DOL_VERSION, these versions must match
  1193. */
  1194. function bx_get_ver ($bInvalidateCache = false)
  1195. {
  1196. $oDb = BxDolDb::getInstance();
  1197. if ($bInvalidateCache)
  1198. $oDb->cleanMemory('sys_version');
  1199. $sQuery = $oDb->prepare("SELECT `version` FROM `sys_modules` WHERE `name` = 'system'");
  1200. return $oDb->fromMemory('sys_version', 'getOne', $sQuery);
  1201. }
  1202. /**
  1203. * Check if site maintetance mode is enabled.
  1204. * Maintetance mode is enabled when '.bx_maintenance' file exists in the script root folder,
  1205. * please note that this is hidden file and some file managers don't show it.
  1206. * @param $bShowHttpError show 503 HTTP error if site is in mainenance mode
  1207. * @return true if site is in maintenance mode, or false otherwise
  1208. */
  1209. function bx_check_maintenance_mode ($bShowHttpError = false)
  1210. {
  1211. $bMaintetance = file_exists(BX_DIRECTORY_PATH_ROOT . BX_MAINTENANCE_FILE) && !defined('BX_DOL_UPGRADING');
  1212. if ($bMaintetance && $bShowHttpError)
  1213. bx_show_service_unavailable_error_and_exit ('Site is temporarily unavailable due to scheduled maintenance, please try again in a minute.', 600);
  1214. return $bMaintetance;
  1215. }
  1216. /**
  1217. * Check for minimal requirements.
  1218. * if BX_DISABLE_REQUIREMENTS_CHECK is defined then this requirements checking is skipped.
  1219. * @param $bShowHttpError show 503 HTTP error if site doesn't meet minimal requirements
  1220. * @return false if requirements are met, or array of errors of requirements aren't met
  1221. */
  1222. function bx_check_minimal_requirements ($bShowHttpError = false)
  1223. {
  1224. if (defined('BX_DISABLE_REQUIREMENTS_CHECK'))
  1225. return false;
  1226. $aErrors = array();
  1227. $aErrors[] = (ini_get('register_globals') == 0) ? '' : '<b>register_globals</b> is on (you need to disable it, or your site will be unsafe)';
  1228. $aErrors[] = (ini_get('safe_mode') == 0) ? '' : '<b>safe_mode</b> is on (you need to disable it)';
  1229. $aErrors[] = (version_compare(PHP_VERSION, '5.3.0', '<')) ? 'PHP version is too old (please update to <b>PHP 5.3.0</b> at least)' : '';
  1230. $aErrors[] = (!extension_loaded( 'mbstring')) ? '<b>mbstring</b> extension not installed (the script cannot work without it)' : '';
  1231. $aErrors[] = (ini_get('allow_url_include') == 0) ? '' : '<b>allow_url_include</b> is on (you need to disable it, or your site will be unsafe)';
  1232. $aErrors = array_diff($aErrors, array('')); // delete empty
  1233. $bFailedMinimalRequirements = !empty($aErrors);
  1234. if ($bFailedMinimalRequirements && $bShowHttpError) {
  1235. $sErrors = implode(" <br /> ", $aErrors);
  1236. bx_show_service_unavailable_error_and_exit($sErrors);
  1237. }
  1238. return $bFailedMinimalRequirements ? $aErrors : false;
  1239. }
  1240. /**
  1241. * Check if redirect to the correct hostname is required, for example redirect from site.com to www.site.com
  1242. * @param $bProcessRedirect process redirect and exit if needed
  1243. */
  1244. function bx_check_redirect_to_correct_hostname ($bProcessRedirect = false)
  1245. {
  1246. $aUrl = parse_url(BX_DOL_URL_ROOT);
  1247. $iPortDefault = 'https' == $aUrl['scheme'] ? '443' : '80';
  1248. $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));
  1249. if ($bRedirectRequired && $bProcessRedirect) {
  1250. $sPort = empty($aUrl['port']) || 80 == $aUrl['port'] || 443 == $aUrl['port'] ? '' : ':' . $aUrl['port'];
  1251. header("Location:{$aUrl['scheme']}://{$aUrl['host']}{$sPort}{$_SERVER['REQUEST_URI']}", true, 301);
  1252. exit;
  1253. }
  1254. return $bRedirectRequired;
  1255. }
  1256. /**
  1257. * Check if redirect to remove install folder.
  1258. * If BX_SKIP_INSTALL_CHECK is defined then this redirect checking is skipped.
  1259. * @param $bProcessRedirect process redirect and exit if needed
  1260. */
  1261. function bx_check_redirect_to_remove_install_folder ($bProcessRedirect = false)
  1262. {
  1263. $bRemoveInstallFolder = !defined ('BX_SKIP_INSTALL_CHECK') && file_exists(BX_DIRECTORY_PATH_ROOT . 'install');
  1264. if ($bRemoveInstallFolder && $bProcessRedirect) {
  1265. header('Location:' . BX_DOL_URL_ROOT . 'install/index.php?action=remove_install');
  1266. exit;
  1267. }
  1268. return $bRemoveInstallFolder;
  1269. }
  1270. /**
  1271. * Show HTTP 503 service unavailable error and exit
  1272. */
  1273. function bx_show_service_unavailable_error_and_exit ($sMsg = false, $iRetryAfter = 86400)
  1274. {
  1275. header('HTTP/1.0 503 Service Unavailable', true, 503);
  1276. header('Retry-After: 600');
  1277. echo $sMsg ? $sMsg : 'Service temporarily unavailable';
  1278. exit;
  1279. }
  1280. /**
  1281. * The function is sumilar to php readfile, but it send all required headers and can send file by chunks and suports file seek
  1282. * @param $sPath path to file to output to the browser
  1283. * @param $sFilename filename without path, ig file is saved from browser, then this name is used, not used(empty) by default
  1284. * @param $sMimeType file mime type, by default 'application/octet-stream'
  1285. * @param $iCacheAge file cache age, by default 0
  1286. * @param $sCachePrivacy cache privacy 'public' (default value) or 'private'
  1287. * @return true on success or false on error
  1288. */
  1289. function bx_smart_readfile($sPath, $sFilename = '', $sMimeType = 'application/octet-stream', $iCacheAge = 0, $sCachePrivacy = 'public')
  1290. {
  1291. if (!file_exists($sPath))
  1292. return false;
  1293. $fp = @fopen($sPath, 'rb');
  1294. $size = filesize($sPath);
  1295. $length = $size;
  1296. $start = 0;
  1297. $end = $size - 1;
  1298. header('Content-type: ' . $sMimeType);
  1299. header('Cache-Control: ' . $sCachePrivacy . ', must-revalidate, max-age=' . $iCacheAge);
  1300. header("Accept-Ranges: 0-$length");
  1301. if ($sFilename)
  1302. header('Content-Disposition: inline; filename="' . $sFilename . '"');
  1303. if (isset($_SERVER['HTTP_RANGE'])) {
  1304. $c_start = $start;
  1305. $c_end = $end;
  1306. list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
  1307. if (strpos($range, ',') !== false) {
  1308. header('HTTP/1.1 416 Requested Range Not Satisfiable');
  1309. header("Content-Range: bytes $start-$end/$size");
  1310. return false;
  1311. }
  1312. if ($range == '-') {
  1313. $c_start = $size - substr($range, 1);
  1314. }else{
  1315. $range = explode('-', $range);
  1316. $c_start = $range[0];
  1317. $c_end = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $size;
  1318. }
  1319. $c_end = ($c_end > $end) ? $end : $c_end;
  1320. if ($c_start > $c_end || $c_start > $size - 1 || $c_end >= $size) {
  1321. header('HTTP/1.1 416 Requested Range Not Satisfiable');
  1322. header("Content-Range: bytes $start-$end/$size");
  1323. return false;
  1324. }
  1325. $start = $c_start;
  1326. $end = $c_end;
  1327. $length = $end - $start + 1;
  1328. fseek($fp, $start);
  1329. header('HTTP/1.1 206 Partial Content');
  1330. }
  1331. header("Content-Range: bytes $start-$end/$size");
  1332. header("Content-Length: ".$length);
  1333. $buffer = 1024 * 8;
  1334. while(!feof($fp) && ($p = ftell($fp)) <= $end) {
  1335. if ($p + $buffer > $end) {
  1336. $buffer = $end - $p + 1;
  1337. }
  1338. set_time_limit(0);
  1339. echo fread($fp, $buffer);
  1340. flush();
  1341. }
  1342. fclose($fp);
  1343. return true;
  1344. }
  1345. /**
  1346. * Wrap in A tag links in TEXT string
  1347. * @param $text - text string without tags
  1348. * @param $sAttrs - attributes string to add to the added A tag
  1349. * @param $bHtmlSpecialChars - apply htmlspecialchars before processing
  1350. * @return string where all links are wrapped in A tag
  1351. */
  1352. function bx_linkify($text, $sAttrs = '', $bHtmlSpecialChars = false)
  1353. {
  1354. if ($bHtmlSpecialChars)
  1355. $text = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8');
  1356. $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_!~*'().;?:\@&=+$,%#-]+)*/?)@";
  1357. preg_match_all($re, $text, $matches, PREG_OFFSET_CAPTURE);
  1358. $matches = $matches[0];
  1359. if ($i = count($matches))
  1360. $bAddNofollow = getParam('sys_add_nofollow') == 'on';
  1361. while ($i--)
  1362. {
  1363. $sAttrsLocal = $sAttrs;
  1364. $url = $matches[$i][0];
  1365. if (!preg_match('@^https?://@', $url))
  1366. $url = 'http://'.$url;
  1367. if (strncmp(BX_DOL_URL_ROOT, $url, strlen(BX_DOL_URL_ROOT)) !== 0) {
  1368. $sAttrsLocal .= ' target="_blank" ';
  1369. if ($bAddNofollow)
  1370. $sAttrsLocal .= ' rel="nofollow" ';
  1371. }
  1372. $text = substr_replace($text, '<a ' . $sAttrsLocal . ' href="'.$url.'">'.$matches[$i][0].'</a>', $matches[$i][1], strlen($matches[$i][0]));
  1373. }
  1374. // email pattern
  1375. $mail_pattern = "/([A-z0-9\._-]+\@[A-z0-9_-]+\.)([A-z0-9\_\-\.]{1,}[A-z])/";
  1376. $text = preg_replace($mail_pattern, '<a href="mailto:$1$2">$1$2</a>', $text);
  1377. return $text;
  1378. }
  1379. /**
  1380. * Wrap in A tag links in HTML string, which aren't wrapped in A tag yet
  1381. * @param $sHtmlOrig - HTML string
  1382. * @param $sAttrs - attributes string to add to the added A tag
  1383. * @return modified HTML string, in case of errror original string is returned
  1384. */
  1385. function bx_linkify_html($sHtmlOrig, $sAttrs = '')
  1386. {
  1387. if (!trim($sHtmlOrig))
  1388. return $sHtmlOrig;
  1389. $sId = 'bx-linkify-' . md5(microtime());
  1390. $dom = new DOMDocument();
  1391. @$dom->loadHTML('<?xml encoding="UTF-8"><div id="' . $sId . '">' . $sHtmlOrig . '</div>');
  1392. $xpath = new DOMXpath($dom);
  1393. foreach ($xpath->query('//text()') as $text) {
  1394. if (!empty($text->parentNode) && !empty($text->parentNode->tagName) && 'a' == $text->parentNode->tagName)
  1395. continue;
  1396. $frag = $dom->createDocumentFragment();
  1397. @$frag->appendXML(bx_linkify($text->nodeValue, $sAttrs, true));
  1398. $text->parentNode->replaceChild($frag, $text);
  1399. }
  1400. if (version_compare(PHP_VERSION, '5.3.6') >= 0)
  1401. $s = $dom->saveHTML($dom->getElementById($sId));
  1402. else
  1403. $s = $dom->saveXML($dom->getElementById($sId), LIBXML_NOEMPTYTAG);
  1404. if (false === $s) // in case of error return original string
  1405. return $sHtmlOrig;
  1406. if (false !== ($iPos = mb_strpos($s, '<html><body>')) && $iPos < mb_strpos($s, $sId))
  1407. $s = mb_substr($s, $iPos + 12, -15); // strip <html><body> tags and everything before them
  1408. return mb_substr($s, 54, -6); // strip added tags
  1409. }
  1410. /**
  1411. * Returns current site protocol http:// or https://
  1412. */
  1413. function bx_proto()
  1414. {
  1415. return 0 === strncmp('https', BX_DOL_URL_ROOT, 5) ? 'https' : 'http';
  1416. }
  1417. /**
  1418. * Checks protocol in the link
  1419. */
  1420. function bx_has_proto($sLink)
  1421. {
  1422. return preg_match('@^https?://@', $sLink);
  1423. }
  1424. function bx_is_empty_array ($a)
  1425. {
  1426. if (!is_array($a))
  1427. return true;
  1428. if (empty($a))
  1429. return true;
  1430. foreach ($a as $k => $v)
  1431. if ($v)
  1432. return false;
  1433. return true;
  1434. }
  1435. function bx_is_full_array ($a)
  1436. {
  1437. if (!is_array($a))
  1438. return false;
  1439. if (empty($a))
  1440. return false;
  1441. foreach ($a as $k => $v)
  1442. if (empty($v))
  1443. return false;
  1444. return true;
  1445. }
  1446. function bx_is_url_in_content ($sContent)
  1447. {
  1448. $a = array(
  1449. 'http://',
  1450. 'https://',
  1451. 'https/',
  1452. 'http/',
  1453. 'www.',
  1454. '.com'
  1455. );
  1456. foreach ($a as $s)
  1457. if (false !== strpos($sContent, $s))
  1458. return true;
  1459. return false;
  1460. }
  1461. function bx_is_dynamic_request ()
  1462. {
  1463. return bx_get('dynamic') || (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && 'XMLHttpRequest' == $_SERVER['HTTP_X_REQUESTED_WITH']);
  1464. }
  1465. /** @} */