PageRenderTime 64ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/program/lib/Roundcube/rcube_utils.php

https://github.com/trimbakgopalghare/roundcubemail
PHP | 1085 lines | 754 code | 114 blank | 217 comment | 133 complexity | 8d3761be809f0ebb9233961e9e72f594 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.1
  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('/^(([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. if (preg_match('/[^a-zA-Z]/', array_pop($domain_array))) {
  98. return false;
  99. }
  100. $rcube = rcube::get_instance();
  101. if (!$dns_check || !$rcube->config->get('email_dns_check')) {
  102. return true;
  103. }
  104. if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' && version_compare(PHP_VERSION, '5.3.0', '<')) {
  105. $lookup = array();
  106. @exec("nslookup -type=MX " . escapeshellarg($domain_part) . " 2>&1", $lookup);
  107. foreach ($lookup as $line) {
  108. if (strpos($line, 'MX preference')) {
  109. return true;
  110. }
  111. }
  112. return false;
  113. }
  114. // find MX record(s)
  115. if (!function_exists('getmxrr') || getmxrr($domain_part, $mx_records)) {
  116. return true;
  117. }
  118. // find any DNS record
  119. if (!function_exists('checkdnsrr') || checkdnsrr($domain_part, 'ANY')) {
  120. return true;
  121. }
  122. }
  123. return false;
  124. }
  125. /**
  126. * Validates IPv4 or IPv6 address
  127. *
  128. * @param string $ip IP address in v4 or v6 format
  129. *
  130. * @return bool True if the address is valid
  131. */
  132. public static function check_ip($ip)
  133. {
  134. // IPv6, but there's no build-in IPv6 support
  135. if (strpos($ip, ':') !== false && !defined('AF_INET6')) {
  136. $parts = explode(':', $ip);
  137. $count = count($parts);
  138. if ($count > 8 || $count < 2) {
  139. return false;
  140. }
  141. foreach ($parts as $idx => $part) {
  142. $length = strlen($part);
  143. if (!$length) {
  144. // there can be only one ::
  145. if ($found_empty) {
  146. return false;
  147. }
  148. $found_empty = true;
  149. }
  150. // last part can be an IPv4 address
  151. else if ($idx == $count - 1) {
  152. if (!preg_match('/^[0-9a-f]{1,4}$/i', $part)) {
  153. return @inet_pton($part) !== false;
  154. }
  155. }
  156. else if (!preg_match('/^[0-9a-f]{1,4}$/i', $part)) {
  157. return false;
  158. }
  159. }
  160. return true;
  161. }
  162. return @inet_pton($ip) !== false;
  163. }
  164. /**
  165. * Check whether the HTTP referer matches the current request
  166. *
  167. * @return boolean True if referer is the same host+path, false if not
  168. */
  169. public static function check_referer()
  170. {
  171. $uri = parse_url($_SERVER['REQUEST_URI']);
  172. $referer = parse_url(self::request_header('Referer'));
  173. return $referer['host'] == self::request_header('Host') && $referer['path'] == $uri['path'];
  174. }
  175. /**
  176. * Replacing specials characters to a specific encoding type
  177. *
  178. * @param string Input string
  179. * @param string Encoding type: text|html|xml|js|url
  180. * @param string Replace mode for tags: show|replace|remove
  181. * @param boolean Convert newlines
  182. *
  183. * @return string The quoted string
  184. */
  185. public static function rep_specialchars_output($str, $enctype = '', $mode = '', $newlines = true)
  186. {
  187. static $html_encode_arr = false;
  188. static $js_rep_table = false;
  189. static $xml_rep_table = false;
  190. if (!is_string($str)) {
  191. $str = strval($str);
  192. }
  193. // encode for HTML output
  194. if ($enctype == 'html') {
  195. if (!$html_encode_arr) {
  196. $html_encode_arr = get_html_translation_table(HTML_SPECIALCHARS);
  197. unset($html_encode_arr['?']);
  198. }
  199. $encode_arr = $html_encode_arr;
  200. // don't replace quotes and html tags
  201. if ($mode == 'show' || $mode == '') {
  202. $ltpos = strpos($str, '<');
  203. if ($ltpos !== false && strpos($str, '>', $ltpos) !== false) {
  204. unset($encode_arr['"']);
  205. unset($encode_arr['<']);
  206. unset($encode_arr['>']);
  207. unset($encode_arr['&']);
  208. }
  209. }
  210. else if ($mode == 'remove') {
  211. $str = strip_tags($str);
  212. }
  213. $out = strtr($str, $encode_arr);
  214. return $newlines ? nl2br($out) : $out;
  215. }
  216. // if the replace tables for XML and JS are not yet defined
  217. if ($js_rep_table === false) {
  218. $js_rep_table = $xml_rep_table = array();
  219. $xml_rep_table['&'] = '&amp;';
  220. // can be increased to support more charsets
  221. for ($c=160; $c<256; $c++) {
  222. $xml_rep_table[chr($c)] = "&#$c;";
  223. }
  224. $xml_rep_table['"'] = '&quot;';
  225. $js_rep_table['"'] = '\\"';
  226. $js_rep_table["'"] = "\\'";
  227. $js_rep_table["\\"] = "\\\\";
  228. // Unicode line and paragraph separators (#1486310)
  229. $js_rep_table[chr(hexdec(E2)).chr(hexdec(80)).chr(hexdec(A8))] = '&#8232;';
  230. $js_rep_table[chr(hexdec(E2)).chr(hexdec(80)).chr(hexdec(A9))] = '&#8233;';
  231. }
  232. // encode for javascript use
  233. if ($enctype == 'js') {
  234. return preg_replace(array("/\r?\n/", "/\r/", '/<\\//'), array('\n', '\n', '<\\/'), strtr($str, $js_rep_table));
  235. }
  236. // encode for plaintext
  237. if ($enctype == 'text') {
  238. return str_replace("\r\n", "\n", $mode=='remove' ? strip_tags($str) : $str);
  239. }
  240. if ($enctype == 'url') {
  241. return rawurlencode($str);
  242. }
  243. // encode for XML
  244. if ($enctype == 'xml') {
  245. return strtr($str, $xml_rep_table);
  246. }
  247. // no encoding given -> return original string
  248. return $str;
  249. }
  250. /**
  251. * Read input value and convert it for internal use
  252. * Performs stripslashes() and charset conversion if necessary
  253. *
  254. * @param string Field name to read
  255. * @param int Source to get value from (GPC)
  256. * @param boolean Allow HTML tags in field value
  257. * @param string Charset to convert into
  258. *
  259. * @return string Field value or NULL if not available
  260. */
  261. public static function get_input_value($fname, $source, $allow_html=FALSE, $charset=NULL)
  262. {
  263. $value = NULL;
  264. if ($source == self::INPUT_GET) {
  265. if (isset($_GET[$fname])) {
  266. $value = $_GET[$fname];
  267. }
  268. }
  269. else if ($source == self::INPUT_POST) {
  270. if (isset($_POST[$fname])) {
  271. $value = $_POST[$fname];
  272. }
  273. }
  274. else if ($source == self::INPUT_GPC) {
  275. if (isset($_POST[$fname])) {
  276. $value = $_POST[$fname];
  277. }
  278. else if (isset($_GET[$fname])) {
  279. $value = $_GET[$fname];
  280. }
  281. else if (isset($_COOKIE[$fname])) {
  282. $value = $_COOKIE[$fname];
  283. }
  284. }
  285. return self::parse_input_value($value, $allow_html, $charset);
  286. }
  287. /**
  288. * Parse/validate input value. See self::get_input_value()
  289. * Performs stripslashes() and charset conversion if necessary
  290. *
  291. * @param string Input value
  292. * @param boolean Allow HTML tags in field value
  293. * @param string Charset to convert into
  294. *
  295. * @return string Parsed value
  296. */
  297. public static function parse_input_value($value, $allow_html=FALSE, $charset=NULL)
  298. {
  299. global $OUTPUT;
  300. if (empty($value)) {
  301. return $value;
  302. }
  303. if (is_array($value)) {
  304. foreach ($value as $idx => $val) {
  305. $value[$idx] = self::parse_input_value($val, $allow_html, $charset);
  306. }
  307. return $value;
  308. }
  309. // strip slashes if magic_quotes enabled
  310. if (get_magic_quotes_gpc() || get_magic_quotes_runtime()) {
  311. $value = stripslashes($value);
  312. }
  313. // remove HTML tags if not allowed
  314. if (!$allow_html) {
  315. $value = strip_tags($value);
  316. }
  317. $output_charset = is_object($OUTPUT) ? $OUTPUT->get_charset() : null;
  318. // remove invalid characters (#1488124)
  319. if ($output_charset == 'UTF-8') {
  320. $value = rcube_charset::clean($value);
  321. }
  322. // convert to internal charset
  323. if ($charset && $output_charset) {
  324. $value = rcube_charset::convert($value, $output_charset, $charset);
  325. }
  326. return $value;
  327. }
  328. /**
  329. * Convert array of request parameters (prefixed with _)
  330. * to a regular array with non-prefixed keys.
  331. *
  332. * @param int $mode Source to get value from (GPC)
  333. * @param string $ignore PCRE expression to skip parameters by name
  334. * @param boolean $allow_html Allow HTML tags in field value
  335. *
  336. * @return array Hash array with all request parameters
  337. */
  338. public static function request2param($mode = null, $ignore = 'task|action', $allow_html = false)
  339. {
  340. $out = array();
  341. $src = $mode == self::INPUT_GET ? $_GET : ($mode == self::INPUT_POST ? $_POST : $_REQUEST);
  342. foreach (array_keys($src) as $key) {
  343. $fname = $key[0] == '_' ? substr($key, 1) : $key;
  344. if ($ignore && !preg_match('/^(' . $ignore . ')$/', $fname)) {
  345. $out[$fname] = self::get_input_value($key, $mode, $allow_html);
  346. }
  347. }
  348. return $out;
  349. }
  350. /**
  351. * Convert the given string into a valid HTML identifier
  352. * Same functionality as done in app.js with rcube_webmail.html_identifier()
  353. */
  354. public static function html_identifier($str, $encode=false)
  355. {
  356. if ($encode) {
  357. return rtrim(strtr(base64_encode($str), '+/', '-_'), '=');
  358. }
  359. else {
  360. return asciiwords($str, true, '_');
  361. }
  362. }
  363. /**
  364. * Replace all css definitions with #container [def]
  365. * and remove css-inlined scripting
  366. *
  367. * @param string CSS source code
  368. * @param string Container ID to use as prefix
  369. *
  370. * @return string Modified CSS source
  371. */
  372. public static function mod_css_styles($source, $container_id, $allow_remote=false)
  373. {
  374. $last_pos = 0;
  375. $replacements = new rcube_string_replacer;
  376. // ignore the whole block if evil styles are detected
  377. $source = self::xss_entity_decode($source);
  378. $stripped = preg_replace('/[^a-z\(:;]/i', '', $source);
  379. $evilexpr = 'expression|behavior|javascript:|import[^a]' . (!$allow_remote ? '|url\(' : '');
  380. if (preg_match("/$evilexpr/i", $stripped)) {
  381. return '/* evil! */';
  382. }
  383. $strict_url_regexp = '!url\s*\([ "\'](https?:)//[a-z0-9/._+-]+["\' ]\)!Uims';
  384. // cut out all contents between { and }
  385. while (($pos = strpos($source, '{', $last_pos)) && ($pos2 = strpos($source, '}', $pos))) {
  386. $nested = strpos($source, '{', $pos+1);
  387. if ($nested && $nested < $pos2) // when dealing with nested blocks (e.g. @media), take the inner one
  388. $pos = $nested;
  389. $length = $pos2 - $pos - 1;
  390. $styles = substr($source, $pos+1, $length);
  391. // check every line of a style block...
  392. if ($allow_remote) {
  393. $a_styles = preg_split('/;[\r\n]*/', $styles, -1, PREG_SPLIT_NO_EMPTY);
  394. foreach ($a_styles as $line) {
  395. $stripped = preg_replace('/[^a-z\(:;]/i', '', $line);
  396. // ... and only allow strict url() values
  397. if (stripos($stripped, 'url(') && !preg_match($strict_url_regexp, $line)) {
  398. $a_styles = array('/* evil! */');
  399. break;
  400. }
  401. }
  402. $styles = join(";\n", $a_styles);
  403. }
  404. $key = $replacements->add($styles);
  405. $repl = $replacements->get_replacement($key);
  406. $source = substr_replace($source, $repl, $pos+1, $length);
  407. $last_pos = $pos2 - ($length - strlen($repl));
  408. }
  409. // remove html comments and add #container to each tag selector.
  410. // also replace body definition because we also stripped off the <body> tag
  411. $source = preg_replace(
  412. array(
  413. '/(^\s*<\!--)|(-->\s*$)/m',
  414. '/(^\s*|,\s*|\}\s*)([a-z0-9\._#\*][a-z0-9\.\-_]*)/im',
  415. '/'.preg_quote($container_id, '/').'\s+body/i',
  416. ),
  417. array(
  418. '',
  419. "\\1#$container_id \\2",
  420. $container_id,
  421. ),
  422. $source);
  423. // put block contents back in
  424. $source = $replacements->resolve($source);
  425. return $source;
  426. }
  427. /**
  428. * Generate CSS classes from mimetype and filename extension
  429. *
  430. * @param string $mimetype Mimetype
  431. * @param string $filename Filename
  432. *
  433. * @return string CSS classes separated by space
  434. */
  435. public static function file2class($mimetype, $filename)
  436. {
  437. $mimetype = strtolower($mimetype);
  438. $filename = strtolower($filename);
  439. list($primary, $secondary) = explode('/', $mimetype);
  440. $classes = array($primary ? $primary : 'unknown');
  441. if ($secondary) {
  442. $classes[] = $secondary;
  443. }
  444. if (preg_match('/\.([a-z0-9]+)$/', $filename, $m)) {
  445. if (!in_array($m[1], $classes)) {
  446. $classes[] = $m[1];
  447. }
  448. }
  449. return join(" ", $classes);
  450. }
  451. /**
  452. * Decode escaped entities used by known XSS exploits.
  453. * See http://downloads.securityfocus.com/vulnerabilities/exploits/26800.eml for examples
  454. *
  455. * @param string CSS content to decode
  456. *
  457. * @return string Decoded string
  458. */
  459. public static function xss_entity_decode($content)
  460. {
  461. $out = html_entity_decode(html_entity_decode($content));
  462. $out = preg_replace_callback('/\\\([0-9a-f]{4})/i',
  463. array(self, 'xss_entity_decode_callback'), $out);
  464. $out = preg_replace('#/\*.*\*/#Ums', '', $out);
  465. return $out;
  466. }
  467. /**
  468. * preg_replace_callback callback for xss_entity_decode
  469. *
  470. * @param array $matches Result from preg_replace_callback
  471. *
  472. * @return string Decoded entity
  473. */
  474. public static function xss_entity_decode_callback($matches)
  475. {
  476. return chr(hexdec($matches[1]));
  477. }
  478. /**
  479. * Check if we can process not exceeding memory_limit
  480. *
  481. * @param integer Required amount of memory
  482. *
  483. * @return boolean True if memory won't be exceeded, False otherwise
  484. */
  485. public static function mem_check($need)
  486. {
  487. $mem_limit = parse_bytes(ini_get('memory_limit'));
  488. $memory = function_exists('memory_get_usage') ? memory_get_usage() : 16*1024*1024; // safe value: 16MB
  489. return $mem_limit > 0 && $memory + $need > $mem_limit ? false : true;
  490. }
  491. /**
  492. * Check if working in SSL mode
  493. *
  494. * @param integer $port HTTPS port number
  495. * @param boolean $use_https Enables 'use_https' option checking
  496. *
  497. * @return boolean
  498. */
  499. public static function https_check($port=null, $use_https=true)
  500. {
  501. if (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) != 'off') {
  502. return true;
  503. }
  504. if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO'])
  505. && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https'
  506. && in_array($_SERVER['REMOTE_ADDR'], rcube::get_instance()->config->get('proxy_whitelist', array()))) {
  507. return true;
  508. }
  509. if ($port && $_SERVER['SERVER_PORT'] == $port) {
  510. return true;
  511. }
  512. if ($use_https && rcube::get_instance()->config->get('use_https')) {
  513. return true;
  514. }
  515. return false;
  516. }
  517. /**
  518. * Replaces hostname variables.
  519. *
  520. * @param string $name Hostname
  521. * @param string $host Optional IMAP hostname
  522. *
  523. * @return string Hostname
  524. */
  525. public static function parse_host($name, $host = '')
  526. {
  527. if (!is_string($name)) {
  528. return $name;
  529. }
  530. // %n - host
  531. $n = preg_replace('/:\d+$/', '', $_SERVER['SERVER_NAME']);
  532. // %t - host name without first part, e.g. %n=mail.domain.tld, %t=domain.tld
  533. $t = preg_replace('/^[^\.]+\./', '', $n);
  534. // %d - domain name without first part
  535. $d = preg_replace('/^[^\.]+\./', '', $_SERVER['HTTP_HOST']);
  536. // %h - IMAP host
  537. $h = $_SESSION['storage_host'] ? $_SESSION['storage_host'] : $host;
  538. // %z - IMAP domain without first part, e.g. %h=imap.domain.tld, %z=domain.tld
  539. $z = preg_replace('/^[^\.]+\./', '', $h);
  540. // %s - domain name after the '@' from e-mail address provided at login screen. Returns FALSE if an invalid email is provided
  541. if (strpos($name, '%s') !== false) {
  542. $user_email = self::get_input_value('_user', self::INPUT_POST);
  543. $user_email = self::idn_convert($user_email, true);
  544. $matches = preg_match('/(.*)@([a-z0-9\.\-\[\]\:]+)/i', $user_email, $s);
  545. if ($matches < 1 || filter_var($s[1]."@".$s[2], FILTER_VALIDATE_EMAIL) === false) {
  546. return false;
  547. }
  548. }
  549. return str_replace(array('%n', '%t', '%d', '%h', '%z', '%s'), array($n, $t, $d, $h, $z, $s[2]), $name);
  550. }
  551. /**
  552. * Returns remote IP address and forwarded addresses if found
  553. *
  554. * @return string Remote IP address(es)
  555. */
  556. public static function remote_ip()
  557. {
  558. $address = $_SERVER['REMOTE_ADDR'];
  559. // append the NGINX X-Real-IP header, if set
  560. if (!empty($_SERVER['HTTP_X_REAL_IP'])) {
  561. $remote_ip[] = 'X-Real-IP: ' . $_SERVER['HTTP_X_REAL_IP'];
  562. }
  563. // append the X-Forwarded-For header, if set
  564. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  565. $remote_ip[] = 'X-Forwarded-For: ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
  566. }
  567. if (!empty($remote_ip)) {
  568. $address .= '(' . implode(',', $remote_ip) . ')';
  569. }
  570. return $address;
  571. }
  572. /**
  573. * Returns the real remote IP address
  574. *
  575. * @return string Remote IP address
  576. */
  577. public static function remote_addr()
  578. {
  579. // Check if any of the headers are set first to improve performance
  580. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) || !empty($_SERVER['HTTP_X_REAL_IP'])) {
  581. $proxy_whitelist = rcube::get_instance()->config->get('proxy_whitelist', array());
  582. if (in_array($_SERVER['REMOTE_ADDR'], $proxy_whitelist)) {
  583. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  584. foreach(array_reverse(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])) as $forwarded_ip) {
  585. if (!in_array($forwarded_ip, $proxy_whitelist)) {
  586. return $forwarded_ip;
  587. }
  588. }
  589. }
  590. if (!empty($_SERVER['HTTP_X_REAL_IP'])) {
  591. return $_SERVER['HTTP_X_REAL_IP'];
  592. }
  593. }
  594. }
  595. if (!empty($_SERVER['REMOTE_ADDR'])) {
  596. return $_SERVER['REMOTE_ADDR'];
  597. }
  598. return '';
  599. }
  600. /**
  601. * Read a specific HTTP request header.
  602. *
  603. * @param string $name Header name
  604. *
  605. * @return mixed Header value or null if not available
  606. */
  607. public static function request_header($name)
  608. {
  609. if (function_exists('getallheaders')) {
  610. $hdrs = array_change_key_case(getallheaders(), CASE_UPPER);
  611. $key = strtoupper($name);
  612. }
  613. else {
  614. $key = 'HTTP_' . strtoupper(strtr($name, '-', '_'));
  615. $hdrs = array_change_key_case($_SERVER, CASE_UPPER);
  616. }
  617. return $hdrs[$key];
  618. }
  619. /**
  620. * Explode quoted string
  621. *
  622. * @param string Delimiter expression string for preg_match()
  623. * @param string Input string
  624. *
  625. * @return array String items
  626. */
  627. public static function explode_quoted_string($delimiter, $string)
  628. {
  629. $result = array();
  630. $strlen = strlen($string);
  631. for ($q=$p=$i=0; $i < $strlen; $i++) {
  632. if ($string[$i] == "\"" && $string[$i-1] != "\\") {
  633. $q = $q ? false : true;
  634. }
  635. else if (!$q && preg_match("/$delimiter/", $string[$i])) {
  636. $result[] = substr($string, $p, $i - $p);
  637. $p = $i + 1;
  638. }
  639. }
  640. $result[] = (string) substr($string, $p);
  641. return $result;
  642. }
  643. /**
  644. * Improved equivalent to strtotime()
  645. *
  646. * @param string $date Date string
  647. *
  648. * @return int Unix timestamp
  649. */
  650. public static function strtotime($date)
  651. {
  652. $date = self::clean_datestr($date);
  653. // unix timestamp
  654. if (is_numeric($date)) {
  655. return (int) $date;
  656. }
  657. // if date parsing fails, we have a date in non-rfc format.
  658. // remove token from the end and try again
  659. while ((($ts = @strtotime($date)) === false) || ($ts < 0)) {
  660. $d = explode(' ', $date);
  661. array_pop($d);
  662. if (!$d) {
  663. break;
  664. }
  665. $date = implode(' ', $d);
  666. }
  667. return (int) $ts;
  668. }
  669. /**
  670. * Date parsing function that turns the given value into a DateTime object
  671. *
  672. * @param string $date Date string
  673. *
  674. * @return object DateTime instance or false on failure
  675. */
  676. public static function anytodatetime($date)
  677. {
  678. if (is_object($date) && is_a($date, 'DateTime')) {
  679. return $date;
  680. }
  681. $dt = false;
  682. $date = self::clean_datestr($date);
  683. // try to parse string with DateTime first
  684. if (!empty($date)) {
  685. try {
  686. $dt = new DateTime($date);
  687. }
  688. catch (Exception $e) {
  689. // ignore
  690. }
  691. }
  692. // try our advanced strtotime() method
  693. if (!$dt && ($timestamp = self::strtotime($date))) {
  694. try {
  695. $dt = new DateTime("@".$timestamp);
  696. }
  697. catch (Exception $e) {
  698. // ignore
  699. }
  700. }
  701. return $dt;
  702. }
  703. /**
  704. * Clean up date string for strtotime() input
  705. *
  706. * @param string $date Date string
  707. *
  708. * @return string Date string
  709. */
  710. public static function clean_datestr($date)
  711. {
  712. $date = trim($date);
  713. // check for MS Outlook vCard date format YYYYMMDD
  714. if (preg_match('/^([12][90]\d\d)([01]\d)([0123]\d)$/', $date, $m)) {
  715. return sprintf('%04d-%02d-%02d 00:00:00', intval($m[1]), intval($m[2]), intval($m[3]));
  716. }
  717. // Clean malformed data
  718. $date = preg_replace(
  719. array(
  720. '/GMT\s*([+-][0-9]+)/', // support non-standard "GMTXXXX" literal
  721. '/[^a-z0-9\x20\x09:+-\/]/i', // remove any invalid characters
  722. '/\s*(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s*/i', // remove weekday names
  723. ),
  724. array(
  725. '\\1',
  726. '',
  727. '',
  728. ), $date);
  729. $date = trim($date);
  730. // try to fix dd/mm vs. mm/dd discrepancy, we can't do more here
  731. if (preg_match('/^(\d{1,2})[.\/-](\d{1,2})[.\/-](\d{4})$/', $date, $m)) {
  732. $mdy = $m[2] > 12 && $m[1] <= 12;
  733. $day = $mdy ? $m[2] : $m[1];
  734. $month = $mdy ? $m[1] : $m[2];
  735. $date = sprintf('%04d-%02d-%02d 00:00:00', intval($m[3]), $month, $day);
  736. }
  737. // I've found that YYYY.MM.DD is recognized wrong, so here's a fix
  738. else if (preg_match('/^(\d{4})\.(\d{1,2})\.(\d{1,2})$/', $date)) {
  739. $date = str_replace('.', '-', $date) . ' 00:00:00';
  740. }
  741. return $date;
  742. }
  743. /*
  744. * Idn_to_ascii wrapper.
  745. * Intl/Idn modules version of this function doesn't work with e-mail address
  746. */
  747. public static function idn_to_ascii($str)
  748. {
  749. return self::idn_convert($str, true);
  750. }
  751. /*
  752. * Idn_to_ascii wrapper.
  753. * Intl/Idn modules version of this function doesn't work with e-mail address
  754. */
  755. public static function idn_to_utf8($str)
  756. {
  757. return self::idn_convert($str, false);
  758. }
  759. public static function idn_convert($input, $is_utf=false)
  760. {
  761. if ($at = strpos($input, '@')) {
  762. $user = substr($input, 0, $at);
  763. $domain = substr($input, $at+1);
  764. }
  765. else {
  766. $domain = $input;
  767. }
  768. $domain = $is_utf ? idn_to_ascii($domain) : idn_to_utf8($domain);
  769. if ($domain === false) {
  770. return '';
  771. }
  772. return $at ? $user . '@' . $domain : $domain;
  773. }
  774. /**
  775. * Split the given string into word tokens
  776. *
  777. * @param string Input to tokenize
  778. * @return array List of tokens
  779. */
  780. public static function tokenize_string($str)
  781. {
  782. return explode(" ", preg_replace(
  783. array('/[\s;\/+-]+/i', '/(\d)[-.\s]+(\d)/', '/\s\w{1,3}\s/u'),
  784. array(' ', '\\1\\2', ' '),
  785. $str));
  786. }
  787. /**
  788. * Normalize the given string for fulltext search.
  789. * Currently only optimized for ISO-8859-1 and ISO-8859-2 characters; to be extended
  790. *
  791. * @param string Input string (UTF-8)
  792. * @param boolean True to return list of words as array
  793. *
  794. * @return mixed Normalized string or a list of normalized tokens
  795. */
  796. public static function normalize_string($str, $as_array = false)
  797. {
  798. // replace 4-byte unicode characters with '?' character,
  799. // these are not supported in default utf-8 charset on mysql,
  800. // the chance we'd need them in searching is very low
  801. $str = preg_replace('/('
  802. . '\xF0[\x90-\xBF][\x80-\xBF]{2}'
  803. . '|[\xF1-\xF3][\x80-\xBF]{3}'
  804. . '|\xF4[\x80-\x8F][\x80-\xBF]{2}'
  805. . ')/', '?', $str);
  806. // split by words
  807. $arr = self::tokenize_string($str);
  808. // detect character set
  809. if (utf8_encode(utf8_decode($str)) == $str) {
  810. // ISO-8859-1 (or ASCII)
  811. preg_match_all('/./u', 'äâàåáãæçéêëèïîìíñöôòøõóüûùúýÿ', $keys);
  812. preg_match_all('/./', 'aaaaaaaceeeeiiiinoooooouuuuyy', $values);
  813. $mapping = array_combine($keys[0], $values[0]);
  814. $mapping = array_merge($mapping, array('ß' => 'ss', 'ae' => 'a', 'oe' => 'o', 'ue' => 'u'));
  815. }
  816. else if (rcube_charset::convert(rcube_charset::convert($str, 'UTF-8', 'ISO-8859-2'), 'ISO-8859-2', 'UTF-8') == $str) {
  817. // ISO-8859-2
  818. preg_match_all('/./u', 'ąáâäćçčéęëěíîłľĺńňóôöŕřśšşťţůúűüźžżý', $keys);
  819. preg_match_all('/./', 'aaaaccceeeeiilllnnooorrsssttuuuuzzzy', $values);
  820. $mapping = array_combine($keys[0], $values[0]);
  821. $mapping = array_merge($mapping, array('ß' => 'ss', 'ae' => 'a', 'oe' => 'o', 'ue' => 'u'));
  822. }
  823. foreach ($arr as $i => $part) {
  824. $part = mb_strtolower($part);
  825. if (!empty($mapping)) {
  826. $part = strtr($part, $mapping);
  827. }
  828. $arr[$i] = $part;
  829. }
  830. return $as_array ? $arr : join(" ", $arr);
  831. }
  832. /**
  833. * Parse commandline arguments into a hash array
  834. *
  835. * @param array $aliases Argument alias names
  836. *
  837. * @return array Argument values hash
  838. */
  839. public static function get_opt($aliases = array())
  840. {
  841. $args = array();
  842. for ($i=1; $i < count($_SERVER['argv']); $i++) {
  843. $arg = $_SERVER['argv'][$i];
  844. $value = true;
  845. $key = null;
  846. if ($arg[0] == '-') {
  847. $key = preg_replace('/^-+/', '', $arg);
  848. $sp = strpos($arg, '=');
  849. if ($sp > 0) {
  850. $key = substr($key, 0, $sp - 2);
  851. $value = substr($arg, $sp+1);
  852. }
  853. else if (strlen($_SERVER['argv'][$i+1]) && $_SERVER['argv'][$i+1][0] != '-') {
  854. $value = $_SERVER['argv'][++$i];
  855. }
  856. $args[$key] = is_string($value) ? preg_replace(array('/^["\']/', '/["\']$/'), '', $value) : $value;
  857. }
  858. else {
  859. $args[] = $arg;
  860. }
  861. if ($alias = $aliases[$key]) {
  862. $args[$alias] = $args[$key];
  863. }
  864. }
  865. return $args;
  866. }
  867. /**
  868. * Safe password prompt for command line
  869. * from http://blogs.sitepoint.com/2009/05/01/interactive-cli-password-prompt-in-php/
  870. *
  871. * @return string Password
  872. */
  873. public static function prompt_silent($prompt = "Password:")
  874. {
  875. if (preg_match('/^win/i', PHP_OS)) {
  876. $vbscript = sys_get_temp_dir() . 'prompt_password.vbs';
  877. $vbcontent = 'wscript.echo(InputBox("' . addslashes($prompt) . '", "", "password here"))';
  878. file_put_contents($vbscript, $vbcontent);
  879. $command = "cscript //nologo " . escapeshellarg($vbscript);
  880. $password = rtrim(shell_exec($command));
  881. unlink($vbscript);
  882. return $password;
  883. }
  884. else {
  885. $command = "/usr/bin/env bash -c 'echo OK'";
  886. if (rtrim(shell_exec($command)) !== 'OK') {
  887. echo $prompt;
  888. $pass = trim(fgets(STDIN));
  889. echo chr(8)."\r" . $prompt . str_repeat("*", strlen($pass))."\n";
  890. return $pass;
  891. }
  892. $command = "/usr/bin/env bash -c 'read -s -p \"" . addslashes($prompt) . "\" mypassword && echo \$mypassword'";
  893. $password = rtrim(shell_exec($command));
  894. echo "\n";
  895. return $password;
  896. }
  897. }
  898. /**
  899. * Find out if the string content means true or false
  900. *
  901. * @param string $str Input value
  902. *
  903. * @return boolean Boolean value
  904. */
  905. public static function get_boolean($str)
  906. {
  907. $str = strtolower($str);
  908. return !in_array($str, array('false', '0', 'no', 'off', 'nein', ''), true);
  909. }
  910. /**
  911. * OS-dependent absolute path detection
  912. */
  913. public static function is_absolute_path($path)
  914. {
  915. if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
  916. return (bool) preg_match('!^[a-z]:[\\\\/]!i', $path);
  917. }
  918. else {
  919. return $path[0] == DIRECTORY_SEPARATOR;
  920. }
  921. }
  922. }