utils.inc.php 53 KB

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