utils.inc.php 52 KB

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