utils.inc.php 64 KB

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