utils.inc.php 56 KB

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