rcube_utils.php 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295
  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. // remove HTML tags if not allowed
  273. if (!$allow_html) {
  274. $value = strip_tags($value);
  275. }
  276. $output_charset = is_object($OUTPUT) ? $OUTPUT->get_charset() : null;
  277. // remove invalid characters (#1488124)
  278. if ($output_charset == 'UTF-8') {
  279. $value = rcube_charset::clean($value);
  280. }
  281. // convert to internal charset
  282. if ($charset && $output_charset) {
  283. $value = rcube_charset::convert($value, $output_charset, $charset);
  284. }
  285. return $value;
  286. }
  287. /**
  288. * Convert array of request parameters (prefixed with _)
  289. * to a regular array with non-prefixed keys.
  290. *
  291. * @param int $mode Source to get value from (GPC)
  292. * @param string $ignore PCRE expression to skip parameters by name
  293. * @param boolean $allow_html Allow HTML tags in field value
  294. *
  295. * @return array Hash array with all request parameters
  296. */
  297. public static function request2param($mode = null, $ignore = 'task|action', $allow_html = false)
  298. {
  299. $out = array();
  300. $src = $mode == self::INPUT_GET ? $_GET : ($mode == self::INPUT_POST ? $_POST : $_REQUEST);
  301. foreach (array_keys($src) as $key) {
  302. $fname = $key[0] == '_' ? substr($key, 1) : $key;
  303. if ($ignore && !preg_match('/^(' . $ignore . ')$/', $fname)) {
  304. $out[$fname] = self::get_input_value($key, $mode, $allow_html);
  305. }
  306. }
  307. return $out;
  308. }
  309. /**
  310. * Convert the given string into a valid HTML identifier
  311. * Same functionality as done in app.js with rcube_webmail.html_identifier()
  312. */
  313. public static function html_identifier($str, $encode=false)
  314. {
  315. if ($encode) {
  316. return rtrim(strtr(base64_encode($str), '+/', '-_'), '=');
  317. }
  318. else {
  319. return asciiwords($str, true, '_');
  320. }
  321. }
  322. /**
  323. * Replace all css definitions with #container [def]
  324. * and remove css-inlined scripting, make position style safe
  325. *
  326. * @param string CSS source code
  327. * @param string Container ID to use as prefix
  328. * @param bool Allow remote content
  329. *
  330. * @return string Modified CSS source
  331. */
  332. public static function mod_css_styles($source, $container_id, $allow_remote = false)
  333. {
  334. $last_pos = 0;
  335. $replacements = new rcube_string_replacer;
  336. // ignore the whole block if evil styles are detected
  337. $source = self::xss_entity_decode($source);
  338. $stripped = preg_replace('/[^a-z\(:;]/i', '', $source);
  339. $evilexpr = 'expression|behavior|javascript:|import[^a]' . (!$allow_remote ? '|url\(' : '');
  340. if (preg_match("/$evilexpr/i", $stripped)) {
  341. return '/* evil! */';
  342. }
  343. $strict_url_regexp = '!url\s*\([ "\'](https?:)//[a-z0-9/._+-]+["\' ]\)!Uims';
  344. // cut out all contents between { and }
  345. while (($pos = strpos($source, '{', $last_pos)) && ($pos2 = strpos($source, '}', $pos))) {
  346. $nested = strpos($source, '{', $pos+1);
  347. if ($nested && $nested < $pos2) // when dealing with nested blocks (e.g. @media), take the inner one
  348. $pos = $nested;
  349. $length = $pos2 - $pos - 1;
  350. $styles = substr($source, $pos+1, $length);
  351. // Convert position:fixed to position:absolute (#5264)
  352. $styles = preg_replace('/position:[\s\r\n]*fixed/i', 'position: absolute', $styles);
  353. // check every line of a style block...
  354. if ($allow_remote) {
  355. $a_styles = preg_split('/;[\r\n]*/', $styles, -1, PREG_SPLIT_NO_EMPTY);
  356. foreach ($a_styles as $line) {
  357. $stripped = preg_replace('/[^a-z\(:;]/i', '', $line);
  358. // ... and only allow strict url() values
  359. if (stripos($stripped, 'url(') && !preg_match($strict_url_regexp, $line)) {
  360. $a_styles = array('/* evil! */');
  361. break;
  362. }
  363. }
  364. $styles = join(";\n", $a_styles);
  365. }
  366. $key = $replacements->add($styles);
  367. $repl = $replacements->get_replacement($key);
  368. $source = substr_replace($source, $repl, $pos+1, $length);
  369. $last_pos = $pos2 - ($length - strlen($repl));
  370. }
  371. // remove html comments and add #container to each tag selector.
  372. // also replace body definition because we also stripped off the <body> tag
  373. $source = preg_replace(
  374. array(
  375. '/(^\s*<\!--)|(-->\s*$)/m',
  376. '/(^\s*|,\s*|\}\s*)([a-z0-9\._#\*][a-z0-9\.\-_]*)/im',
  377. '/'.preg_quote($container_id, '/').'\s+body/i',
  378. ),
  379. array(
  380. '',
  381. "\\1#$container_id \\2",
  382. $container_id,
  383. ),
  384. $source);
  385. // put block contents back in
  386. $source = $replacements->resolve($source);
  387. return $source;
  388. }
  389. /**
  390. * Generate CSS classes from mimetype and filename extension
  391. *
  392. * @param string $mimetype Mimetype
  393. * @param string $filename Filename
  394. *
  395. * @return string CSS classes separated by space
  396. */
  397. public static function file2class($mimetype, $filename)
  398. {
  399. $mimetype = strtolower($mimetype);
  400. $filename = strtolower($filename);
  401. list($primary, $secondary) = explode('/', $mimetype);
  402. $classes = array($primary ?: 'unknown');
  403. if ($secondary) {
  404. $classes[] = $secondary;
  405. }
  406. if (preg_match('/\.([a-z0-9]+)$/', $filename, $m)) {
  407. if (!in_array($m[1], $classes)) {
  408. $classes[] = $m[1];
  409. }
  410. }
  411. return join(" ", $classes);
  412. }
  413. /**
  414. * Decode escaped entities used by known XSS exploits.
  415. * See http://downloads.securityfocus.com/vulnerabilities/exploits/26800.eml for examples
  416. *
  417. * @param string CSS content to decode
  418. *
  419. * @return string Decoded string
  420. */
  421. public static function xss_entity_decode($content)
  422. {
  423. $out = html_entity_decode(html_entity_decode($content));
  424. $out = preg_replace_callback('/\\\([0-9a-f]{4})/i',
  425. array(self, 'xss_entity_decode_callback'), $out);
  426. $out = preg_replace('#/\*.*\*/#Ums', '', $out);
  427. return $out;
  428. }
  429. /**
  430. * preg_replace_callback callback for xss_entity_decode
  431. *
  432. * @param array $matches Result from preg_replace_callback
  433. *
  434. * @return string Decoded entity
  435. */
  436. public static function xss_entity_decode_callback($matches)
  437. {
  438. return chr(hexdec($matches[1]));
  439. }
  440. /**
  441. * Check if we can process not exceeding memory_limit
  442. *
  443. * @param integer Required amount of memory
  444. *
  445. * @return boolean True if memory won't be exceeded, False otherwise
  446. */
  447. public static function mem_check($need)
  448. {
  449. $mem_limit = parse_bytes(ini_get('memory_limit'));
  450. $memory = function_exists('memory_get_usage') ? memory_get_usage() : 16*1024*1024; // safe value: 16MB
  451. return $mem_limit > 0 && $memory + $need > $mem_limit ? false : true;
  452. }
  453. /**
  454. * Check if working in SSL mode
  455. *
  456. * @param integer $port HTTPS port number
  457. * @param boolean $use_https Enables 'use_https' option checking
  458. *
  459. * @return boolean
  460. */
  461. public static function https_check($port=null, $use_https=true)
  462. {
  463. if (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) != 'off') {
  464. return true;
  465. }
  466. if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO'])
  467. && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https'
  468. && in_array($_SERVER['REMOTE_ADDR'], rcube::get_instance()->config->get('proxy_whitelist', array()))
  469. ) {
  470. return true;
  471. }
  472. if ($port && $_SERVER['SERVER_PORT'] == $port) {
  473. return true;
  474. }
  475. if ($use_https && rcube::get_instance()->config->get('use_https')) {
  476. return true;
  477. }
  478. return false;
  479. }
  480. /**
  481. * Replaces hostname variables.
  482. *
  483. * @param string $name Hostname
  484. * @param string $host Optional IMAP hostname
  485. *
  486. * @return string Hostname
  487. */
  488. public static function parse_host($name, $host = '')
  489. {
  490. if (!is_string($name)) {
  491. return $name;
  492. }
  493. // %n - host
  494. $n = preg_replace('/:\d+$/', '', $_SERVER['SERVER_NAME']);
  495. // %t - host name without first part, e.g. %n=mail.domain.tld, %t=domain.tld
  496. $t = preg_replace('/^[^\.]+\./', '', $n);
  497. // %d - domain name without first part
  498. $d = preg_replace('/^[^\.]+\./', '', $_SERVER['HTTP_HOST']);
  499. // %h - IMAP host
  500. $h = $_SESSION['storage_host'] ?: $host;
  501. // %z - IMAP domain without first part, e.g. %h=imap.domain.tld, %z=domain.tld
  502. $z = preg_replace('/^[^\.]+\./', '', $h);
  503. // %s - domain name after the '@' from e-mail address provided at login screen.
  504. // Returns FALSE if an invalid email is provided
  505. if (strpos($name, '%s') !== false) {
  506. $user_email = self::get_input_value('_user', self::INPUT_POST);
  507. $user_email = self::idn_convert($user_email, true);
  508. $matches = preg_match('/(.*)@([a-z0-9\.\-\[\]\:]+)/i', $user_email, $s);
  509. if ($matches < 1 || filter_var($s[1]."@".$s[2], FILTER_VALIDATE_EMAIL) === false) {
  510. return false;
  511. }
  512. }
  513. return str_replace(array('%n', '%t', '%d', '%h', '%z', '%s'), array($n, $t, $d, $h, $z, $s[2]), $name);
  514. }
  515. /**
  516. * Returns remote IP address and forwarded addresses if found
  517. *
  518. * @return string Remote IP address(es)
  519. */
  520. public static function remote_ip()
  521. {
  522. $address = $_SERVER['REMOTE_ADDR'];
  523. // append the NGINX X-Real-IP header, if set
  524. if (!empty($_SERVER['HTTP_X_REAL_IP'])) {
  525. $remote_ip[] = 'X-Real-IP: ' . $_SERVER['HTTP_X_REAL_IP'];
  526. }
  527. // append the X-Forwarded-For header, if set
  528. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  529. $remote_ip[] = 'X-Forwarded-For: ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
  530. }
  531. if (!empty($remote_ip)) {
  532. $address .= '(' . implode(',', $remote_ip) . ')';
  533. }
  534. return $address;
  535. }
  536. /**
  537. * Returns the real remote IP address
  538. *
  539. * @return string Remote IP address
  540. */
  541. public static function remote_addr()
  542. {
  543. // Check if any of the headers are set first to improve performance
  544. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) || !empty($_SERVER['HTTP_X_REAL_IP'])) {
  545. $proxy_whitelist = rcube::get_instance()->config->get('proxy_whitelist', array());
  546. if (in_array($_SERVER['REMOTE_ADDR'], $proxy_whitelist)) {
  547. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  548. foreach(array_reverse(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])) as $forwarded_ip) {
  549. if (!in_array($forwarded_ip, $proxy_whitelist)) {
  550. return $forwarded_ip;
  551. }
  552. }
  553. }
  554. if (!empty($_SERVER['HTTP_X_REAL_IP'])) {
  555. return $_SERVER['HTTP_X_REAL_IP'];
  556. }
  557. }
  558. }
  559. if (!empty($_SERVER['REMOTE_ADDR'])) {
  560. return $_SERVER['REMOTE_ADDR'];
  561. }
  562. return '';
  563. }
  564. /**
  565. * Read a specific HTTP request header.
  566. *
  567. * @param string $name Header name
  568. *
  569. * @return mixed Header value or null if not available
  570. */
  571. public static function request_header($name)
  572. {
  573. if (function_exists('getallheaders')) {
  574. $hdrs = array_change_key_case(getallheaders(), CASE_UPPER);
  575. $key = strtoupper($name);
  576. }
  577. else {
  578. $key = 'HTTP_' . strtoupper(strtr($name, '-', '_'));
  579. $hdrs = array_change_key_case($_SERVER, CASE_UPPER);
  580. }
  581. return $hdrs[$key];
  582. }
  583. /**
  584. * Explode quoted string
  585. *
  586. * @param string Delimiter expression string for preg_match()
  587. * @param string Input string
  588. *
  589. * @return array String items
  590. */
  591. public static function explode_quoted_string($delimiter, $string)
  592. {
  593. $result = array();
  594. $strlen = strlen($string);
  595. for ($q=$p=$i=0; $i < $strlen; $i++) {
  596. if ($string[$i] == "\"" && $string[$i-1] != "\\") {
  597. $q = $q ? false : true;
  598. }
  599. else if (!$q && preg_match("/$delimiter/", $string[$i])) {
  600. $result[] = substr($string, $p, $i - $p);
  601. $p = $i + 1;
  602. }
  603. }
  604. $result[] = (string) substr($string, $p);
  605. return $result;
  606. }
  607. /**
  608. * Improved equivalent to strtotime()
  609. *
  610. * @param string $date Date string
  611. * @param DateTimeZone $timezone Timezone to use for DateTime object
  612. *
  613. * @return int Unix timestamp
  614. */
  615. public static function strtotime($date, $timezone = null)
  616. {
  617. $date = self::clean_datestr($date);
  618. $tzname = $timezone ? ' ' . $timezone->getName() : '';
  619. // unix timestamp
  620. if (is_numeric($date)) {
  621. return (int) $date;
  622. }
  623. // if date parsing fails, we have a date in non-rfc format.
  624. // remove token from the end and try again
  625. while ((($ts = @strtotime($date . $tzname)) === false) || ($ts < 0)) {
  626. $d = explode(' ', $date);
  627. array_pop($d);
  628. if (!$d) {
  629. break;
  630. }
  631. $date = implode(' ', $d);
  632. }
  633. return (int) $ts;
  634. }
  635. /**
  636. * Date parsing function that turns the given value into a DateTime object
  637. *
  638. * @param string $date Date string
  639. * @param DateTimeZone $timezone Timezone to use for DateTime object
  640. *
  641. * @return DateTime instance or false on failure
  642. */
  643. public static function anytodatetime($date, $timezone = null)
  644. {
  645. if ($date instanceof DateTime) {
  646. return $date;
  647. }
  648. $dt = false;
  649. $date = self::clean_datestr($date);
  650. // try to parse string with DateTime first
  651. if (!empty($date)) {
  652. try {
  653. $dt = $timezone ? new DateTime($date, $timezone) : new DateTime($date);
  654. }
  655. catch (Exception $e) {
  656. // ignore
  657. }
  658. }
  659. // try our advanced strtotime() method
  660. if (!$dt && ($timestamp = self::strtotime($date, $timezone))) {
  661. try {
  662. $dt = new DateTime("@".$timestamp);
  663. if ($timezone) {
  664. $dt->setTimezone($timezone);
  665. }
  666. }
  667. catch (Exception $e) {
  668. // ignore
  669. }
  670. }
  671. return $dt;
  672. }
  673. /**
  674. * Clean up date string for strtotime() input
  675. *
  676. * @param string $date Date string
  677. *
  678. * @return string Date string
  679. */
  680. public static function clean_datestr($date)
  681. {
  682. $date = trim($date);
  683. // check for MS Outlook vCard date format YYYYMMDD
  684. if (preg_match('/^([12][90]\d\d)([01]\d)([0123]\d)$/', $date, $m)) {
  685. return sprintf('%04d-%02d-%02d 00:00:00', intval($m[1]), intval($m[2]), intval($m[3]));
  686. }
  687. // Clean malformed data
  688. $date = preg_replace(
  689. array(
  690. '/GMT\s*([+-][0-9]+)/', // support non-standard "GMTXXXX" literal
  691. '/[^a-z0-9\x20\x09:+-\/]/i', // remove any invalid characters
  692. '/\s*(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s*/i', // remove weekday names
  693. ),
  694. array(
  695. '\\1',
  696. '',
  697. '',
  698. ), $date);
  699. $date = trim($date);
  700. // try to fix dd/mm vs. mm/dd discrepancy, we can't do more here
  701. if (preg_match('/^(\d{1,2})[.\/-](\d{1,2})[.\/-](\d{4})(\s.*)?$/', $date, $m)) {
  702. $mdy = $m[2] > 12 && $m[1] <= 12;
  703. $day = $mdy ? $m[2] : $m[1];
  704. $month = $mdy ? $m[1] : $m[2];
  705. $date = sprintf('%04d-%02d-%02d%s', $m[3], $month, $day, $m[4] ?: ' 00:00:00');
  706. }
  707. // I've found that YYYY.MM.DD is recognized wrong, so here's a fix
  708. else if (preg_match('/^(\d{4})\.(\d{1,2})\.(\d{1,2})(\s.*)?$/', $date, $m)) {
  709. $date = sprintf('%04d-%02d-%02d%s', $m[1], $m[2], $m[3], $m[4] ?: ' 00:00:00');
  710. }
  711. return $date;
  712. }
  713. /**
  714. * Turns the given date-only string in defined format into YYYY-MM-DD format.
  715. *
  716. * Supported formats: 'Y/m/d', 'Y.m.d', 'd-m-Y', 'd/m/Y', 'd.m.Y', 'j.n.Y'
  717. *
  718. * @param string $date Date string
  719. * @param string $format Input date format
  720. *
  721. * @return strin Date string in YYYY-MM-DD format, or the original string
  722. * if format is not supported
  723. */
  724. public static function format_datestr($date, $format)
  725. {
  726. $format_items = preg_split('/[.-\/\\\\]/', $format);
  727. $date_items = preg_split('/[.-\/\\\\]/', $date);
  728. $iso_format = '%04d-%02d-%02d';
  729. if (count($format_items) == 3 && count($date_items) == 3) {
  730. if ($format_items[0] == 'Y') {
  731. $date = sprintf($iso_format, $date_items[0], $date_items[1], $date_items[2]);
  732. }
  733. else if (strpos('dj', $format_items[0]) !== false) {
  734. $date = sprintf($iso_format, $date_items[2], $date_items[1], $date_items[0]);
  735. }
  736. else if (strpos('mn', $format_items[0]) !== false) {
  737. $date = sprintf($iso_format, $date_items[2], $date_items[0], $date_items[1]);
  738. }
  739. }
  740. return $date;
  741. }
  742. /*
  743. * Idn_to_ascii wrapper.
  744. * Intl/Idn modules version of this function doesn't work with e-mail address
  745. */
  746. public static function idn_to_ascii($str)
  747. {
  748. return self::idn_convert($str, true);
  749. }
  750. /*
  751. * Idn_to_ascii wrapper.
  752. * Intl/Idn modules version of this function doesn't work with e-mail address
  753. */
  754. public static function idn_to_utf8($str)
  755. {
  756. return self::idn_convert($str, false);
  757. }
  758. public static function idn_convert($input, $is_utf = false)
  759. {
  760. if ($at = strpos($input, '@')) {
  761. $user = substr($input, 0, $at);
  762. $domain = substr($input, $at+1);
  763. }
  764. else {
  765. $domain = $input;
  766. }
  767. $domain = $is_utf ? idn_to_ascii($domain) : idn_to_utf8($domain);
  768. if ($domain === false) {
  769. return '';
  770. }
  771. return $at ? $user . '@' . $domain : $domain;
  772. }
  773. /**
  774. * Split the given string into word tokens
  775. *
  776. * @param string Input to tokenize
  777. * @param integer Minimum length of a single token
  778. * @return array List of tokens
  779. */
  780. public static function tokenize_string($str, $minlen = 2)
  781. {
  782. $expr = array('/[\s;,"\'\/+-]+/ui', '/(\d)[-.\s]+(\d)/u');
  783. $repl = array(' ', '\\1\\2');
  784. if ($minlen > 1) {
  785. $minlen--;
  786. $expr[] = "/(^|\s+)\w{1,$minlen}(\s+|$)/u";
  787. $repl[] = ' ';
  788. }
  789. return array_filter(explode(" ", preg_replace($expr, $repl, $str)));
  790. }
  791. /**
  792. * Normalize the given string for fulltext search.
  793. * Currently only optimized for ISO-8859-1 and ISO-8859-2 characters; to be extended
  794. *
  795. * @param string Input string (UTF-8)
  796. * @param boolean True to return list of words as array
  797. * @param integer Minimum length of tokens
  798. *
  799. * @return mixed Normalized string or a list of normalized tokens
  800. */
  801. public static function normalize_string($str, $as_array = false, $minlen = 2)
  802. {
  803. // replace 4-byte unicode characters with '?' character,
  804. // these are not supported in default utf-8 charset on mysql,
  805. // the chance we'd need them in searching is very low
  806. $str = preg_replace('/('
  807. . '\xF0[\x90-\xBF][\x80-\xBF]{2}'
  808. . '|[\xF1-\xF3][\x80-\xBF]{3}'
  809. . '|\xF4[\x80-\x8F][\x80-\xBF]{2}'
  810. . ')/', '?', $str);
  811. // split by words
  812. $arr = self::tokenize_string($str, $minlen);
  813. // detect character set
  814. if (utf8_encode(utf8_decode($str)) == $str) {
  815. // ISO-8859-1 (or ASCII)
  816. preg_match_all('/./u', 'äâàåáãæçéêëèïîìíñöôòøõóüûùúýÿ', $keys);
  817. preg_match_all('/./', 'aaaaaaaceeeeiiiinoooooouuuuyy', $values);
  818. $mapping = array_combine($keys[0], $values[0]);
  819. $mapping = array_merge($mapping, array('ß' => 'ss', 'ae' => 'a', 'oe' => 'o', 'ue' => 'u'));
  820. }
  821. else if (rcube_charset::convert(rcube_charset::convert($str, 'UTF-8', 'ISO-8859-2'), 'ISO-8859-2', 'UTF-8') == $str) {
  822. // ISO-8859-2
  823. preg_match_all('/./u', 'ąáâäćçčéęëěíîłľĺńňóôöŕřśšşťţůúűüźžżý', $keys);
  824. preg_match_all('/./', 'aaaaccceeeeiilllnnooorrsssttuuuuzzzy', $values);
  825. $mapping = array_combine($keys[0], $values[0]);
  826. $mapping = array_merge($mapping, array('ß' => 'ss', 'ae' => 'a', 'oe' => 'o', 'ue' => 'u'));
  827. }
  828. foreach ($arr as $i => $part) {
  829. $part = mb_strtolower($part);
  830. if (!empty($mapping)) {
  831. $part = strtr($part, $mapping);
  832. }
  833. $arr[$i] = $part;
  834. }
  835. return $as_array ? $arr : join(" ", $arr);
  836. }
  837. /**
  838. * Compare two strings for matching words (order not relevant)
  839. *
  840. * @param string Haystack
  841. * @param string Needle
  842. *
  843. * @return boolean True if match, False otherwise
  844. */
  845. public static function words_match($haystack, $needle)
  846. {
  847. $a_needle = self::tokenize_string($needle, 1);
  848. $_haystack = join(" ", self::tokenize_string($haystack, 1));
  849. $valid = strlen($_haystack) > 0;
  850. $hits = 0;
  851. foreach ($a_needle as $w) {
  852. if ($valid) {
  853. if (stripos($_haystack, $w) !== false) {
  854. $hits++;
  855. }
  856. }
  857. else if (stripos($haystack, $w) !== false) {
  858. $hits++;
  859. }
  860. }
  861. return $hits >= count($a_needle);
  862. }
  863. /**
  864. * Parse commandline arguments into a hash array
  865. *
  866. * @param array $aliases Argument alias names
  867. *
  868. * @return array Argument values hash
  869. */
  870. public static function get_opt($aliases = array())
  871. {
  872. $args = array();
  873. $bool = array();
  874. // find boolean (no value) options
  875. foreach ($aliases as $key => $alias) {
  876. if ($pos = strpos($alias, ':')) {
  877. $aliases[$key] = substr($alias, 0, $pos);
  878. $bool[] = $key;
  879. $bool[] = $aliases[$key];
  880. }
  881. }
  882. for ($i=1; $i < count($_SERVER['argv']); $i++) {
  883. $arg = $_SERVER['argv'][$i];
  884. $value = true;
  885. $key = null;
  886. if ($arg[0] == '-') {
  887. $key = preg_replace('/^-+/', '', $arg);
  888. $sp = strpos($arg, '=');
  889. if ($sp > 0) {
  890. $key = substr($key, 0, $sp - 2);
  891. $value = substr($arg, $sp+1);
  892. }
  893. else if (in_array($key, $bool)) {
  894. $value = true;
  895. }
  896. else if (strlen($_SERVER['argv'][$i+1]) && $_SERVER['argv'][$i+1][0] != '-') {
  897. $value = $_SERVER['argv'][++$i];
  898. }
  899. $args[$key] = is_string($value) ? preg_replace(array('/^["\']/', '/["\']$/'), '', $value) : $value;
  900. }
  901. else {
  902. $args[] = $arg;
  903. }
  904. if ($alias = $aliases[$key]) {
  905. $args[$alias] = $args[$key];
  906. }
  907. }
  908. return $args;
  909. }
  910. /**
  911. * Safe password prompt for command line
  912. * from http://blogs.sitepoint.com/2009/05/01/interactive-cli-password-prompt-in-php/
  913. *
  914. * @return string Password
  915. */
  916. public static function prompt_silent($prompt = "Password:")
  917. {
  918. if (preg_match('/^win/i', PHP_OS)) {
  919. $vbscript = sys_get_temp_dir() . 'prompt_password.vbs';
  920. $vbcontent = 'wscript.echo(InputBox("' . addslashes($prompt) . '", "", "password here"))';
  921. file_put_contents($vbscript, $vbcontent);
  922. $command = "cscript //nologo " . escapeshellarg($vbscript);
  923. $password = rtrim(shell_exec($command));
  924. unlink($vbscript);
  925. return $password;
  926. }
  927. else {
  928. $command = "/usr/bin/env bash -c 'echo OK'";
  929. if (rtrim(shell_exec($command)) !== 'OK') {
  930. echo $prompt;
  931. $pass = trim(fgets(STDIN));
  932. echo chr(8)."\r" . $prompt . str_repeat("*", strlen($pass))."\n";
  933. return $pass;
  934. }
  935. $command = "/usr/bin/env bash -c 'read -s -p \"" . addslashes($prompt) . "\" mypassword && echo \$mypassword'";
  936. $password = rtrim(shell_exec($command));
  937. echo "\n";
  938. return $password;
  939. }
  940. }
  941. /**
  942. * Find out if the string content means true or false
  943. *
  944. * @param string $str Input value
  945. *
  946. * @return boolean Boolean value
  947. */
  948. public static function get_boolean($str)
  949. {
  950. $str = strtolower($str);
  951. return !in_array($str, array('false', '0', 'no', 'off', 'nein', ''), true);
  952. }
  953. /**
  954. * OS-dependent absolute path detection
  955. */
  956. public static function is_absolute_path($path)
  957. {
  958. if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
  959. return (bool) preg_match('!^[a-z]:[\\\\/]!i', $path);
  960. }
  961. else {
  962. return $path[0] == '/';
  963. }
  964. }
  965. /**
  966. * Resolve relative URL
  967. *
  968. * @param string $url Relative URL
  969. *
  970. * @return string Absolute URL
  971. */
  972. public static function resolve_url($url)
  973. {
  974. // prepend protocol://hostname:port
  975. if (!preg_match('|^https?://|', $url)) {
  976. $schema = 'http';
  977. $default_port = 80;
  978. if (self::https_check()) {
  979. $schema = 'https';
  980. $default_port = 443;
  981. }
  982. $prefix = $schema . '://' . preg_replace('/:\d+$/', '', $_SERVER['HTTP_HOST']);
  983. if ($_SERVER['SERVER_PORT'] != $default_port) {
  984. $prefix .= ':' . $_SERVER['SERVER_PORT'];
  985. }
  986. $url = $prefix . ($url[0] == '/' ? '' : '/') . $url;
  987. }
  988. return $url;
  989. }
  990. /**
  991. * Generate a random string
  992. *
  993. * @param int $length String length
  994. * @param bool $raw Return RAW data instead of ascii
  995. *
  996. * @return string The generated random string
  997. */
  998. public static function random_bytes($length, $raw = false)
  999. {
  1000. // Use PHP7 true random generator
  1001. if (function_exists('random_bytes')) {
  1002. // random_bytes() can throw an Error/TypeError/Exception in some cases
  1003. try {
  1004. $random = random_bytes($length);
  1005. }
  1006. catch (Throwable $e) {}
  1007. }
  1008. if (!$random) {
  1009. $random = openssl_random_pseudo_bytes($length);
  1010. }
  1011. if ($raw) {
  1012. return $random;
  1013. }
  1014. $random = self::bin2ascii($random);
  1015. // truncate to the specified size...
  1016. if ($length < strlen($random)) {
  1017. $random = substr($random, 0, $length);
  1018. }
  1019. return $random;
  1020. }
  1021. /**
  1022. * Convert binary data into readable form (containing a-zA-Z0-9 characters)
  1023. *
  1024. * @param string $input Binary input
  1025. *
  1026. * @return string Readable output
  1027. */
  1028. public static function bin2ascii($input)
  1029. {
  1030. // Above method returns "hexits".
  1031. // Based on bin_to_readable() function in ext/session/session.c.
  1032. // Note: removed ",-" characters from hextab
  1033. $hextab = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  1034. $nbits = 6; // can be 4, 5 or 6
  1035. $length = strlen($input);
  1036. $result = '';
  1037. $char = 0;
  1038. $i = 0;
  1039. $have = 0;
  1040. $mask = (1 << $nbits) - 1;
  1041. while (true) {
  1042. if ($have < $nbits) {
  1043. if ($i < $length) {
  1044. $char |= ord($input[$i++]) << $have;
  1045. $have += 8;
  1046. }
  1047. else if (!$have) {
  1048. break;
  1049. }
  1050. else {
  1051. $have = $nbits;
  1052. }
  1053. }
  1054. // consume nbits
  1055. $result .= $hextab[$char & $mask];
  1056. $char >>= $nbits;
  1057. $have -= $nbits;
  1058. }
  1059. return $result;
  1060. }
  1061. /**
  1062. * Format current date according to specified format.
  1063. * This method supports microseconds (u).
  1064. *
  1065. * @param string $format Date format (default: 'd-M-Y H:i:s O')
  1066. *
  1067. * @return string Formatted date
  1068. */
  1069. public static function date_format($format = null)
  1070. {
  1071. if (empty($format)) {
  1072. $format = 'd-M-Y H:i:s O';
  1073. }
  1074. if (strpos($format, 'u') !== false) {
  1075. $dt = number_format(microtime(true), 6, '.', '');
  1076. $dt .= '.' . date_default_timezone_get();
  1077. if ($date = date_create_from_format('U.u.e', $dt)) {
  1078. return $date->format($format);
  1079. }
  1080. }
  1081. return date($format);
  1082. }
  1083. /**
  1084. * Parses socket options and returns options for specified hostname.
  1085. *
  1086. * @param array &$options Configured socket options
  1087. * @param string $host Hostname
  1088. */
  1089. public static function parse_socket_options(&$options, $host = null)
  1090. {
  1091. if (empty($host) || empty($options)) {
  1092. return $options;
  1093. }
  1094. // get rid of schema and port from the hostname
  1095. $host_url = parse_url($host);
  1096. if (isset($host_url['host'])) {
  1097. $host = $host_url['host'];
  1098. }
  1099. // find per-host options
  1100. if (array_key_exists($host, $options)) {
  1101. $options = $options[$host];
  1102. }
  1103. }
  1104. /**
  1105. * Get maximum upload size
  1106. *
  1107. * @return int Maximum size in bytes
  1108. */
  1109. public static function max_upload_size()
  1110. {
  1111. // find max filesize value
  1112. $max_filesize = parse_bytes(ini_get('upload_max_filesize'));
  1113. $max_postsize = parse_bytes(ini_get('post_max_size'));
  1114. if ($max_postsize && $max_postsize < $max_filesize) {
  1115. $max_filesize = $max_postsize;
  1116. }
  1117. return $max_filesize;
  1118. }
  1119. }