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 42KB

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