utils.inc.php 55 KB

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