utils.inc.php 55 KB

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