utils.inc.php 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806
  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_set ($sName, $sValue, $sMethod = false)
  917. {
  918. if(!$sMethod)
  919. $sMethod = 'get';
  920. $bResult = true;
  921. switch($sMethod) {
  922. case 'get':
  923. $_GET[$sName] = $sValue;
  924. break;
  925. case 'post':
  926. $_POST[$sName] = $sValue;
  927. break;
  928. default:
  929. $bResult = false;
  930. }
  931. return $bResult;
  932. }
  933. function bx_get_with_prefix ($sPrefix, $sMethod = false)
  934. {
  935. $aSources = array('get' => &$_GET, 'post' => &$_POST);
  936. $aFiltered = array();
  937. foreach($aSources as $sName => $aSource)
  938. if($sMethod == $sName || !$sMethod)
  939. $aFiltered = array_merge($aFiltered, array_filter($aSource, function($sKey) use ($sPrefix) {
  940. return strpos($sKey, $sPrefix) === 0;
  941. }, ARRAY_FILTER_USE_KEY));
  942. $aUpdated = array();
  943. array_walk($aFiltered, function($sValue, $sKey) use ($sPrefix, &$aUpdated) {
  944. $aUpdated[trim(str_replace($sPrefix, '', $sKey), '_-')] = $sValue;
  945. });
  946. return $aUpdated;
  947. }
  948. function bx_get_base_url_inline($aParams = array())
  949. {
  950. $aBaseLink = parse_url(BX_DOL_URL_ROOT);
  951. $sPageLink = (!empty($aBaseLink['scheme']) ? $aBaseLink['scheme'] : 'http') . '://' . $aBaseLink['host'] . $_SERVER['REQUEST_URI'];
  952. list($sPageLink, $aPageParams) = bx_get_base_url($sPageLink);
  953. if(!empty($_SERVER['QUERY_STRING'])) {
  954. $aPageParamsAdd = array();
  955. parse_str($_SERVER['QUERY_STRING'], $aPageParamsAdd);
  956. if(!empty($aPageParamsAdd) && is_array($aPageParamsAdd))
  957. $aPageParams = array_merge($aPageParams, $aPageParamsAdd);
  958. }
  959. if(!empty($aParams) && is_array($aParams))
  960. $aPageParams = array_merge($aPageParams, $aParams);
  961. return array($sPageLink, $aPageParams);
  962. }
  963. function bx_get_base_url_popup($aParams = array())
  964. {
  965. list($sPageLink, $aPageParams) = bx_get_base_url($_SERVER['HTTP_REFERER']);
  966. if(!empty($aParams) && is_array($aParams))
  967. $aPageParams = array_merge($aPageParams, $aParams);
  968. return array($sPageLink, $aPageParams);
  969. }
  970. function bx_get_base_url($sPageLink)
  971. {
  972. $sPageLink = BxDolPermalinks::getInstance()->unpermalink($sPageLink, false);
  973. $sPageParams = '';
  974. if(strpos($sPageLink, '?') !== false)
  975. list($sPageLink, $sPageParams) = explode('?', $sPageLink);
  976. $aPageParams = array();
  977. if(!empty($sPageParams))
  978. parse_str($sPageParams, $aPageParams);
  979. return array($sPageLink, $aPageParams);
  980. }
  981. function bx_get_location_bounds_latlng($fLatitude, $fLongitude, $iRadiusInKm)
  982. {
  983. $fEquatorLatInKm = 111.321;
  984. $aRv = array();
  985. $aRv['max_lat'] = $fLatitude + $iRadiusInKm / $fEquatorLatInKm;
  986. $aRv['min_lat'] = $fLatitude - ($aRv['max_lat'] - $fLatitude);
  987. $aRv['max_lng'] = $fLongitude + $iRadiusInKm / (cos($aRv['min_lat'] * M_PI / 180) * $fEquatorLatInKm);
  988. $aRv['min_lng'] = $fLongitude - ($aRv['max_lng'] - $fLongitude);
  989. return $aRv;
  990. }
  991. function bx_encode_url_params ($a, $aExcludeKeys = array (), $aOnlyKeys = false)
  992. {
  993. $s = '';
  994. foreach ($a as $sKey => $sVal) {
  995. if (in_array($sKey, $aExcludeKeys))
  996. continue;
  997. if (false !== $aOnlyKeys && !in_array($sKey, $aOnlyKeys))
  998. continue;
  999. if (is_array($sVal)) {
  1000. foreach ($sVal as $sSubVal) {
  1001. $s .= rawurlencode($sKey) . '[]=' . rawurlencode(is_array($sSubVal) ? 'array' : $sSubVal) . '&';
  1002. }
  1003. } else {
  1004. $s .= rawurlencode($sKey) . '=' . rawurlencode($sVal) . '&';
  1005. }
  1006. }
  1007. return $s;
  1008. }
  1009. function bx_append_url_params ($sUrl, $mixedParams)
  1010. {
  1011. if (!$mixedParams)
  1012. return $sUrl;
  1013. $sParams = false == strpos($sUrl, '?') ? '?' : '&';
  1014. if (is_array($mixedParams)) {
  1015. foreach($mixedParams as $sKey => $sValue) {
  1016. if (!is_array($sValue)) {
  1017. $sParams .= $sKey . '=' . $sValue . '&';
  1018. }
  1019. else {
  1020. foreach($sValue as $sSubValue)
  1021. $sParams .= $sKey . '[]=' . $sSubValue . '&';
  1022. }
  1023. }
  1024. $sParams = substr($sParams, 0, -1);
  1025. } else {
  1026. $sParams .= $mixedParams;
  1027. }
  1028. return $sUrl . $sParams;
  1029. }
  1030. function bx_rrmdir($directory)
  1031. {
  1032. if (substr($directory,-1) == "/")
  1033. $directory = substr($directory,0,-1);
  1034. if (!file_exists($directory) || !is_dir($directory))
  1035. return false;
  1036. elseif (!is_readable($directory))
  1037. return false;
  1038. if (!($directoryHandle = opendir($directory)))
  1039. return false;
  1040. while ($contents = readdir($directoryHandle)) {
  1041. if ($contents != '.' && $contents != '..') {
  1042. $path = $directory . "/" . $contents;
  1043. if (is_dir($path))
  1044. bx_rrmdir($path);
  1045. else
  1046. unlink($path);
  1047. }
  1048. }
  1049. closedir($directoryHandle);
  1050. if (!rmdir($directory))
  1051. return false;
  1052. return true;
  1053. }
  1054. function bx_clear_folder ($sPath, $aExts = array ())
  1055. {
  1056. if (substr($$sPath,-1) == "/")
  1057. $sPath = substr($sPath,0,-1);
  1058. if (!file_exists($sPath) || !is_dir($sPath))
  1059. return false;
  1060. elseif (!is_readable($sPath))
  1061. return false;
  1062. if (!($h = opendir($sPath)))
  1063. return false;
  1064. while ($sFile = readdir($h)) {
  1065. if ('.' == $sFile || '..' == $sFile)
  1066. continue;
  1067. $sFullPath = $sPath . '/' . $sFile;
  1068. if (is_dir($sFullPath))
  1069. continue;
  1070. if (!$aExts || (($sExt = pathinfo($sFullPath, PATHINFO_EXTENSION)) && in_array($sExt, $aExts)))
  1071. @unlink($sFullPath);
  1072. }
  1073. closedir($h);
  1074. return true;
  1075. }
  1076. function bx_ltrim_str ($sString, $sPrefix, $sReplace = '')
  1077. {
  1078. if ($sReplace && substr($sString, 0, strlen($sReplace)) == $sReplace)
  1079. return $sString;
  1080. if (substr($sString, 0, strlen($sPrefix)) == $sPrefix)
  1081. return $sReplace . substr($sString, strlen($sPrefix));
  1082. return $sString;
  1083. }
  1084. function bx_rtrim_str ($sString, $sPrefix, $sReplace = '')
  1085. {
  1086. if ($sReplace && substr($sString, -strlen($sReplace)) == $sReplace)
  1087. return $sString;
  1088. if (substr($sString, -strlen($sPrefix)) == $sPrefix)
  1089. return substr($sString, 0, -strlen($sPrefix)) . $sReplace;
  1090. return $sString;
  1091. }
  1092. /**
  1093. * Strip all lines with no information for example: <p></p>, <br /><br />
  1094. */
  1095. function bx_trim_nl_duplicates($s)
  1096. {
  1097. $sStrip = implode('', array_keys(get_html_translation_table(HTML_ENTITIES)));
  1098. return implode('', array_filter(mb_split("[\n\r]", $s), function($s) use ($sStrip) {
  1099. return trim(strip_tags($s, '<button><canvas><embed><hr><iframe><img><input><object><select><svg><video>'), $sStrip) !== '';
  1100. }));
  1101. }
  1102. /**
  1103. * Convert array to attributes string
  1104. *
  1105. * Example:
  1106. * @code
  1107. * $a = array('name' => 'test', 'value' => 5);
  1108. * $s = bx_convert_array2attrs($a);
  1109. * echo $s; // outputs: name="test" value="5"
  1110. * @endcode
  1111. *
  1112. * @param $a - array of attributes
  1113. * @param $sClasses - classes to merge with 'class' attribute
  1114. * @param $sStyles - styles to merge with 'style' attribute
  1115. * @return string
  1116. */
  1117. function bx_convert_array2attrs ($a, $sClasses = false, $sStyles = false)
  1118. {
  1119. $sRet = '';
  1120. if (!$a || !is_array($a))
  1121. $a = array();
  1122. if ($sClasses) {
  1123. $sClasses = trim($sClasses);
  1124. $a['class'] = $sClasses . (!empty($a['class']) ? ' ' . $a['class'] : '');
  1125. }
  1126. if ($sStyles) {
  1127. $sStyles = trim($sStyles);
  1128. if (';' != $sStyles[strlen($sStyles)-1])
  1129. $sStyles .= ';';
  1130. $a['style'] = $sStyles . (!empty($a['style']) ? ' ' . $a['style'] : '');
  1131. }
  1132. foreach ($a as $sKey => $sValue) {
  1133. if(is_null($sValue)) // pass NULL values
  1134. continue;
  1135. $sValueC = bx_html_attribute($sValue, BX_ESCAPE_STR_QUOTE);
  1136. $sRet .= " $sKey=\"$sValueC\"";
  1137. }
  1138. return $sRet;
  1139. }
  1140. function bx_unicode_urldecode($s)
  1141. {
  1142. preg_match_all('/%u([[:alnum:]]{4})/', $s, $a);
  1143. foreach ($a[1] as $uniord) {
  1144. $dec = hexdec($uniord);
  1145. $utf = '';
  1146. if ($dec < 128) {
  1147. $utf = chr($dec);
  1148. } else if ($dec < 2048) {
  1149. $utf = chr(192 + (($dec - ($dec % 64)) / 64));
  1150. $utf .= chr(128 + ($dec % 64));
  1151. } else {
  1152. $utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
  1153. $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
  1154. $utf .= chr(128 + ($dec % 64));
  1155. }
  1156. $s = str_replace('%u'.$uniord, $utf, $s);
  1157. }
  1158. return urldecode($s);
  1159. }
  1160. /**
  1161. * Raise an audit event
  1162. * @param int $iProfileId - sender (action's author) profile id, if it is false - then currectly logged in profile id is used
  1163. * @param int $iContentId - content id
  1164. * @param string $sContentModule - module name
  1165. * @param string $sAction - system action key
  1166. * @param string $sContentTitle - needed in case when original content was deleted
  1167. * @param string $sContentInfoObject - content info object
  1168. * @param int $iContextProfileId - context profile id
  1169. * @param string $sContextProfileTitle - needed in case when original context was deleted
  1170. * @param array $aActionParams - serialized array of parameters to pass to 'action lang key', for example friend name in case if 'befriend' action
  1171. */
  1172. function bx_audit($iContentId, $sContentModule, $sAction, $sContentTitle = '', $sContentInfoObject = '', $iContextProfileId = 0, $sContextProfileTitle = '', $aExtras = array(), $aActionParams = array(), $iProfileId = false)
  1173. {
  1174. if (!$iProfileId)
  1175. $iProfileId = bx_get_logged_profile_id();
  1176. $oDb = BxDolDb::getInstance();
  1177. $sSql = $oDb->prepare("INSERT INTO `sys_audit`(profile_id, content_id, content_title, content_module, context_profile_id, context_profile_title, action_lang_key, action_lang_key_params, content_info_object, extras) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
  1178. , $iProfileId, $iContentId, $sContentTitle, $sContentModule, $iContextProfileId, $sContextProfileTitle, $sAction, (count($aActionParams) > 0 ? serialize($aActionParams) : '') ,$sContentInfoObject, (count($aExtras) > 0 ? serialize($aExtras) : ''));
  1179. return !$oDb->query($sSql);
  1180. }
  1181. /**
  1182. * Raise an alert
  1183. * @param string $sUnit - system type
  1184. * @param string $sAction - system action
  1185. * @param int $iObjectId - object id
  1186. * @param int $iSender - sender (action's author) profile id, if it is false - then currectly logged in profile id is used
  1187. * @param array $aExtras - extra parameters
  1188. */
  1189. function bx_alert($sUnit, $sAction, $iObjectId, $iSender = false, $aExtras = array())
  1190. {
  1191. $o = new BxDolAlerts($sUnit, $sAction, $iObjectId, $iSender, $aExtras);
  1192. $o->alert();
  1193. }
  1194. /**
  1195. * Perform serice call
  1196. * @param $mixed module name or module id
  1197. * @param $sMethod service method name in format 'method_name', corresponding class metod is serviceMethodName
  1198. * @param $aParams params to pass to service method
  1199. * @param $sClass class to search for service method, by default it is main module class
  1200. * @return service call result
  1201. */
  1202. function bx_srv($mixed, $sMethod, $aParams = array(), $sClass = 'Module', $bIgnoreCache = false)
  1203. {
  1204. return BxDolService::call($mixed, $sMethod, $aParams, $sClass, $bIgnoreCache);
  1205. }
  1206. function bx_replace_markers($mixed, $aMarkers)
  1207. {
  1208. if (empty($aMarkers))
  1209. return $mixed;
  1210. if (is_array($mixed)) {
  1211. foreach ($mixed as $sKey => $sValue)
  1212. $mixed[$sKey] = bx_replace_markers ($sValue, $aMarkers);
  1213. } else {
  1214. foreach ($aMarkers as $sKey => $sValue)
  1215. $mixed = str_replace('{' . $sKey . '}', $sValue, $mixed);
  1216. }
  1217. return $mixed;
  1218. }
  1219. function bx_site_hash($sSalt = '', $isSkipVersion = false)
  1220. {
  1221. return md5($sSalt . ($isSkipVersion ? '' : bx_get_ver() . getParam('sys_revision')) . BX_DOL_SECRET . BX_DOL_URL_ROOT);
  1222. }
  1223. /**
  1224. * Transform string to method name string, for example it changes 'some_method' string to 'SomeMethod' string
  1225. * @param $s string where words are separated with underscore
  1226. * @param $aWordsDelimiter word delimeters
  1227. * @return string where every word begins with capital letter
  1228. */
  1229. function bx_gen_method_name ($s, $aWordsDelimiter = array('_'))
  1230. {
  1231. return str_replace(' ', '', ucwords(str_replace($aWordsDelimiter, ' ', $s)));
  1232. }
  1233. /**
  1234. * Trigger user error
  1235. * @param $sMsg message to display
  1236. * @param $iNumLevelsBack add additional debug backtracing N levels back
  1237. */
  1238. function bx_trigger_error ($sMsg, $iNumLevelsBack = 0)
  1239. {
  1240. $a = debug_backtrace();
  1241. $sMsgAdd = "<br />\n related code in <b>{$a[$iNumLevelsBack]['file']}</b> on line <b>{$a[$iNumLevelsBack]['line']}</b> <br />\n";
  1242. trigger_error ($sMsg . $sMsgAdd, E_USER_ERROR);
  1243. }
  1244. /**
  1245. * Get system DB version, for files version @see BX_DOL_VERSION, these versions must match
  1246. */
  1247. function bx_get_ver ($bInvalidateCache = false)
  1248. {
  1249. $oDb = BxDolDb::getInstance();
  1250. if ($bInvalidateCache)
  1251. $oDb->cleanMemory('sys_version');
  1252. $sQuery = $oDb->prepare("SELECT `version` FROM `sys_modules` WHERE `name` = 'system'");
  1253. return $oDb->fromMemory('sys_version', 'getOne', $sQuery);
  1254. }
  1255. /**
  1256. * Check if site maintetance mode is enabled.
  1257. * Maintetance mode is enabled when '.bx_maintenance' file exists in the script root folder,
  1258. * please note that this is hidden file and some file managers don't show it.
  1259. * @param $bShowHttpError show 503 HTTP error if site is in mainenance mode
  1260. * @return true if site is in maintenance mode, or false otherwise
  1261. */
  1262. function bx_check_maintenance_mode ($bShowHttpError = false)
  1263. {
  1264. $bMaintetance = file_exists(BX_DIRECTORY_PATH_ROOT . BX_MAINTENANCE_FILE) && !defined('BX_DOL_UPGRADING');
  1265. if ($bMaintetance && $bShowHttpError)
  1266. bx_show_service_unavailable_error_and_exit ('Site is temporarily unavailable due to scheduled maintenance, please try again in a minute.', 600);
  1267. return $bMaintetance;
  1268. }
  1269. /**
  1270. * Check for minimal requirements.
  1271. * if BX_DISABLE_REQUIREMENTS_CHECK is defined then this requirements checking is skipped.
  1272. * @param $bShowHttpError show 503 HTTP error if site doesn't meet minimal requirements
  1273. * @return false if requirements are met, or array of errors of requirements aren't met
  1274. */
  1275. function bx_check_minimal_requirements ($bShowHttpError = false)
  1276. {
  1277. if (defined('BX_DISABLE_REQUIREMENTS_CHECK'))
  1278. return false;
  1279. $aErrors = array();
  1280. $aErrors[] = (ini_get('register_globals') == 0) ? '' : '<b>register_globals</b> is on (you need to disable it, or your site will be unsafe)';
  1281. $aErrors[] = (ini_get('safe_mode') == 0) ? '' : '<b>safe_mode</b> is on (you need to disable it)';
  1282. $aErrors[] = (version_compare(PHP_VERSION, '5.3.0', '<')) ? 'PHP version is too old (please update to <b>PHP 5.3.0</b> at least)' : '';
  1283. $aErrors[] = (!extension_loaded( 'mbstring')) ? '<b>mbstring</b> extension not installed (the script cannot work without it)' : '';
  1284. $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)';
  1285. $aErrors = array_diff($aErrors, array('')); // delete empty
  1286. $bFailedMinimalRequirements = !empty($aErrors);
  1287. if ($bFailedMinimalRequirements && $bShowHttpError) {
  1288. $sErrors = implode(" <br /> ", $aErrors);
  1289. bx_show_service_unavailable_error_and_exit($sErrors);
  1290. }
  1291. return $bFailedMinimalRequirements ? $aErrors : false;
  1292. }
  1293. /**
  1294. * Check if redirect to the correct hostname is required, for example redirect from site.com to www.site.com
  1295. * @param $bProcessRedirect process redirect and exit if needed
  1296. */
  1297. function bx_check_redirect_to_correct_hostname ($bProcessRedirect = false)
  1298. {
  1299. $aUrl = parse_url(BX_DOL_URL_ROOT);
  1300. $iPortDefault = 'https' == $aUrl['scheme'] ? '443' : '80';
  1301. $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));
  1302. if ($bRedirectRequired && $bProcessRedirect) {
  1303. $sPort = empty($aUrl['port']) || 80 == $aUrl['port'] || 443 == $aUrl['port'] ? '' : ':' . $aUrl['port'];
  1304. header("Location:{$aUrl['scheme']}://{$aUrl['host']}{$sPort}{$_SERVER['REQUEST_URI']}", true, 301);
  1305. exit;
  1306. }
  1307. return $bRedirectRequired;
  1308. }
  1309. /**
  1310. * Check if redirect to remove install folder.
  1311. * If BX_SKIP_INSTALL_CHECK is defined then this redirect checking is skipped.
  1312. * @param $bProcessRedirect process redirect and exit if needed
  1313. */
  1314. function bx_check_redirect_to_remove_install_folder ($bProcessRedirect = false)
  1315. {
  1316. $bRemoveInstallFolder = !defined ('BX_SKIP_INSTALL_CHECK') && file_exists(BX_DIRECTORY_PATH_ROOT . 'install');
  1317. if ($bRemoveInstallFolder && $bProcessRedirect) {
  1318. header('Location:' . BX_DOL_URL_ROOT . 'install/index.php?action=remove_install');
  1319. exit;
  1320. }
  1321. return $bRemoveInstallFolder;
  1322. }
  1323. /**
  1324. * Show HTTP 503 service unavailable error and exit
  1325. */
  1326. function bx_show_service_unavailable_error_and_exit ($sMsg = false, $iRetryAfter = 86400)
  1327. {
  1328. header('HTTP/1.0 503 Service Unavailable', true, 503);
  1329. header('Retry-After: 600');
  1330. echo $sMsg ? $sMsg : 'Service temporarily unavailable';
  1331. exit;
  1332. }
  1333. /**
  1334. * The function is sumilar to php readfile, but it send all required headers and can send file by chunks and suports file seek
  1335. * @param $sPath path to file to output to the browser
  1336. * @param $sFilename filename without path, ig file is saved from browser, then this name is used, not used(empty) by default
  1337. * @param $sMimeType file mime type, by default 'application/octet-stream'
  1338. * @param $iCacheAge file cache age, by default 0
  1339. * @param $sCachePrivacy cache privacy 'public' (default value) or 'private'
  1340. * @return true on success or false on error
  1341. */
  1342. function bx_smart_readfile($sPath, $sFilename = '', $sMimeType = 'application/octet-stream', $iCacheAge = 0, $sCachePrivacy = 'public')
  1343. {
  1344. if (!file_exists($sPath))
  1345. return false;
  1346. $fp = @fopen($sPath, 'rb');
  1347. $size = filesize($sPath);
  1348. $length = $size;
  1349. $start = 0;
  1350. $end = $size - 1;
  1351. header('Content-type: ' . $sMimeType);
  1352. header('Cache-Control: ' . $sCachePrivacy . ', must-revalidate, max-age=' . $iCacheAge);
  1353. header("Accept-Ranges: 0-$length");
  1354. if ($sFilename)
  1355. header('Content-Disposition: inline; filename="' . $sFilename . '"');
  1356. if (isset($_SERVER['HTTP_RANGE'])) {
  1357. $c_start = $start;
  1358. $c_end = $end;
  1359. list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
  1360. if (strpos($range, ',') !== false) {
  1361. header('HTTP/1.1 416 Requested Range Not Satisfiable');
  1362. header("Content-Range: bytes $start-$end/$size");
  1363. return false;
  1364. }
  1365. if ($range == '-') {
  1366. $c_start = $size - substr($range, 1);
  1367. }else{
  1368. $range = explode('-', $range);
  1369. $c_start = $range[0];
  1370. $c_end = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $size;
  1371. }
  1372. $c_end = ($c_end > $end) ? $end : $c_end;
  1373. if ($c_start > $c_end || $c_start > $size - 1 || $c_end >= $size) {
  1374. header('HTTP/1.1 416 Requested Range Not Satisfiable');
  1375. header("Content-Range: bytes $start-$end/$size");
  1376. return false;
  1377. }
  1378. $start = $c_start;
  1379. $end = $c_end;
  1380. $length = $end - $start + 1;
  1381. fseek($fp, $start);
  1382. header('HTTP/1.1 206 Partial Content');
  1383. }
  1384. header("Content-Range: bytes $start-$end/$size");
  1385. header("Content-Length: ".$length);
  1386. $buffer = 1024 * 8;
  1387. while(!feof($fp) && ($p = ftell($fp)) <= $end) {
  1388. if ($p + $buffer > $end) {
  1389. $buffer = $end - $p + 1;
  1390. }
  1391. set_time_limit(0);
  1392. echo fread($fp, $buffer);
  1393. flush();
  1394. }
  1395. fclose($fp);
  1396. return true;
  1397. }
  1398. /**
  1399. * Wrap in A tag links in TEXT string
  1400. * @param $text - text string without tags
  1401. * @param $sAttrs - attributes string to add to the added A tag
  1402. * @param $bHtmlSpecialChars - apply htmlspecialchars before processing
  1403. * @return string where all links are wrapped in A tag
  1404. */
  1405. function bx_linkify($text, $sAttrs = '', $bHtmlSpecialChars = false)
  1406. {
  1407. if ($bHtmlSpecialChars)
  1408. $text = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8');
  1409. $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_!~*'().;?:\@&=+$,%#-]+)*/?)@";
  1410. preg_match_all($re, $text, $matches, PREG_OFFSET_CAPTURE);
  1411. $matches = $matches[0];
  1412. if ($i = count($matches))
  1413. $bAddNofollow = getParam('sys_add_nofollow') == 'on';
  1414. while ($i--)
  1415. {
  1416. $sAttrsLocal = $sAttrs;
  1417. $url = $matches[$i][0];
  1418. if (!preg_match('@^https?://@', $url))
  1419. $url = 'http://'.$url;
  1420. if (strncmp(BX_DOL_URL_ROOT, $url, strlen(BX_DOL_URL_ROOT)) !== 0) {
  1421. $sAttrsLocal .= ' target="_blank" ';
  1422. if ($bAddNofollow)
  1423. $sAttrsLocal .= ' rel="nofollow" ';
  1424. }
  1425. $text = substr_replace($text, '<a ' . $sAttrsLocal . ' href="'.$url.'">'.$matches[$i][0].'</a>', $matches[$i][1], strlen($matches[$i][0]));
  1426. }
  1427. // email pattern
  1428. $mail_pattern = "/([A-z0-9\._-]+\@[A-z0-9_-]+\.)([A-z0-9\_\-\.]{1,}[A-z])/";
  1429. $text = preg_replace($mail_pattern, '<a href="mailto:$1$2">$1$2</a>', $text);
  1430. return $text;
  1431. }
  1432. /**
  1433. * Wrap in A tag links in HTML string, which aren't wrapped in A tag yet
  1434. * @param $sHtmlOrig - HTML string
  1435. * @param $sAttrs - attributes string to add to the added A tag
  1436. * @return modified HTML string, in case of errror original string is returned
  1437. */
  1438. function bx_linkify_html($sHtmlOrig, $sAttrs = '')
  1439. {
  1440. if (!trim($sHtmlOrig))
  1441. return $sHtmlOrig;
  1442. $sId = 'bx-linkify-' . md5(microtime());
  1443. $dom = new DOMDocument();
  1444. @$dom->loadHTML('<?xml encoding="UTF-8"><div id="' . $sId . '">' . $sHtmlOrig . '</div>');
  1445. $xpath = new DOMXpath($dom);
  1446. foreach ($xpath->query('//text()') as $text) {
  1447. if (!empty($text->parentNode) && !empty($text->parentNode->tagName) && 'a' == $text->parentNode->tagName)
  1448. continue;
  1449. $frag = $dom->createDocumentFragment();
  1450. @$frag->appendXML(bx_linkify($text->nodeValue, $sAttrs, true));
  1451. $text->parentNode->replaceChild($frag, $text);
  1452. }
  1453. if (version_compare(PHP_VERSION, '5.3.6') >= 0)
  1454. $s = $dom->saveHTML($dom->getElementById($sId));
  1455. else
  1456. $s = $dom->saveXML($dom->getElementById($sId), LIBXML_NOEMPTYTAG);
  1457. if (false === $s) // in case of error return original string
  1458. return $sHtmlOrig;
  1459. if (false !== ($iPos = mb_strpos($s, '<html><body>')) && $iPos < mb_strpos($s, $sId))
  1460. $s = mb_substr($s, $iPos + 12, -15); // strip <html><body> tags and everything before them
  1461. return mb_substr($s, 54, -6); // strip added tags
  1462. }
  1463. /**
  1464. * Returns current site protocol http:// or https://
  1465. */
  1466. function bx_proto()
  1467. {
  1468. return 0 === strncmp('https', BX_DOL_URL_ROOT, 5) ? 'https' : 'http';
  1469. }
  1470. /**
  1471. * Checks protocol in the link
  1472. */
  1473. function bx_has_proto($sLink)
  1474. {
  1475. return preg_match('@^https?://@', $sLink);
  1476. }
  1477. function bx_is_empty_array ($a)
  1478. {
  1479. if (!is_array($a))
  1480. return true;
  1481. if (empty($a))
  1482. return true;
  1483. foreach ($a as $k => $v)
  1484. if ($v)
  1485. return false;
  1486. return true;
  1487. }
  1488. function bx_is_full_array ($a)
  1489. {
  1490. if (!is_array($a))
  1491. return false;
  1492. if (empty($a))
  1493. return false;
  1494. foreach ($a as $k => $v)
  1495. if (empty($v))
  1496. return false;
  1497. return true;
  1498. }
  1499. function bx_is_url_in_content ($sContent)
  1500. {
  1501. $a = array(
  1502. 'http://',
  1503. 'https://',
  1504. 'https/',
  1505. 'http/',
  1506. 'www.',
  1507. '.com'
  1508. );
  1509. foreach ($a as $s)
  1510. if (false !== strpos($sContent, $s))
  1511. return true;
  1512. return false;
  1513. }
  1514. function bx_is_dynamic_request ()
  1515. {
  1516. return bx_get('dynamic') || (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && 'XMLHttpRequest' == $_SERVER['HTTP_X_REQUESTED_WITH']);
  1517. }
  1518. /** @} */