utils.inc.php 57 KB

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