utils.inc.php 51 KB

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