utils.inc.php 60 KB

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