You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

rcube_utils.php 40KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258
  1. <?php
  2. /**
  3. +-----------------------------------------------------------------------+
  4. | This file is part of the Roundcube Webmail client |
  5. | Copyright (C) 2008-2012, The Roundcube Dev Team |
  6. | Copyright (C) 2011-2012, Kolab Systems AG |
  7. | |
  8. | Licensed under the GNU General Public License version 3 or |
  9. | any later version with exceptions for skins & plugins. |
  10. | See the README file for a full license statement. |
  11. | |
  12. | PURPOSE: |
  13. | Utility class providing common functions |
  14. +-----------------------------------------------------------------------+
  15. | Author: Thomas Bruederli <roundcube@gmail.com> |
  16. | Author: Aleksander Machniak <alec@alec.pl> |
  17. +-----------------------------------------------------------------------+
  18. */
  19. /**
  20. * Utility class providing common functions
  21. *
  22. * @package Framework
  23. * @subpackage Utils
  24. */
  25. class rcube_utils
  26. {
  27. // define constants for input reading
  28. const INPUT_GET = 0x0101;
  29. const INPUT_POST = 0x0102;
  30. const INPUT_GPC = 0x0103;
  31. /**
  32. * Helper method to set a cookie with the current path and host settings
  33. *
  34. * @param string Cookie name
  35. * @param string Cookie value
  36. * @param string Expiration time
  37. */
  38. public static function setcookie($name, $value, $exp = 0)
  39. {
  40. if (headers_sent()) {
  41. return;
  42. }
  43. $cookie = session_get_cookie_params();
  44. $secure = $cookie['secure'] || self::https_check();
  45. setcookie($name, $value, $exp, $cookie['path'], $cookie['domain'], $secure, true);
  46. }
  47. /**
  48. * E-mail address validation.
  49. *
  50. * @param string $email Email address
  51. * @param boolean $dns_check True to check dns
  52. *
  53. * @return boolean True on success, False if address is invalid
  54. */
  55. public static function check_email($email, $dns_check=true)
  56. {
  57. // Check for invalid characters
  58. if (preg_match('/[\x00-\x1F\x7F-\xFF]/', $email)) {
  59. return false;
  60. }
  61. // Check for length limit specified by RFC 5321 (#1486453)
  62. if (strlen($email) > 254) {
  63. return false;
  64. }
  65. $email_array = explode('@', $email);
  66. // Check that there's one @ symbol
  67. if (count($email_array) < 2) {
  68. return false;
  69. }
  70. $domain_part = array_pop($email_array);
  71. $local_part = implode('@', $email_array);
  72. // from PEAR::Validate
  73. $regexp = '&^(?:
  74. ("\s*(?:[^"\f\n\r\t\v\b\s]+\s*)+")| #1 quoted name
  75. ([-\w!\#\$%\&\'*+~/^`|{}=]+(?:\.[-\w!\#\$%\&\'*+~/^`|{}=]+)*)) #2 OR dot-atom (RFC5322)
  76. $&xi';
  77. if (!preg_match($regexp, $local_part)) {
  78. return false;
  79. }
  80. // Validate domain part
  81. if (preg_match('/^\[((IPv6:[0-9a-f:.]+)|([0-9.]+))\]$/i', $domain_part, $matches)) {
  82. return self::check_ip(preg_replace('/^IPv6:/i', '', $matches[1])); // valid IPv4 or IPv6 address
  83. }
  84. else {
  85. // If not an IP address
  86. $domain_array = explode('.', $domain_part);
  87. // Not enough parts to be a valid domain
  88. if (sizeof($domain_array) < 2) {
  89. return false;
  90. }
  91. foreach ($domain_array as $part) {
  92. if (!preg_match('/^((xn--)?([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]))$/', $part)) {
  93. return false;
  94. }
  95. }
  96. // last domain part
  97. $last_part = array_pop($domain_array);
  98. if (strpos($last_part, 'xn--') !== 0 && preg_match('/[^a-zA-Z]/', $last_part)) {
  99. return false;
  100. }
  101. $rcube = rcube::get_instance();
  102. if (!$dns_check || !$rcube->config->get('email_dns_check')) {
  103. return true;
  104. }
  105. // find MX record(s)
  106. if (!function_exists('getmxrr') || getmxrr($domain_part, $mx_records)) {
  107. return true;
  108. }
  109. // find any DNS record
  110. if (!function_exists('checkdnsrr') || checkdnsrr($domain_part, 'ANY')) {
  111. return true;
  112. }
  113. }
  114. return false;
  115. }
  116. /**
  117. * Validates IPv4 or IPv6 address
  118. *
  119. * @param string $ip IP address in v4 or v6 format
  120. *
  121. * @return bool True if the address is valid
  122. */
  123. public static function check_ip($ip)
  124. {
  125. return filter_var($ip, FILTER_VALIDATE_IP) !== false;
  126. }
  127. /**
  128. * Check whether the HTTP referer matches the current request
  129. *
  130. * @return boolean True if referer is the same host+path, false if not
  131. */
  132. public static function check_referer()
  133. {
  134. $uri = parse_url($_SERVER['REQUEST_URI']);
  135. $referer = parse_url(self::request_header('Referer'));
  136. return $referer['host'] == self::request_header('Host') && $referer['path'] == $uri['path'];
  137. }
  138. /**
  139. * Replacing specials characters to a specific encoding type
  140. *
  141. * @param string Input string
  142. * @param string Encoding type: text|html|xml|js|url
  143. * @param string Replace mode for tags: show|remove|strict
  144. * @param boolean Convert newlines
  145. *
  146. * @return string The quoted string
  147. */
  148. public static function rep_specialchars_output($str, $enctype = '', $mode = '', $newlines = true)
  149. {
  150. static $html_encode_arr = false;
  151. static $js_rep_table = false;
  152. static $xml_rep_table = false;
  153. if (!is_string($str)) {
  154. $str = strval($str);
  155. }
  156. // encode for HTML output
  157. if ($enctype == 'html') {
  158. if (!$html_encode_arr) {
  159. $html_encode_arr = get_html_translation_table(HTML_SPECIALCHARS);
  160. unset($html_encode_arr['?']);
  161. }
  162. $encode_arr = $html_encode_arr;
  163. if ($mode == 'remove') {
  164. $str = strip_tags($str);
  165. }
  166. else if ($mode != 'strict') {
  167. // don't replace quotes and html tags
  168. $ltpos = strpos($str, '<');
  169. if ($ltpos !== false && strpos($str, '>', $ltpos) !== false) {
  170. unset($encode_arr['"']);
  171. unset($encode_arr['<']);
  172. unset($encode_arr['>']);
  173. unset($encode_arr['&']);
  174. }
  175. }
  176. $out = strtr($str, $encode_arr);
  177. return $newlines ? nl2br($out) : $out;
  178. }
  179. // if the replace tables for XML and JS are not yet defined
  180. if ($js_rep_table === false) {
  181. $js_rep_table = $xml_rep_table = array();
  182. $xml_rep_table['&'] = '&amp;';
  183. // can be increased to support more charsets
  184. for ($c=160; $c<256; $c++) {
  185. $xml_rep_table[chr($c)] = "&#$c;";
  186. }
  187. $xml_rep_table['"'] = '&quot;';
  188. $js_rep_table['"'] = '\\"';
  189. $js_rep_table["'"] = "\\'";
  190. $js_rep_table["\\"] = "\\\\";
  191. // Unicode line and paragraph separators (#1486310)
  192. $js_rep_table[chr(hexdec('E2')).chr(hexdec('80')).chr(hexdec('A8'))] = '&#8232;';
  193. $js_rep_table[chr(hexdec('E2')).chr(hexdec('80')).chr(hexdec('A9'))] = '&#8233;';
  194. }
  195. // encode for javascript use
  196. if ($enctype == 'js') {
  197. return preg_replace(array("/\r?\n/", "/\r/", '/<\\//'), array('\n', '\n', '<\\/'), strtr($str, $js_rep_table));
  198. }
  199. // encode for plaintext
  200. if ($enctype == 'text') {
  201. return str_replace("\r\n", "\n", $mode == 'remove' ? strip_tags($str) : $str);
  202. }
  203. if ($enctype == 'url') {
  204. return rawurlencode($str);
  205. }
  206. // encode for XML
  207. if ($enctype == 'xml') {
  208. return strtr($str, $xml_rep_table);
  209. }
  210. // no encoding given -> return original string
  211. return $str;
  212. }
  213. /**
  214. * Read input value and convert it for internal use
  215. * Performs stripslashes() and charset conversion if necessary
  216. *
  217. * @param string Field name to read
  218. * @param int Source to get value from (GPC)
  219. * @param boolean Allow HTML tags in field value
  220. * @param string Charset to convert into
  221. *
  222. * @return string Field value or NULL if not available
  223. */
  224. public static function get_input_value($fname, $source, $allow_html = false, $charset = null)
  225. {
  226. $value = null;
  227. if ($source == self::INPUT_GET) {
  228. if (isset($_GET[$fname])) {
  229. $value = $_GET[$fname];
  230. }
  231. }
  232. else if ($source == self::INPUT_POST) {
  233. if (isset($_POST[$fname])) {
  234. $value = $_POST[$fname];
  235. }
  236. }
  237. else if ($source == self::INPUT_GPC) {
  238. if (isset($_POST[$fname])) {
  239. $value = $_POST[$fname];
  240. }
  241. else if (isset($_GET[$fname])) {
  242. $value = $_GET[$fname];
  243. }
  244. else if (isset($_COOKIE[$fname])) {
  245. $value = $_COOKIE[$fname];
  246. }
  247. }
  248. return self::parse_input_value($value, $allow_html, $charset);
  249. }
  250. /**
  251. * Parse/validate input value. See self::get_input_value()
  252. * Performs stripslashes() and charset conversion if necessary
  253. *
  254. * @param string Input value
  255. * @param boolean Allow HTML tags in field value
  256. * @param string Charset to convert into
  257. *
  258. * @return string Parsed value
  259. */
  260. public static function parse_input_value($value, $allow_html = false, $charset = null)
  261. {
  262. global $OUTPUT;
  263. if (empty($value)) {
  264. return $value;
  265. }
  266. if (is_array($value)) {
  267. foreach ($value as $idx => $val) {
  268. $value[$idx] = self::parse_input_value($val, $allow_html, $charset);
  269. }
  270. return $value;
  271. }
  272. // strip slashes if magic_quotes enabled
  273. if (get_magic_quotes_gpc() || get_magic_quotes_runtime()) {
  274. $value = stripslashes($value);
  275. }
  276. // remove HTML tags if not allowed
  277. if (!$allow_html) {
  278. $value = strip_tags($value);
  279. }
  280. $output_charset = is_object($OUTPUT) ? $OUTPUT->get_charset() : null;
  281. // remove invalid characters (#1488124)
  282. if ($output_charset == 'UTF-8') {
  283. $value = rcube_charset::clean($value);
  284. }
  285. // convert to internal charset
  286. if ($charset && $output_charset) {
  287. $value = rcube_charset::convert($value, $output_charset, $charset);
  288. }
  289. return $value;
  290. }
  291. /**
  292. * Convert array of request parameters (prefixed with _)
  293. * to a regular array with non-prefixed keys.
  294. *
  295. * @param int $mode Source to get value from (GPC)
  296. * @param string $ignore PCRE expression to skip parameters by name
  297. * @param boolean $allow_html Allow HTML tags in field value
  298. *
  299. * @return array Hash array with all request parameters
  300. */
  301. public static function request2param($mode = null, $ignore = 'task|action', $allow_html = false)
  302. {
  303. $out = array();
  304. $src = $mode == self::INPUT_GET ? $_GET : ($mode == self::INPUT_POST ? $_POST : $_REQUEST);
  305. foreach (array_keys($src) as $key) {
  306. $fname = $key[0] == '_' ? substr($key, 1) : $key;
  307. if ($ignore && !preg_match('/^(' . $ignore . ')$/', $fname)) {
  308. $out[$fname] = self::get_input_value($key, $mode, $allow_html);
  309. }
  310. }
  311. return $out;
  312. }
  313. /**
  314. * Convert the given string into a valid HTML identifier
  315. * Same functionality as done in app.js with rcube_webmail.html_identifier()
  316. */
  317. public static function html_identifier($str, $encode=false)
  318. {
  319. if ($encode) {
  320. return rtrim(strtr(base64_encode($str), '+/', '-_'), '=');
  321. }
  322. else {
  323. return asciiwords($str, true, '_');
  324. }
  325. }
  326. /**
  327. * Replace all css definitions with #container [def]
  328. * and remove css-inlined scripting, make position style safe
  329. *
  330. * @param string CSS source code
  331. * @param string Container ID to use as prefix
  332. * @param bool Allow remote content
  333. *
  334. * @return string Modified CSS source
  335. */
  336. public static function mod_css_styles($source, $container_id, $allow_remote = false)
  337. {
  338. $last_pos = 0;
  339. $replacements = new rcube_string_replacer;
  340. // ignore the whole block if evil styles are detected
  341. $source = self::xss_entity_decode($source);
  342. $stripped = preg_replace('/[^a-z\(:;]/i', '', $source);
  343. $evilexpr = 'expression|behavior|javascript:|import[^a]' . (!$allow_remote ? '|url\(' : '');
  344. if (preg_match("/$evilexpr/i", $stripped)) {
  345. return '/* evil! */';
  346. }
  347. $strict_url_regexp = '!url\s*\([ "\'](https?:)//[a-z0-9/._+-]+["\' ]\)!Uims';
  348. // cut out all contents between { and }
  349. while (($pos = strpos($source, '{', $last_pos)) && ($pos2 = strpos($source, '}', $pos))) {
  350. $nested = strpos($source, '{', $pos+1);
  351. if ($nested && $nested < $pos2) // when dealing with nested blocks (e.g. @media), take the inner one
  352. $pos = $nested;
  353. $length = $pos2 - $pos - 1;
  354. $styles = substr($source, $pos+1, $length);
  355. // Convert position:fixed to position:absolute (#5264)
  356. $styles = preg_replace('/position:[\s\r\n]*fixed/i', 'position: absolute', $styles);
  357. // check every line of a style block...
  358. if ($allow_remote) {
  359. $a_styles = preg_split('/;[\r\n]*/', $styles, -1, PREG_SPLIT_NO_EMPTY);
  360. foreach ($a_styles as $line) {
  361. $stripped = preg_replace('/[^a-z\(:;]/i', '', $line);
  362. // ... and only allow strict url() values
  363. if (stripos($stripped, 'url(') && !preg_match($strict_url_regexp, $line)) {
  364. $a_styles = array('/* evil! */');
  365. break;
  366. }
  367. }
  368. $styles = join(";\n", $a_styles);
  369. }
  370. $key = $replacements->add($styles);
  371. $repl = $replacements->get_replacement($key);
  372. $source = substr_replace($source, $repl, $pos+1, $length);
  373. $last_pos = $pos2 - ($length - strlen($repl));
  374. }
  375. // remove html comments and add #container to each tag selector.
  376. // also replace body definition because we also stripped off the <body> tag
  377. $source = preg_replace(
  378. array(
  379. '/(^\s*<\!--)|(-->\s*$)/m',
  380. '/(^\s*|,\s*|\}\s*)([a-z0-9\._#\*][a-z0-9\.\-_]*)/im',
  381. '/'.preg_quote($container_id, '/').'\s+body/i',
  382. ),
  383. array(
  384. '',
  385. "\\1#$container_id \\2",
  386. $container_id,
  387. ),
  388. $source);
  389. // put block contents back in
  390. $source = $replacements->resolve($source);
  391. return $source;
  392. }
  393. /**
  394. * Generate CSS classes from mimetype and filename extension
  395. *
  396. * @param string $mimetype Mimetype
  397. * @param string $filename Filename
  398. *
  399. * @return string CSS classes separated by space
  400. */
  401. public static function file2class($mimetype, $filename)
  402. {
  403. $mimetype = strtolower($mimetype);
  404. $filename = strtolower($filename);
  405. list($primary, $secondary) = explode('/', $mimetype);
  406. $classes = array($primary ?: 'unknown');
  407. if ($secondary) {
  408. $classes[] = $secondary;
  409. }
  410. if (preg_match('/\.([a-z0-9]+)$/', $filename, $m)) {
  411. if (!in_array($m[1], $classes)) {
  412. $classes[] = $m[1];
  413. }
  414. }
  415. return join(" ", $classes);
  416. }
  417. /**
  418. * Decode escaped entities used by known XSS exploits.
  419. * See http://downloads.securityfocus.com/vulnerabilities/exploits/26800.eml for examples
  420. *
  421. * @param string CSS content to decode
  422. *
  423. * @return string Decoded string
  424. */
  425. public static function xss_entity_decode($content)
  426. {
  427. $out = html_entity_decode(html_entity_decode($content));
  428. $out = preg_replace_callback('/\\\([0-9a-f]{4})/i',
  429. array(self, 'xss_entity_decode_callback'), $out);
  430. $out = preg_replace('#/\*.*\*/#Ums', '', $out);
  431. return $out;
  432. }
  433. /**
  434. * preg_replace_callback callback for xss_entity_decode
  435. *
  436. * @param array $matches Result from preg_replace_callback
  437. *
  438. * @return string Decoded entity
  439. */
  440. public static function xss_entity_decode_callback($matches)
  441. {
  442. return chr(hexdec($matches[1]));
  443. }
  444. /**
  445. * Check if we can process not exceeding memory_limit
  446. *
  447. * @param integer Required amount of memory
  448. *
  449. * @return boolean True if memory won't be exceeded, False otherwise
  450. */
  451. public static function mem_check($need)
  452. {
  453. $mem_limit = parse_bytes(ini_get('memory_limit'));
  454. $memory = function_exists('memory_get_usage') ? memory_get_usage() : 16*1024*1024; // safe value: 16MB
  455. return $mem_limit > 0 && $memory + $need > $mem_limit ? false : true;
  456. }
  457. /**
  458. * Check if working in SSL mode
  459. *
  460. * @param integer $port HTTPS port number
  461. * @param boolean $use_https Enables 'use_https' option checking
  462. *
  463. * @return boolean
  464. */
  465. public static function https_check($port=null, $use_https=true)
  466. {
  467. if (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) != 'off') {
  468. return true;
  469. }
  470. if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO'])
  471. && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https'
  472. && in_array($_SERVER['REMOTE_ADDR'], rcube::get_instance()->config->get('proxy_whitelist', array()))
  473. ) {
  474. return true;
  475. }
  476. if ($port && $_SERVER['SERVER_PORT'] == $port) {
  477. return true;
  478. }
  479. if ($use_https && rcube::get_instance()->config->get('use_https')) {
  480. return true;
  481. }
  482. return false;
  483. }
  484. /**
  485. * Replaces hostname variables.
  486. *
  487. * @param string $name Hostname
  488. * @param string $host Optional IMAP hostname
  489. *
  490. * @return string Hostname
  491. */
  492. public static function parse_host($name, $host = '')
  493. {
  494. if (!is_string($name)) {
  495. return $name;
  496. }
  497. // %n - host
  498. $n = preg_replace('/:\d+$/', '', $_SERVER['SERVER_NAME']);
  499. // %t - host name without first part, e.g. %n=mail.domain.tld, %t=domain.tld
  500. $t = preg_replace('/^[^\.]+\./', '', $n);
  501. // %d - domain name without first part
  502. $d = preg_replace('/^[^\.]+\./', '', $_SERVER['HTTP_HOST']);
  503. // %h - IMAP host
  504. $h = $_SESSION['storage_host'] ?: $host;
  505. // %z - IMAP domain without first part, e.g. %h=imap.domain.tld, %z=domain.tld
  506. $z = preg_replace('/^[^\.]+\./', '', $h);
  507. // %s - domain name after the '@' from e-mail address provided at login screen.
  508. // Returns FALSE if an invalid email is provided
  509. if (strpos($name, '%s') !== false) {
  510. $user_email = self::get_input_value('_user', self::INPUT_POST);
  511. $user_email = self::idn_convert($user_email, true);
  512. $matches = preg_match('/(.*)@([a-z0-9\.\-\[\]\:]+)/i', $user_email, $s);
  513. if ($matches < 1 || filter_var($s[1]."@".$s[2], FILTER_VALIDATE_EMAIL) === false) {
  514. return false;
  515. }
  516. }
  517. return str_replace(array('%n', '%t', '%d', '%h', '%z', '%s'), array($n, $t, $d, $h, $z, $s[2]), $name);
  518. }
  519. /**
  520. * Returns remote IP address and forwarded addresses if found
  521. *
  522. * @return string Remote IP address(es)
  523. */
  524. public static function remote_ip()
  525. {
  526. $address = $_SERVER['REMOTE_ADDR'];
  527. // append the NGINX X-Real-IP header, if set
  528. if (!empty($_SERVER['HTTP_X_REAL_IP'])) {
  529. $remote_ip[] = 'X-Real-IP: ' . $_SERVER['HTTP_X_REAL_IP'];
  530. }
  531. // append the X-Forwarded-For header, if set
  532. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  533. $remote_ip[] = 'X-Forwarded-For: ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
  534. }
  535. if (!empty($remote_ip)) {
  536. $address .= '(' . implode(',', $remote_ip) . ')';
  537. }
  538. return $address;
  539. }
  540. /**
  541. * Returns the real remote IP address
  542. *
  543. * @return string Remote IP address
  544. */
  545. public static function remote_addr()
  546. {
  547. // Check if any of the headers are set first to improve performance
  548. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) || !empty($_SERVER['HTTP_X_REAL_IP'])) {
  549. $proxy_whitelist = rcube::get_instance()->config->get('proxy_whitelist', array());
  550. if (in_array($_SERVER['REMOTE_ADDR'], $proxy_whitelist)) {
  551. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  552. foreach(array_reverse(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])) as $forwarded_ip) {
  553. if (!in_array($forwarded_ip, $proxy_whitelist)) {
  554. return $forwarded_ip;
  555. }
  556. }
  557. }
  558. if (!empty($_SERVER['HTTP_X_REAL_IP'])) {
  559. return $_SERVER['HTTP_X_REAL_IP'];
  560. }
  561. }
  562. }
  563. if (!empty($_SERVER['REMOTE_ADDR'])) {
  564. return $_SERVER['REMOTE_ADDR'];
  565. }
  566. return '';
  567. }
  568. /**
  569. * Read a specific HTTP request header.
  570. *
  571. * @param string $name Header name
  572. *
  573. * @return mixed Header value or null if not available
  574. */
  575. public static function request_header($name)
  576. {
  577. if (function_exists('getallheaders')) {
  578. $hdrs = array_change_key_case(getallheaders(), CASE_UPPER);
  579. $key = strtoupper($name);
  580. }
  581. else {
  582. $key = 'HTTP_' . strtoupper(strtr($name, '-', '_'));
  583. $hdrs = array_change_key_case($_SERVER, CASE_UPPER);
  584. }
  585. return $hdrs[$key];
  586. }
  587. /**
  588. * Explode quoted string
  589. *
  590. * @param string Delimiter expression string for preg_match()
  591. * @param string Input string
  592. *
  593. * @return array String items
  594. */
  595. public static function explode_quoted_string($delimiter, $string)
  596. {
  597. $result = array();
  598. $strlen = strlen($string);
  599. for ($q=$p=$i=0; $i < $strlen; $i++) {
  600. if ($string[$i] == "\"" && $string[$i-1] != "\\") {
  601. $q = $q ? false : true;
  602. }
  603. else if (!$q && preg_match("/$delimiter/", $string[$i])) {
  604. $result[] = substr($string, $p, $i - $p);
  605. $p = $i + 1;
  606. }
  607. }
  608. $result[] = (string) substr($string, $p);
  609. return $result;
  610. }
  611. /**
  612. * Improved equivalent to strtotime()
  613. *
  614. * @param string $date Date string
  615. * @param DateTimeZone $timezone Timezone to use for DateTime object
  616. *
  617. * @return int Unix timestamp
  618. */
  619. public static function strtotime($date, $timezone = null)
  620. {
  621. $date = self::clean_datestr($date);
  622. $tzname = $timezone ? ' ' . $timezone->getName() : '';
  623. // unix timestamp
  624. if (is_numeric($date)) {
  625. return (int) $date;
  626. }
  627. // if date parsing fails, we have a date in non-rfc format.
  628. // remove token from the end and try again
  629. while ((($ts = @strtotime($date . $tzname)) === false) || ($ts < 0)) {
  630. $d = explode(' ', $date);
  631. array_pop($d);
  632. if (!$d) {
  633. break;
  634. }
  635. $date = implode(' ', $d);
  636. }
  637. return (int) $ts;
  638. }
  639. /**
  640. * Date parsing function that turns the given value into a DateTime object
  641. *
  642. * @param string $date Date string
  643. * @param DateTimeZone $timezone Timezone to use for DateTime object
  644. *
  645. * @return DateTime instance or false on failure
  646. */
  647. public static function anytodatetime($date, $timezone = null)
  648. {
  649. if ($date instanceof DateTime) {
  650. return $date;
  651. }
  652. $dt = false;
  653. $date = self::clean_datestr($date);
  654. // try to parse string with DateTime first
  655. if (!empty($date)) {
  656. try {
  657. $dt = $timezone ? new DateTime($date, $timezone) : new DateTime($date);
  658. }
  659. catch (Exception $e) {
  660. // ignore
  661. }
  662. }
  663. // try our advanced strtotime() method
  664. if (!$dt && ($timestamp = self::strtotime($date, $timezone))) {
  665. try {
  666. $dt = new DateTime("@".$timestamp);
  667. if ($timezone) {
  668. $dt->setTimezone($timezone);
  669. }
  670. }
  671. catch (Exception $e) {
  672. // ignore
  673. }
  674. }
  675. return $dt;
  676. }
  677. /**
  678. * Clean up date string for strtotime() input
  679. *
  680. * @param string $date Date string
  681. *
  682. * @return string Date string
  683. */
  684. public static function clean_datestr($date)
  685. {
  686. $date = trim($date);
  687. // check for MS Outlook vCard date format YYYYMMDD
  688. if (preg_match('/^([12][90]\d\d)([01]\d)([0123]\d)$/', $date, $m)) {
  689. return sprintf('%04d-%02d-%02d 00:00:00', intval($m[1]), intval($m[2]), intval($m[3]));
  690. }
  691. // Clean malformed data
  692. $date = preg_replace(
  693. array(
  694. '/GMT\s*([+-][0-9]+)/', // support non-standard "GMTXXXX" literal
  695. '/[^a-z0-9\x20\x09:+-\/]/i', // remove any invalid characters
  696. '/\s*(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s*/i', // remove weekday names
  697. ),
  698. array(
  699. '\\1',
  700. '',
  701. '',
  702. ), $date);
  703. $date = trim($date);
  704. // try to fix dd/mm vs. mm/dd discrepancy, we can't do more here
  705. if (preg_match('/^(\d{1,2})[.\/-](\d{1,2})[.\/-](\d{4})(\s.*)?$/', $date, $m)) {
  706. $mdy = $m[2] > 12 && $m[1] <= 12;
  707. $day = $mdy ? $m[2] : $m[1];
  708. $month = $mdy ? $m[1] : $m[2];
  709. $date = sprintf('%04d-%02d-%02d%s', $m[3], $month, $day, $m[4] ?: ' 00:00:00');
  710. }
  711. // I've found that YYYY.MM.DD is recognized wrong, so here's a fix
  712. else if (preg_match('/^(\d{4})\.(\d{1,2})\.(\d{1,2})(\s.*)?$/', $date, $m)) {
  713. $date = sprintf('%04d-%02d-%02d%s', $m[1], $m[2], $m[3], $m[4] ?: ' 00:00:00');
  714. }
  715. return $date;
  716. }
  717. /**
  718. * Turns the given date-only string in defined format into YYYY-MM-DD format.
  719. *
  720. * Supported formats: 'Y/m/d', 'Y.m.d', 'd-m-Y', 'd/m/Y', 'd.m.Y', 'j.n.Y'
  721. *
  722. * @param string $date Date string
  723. * @param string $format Input date format
  724. *
  725. * @return strin Date string in YYYY-MM-DD format, or the original string
  726. * if format is not supported
  727. */
  728. public static function format_datestr($date, $format)
  729. {
  730. $format_items = preg_split('/[.-\/\\\\]/', $format);
  731. $date_items = preg_split('/[.-\/\\\\]/', $date);
  732. $iso_format = '%04d-%02d-%02d';
  733. if (count($format_items) == 3 && count($date_items) == 3) {
  734. if ($format_items[0] == 'Y') {
  735. $date = sprintf($iso_format, $date_items[0], $date_items[1], $date_items[2]);
  736. }
  737. else if (strpos('dj', $format_items[0]) !== false) {
  738. $date = sprintf($iso_format, $date_items[2], $date_items[1], $date_items[0]);
  739. }
  740. else if (strpos('mn', $format_items[0]) !== false) {
  741. $date = sprintf($iso_format, $date_items[2], $date_items[0], $date_items[1]);
  742. }
  743. }
  744. return $date;
  745. }
  746. /*
  747. * Idn_to_ascii wrapper.
  748. * Intl/Idn modules version of this function doesn't work with e-mail address
  749. */
  750. public static function idn_to_ascii($str)
  751. {
  752. return self::idn_convert($str, true);
  753. }
  754. /*
  755. * Idn_to_ascii wrapper.
  756. * Intl/Idn modules version of this function doesn't work with e-mail address
  757. */
  758. public static function idn_to_utf8($str)
  759. {
  760. return self::idn_convert($str, false);
  761. }
  762. public static function idn_convert($input, $is_utf = false)
  763. {
  764. if ($at = strpos($input, '@')) {
  765. $user = substr($input, 0, $at);
  766. $domain = substr($input, $at+1);
  767. }
  768. else {
  769. $domain = $input;
  770. }
  771. $domain = $is_utf ? idn_to_ascii($domain) : idn_to_utf8($domain);
  772. if ($domain === false) {
  773. return '';
  774. }
  775. return $at ? $user . '@' . $domain : $domain;
  776. }
  777. /**
  778. * Split the given string into word tokens
  779. *
  780. * @param string Input to tokenize
  781. * @param integer Minimum length of a single token
  782. * @return array List of tokens
  783. */
  784. public static function tokenize_string($str, $minlen = 2)
  785. {
  786. $expr = array('/[\s;,"\'\/+-]+/ui', '/(\d)[-.\s]+(\d)/u');
  787. $repl = array(' ', '\\1\\2');
  788. if ($minlen > 1) {
  789. $minlen--;
  790. $expr[] = "/(^|\s+)\w{1,$minlen}(\s+|$)/u";
  791. $repl[] = ' ';
  792. }
  793. return array_filter(explode(" ", preg_replace($expr, $repl, $str)));
  794. }
  795. /**
  796. * Normalize the given string for fulltext search.
  797. * Currently only optimized for ISO-8859-1 and ISO-8859-2 characters; to be extended
  798. *
  799. * @param string Input string (UTF-8)
  800. * @param boolean True to return list of words as array
  801. * @param integer Minimum length of tokens
  802. *
  803. * @return mixed Normalized string or a list of normalized tokens
  804. */
  805. public static function normalize_string($str, $as_array = false, $minlen = 2)
  806. {
  807. // replace 4-byte unicode characters with '?' character,
  808. // these are not supported in default utf-8 charset on mysql,
  809. // the chance we'd need them in searching is very low
  810. $str = preg_replace('/('
  811. . '\xF0[\x90-\xBF][\x80-\xBF]{2}'
  812. . '|[\xF1-\xF3][\x80-\xBF]{3}'
  813. . '|\xF4[\x80-\x8F][\x80-\xBF]{2}'
  814. . ')/', '?', $str);
  815. // split by words
  816. $arr = self::tokenize_string($str, $minlen);
  817. // detect character set
  818. if (utf8_encode(utf8_decode($str)) == $str) {
  819. // ISO-8859-1 (or ASCII)
  820. preg_match_all('/./u', 'äâàåáãæçéêëèïîìíñöôòøõóüûùúýÿ', $keys);
  821. preg_match_all('/./', 'aaaaaaaceeeeiiiinoooooouuuuyy', $values);
  822. $mapping = array_combine($keys[0], $values[0]);
  823. $mapping = array_merge($mapping, array('ß' => 'ss', 'ae' => 'a', 'oe' => 'o', 'ue' => 'u'));
  824. }
  825. else if (rcube_charset::convert(rcube_charset::convert($str, 'UTF-8', 'ISO-8859-2'), 'ISO-8859-2', 'UTF-8') == $str) {
  826. // ISO-8859-2
  827. preg_match_all('/./u', 'ąáâäćçčéęëěíîłľĺńňóôöŕřśšşťţůúűüźžżý', $keys);
  828. preg_match_all('/./', 'aaaaccceeeeiilllnnooorrsssttuuuuzzzy', $values);
  829. $mapping = array_combine($keys[0], $values[0]);
  830. $mapping = array_merge($mapping, array('ß' => 'ss', 'ae' => 'a', 'oe' => 'o', 'ue' => 'u'));
  831. }
  832. foreach ($arr as $i => $part) {
  833. $part = mb_strtolower($part);
  834. if (!empty($mapping)) {
  835. $part = strtr($part, $mapping);
  836. }
  837. $arr[$i] = $part;
  838. }
  839. return $as_array ? $arr : join(" ", $arr);
  840. }
  841. /**
  842. * Compare two strings for matching words (order not relevant)
  843. *
  844. * @param string Haystack
  845. * @param string Needle
  846. *
  847. * @return boolean True if match, False otherwise
  848. */
  849. public static function words_match($haystack, $needle)
  850. {
  851. $a_needle = self::tokenize_string($needle, 1);
  852. $_haystack = join(" ", self::tokenize_string($haystack, 1));
  853. $valid = strlen($_haystack) > 0;
  854. $hits = 0;
  855. foreach ($a_needle as $w) {
  856. if ($valid) {
  857. if (stripos($_haystack, $w) !== false) {
  858. $hits++;
  859. }
  860. }
  861. else if (stripos($haystack, $w) !== false) {
  862. $hits++;
  863. }
  864. }
  865. return $hits >= count($a_needle);
  866. }
  867. /**
  868. * Parse commandline arguments into a hash array
  869. *
  870. * @param array $aliases Argument alias names
  871. *
  872. * @return array Argument values hash
  873. */
  874. public static function get_opt($aliases = array())
  875. {
  876. $args = array();
  877. $bool = array();
  878. // find boolean (no value) options
  879. foreach ($aliases as $key => $alias) {
  880. if ($pos = strpos($alias, ':')) {
  881. $aliases[$key] = substr($alias, 0, $pos);
  882. $bool[] = $key;
  883. $bool[] = $aliases[$key];
  884. }
  885. }
  886. for ($i=1; $i < count($_SERVER['argv']); $i++) {
  887. $arg = $_SERVER['argv'][$i];
  888. $value = true;
  889. $key = null;
  890. if ($arg[0] == '-') {
  891. $key = preg_replace('/^-+/', '', $arg);
  892. $sp = strpos($arg, '=');
  893. if ($sp > 0) {
  894. $key = substr($key, 0, $sp - 2);
  895. $value = substr($arg, $sp+1);
  896. }
  897. else if (in_array($key, $bool)) {
  898. $value = true;
  899. }
  900. else if (strlen($_SERVER['argv'][$i+1]) && $_SERVER['argv'][$i+1][0] != '-') {
  901. $value = $_SERVER['argv'][++$i];
  902. }
  903. $args[$key] = is_string($value) ? preg_replace(array('/^["\']/', '/["\']$/'), '', $value) : $value;
  904. }
  905. else {
  906. $args[] = $arg;
  907. }
  908. if ($alias = $aliases[$key]) {
  909. $args[$alias] = $args[$key];
  910. }
  911. }
  912. return $args;
  913. }
  914. /**
  915. * Safe password prompt for command line
  916. * from http://blogs.sitepoint.com/2009/05/01/interactive-cli-password-prompt-in-php/
  917. *
  918. * @return string Password
  919. */
  920. public static function prompt_silent($prompt = "Password:")
  921. {
  922. if (preg_match('/^win/i', PHP_OS)) {
  923. $vbscript = sys_get_temp_dir() . 'prompt_password.vbs';
  924. $vbcontent = 'wscript.echo(InputBox("' . addslashes($prompt) . '", "", "password here"))';
  925. file_put_contents($vbscript, $vbcontent);
  926. $command = "cscript //nologo " . escapeshellarg($vbscript);
  927. $password = rtrim(shell_exec($command));
  928. unlink($vbscript);
  929. return $password;
  930. }
  931. else {
  932. $command = "/usr/bin/env bash -c 'echo OK'";
  933. if (rtrim(shell_exec($command)) !== 'OK') {
  934. echo $prompt;
  935. $pass = trim(fgets(STDIN));
  936. echo chr(8)."\r" . $prompt . str_repeat("*", strlen($pass))."\n";
  937. return $pass;
  938. }
  939. $command = "/usr/bin/env bash -c 'read -s -p \"" . addslashes($prompt) . "\" mypassword && echo \$mypassword'";
  940. $password = rtrim(shell_exec($command));
  941. echo "\n";
  942. return $password;
  943. }
  944. }
  945. /**
  946. * Find out if the string content means true or false
  947. *
  948. * @param string $str Input value
  949. *
  950. * @return boolean Boolean value
  951. */
  952. public static function get_boolean($str)
  953. {
  954. $str = strtolower($str);
  955. return !in_array($str, array('false', '0', 'no', 'off', 'nein', ''), true);
  956. }
  957. /**
  958. * OS-dependent absolute path detection
  959. */
  960. public static function is_absolute_path($path)
  961. {
  962. if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
  963. return (bool) preg_match('!^[a-z]:[\\\\/]!i', $path);
  964. }
  965. else {
  966. return $path[0] == '/';
  967. }
  968. }
  969. /**
  970. * Resolve relative URL
  971. *
  972. * @param string $url Relative URL
  973. *
  974. * @return string Absolute URL
  975. */
  976. public static function resolve_url($url)
  977. {
  978. // prepend protocol://hostname:port
  979. if (!preg_match('|^https?://|', $url)) {
  980. $schema = 'http';
  981. $default_port = 80;
  982. if (self::https_check()) {
  983. $schema = 'https';
  984. $default_port = 443;
  985. }
  986. $prefix = $schema . '://' . preg_replace('/:\d+$/', '', $_SERVER['HTTP_HOST']);
  987. if ($_SERVER['SERVER_PORT'] != $default_port) {
  988. $prefix .= ':' . $_SERVER['SERVER_PORT'];
  989. }
  990. $url = $prefix . ($url[0] == '/' ? '' : '/') . $url;
  991. }
  992. return $url;
  993. }
  994. /**
  995. * Generate a random string
  996. *
  997. * @param int $length String length
  998. * @param bool $raw Return RAW data instead of ascii
  999. *
  1000. * @return string The generated random string
  1001. */
  1002. public static function random_bytes($length, $raw = false)
  1003. {
  1004. // Use PHP7 true random generator
  1005. if (function_exists('random_bytes')) {
  1006. // random_bytes() can throw an Error/TypeError/Exception in some cases
  1007. try {
  1008. $random = random_bytes($length);
  1009. }
  1010. catch (Throwable $e) {}
  1011. }
  1012. if (!$random) {
  1013. $random = openssl_random_pseudo_bytes($length);
  1014. }
  1015. if ($raw) {
  1016. return $random;
  1017. }
  1018. $random = self::bin2ascii($random);
  1019. // truncate to the specified size...
  1020. if ($length < strlen($random)) {
  1021. $random = substr($random, 0, $length);
  1022. }
  1023. return $random;
  1024. }
  1025. /**
  1026. * Convert binary data into readable form (containing a-zA-Z0-9 characters)
  1027. *
  1028. * @param string $input Binary input
  1029. *
  1030. * @return string Readable output
  1031. */
  1032. public static function bin2ascii($input)
  1033. {
  1034. // Above method returns "hexits".
  1035. // Based on bin_to_readable() function in ext/session/session.c.
  1036. // Note: removed ",-" characters from hextab
  1037. $hextab = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  1038. $nbits = 6; // can be 4, 5 or 6
  1039. $length = strlen($input);
  1040. $result = '';
  1041. $char = 0;
  1042. $i = 0;
  1043. $have = 0;
  1044. $mask = (1 << $nbits) - 1;
  1045. while (true) {
  1046. if ($have < $nbits) {
  1047. if ($i < $length) {
  1048. $char |= ord($input[$i++]) << $have;
  1049. $have += 8;
  1050. }
  1051. else if (!$have) {
  1052. break;
  1053. }
  1054. else {
  1055. $have = $nbits;
  1056. }
  1057. }
  1058. // consume nbits
  1059. $result .= $hextab[$char & $mask];
  1060. $char >>= $nbits;
  1061. $have -= $nbits;
  1062. }
  1063. return $result;
  1064. }
  1065. /**
  1066. * Format current date according to specified format.
  1067. * This method supports microseconds (u).
  1068. *
  1069. * @param string $format Date format (default: 'd-M-Y H:i:s O')
  1070. *
  1071. * @return string Formatted date
  1072. */
  1073. public static function date_format($format = null)
  1074. {
  1075. if (empty($format)) {
  1076. $format = 'd-M-Y H:i:s O';
  1077. }
  1078. if (strpos($format, 'u') !== false) {
  1079. $dt = number_format(microtime(true), 6, '.', '');
  1080. $dt .= '.' . date_default_timezone_get();
  1081. if ($date = date_create_from_format('U.u.e', $dt)) {
  1082. return $date->format($format);
  1083. }
  1084. }
  1085. return date($format);
  1086. }
  1087. }