utils.inc.php 55 KB

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