utils.inc.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032
  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 DolphinCore Dolphin Core
  7. * @{
  8. */
  9. define('BX_DATA_TEXT', 1); ///< regular text data type
  10. define('BX_DATA_TEXT_MULTILINE', 2); ///< regular multiline text data type
  11. define('BX_DATA_INT', 3); ///< integer data type
  12. define('BX_DATA_FLOAT', 4); ///< float data type
  13. define('BX_DATA_CHECKBOX', 5); ///< checkbox data type, 'on' or empty value
  14. define('BX_DATA_HTML', 6); ///< HTML data type
  15. define('BX_DATA_DATE', 7); ///< date data type stored as yyyy-mm-dd
  16. define('BX_DATA_DATE_TS', 8); ///< date data type stored as unixtimestamp
  17. define('BX_DATA_DATETIME_TS', 9); ///< date/time data type stored as unixtimestamp
  18. define('BX_SLASHES_AUTO', 0);
  19. define('BX_SLASHES_ADD', 1);
  20. define('BX_SLASHES_STRIP', 2);
  21. define('BX_SLASHES_NO_ACTION', 3);
  22. 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
  23. 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
  24. 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
  25. define('BX_EMAIL_SYSTEM', 0); ///< system email without unsubscribe link, like forgot password or email verification
  26. define('BX_EMAIL_NOTIFY', 1); ///< notification message, with unsubscribe link
  27. define('BX_EMAIL_MASS', 2); ///< mass email, one mesage send to manu users, with unsubscribe link
  28. /**
  29. * The following two functions are needed to convert title to uri and back.
  30. * It usefull when titles are used in URLs, like in Categories and Tags.
  31. */
  32. function title2uri($sValue) {
  33. return str_replace(
  34. array('&', '/', '\\', '"', '+'),
  35. array('[and]', '[slash]', '[backslash]', '[quote]', '[plus]'),
  36. $sValue
  37. );
  38. }
  39. function uri2title($sValue) {
  40. return str_replace(
  41. array('[and]', '[slash]', '[backslash]', '[quote]', '[plus]'),
  42. array('&', '/', '\\', '"', '+'),
  43. $sValue
  44. );
  45. }
  46. /*
  47. * functions for limiting maximal text length
  48. */
  49. function strmaxtextlen($sInput, $iMaxLen = 60, $sEllipsisSign = '&#8230;') {
  50. $sTail = '';
  51. $s = trim(strip_tags($sInput));
  52. if (mb_strlen($s) > $iMaxLen) {
  53. $s = mb_substr($s, 0, $iMaxLen);
  54. $sTail = $sEllipsisSign;
  55. }
  56. return htmlspecialchars_adv($s) . $sTail;
  57. }
  58. function html2txt($content, $tags = "") {
  59. while($content != strip_tags($content, $tags)) {
  60. $content = strip_tags($content, $tags);
  61. }
  62. return $content;
  63. }
  64. function html_encode($text) {
  65. $searcharray = array(
  66. "'([-_\w\d.]+@[-_\w\d.]+)'",
  67. "'((?:(?!://).{3}|^.{0,2}))(www\.[-\d\w\.\/]+)'",
  68. "'(http[s]?:\/\/[-_~\w\d\.\/]+)'");
  69. $replacearray = array(
  70. "<a href=\"mailto:\\1\">\\1</a>",
  71. "\\1http://\\2",
  72. "<a href=\"\\1\" target=_blank>\\1</a>");
  73. return preg_replace($searcharray, $replacearray, stripslashes($text));
  74. }
  75. /**
  76. * Functions to process user input.
  77. * DON'T use to process data before passing to SQL query - use db prepare instead @see BxDolDb::prepare.
  78. * It is ok to use bx_process_input and then db prepare.
  79. * @param $mixedData data to process
  80. * @param $iDataType how to handle data, possible valies:
  81. * BX_DATA_INT - integer value
  82. * BX_DATA_FLOAT - float values
  83. * BX_DATA_CHECKBOX - 'on' or empty string
  84. * BX_DATA_TEXT - text data, single line (default)
  85. * BX_DATA_TEXT_MULTILINE - text data, multiple lines
  86. * BX_DATA_HTML - HTML data
  87. * BX_DATA_DATE - date data type stored as yyyy-mm-dd
  88. * BX_DATA_DATE_TS' - date data type stored as unixtimestamp
  89. * BX_DATA_DATETIME_TS - date/time data type stored as unixtimestamp
  90. * @param $mixedParams optional parameters to pass for validation
  91. * @return the filtered data, or FALSE if the filter fails.
  92. */
  93. function bx_process_input ($mixedData, $iDataType = BX_DATA_TEXT, $mixedParams = false, $isCheckMagicQuotes = true) {
  94. if (is_array($mixedData)) {
  95. foreach ($mixedData as $k => $v)
  96. $mixedData[$k] = bx_process_input($v, $iDataType, $mixedParams);
  97. return $mixedData;
  98. }
  99. if (get_magic_quotes_gpc() && $isCheckMagicQuotes)
  100. $mixedData = stripslashes($mixedData);
  101. switch ($iDataType) {
  102. case BX_DATA_INT:
  103. return filter_var(trim($mixedData), FILTER_VALIDATE_INT);
  104. case BX_DATA_FLOAT:
  105. return filter_var(trim($mixedData), FILTER_VALIDATE_FLOAT);
  106. case BX_DATA_CHECKBOX:
  107. return 'on' == trim($mixedData) ? 'on' : '';
  108. case BX_DATA_DATE:
  109. // maybe consider using strtotime
  110. $mixedData = trim($mixedData);
  111. if (!preg_match('/^\d{4}-\d{1,2}-\d{1,2}$/', $mixedData))
  112. return false;
  113. list($iYear, $iMonth, $iDay) = explode('-', $mixedData); // 1985-10-28
  114. $iDay = intval($iDay);
  115. $iMonth = intval($iMonth);
  116. $iYear = intval($iYear);
  117. return sprintf("%04d-%02d-%02d", $iYear, $iMonth, $iDay);
  118. case BX_DATA_DATE_TS:
  119. $mixedData = trim($mixedData);
  120. if (!preg_match('/^\d{4}-\d{1,2}-\d{1,2}$/', $mixedData))
  121. return false;
  122. list($iYear, $iMonth, $iDay) = explode('-', $mixedData);
  123. $iDay = intval($iDay);
  124. $iMonth = intval($iMonth);
  125. $iYear = intval($iYear);
  126. $iRet = mktime (0, 0, 0, $iMonth, $iDay, $iYear);
  127. return $iRet > 0 ? $iRet : false;
  128. case BX_DATA_DATETIME_TS:
  129. if (!preg_match('#(\d+)\-(\d+)\-(\d+)[\sT]{1}(\d+):(\d+):(\d+)#', $mixedData, $m) && !preg_match('#(\d+)\-(\d+)\-(\d+)[\sT]{1}(\d+):(\d+)#', $mixedData, $m))
  130. return bx_process_input ($mixedData, BX_DATA_DATE_TS, $mixedParams, $isCheckMagicQuotes);
  131. $iDay = $m[3];
  132. $iMonth = $m[2];
  133. $iYear = $m[1];
  134. $iH = $m[4];
  135. $iM = $m[5];
  136. $iS = isset($m[6]) ? $m[6] : 0;
  137. $iRet = mktime ($iH, $iM, $iS, $iMonth, $iDay, $iYear);
  138. return $iRet > 0 ? $iRet : false;
  139. case BX_DATA_HTML:
  140. return clear_xss($mixedData);
  141. case BX_DATA_TEXT_MULTILINE:
  142. return nl2br(htmlspecialchars_adv($mixedData));
  143. case BX_DATA_TEXT:
  144. default:
  145. return $mixedData;
  146. }
  147. }
  148. /*
  149. * Functions to process user output.
  150. * Always use this function before output data which was entered by user before.
  151. * @param $mixedData string to process
  152. * @param $iDataType how to handle data, possible valies the same as in bx_process_input function, see bx_process_input.
  153. * @param $mixedParams optional parameters to pass for validation
  154. * @return the filtered data, or FALSE if the filter fails.
  155. */
  156. function bx_process_output ($mixedData, $iDataType = BX_DATA_TEXT, $mixedParams = false) {
  157. if (is_array($mixedData)) {
  158. foreach ($mixedData as $k => $v)
  159. $mixedData[$k] = bx_process_output($v, $iDataType, $mixedParams);
  160. return $mixedData;
  161. }
  162. switch ($iDataType) {
  163. case BX_DATA_INT:
  164. return filter_var($mixedData, FILTER_VALIDATE_INT);
  165. case BX_DATA_FLOAT:
  166. return filter_var($mixedData, FILTER_VALIDATE_FLOAT);
  167. case BX_DATA_CHECKBOX:
  168. return 'on' == trim($mixedData) ? 'on' : '';
  169. case BX_DATA_DATE:
  170. return $mixedData;
  171. case BX_DATA_DATE_TS:
  172. return empty($mixedData) ? '' : date("Y-m-d", $mixedData);
  173. case BX_DATA_DATETIME_TS:
  174. return empty($mixedData) ? '' : date("Y-m-d H:i", $mixedData);
  175. case BX_DATA_HTML:
  176. return $mixedData;
  177. case BX_DATA_TEXT_MULTILINE:
  178. return $mixedData;
  179. case BX_DATA_TEXT:
  180. default:
  181. return htmlspecialchars_adv($mixedData);
  182. }
  183. }
  184. /*
  185. * This function apply bx_process_input and then bx_process_output.
  186. * Use this function to output data immediately after receiving, without saving to database.
  187. * Patams are the same as bx_process_input function - @see bx_process_input
  188. */
  189. function bx_process_pass ($mixedData, $iDataType = BX_DATA_TEXT, $mixedParams = false, $isCheckMagicQuotes = true) {
  190. return bx_process_output(bx_process_input ($mixedData, $iDataType, $mixedParams, $isCheckMagicQuotes), $iDataType, $mixedParams);
  191. }
  192. /**
  193. * DEPRECATED
  194. * use bx_process_input + bx_process_output instead
  195. * --------
  196. * function for processing pass data
  197. *
  198. * This function cleans the GET/POST/COOKIE data if magic_quotes_gpc() is on
  199. * for data which should be outputed immediately after submit
  200. */
  201. /*
  202. function process_pass_data( $text, $strip_tags = 0 ) {
  203. if ( $strip_tags )
  204. $text = strip_tags($text);
  205. if ( !get_magic_quotes_gpc() )
  206. return $text;
  207. else
  208. return stripslashes($text);
  209. }
  210. */
  211. /*
  212. * function for output data from database into html
  213. */
  214. function htmlspecialchars_adv( $string ) {
  215. return htmlspecialchars($string, ENT_COMPAT, 'UTF-8');
  216. }
  217. /**
  218. * Send mail to user by parsing email template
  219. */
  220. function sendMailTemplate($sTemplateName, $iAccountId = 0, $iProfileId = 0, $aReplaceVars = array(), $iEmailType = BX_EMAIL_NOTIFY) {
  221. bx_import('BxDolAccount');
  222. $oAccount = BxDolAccount::getInstance($iAccountId);
  223. bx_import('BxDolProfile');
  224. $oProfile = BxDolProfile::getInstance($iProfileId);
  225. bx_import('BxDolEmailTemplates');
  226. $oEmailTemplates = BxDolEmailTemplates::getInstance();
  227. if (!$oAccount || !$oProfile || !$oEmailTemplates)
  228. return false;
  229. $aTemplate = $oEmailTemplates->parseTemplate($sTemplateName, $aReplaceVars, $iAccountId, $iProfileId);
  230. if (!$aTemplate)
  231. return false;
  232. return sendMail($oAccount->getEmail(), $aTemplate['Subject'], $aTemplate['Body'], 0, array(), $iEmailType);
  233. }
  234. /**
  235. * Send email function
  236. *
  237. * @param $sRecipientEmail - Email where email should be send
  238. * @param $sMailSubject - subject of the message
  239. * @param $sMailBody - Body of the message
  240. * @param $iRecipientID - ID of recipient profile
  241. * @param $aPlus - Array of additional information
  242. * @param $iEmailType - email message type: BX_EMAIL_SYSTEM, BX_EMAIL_NOTIFY or BX_EMAIL_MASS
  243. * @return true if message was send or false otherwise
  244. */
  245. function sendMail($sRecipientEmail, $sMailSubject, $sMailBody, $iRecipientID = 0, $aPlus = array(), $iEmailType = BX_EMAIL_NOTIFY, $sEmailFlag = 'html', $isDisableAlert = false) {
  246. // make sure that recipient's email is valid and message isn't empty
  247. if (!$sMailBody || !$sRecipientEmail || preg_match('/\(2\)$/', $sRecipientEmail))
  248. return false;
  249. // get recipient account
  250. bx_import('BxDolAccount');
  251. $oAccount = BxDolAccount::getInstance($sRecipientEmail);
  252. $aAccountInfo = $oAccount ? $oAccount->getInfo() : false;
  253. // don't send bulk emails if user didn't subscribed to site news or email is unconfirmed
  254. if ($aAccountInfo && BX_EMAIL_MASS == $iEmailType && (!$aAccountInfo['email_confirmed'] || !$aAccountInfo['receive_news']))
  255. return false;
  256. // don't send email notifications if user didn't subscribed to notifications or email is unconfirmed
  257. if ($aAccountInfo && BX_EMAIL_NOTIFY == $iEmailType && (!$aAccountInfo['email_confirmed'] || !$aAccountInfo['receive_updates']))
  258. return false;
  259. // if profile id is provided - get profile's info
  260. $aRecipientInfo = false;
  261. if ($iRecipientID) {
  262. bx_import('BxDolProfile');
  263. $oProfile = BxDolProfile::getInstance($iRecipientID);
  264. if ($oProfile)
  265. $aRecipientInfo = $oProfile->getInfo();
  266. }
  267. // get site vars
  268. $sEmailNotify = getParam('site_email_notify');
  269. $sSiteTitle = getParam('site_title');
  270. // add unsubscribe link
  271. if (empty($aPlus['unsubscribe'])) {
  272. $aPlus['unsubscribe'] = '';
  273. if ($oAccount && (BX_EMAIL_MASS == $iEmailType || BX_EMAIL_NOTIFY == $iEmailType))
  274. $aPlus['unsubscribe'] = ($sLink = $oAccount->getUnsubscribeLink($iEmailType)) ? '<a href="' . BX_DOL_URL_ROOT . $sLink . '">' . _t('_sys_et_txt_unsubscribe') . '</a>' : '';
  275. }
  276. // parse template
  277. if ($aPlus || $iRecipientID) {
  278. if(!is_array($aPlus))
  279. $aPlus = array();
  280. bx_import('BxDolEmailTemplates');
  281. $oEmailTemplates = BxDolEmailTemplates::getInstance();
  282. $sMailSubject = $oEmailTemplates->parseContent($sMailSubject, $aPlus, $iRecipientID);
  283. $sMailBody = $oEmailTemplates->parseContent($sMailBody, $aPlus, $iRecipientID);
  284. }
  285. // email message headers
  286. $sMailHeader = "From: =?UTF-8?B?" . base64_encode( $sSiteTitle ) . "?= <{$sEmailNotify}>";
  287. $sMailParameters = "-f{$sEmailNotify}";
  288. $sMailSubject = '=?UTF-8?B?' . base64_encode( $sMailSubject ) . '?=';
  289. $sMailHeader = "MIME-Version: 1.0\r\n" . $sMailHeader;
  290. // build data for alert handler
  291. $bResult = null;
  292. $aAlert = array(
  293. 'email' => $sRecipientEmail,
  294. 'subject' => $sMailSubject,
  295. 'body' => $sMailBody,
  296. 'header' => $sMailHeader,
  297. 'params' => $sMailParameters,
  298. 'recipient' => $aRecipientInfo,
  299. 'html' => 'html' == $sEmailFlag ? true : false,
  300. 'override_result' => &$bResult,
  301. );
  302. // system alert
  303. if (!$isDisableAlert) {
  304. bx_alert('system', 'before_send_mail', (isset($aRecipientInfo['ID']) ? $aRecipientInfo['ID'] : 0), '', $aAlert);
  305. if ($bResult !== null)
  306. return $bResult;
  307. unset($aAlert['override_result']);
  308. }
  309. // send mail
  310. if( 'html' == $sEmailFlag) {
  311. $sMailHeader = "Content-type: text/html; charset=UTF-8\r\n" . $sMailHeader;
  312. $iSendingResult = mail( $sRecipientEmail, $sMailSubject, $sMailBody, $sMailHeader, $sMailParameters );
  313. } else {
  314. $sMailHeader = "Content-type: text/plain; charset=UTF-8\r\n" . $sMailHeader;
  315. $sMailBody = html2txt($sMailBody);
  316. $iSendingResult = mail( $sRecipientEmail, $sMailSubject, html2txt($sMailBody), $sMailHeader, $sMailParameters );
  317. }
  318. // system alert
  319. if (!$isDisableAlert)
  320. bx_alert('system', 'send_mail', (isset($aRecipientInfo['ID']) ? $aRecipientInfo['ID'] : 0), '', $aAlert);
  321. return $iSendingResult;
  322. }
  323. /*
  324. * Getting an array with Templates' Names
  325. */
  326. function get_templates_array($bEnabledOnly = true, $bShortInfo = true) {
  327. bx_import('BxDolDb');
  328. $oDb = BxDolDb::getInstance();
  329. $sWhereAddon = $bEnabledOnly ? " AND `enabled`='1'" : "";
  330. if($bShortInfo)
  331. return $oDb->getPairs("SELECT `uri`, `title` FROM `sys_modules` WHERE 1 AND `type`='" . BX_DOL_MODULE_TYPE_TEMPLATE . "'" . $sWhereAddon, "uri", "title");
  332. else
  333. return $oDb->getAllWithKey("SELECT * FROM `sys_modules` WHERE 1 AND `type`='" . BX_DOL_MODULE_TYPE_TEMPLATE . "'" . $sWhereAddon, "uri");
  334. }
  335. function extFileExists( $sFileSrc ) {
  336. return (file_exists( $sFileSrc ) && is_file( $sFileSrc )) ? true : false;
  337. }
  338. function getVisitorIP() {
  339. $ip = "0.0.0.0";
  340. if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  341. $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
  342. } elseif (isset( $_SERVER['HTTP_CLIENT_IP']) && !empty($_SERVER['HTTP_CLIENT_IP'])) {
  343. $ip = explode(".",$_SERVER['HTTP_CLIENT_IP']);
  344. $ip = $ip[3].".".$ip[2].".".$ip[1].".".$ip[0];
  345. } elseif (!isset( $_SERVER['HTTP_X_FORWARDED_FOR']) || empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  346. if (!isset( $_SERVER['HTTP_CLIENT_IP']) && empty($_SERVER['HTTP_CLIENT_IP']) && isset($_SERVER['REMOTE_ADDR']))
  347. $ip = $_SERVER['REMOTE_ADDR'];
  348. }
  349. return $ip;
  350. }
  351. function genFlag( $country ) {
  352. return '<img src="' . genFlagUrl($country) . '" />';
  353. }
  354. function genFlagUrl($country) {
  355. bx_import('BxDolTemplate');
  356. return BxDolTemplate::getInstance()->getIconUrl('sys_fl_' . strtolower($country) . '.gif');
  357. }
  358. // print debug information ( e.g. arrays )
  359. function echoDbg( $what, $desc = '' ) {
  360. if ( $desc )
  361. echo "<b>$desc:</b> ";
  362. echo "<pre>";
  363. print_r( $what );
  364. echo "</pre>\n";
  365. }
  366. function echoDbgLog($mWhat, $sDesc = '', $sFileName = 'debug.log') {
  367. $sCont =
  368. '--- ' . date('r') . ' (' . BX_DOL_START_TIME . ") ---\n" .
  369. $sDesc . "\n" .
  370. print_r($mWhat, true) . "\n\n\n";
  371. $rFile = fopen(BxDolConfig::getInstance()->get('path_dynamic', 'tmp') . $sFileName, 'a');
  372. fwrite($rFile, $sCont);
  373. fclose($rFile);
  374. }
  375. function clear_xss($val) {
  376. if ($GLOBALS['logged']['admin'])
  377. return $val;
  378. // HTML Purifier plugin
  379. global $oHtmlPurifier;
  380. require_once( BX_DIRECTORY_PATH_PLUGINS . 'htmlpurifier/HTMLPurifier.standalone.php' );
  381. if (!isset($oHtmlPurifier)) {
  382. HTMLPurifier_Bootstrap::registerAutoload();
  383. $oConfig = HTMLPurifier_Config::createDefault();
  384. $oConfig->set('Cache.SerializerPath', rtrim(BX_DIRECTORY_PATH_CACHE, '/'));
  385. $oConfig->set('HTML.SafeObject', 'true');
  386. $oConfig->set('Output.FlashCompat', 'true');
  387. $oConfig->set('HTML.FlashAllowFullScreen', 'true');
  388. if (getParam('sys_add_nofollow')) {
  389. $sHost = parse_url(BX_DOL_URL_ROOT, PHP_URL_HOST);
  390. $oConfig->set('URI.Host', $sHost);
  391. $oConfig->set('HTML.Nofollow', 'true');
  392. }
  393. $oConfig->set('Filter.Custom', array (new HTMLPurifier_Filter_YouTube(), new HTMLPurifier_Filter_YoutubeIframe()));
  394. $oDef = $oConfig->getHTMLDefinition(true);
  395. $oDef->addAttribute('a', 'target', 'Enum#_blank,_self,_target,_top');
  396. $oHtmlPurifier = new HTMLPurifier($oConfig);
  397. }
  398. return $oHtmlPurifier->purify($val);
  399. }
  400. //--------------------------------------- friendly permalinks --------------------------------------//
  401. //------------------------------------------- main functions ---------------------------------------//
  402. function uriGenerate ($s, $sTable, $sField, $sEmpty = '-') {
  403. $s = uriFilter($s, $sEmpty);
  404. if(uriCheckUniq($s, $sTable, $sField))
  405. return $s;
  406. // cut off redundant part
  407. if(get_mb_len($s) > 240)
  408. $s = get_mb_substr($s, 0, 240);
  409. // try to add date
  410. $s .= '-' . date('Y-m-d');
  411. if(uriCheckUniq($s, $sTable, $sField))
  412. return $s;
  413. // try to add number
  414. for($i = 0 ; $i < 999 ; ++$i)
  415. if(uriCheckUniq($s . '-' . $i, $sTable, $sField))
  416. return ($s . '-' . $i);
  417. return rand(0, 999999999);
  418. }
  419. function uriFilter ($s, $sEmpty = '-') {
  420. bx_import('BxTemplConfig');
  421. if (BxTemplConfig::getInstance()->bAllowUnicodeInPreg)
  422. $s = get_mb_replace ('/[^\pL^\pN]+/u', '-', $s); // unicode characters
  423. else
  424. $s = get_mb_replace ('/([^\d^\w]+)/u', '-', $s); // latin characters only
  425. $s = get_mb_replace ('/([-^]+)/', '-', $s);
  426. $s = get_mb_replace ('/([-]+)$/', '', $s); // remove trailing dash
  427. if (!$s) $s = $sEmpty;
  428. return $s;
  429. }
  430. function uriCheckUniq ($s, $sTable, $sField) {
  431. bx_import('BxDolDb');
  432. $oDb = BxDolDb::getInstance();
  433. $sSql = $oDb->prepare("SELECT 1 FROM `$sTable` WHERE `$sField`=? LIMIT 1", $s);
  434. return !$oDb->query($sSql);
  435. }
  436. function get_mb_replace ($sPattern, $sReplace, $s) {
  437. return preg_replace ($sPattern, $sReplace, $s);
  438. }
  439. function get_mb_len ($s) {
  440. return (function_exists('mb_strlen')) ? mb_strlen($s) : strlen($s);
  441. }
  442. function get_mb_substr ($s, $iStart, $iLen) {
  443. return (function_exists('mb_substr')) ? mb_substr ($s, $iStart, $iLen) : substr ($s, $iStart, $iLen);
  444. }
  445. function bx_mb_substr_replace($s, $sReplace, $iPosStart, $iLength) {
  446. return mb_substr($s, 0, $iPosStart) . $sReplace . mb_substr($s, $iPosStart + $iLength);
  447. }
  448. function bx_mb_strpos ($s, $sReplacement, $iStart = 0) {
  449. return mb_strpos($s, $sReplacement, $iStart);
  450. }
  451. /**
  452. * Import class file, it automatically detects class path by its prefix or module array/name
  453. *
  454. * @param $sClassName - full class name or class postfix(withoit prefix) in the case of module class
  455. * @param $mixedModule - module array or module name in the case of module class
  456. */
  457. function bx_import($sClassName, $mixedModule = array()) {
  458. if (class_exists($sClassName))
  459. return;
  460. $aModule = false;
  461. if ($mixedModule) {
  462. if (is_array($mixedModule)) {
  463. $aModule = $mixedModule;
  464. } elseif (is_string($mixedModule)) {
  465. bx_import('BxDolModule');
  466. $o = BxDolModule::getInstance($mixedModule);
  467. $aModule = $o->_aModule;
  468. } elseif (is_bool($mixedModule) && true === $mixedModule) {
  469. $aModule = $GLOBALS['aModule'];
  470. }
  471. }
  472. if ($aModule) {
  473. if (class_exists($aModule['class_prefix'] . $sClassName))
  474. return;
  475. require_once (BX_DIRECTORY_PATH_MODULES . $aModule['path'] . 'classes/' . $aModule['class_prefix'] . $sClassName . '.php');
  476. return;
  477. }
  478. if (0 == strncmp($sClassName, 'BxDol', 5)) {
  479. if (0 == strncmp($sClassName, 'BxDolStudio', 11))
  480. require_once(BX_DOL_DIR_STUDIO_CLASSES . $sClassName . '.php');
  481. else
  482. require_once(BX_DIRECTORY_PATH_CLASSES . $sClassName . '.php');
  483. return;
  484. }
  485. if (0 == strncmp($sClassName, 'BxBase', 6)) {
  486. if (0 == strncmp($sClassName, 'BxBaseMod', 9)) {
  487. $aMatches = array();
  488. if (preg_match('/BxBaseMod([A-Z][a-z]+)/', $sClassName, $aMatches)) {
  489. require_once(BX_DIRECTORY_PATH_MODULES . 'base/' . strtolower($aMatches[1]) . '/classes/' . $sClassName . '.php');
  490. return;
  491. }
  492. } if (0 == strncmp($sClassName, 'BxBaseStudio', 12)) {
  493. require_once(BX_DOL_DIR_STUDIO_BASE . 'scripts/' . $sClassName . '.php');
  494. return;
  495. } else {
  496. require_once(BX_DIRECTORY_PATH_BASE . 'scripts/' . $sClassName . '.php');
  497. return;
  498. }
  499. }
  500. if (0 == strncmp($sClassName, 'BxTempl', 7) && !class_exists($sClassName)) {
  501. if(0 == strncmp($sClassName, 'BxTemplStudio', 13)) {
  502. bx_import('BxDolStudioTemplate');
  503. $sPath = BX_DIRECTORY_PATH_MODULES . BxDolStudioTemplate::getInstance()->getPath() . 'data/template/studio/scripts/' . $sClassName . '.php';
  504. }
  505. else {
  506. bx_import('BxDolTemplate');
  507. $sPath = BX_DIRECTORY_PATH_MODULES . BxDolTemplate::getInstance()->getPath() . 'data/template/system/scripts/' . $sClassName . '.php';
  508. }
  509. if (file_exists($sPath)) {
  510. require_once($sPath);
  511. return;
  512. }
  513. trigger_error ("bx_import fatal error: class (" . $sClassName . ") wasn't found", E_USER_ERROR);
  514. }
  515. }
  516. /**
  517. * Gets an instance of class pathing necessary parameters if it's necessary.
  518. *
  519. * @param string $sClassName class name.
  520. * @param array $aParams an array of parameters to be pathed to the constructor of the class.
  521. * @param array $aModule an array with module description. Is used when the requested class is located in some module.
  522. * @return unknown
  523. */
  524. function bx_instance($sClassName, $aParams = array(), $aModule = array()) {
  525. if(isset($GLOBALS['bxDolClasses'][$sClassName]))
  526. return $GLOBALS['bxDolClasses'][$sClassName];
  527. bx_import((empty($aModule) ? $sClassName : str_replace($aModule['class_prefix'], '', $sClassName)), $aModule);
  528. $oClass = new ReflectionClass($sClassName);
  529. $GLOBALS['bxDolClasses'][$sClassName] = empty($aParams) ? $oClass->newInstance() : $oClass->newInstanceArgs($aParams);
  530. return $GLOBALS['bxDolClasses'][$sClassName];
  531. }
  532. /**
  533. * Escapes string/array ready to pass to js script with filtered symbols like ', " etc
  534. *
  535. * @param $mixedInput - string/array which should be filtered
  536. * @param $iQuoteType - string escaping method: BX_ESCAPE_STR_AUTO(default), BX_ESCAPE_STR_APOS or BX_ESCAPE_STR_QUOTE
  537. * @return converted string / array
  538. */
  539. function bx_js_string ($mixedInput, $iQuoteType = BX_ESCAPE_STR_AUTO) {
  540. $aUnits = array(
  541. "\n" => "\\n",
  542. "\r" => "",
  543. );
  544. if (BX_ESCAPE_STR_APOS == $iQuoteType) {
  545. $aUnits["'"] = "\\'";
  546. $aUnits['<script'] = "<scr' + 'ipt";
  547. $aUnits['</script>'] = "</scr' + 'ipt>";
  548. } elseif (BX_ESCAPE_STR_QUOTE == $iQuoteType) {
  549. $aUnits['"'] = '\\"';
  550. $aUnits['<script'] = '<scr" + "ipt';
  551. $aUnits['</script>'] = '</scr" + "ipt>';
  552. } else {
  553. $aUnits['"'] = '&quote;';
  554. $aUnits["'"] = '&apos;';
  555. $aUnits["<"] = '&lt;';
  556. $aUnits[">"] = '&gt;';
  557. }
  558. return str_replace(array_keys($aUnits), array_values($aUnits), $mixedInput);
  559. }
  560. /**
  561. * Return input string/array ready to pass to html attribute with filtered symbols like ', " etc
  562. *
  563. * @param mixed $mixedInput - string/array which should be filtered
  564. * @return converted string / array
  565. */
  566. function bx_html_attribute ($mixedInput, $iQuoteType = BX_ESCAPE_STR_AUTO) {
  567. $aUnits = array ();
  568. if (BX_ESCAPE_STR_APOS == $iQuoteType)
  569. $aUnits["'"] = "\\'";
  570. elseif (BX_ESCAPE_STR_QUOTE == $iQuoteType)
  571. $aUnits['"'] = '&quot;';
  572. else
  573. $aUnits = array("\"" => "&quot;", "'" => "&apos;");
  574. return str_replace(array_keys($aUnits), array_values($aUnits), $mixedInput);
  575. }
  576. /**
  577. * Escapes string/array ready to pass to php script with filtered symbols like ', " etc
  578. *
  579. * @param mixed $mixedInput - string/array which should be filtered
  580. * @return converted string / array
  581. */
  582. function bx_php_string_apos ($mixedInput) {
  583. return str_replace("'", "\\'", $mixedInput);
  584. }
  585. function bx_php_string_quot ($mixedInput) {
  586. return str_replace('"', '\\"', $mixedInput);
  587. }
  588. /**
  589. * Gets file contents by URL.
  590. *
  591. * @param string $sFileUrl - file URL to be read.
  592. * @param array $aParams - an array of parameters to be pathed with URL.
  593. * @return string the file's contents.
  594. */
  595. function bx_file_get_contents($sFileUrl, $aParams = array(), $bChangeTimeout = false) {
  596. if ($aParams)
  597. $sFileUrl = bx_append_url_params($sFileUrl, $aParams);
  598. $sResult = '';
  599. if(function_exists('curl_init')) {
  600. $rConnect = curl_init();
  601. curl_setopt($rConnect, CURLOPT_URL, $sFileUrl);
  602. curl_setopt($rConnect, CURLOPT_HEADER, 0);
  603. curl_setopt($rConnect, CURLOPT_RETURNTRANSFER, 1);
  604. curl_setopt($rConnect, CURLOPT_FOLLOWLOCATION, 1);
  605. if ($bChangeTimeout) {
  606. curl_setopt($rConnect, CURLOPT_CONNECTTIMEOUT, 3);
  607. curl_setopt($rConnect, CURLOPT_TIMEOUT, 3);
  608. }
  609. $sAllCookies = '';
  610. foreach($_COOKIE as $sKey=>$sValue){
  611. $sAllCookies .= $sKey."=".$sValue.";";
  612. }
  613. curl_setopt($rConnect, CURLOPT_COOKIE, $sAllCookies);
  614. $sResult = curl_exec($rConnect);
  615. curl_close($rConnect);
  616. } else {
  617. $iSaveTimeout = false;
  618. if ($bChangeTimeout) {
  619. $iSaveTimeout = ini_get('default_socket_timeout');
  620. ini_set('default_socket_timeout', 3);
  621. }
  622. $sResult = @file_get_contents($sFileUrl);
  623. if ($bChangeTimeout && false !== $iSaveTimeout) {
  624. ini_set('default_socket_timeout', $iSaveTimeout);
  625. }
  626. }
  627. return $sResult;
  628. }
  629. // calculation ini_get('upload_max_filesize') in bytes as example
  630. function return_bytes($val) {
  631. $val = trim($val);
  632. $last = strtolower($val{strlen($val)-1});
  633. $val = (int)$val;
  634. switch($last) {
  635. // The 'G' modifier is available since PHP 5.1.0
  636. case 'k':
  637. $val *= 1024;
  638. break;
  639. case 'm':
  640. $val *= 1024 * 1024;
  641. break;
  642. case 'g':
  643. $val *= 1024 * 1024 * 1024;
  644. break;
  645. }
  646. return $val;
  647. }
  648. // Generate Random Password
  649. function genRndPwd($iLength = 8, $bSpecialCharacters = true) {
  650. $sPassword = '';
  651. $sChars = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
  652. if($bSpecialCharacters === true)
  653. $sChars .= "!?=/&+,.";
  654. srand((double)microtime()*1000000);
  655. for($i = 0; $i < $iLength; $i++) {
  656. $x = mt_rand(0, strlen($sChars) -1);
  657. $sPassword .= $sChars{$x};
  658. }
  659. return $sPassword;
  660. }
  661. // Generate Random Salt for Password encryption
  662. function genRndSalt() {
  663. return genRndPwd(8, true);
  664. }
  665. // Encrypt User Password
  666. function encryptUserPwd($sPwd, $sSalt) {
  667. return sha1(md5($sPwd) . $sSalt);
  668. }
  669. function bx_get ($sName) {
  670. if (isset($_GET[$sName]))
  671. return $_GET[$sName];
  672. elseif (isset($_POST[$sName]))
  673. return $_POST[$sName];
  674. else
  675. return false;
  676. }
  677. function bx_encode_url_params ($a, $aExcludeKeys = array (), $aOnlyKeys = false) {
  678. $s = '';
  679. foreach ($a as $sKey => $sVal) {
  680. if (in_array($sKey, $aExcludeKeys))
  681. continue;
  682. if (false !== $aOnlyKeys && !in_array($sKey, $aOnlyKeys))
  683. continue;
  684. if (is_array($sVal)) {
  685. foreach ($sVal as $sSubVal) {
  686. $s .= rawurlencode($sKey) . '[]=' . rawurlencode(is_array($sSubVal) ? 'array' : $sSubVal) . '&';
  687. }
  688. } else {
  689. $s .= rawurlencode($sKey) . '=' . rawurlencode($sVal) . '&';
  690. }
  691. }
  692. return $s;
  693. }
  694. function bx_append_url_params ($sUrl, $mixedParams) {
  695. if (!$mixedParams)
  696. return $sUrl;
  697. $sParams = false == strpos($sUrl, '?') ? '?' : '&';
  698. if (is_array($mixedParams)) {
  699. foreach($mixedParams as $sKey => $sValue)
  700. $sParams .= $sKey . '=' . $sValue . '&';
  701. $sParams = substr($sParams, 0, -1);
  702. } else {
  703. $sParams .= $mixedParams;
  704. }
  705. return $sUrl . $sParams;
  706. }
  707. function bx_rrmdir($directory) {
  708. if (substr($directory,-1) == "/")
  709. $directory = substr($directory,0,-1);
  710. if (!file_exists($directory) || !is_dir($directory))
  711. return false;
  712. elseif (!is_readable($directory))
  713. return false;
  714. if (!($directoryHandle = opendir($directory)))
  715. return false;
  716. while ($contents = readdir($directoryHandle)) {
  717. if ($contents != '.' && $contents != '..') {
  718. $path = $directory . "/" . $contents;
  719. if (is_dir($path))
  720. bx_rrmdir($path);
  721. else
  722. unlink($path);
  723. }
  724. }
  725. closedir($directoryHandle);
  726. if (!rmdir($directory))
  727. return false;
  728. return true;
  729. }
  730. function bx_clear_folder ($sPath, $aExts = array ()) {
  731. if (substr($$sPath,-1) == "/")
  732. $sPath = substr($sPath,0,-1);
  733. if (!file_exists($sPath) || !is_dir($sPath))
  734. return false;
  735. elseif (!is_readable($sPath))
  736. return false;
  737. if (!($h = opendir($sPath)))
  738. return false;
  739. while ($sFile = readdir($h)) {
  740. if ('.' == $sFile || '..' == $sFile)
  741. continue;
  742. $sFullPath = $sPath . '/' . $sFile;
  743. if (is_dir($sFullPath))
  744. continue;
  745. if (!$aExts || (($sExt = pathinfo($sFullPath, PATHINFO_EXTENSION)) && in_array($sExt, $aExts)))
  746. @unlink($sFullPath);
  747. }
  748. closedir($h);
  749. return true;
  750. }
  751. function bx_ltrim_str ($sString, $sPrefix, $sReplace = '') {
  752. if ($sReplace && substr($sString, 0, strlen($sReplace)) == $sReplace)
  753. return $sString;
  754. if (substr($sString, 0, strlen($sPrefix)) == $sPrefix)
  755. return $sReplace . substr($sString, strlen($sPrefix));
  756. return $sString;
  757. }
  758. /**
  759. * Convert array to attributes string
  760. *
  761. * Example:
  762. * @code
  763. * $a = array('name' => 'test', 'value' => 5);
  764. * $s = bx_convert_array2attrs($a);
  765. * echo $s; // outputs: name="test" value="5"
  766. * @endcode
  767. *
  768. * @param $a - array of attributes
  769. * @param $sClasses - classes to merge with 'class' attribute
  770. * @param $sStyles - styles to merge with 'style' attribute
  771. * @return string
  772. */
  773. function bx_convert_array2attrs ($a, $sClasses = false, $sStyles = false) {
  774. $sRet = '';
  775. if (!$a || !is_array($a))
  776. $a = array();
  777. if ($sClasses) {
  778. $sClasses = trim($sClasses);
  779. $a['class'] = $sClasses . (!empty($a['class']) ? ' ' . $a['class'] : '');
  780. }
  781. if ($sStyles) {
  782. $sStyles = trim($sStyles);
  783. if (';' != $sStyles[strlen($sStyles)-1])
  784. $sStyles .= ';';
  785. $a['style'] = $sStyles . (!empty($a['style']) ? ' ' . $a['style'] : '');
  786. }
  787. foreach ($a as $sKey => $sValue) {
  788. if(is_null($sValue)) // pass NULL values
  789. continue;
  790. $sValueC = bx_html_attribute($sValue, BX_ESCAPE_STR_QUOTE);
  791. $sRet .= " $sKey=\"$sValueC\"";
  792. }
  793. return $sRet;
  794. }
  795. function bx_unicode_urldecode($s) {
  796. preg_match_all('/%u([[:alnum:]]{4})/', $s, $a);
  797. foreach ($a[1] as $uniord)
  798. {
  799. $dec = hexdec($uniord);
  800. $utf = '';
  801. if ($dec < 128)
  802. {
  803. $utf = chr($dec);
  804. }
  805. else if ($dec < 2048)
  806. {
  807. $utf = chr(192 + (($dec - ($dec % 64)) / 64));
  808. $utf .= chr(128 + ($dec % 64));
  809. }
  810. else
  811. {
  812. $utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
  813. $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
  814. $utf .= chr(128 + ($dec % 64));
  815. }
  816. $s = str_replace('%u'.$uniord, $utf, $s);
  817. }
  818. return urldecode($s);
  819. }
  820. /**
  821. * Raise an alert
  822. * @param string $sType - system type
  823. * @param string $sAction - system action
  824. * @param int $iObjectId - object id
  825. * @param int $iSenderId - sender (action's author) profile id, if it is false - then currectly logged in profile id is used
  826. */
  827. function bx_alert($sUnit, $sAction, $iObjectId, $iSender = false, $aExtras = array()) {
  828. $o = new BxDolAlerts($sUnit, $sAction, $iObjectId, $iSender, $aExtras);
  829. $o->alert();
  830. }
  831. function bx_replace_markers($mixed, $aMarkers) {
  832. if (empty($aMarkers))
  833. return $mixed;
  834. if (is_array($mixed)) {
  835. foreach ($mixed as $sKey => $sValue)
  836. $mixed[$sKey] = bx_replace_markers ($sValue, $aMarkers);
  837. } else {
  838. foreach ($aMarkers as $sKey => $sValue)
  839. $mixed = str_replace('{' . $sKey . '}', $sValue, $mixed);
  840. }
  841. return $mixed;
  842. }
  843. function bx_site_hash($sSalt = '', $isSkipVersion = false) {
  844. return md5($sSalt . ($isSkipVersion ? '' : getParam('sys_version')) . BX_DOL_SECRET . BX_DOL_URL_ROOT);
  845. }
  846. /**
  847. * Transform string to method name string, for example it changes 'some_method' string to 'SomeMethod' string
  848. * @param string where words are separated with underscore
  849. * @return string where every word begins with capital letter
  850. */
  851. function bx_gen_method_name ($s, $sWordsDelimiter = '_') {
  852. return str_replace(' ', '', ucwords(str_replace($sWordsDelimiter, ' ', $s)));
  853. }
  854. /**
  855. * Trigger user error
  856. * @param $sMsg message to display
  857. * @param $iNumLevelsBack add additional debug backtracing N levels back
  858. */
  859. function bx_trigger_error ($sMsg, $iNumLevelsBack = 0) {
  860. $a = debug_backtrace();
  861. $sMsgAdd = "<br />\n related code in <b>{$a[$iNumLevelsBack]['file']}</b> on line <b>{$a[$iNumLevelsBack]['line']}</b> <br />\n";
  862. trigger_error ($sMsg . $sMsgAdd, E_USER_ERROR);
  863. }
  864. /** @} */