PageRenderTime 54ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/program/include/rcube_utils.php

https://github.com/netconstructor/roundcubemail
PHP | 886 lines | 615 code | 88 blank | 183 comment | 103 complexity | 4739ed9201eec5e9fa8754f99322f0f8 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.1
  1. <?php
  2. /*
  3. +-----------------------------------------------------------------------+
  4. | program/include/rcube_utils.php |
  5. | |
  6. | This file is part of the Roundcube Webmail client |
  7. | Copyright (C) 2008-2012, The Roundcube Dev Team |
  8. | Copyright (C) 2011-2012, Kolab Systems AG |
  9. | |
  10. | Licensed under the GNU General Public License version 3 or |
  11. | any later version with exceptions for skins & plugins. |
  12. | See the README file for a full license statement. |
  13. | |
  14. | PURPOSE: |
  15. | Utility class providing common functions |
  16. +-----------------------------------------------------------------------+
  17. | Author: Thomas Bruederli <roundcube@gmail.com> |
  18. | Author: Aleksander Machniak <alec@alec.pl> |
  19. +-----------------------------------------------------------------------+
  20. */
  21. /**
  22. * Utility class providing common functions
  23. *
  24. * @package Framework
  25. * @subpackage Utils
  26. */
  27. class rcube_utils
  28. {
  29. // define constants for input reading
  30. const INPUT_GET = 0x0101;
  31. const INPUT_POST = 0x0102;
  32. const INPUT_GPC = 0x0103;
  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 (sizeof($domain_array) < 2) {
  91. return false;
  92. }
  93. foreach ($domain_array as $part) {
  94. if (!preg_match('/^(([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. if (preg_match('/[^a-zA-Z]/', array_pop($domain_array))) {
  100. return false;
  101. }
  102. $rcube = rcube::get_instance();
  103. if (!$dns_check || !$rcube->config->get('email_dns_check')) {
  104. return true;
  105. }
  106. if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' && version_compare(PHP_VERSION, '5.3.0', '<')) {
  107. $lookup = array();
  108. @exec("nslookup -type=MX " . escapeshellarg($domain_part) . " 2>&1", $lookup);
  109. foreach ($lookup as $line) {
  110. if (strpos($line, 'MX preference')) {
  111. return true;
  112. }
  113. }
  114. return false;
  115. }
  116. // find MX record(s)
  117. if (getmxrr($domain_part, $mx_records)) {
  118. return true;
  119. }
  120. // find any DNS record
  121. if (checkdnsrr($domain_part, 'ANY')) {
  122. return true;
  123. }
  124. }
  125. return false;
  126. }
  127. /**
  128. * Validates IPv4 or IPv6 address
  129. *
  130. * @param string $ip IP address in v4 or v6 format
  131. *
  132. * @return bool True if the address is valid
  133. */
  134. public static function check_ip($ip)
  135. {
  136. // IPv6, but there's no build-in IPv6 support
  137. if (strpos($ip, ':') !== false && !defined('AF_INET6')) {
  138. $parts = explode(':', $domain_part);
  139. $count = count($parts);
  140. if ($count > 8 || $count < 2) {
  141. return false;
  142. }
  143. foreach ($parts as $idx => $part) {
  144. $length = strlen($part);
  145. if (!$length) {
  146. // there can be only one ::
  147. if ($found_empty) {
  148. return false;
  149. }
  150. $found_empty = true;
  151. }
  152. // last part can be an IPv4 address
  153. else if ($idx == $count - 1) {
  154. if (!preg_match('/^[0-9a-f]{1,4}$/i', $part)) {
  155. return @inet_pton($part) !== false;
  156. }
  157. }
  158. else if (!preg_match('/^[0-9a-f]{1,4}$/i', $part)) {
  159. return false;
  160. }
  161. }
  162. return true;
  163. }
  164. return @inet_pton($ip) !== false;
  165. }
  166. /**
  167. * Check whether the HTTP referer matches the current request
  168. *
  169. * @return boolean True if referer is the same host+path, false if not
  170. */
  171. public static function check_referer()
  172. {
  173. $uri = parse_url($_SERVER['REQUEST_URI']);
  174. $referer = parse_url(self::request_header('Referer'));
  175. return $referer['host'] == self::request_header('Host') && $referer['path'] == $uri['path'];
  176. }
  177. /**
  178. * Replacing specials characters to a specific encoding type
  179. *
  180. * @param string Input string
  181. * @param string Encoding type: text|html|xml|js|url
  182. * @param string Replace mode for tags: show|replace|remove
  183. * @param boolean Convert newlines
  184. *
  185. * @return string The quoted string
  186. */
  187. public static function rep_specialchars_output($str, $enctype = '', $mode = '', $newlines = true)
  188. {
  189. static $html_encode_arr = false;
  190. static $js_rep_table = false;
  191. static $xml_rep_table = false;
  192. if (!is_string($str)) {
  193. $str = strval($str);
  194. }
  195. // encode for HTML output
  196. if ($enctype == 'html') {
  197. if (!$html_encode_arr) {
  198. $html_encode_arr = get_html_translation_table(HTML_SPECIALCHARS);
  199. unset($html_encode_arr['?']);
  200. }
  201. $encode_arr = $html_encode_arr;
  202. // don't replace quotes and html tags
  203. if ($mode == 'show' || $mode == '') {
  204. $ltpos = strpos($str, '<');
  205. if ($ltpos !== false && strpos($str, '>', $ltpos) !== false) {
  206. unset($encode_arr['"']);
  207. unset($encode_arr['<']);
  208. unset($encode_arr['>']);
  209. unset($encode_arr['&']);
  210. }
  211. }
  212. else if ($mode == 'remove') {
  213. $str = strip_tags($str);
  214. }
  215. $out = strtr($str, $encode_arr);
  216. return $newlines ? nl2br($out) : $out;
  217. }
  218. // if the replace tables for XML and JS are not yet defined
  219. if ($js_rep_table === false) {
  220. $js_rep_table = $xml_rep_table = array();
  221. $xml_rep_table['&'] = '&amp;';
  222. // can be increased to support more charsets
  223. for ($c=160; $c<256; $c++) {
  224. $xml_rep_table[chr($c)] = "&#$c;";
  225. }
  226. $xml_rep_table['"'] = '&quot;';
  227. $js_rep_table['"'] = '\\"';
  228. $js_rep_table["'"] = "\\'";
  229. $js_rep_table["\\"] = "\\\\";
  230. // Unicode line and paragraph separators (#1486310)
  231. $js_rep_table[chr(hexdec(E2)).chr(hexdec(80)).chr(hexdec(A8))] = '&#8232;';
  232. $js_rep_table[chr(hexdec(E2)).chr(hexdec(80)).chr(hexdec(A9))] = '&#8233;';
  233. }
  234. // encode for javascript use
  235. if ($enctype == 'js') {
  236. return preg_replace(array("/\r?\n/", "/\r/", '/<\\//'), array('\n', '\n', '<\\/'), strtr($str, $js_rep_table));
  237. }
  238. // encode for plaintext
  239. if ($enctype == 'text') {
  240. return str_replace("\r\n", "\n", $mode=='remove' ? strip_tags($str) : $str);
  241. }
  242. if ($enctype == 'url') {
  243. return rawurlencode($str);
  244. }
  245. // encode for XML
  246. if ($enctype == 'xml') {
  247. return strtr($str, $xml_rep_table);
  248. }
  249. // no encoding given -> return original string
  250. return $str;
  251. }
  252. /**
  253. * Read input value and convert it for internal use
  254. * Performs stripslashes() and charset conversion if necessary
  255. *
  256. * @param string Field name to read
  257. * @param int Source to get value from (GPC)
  258. * @param boolean Allow HTML tags in field value
  259. * @param string Charset to convert into
  260. *
  261. * @return string Field value or NULL if not available
  262. */
  263. public static function get_input_value($fname, $source, $allow_html=FALSE, $charset=NULL)
  264. {
  265. $value = NULL;
  266. if ($source == self::INPUT_GET) {
  267. if (isset($_GET[$fname])) {
  268. $value = $_GET[$fname];
  269. }
  270. }
  271. else if ($source == self::INPUT_POST) {
  272. if (isset($_POST[$fname])) {
  273. $value = $_POST[$fname];
  274. }
  275. }
  276. else if ($source == self::INPUT_GPC) {
  277. if (isset($_POST[$fname])) {
  278. $value = $_POST[$fname];
  279. }
  280. else if (isset($_GET[$fname])) {
  281. $value = $_GET[$fname];
  282. }
  283. else if (isset($_COOKIE[$fname])) {
  284. $value = $_COOKIE[$fname];
  285. }
  286. }
  287. return self::parse_input_value($value, $allow_html, $charset);
  288. }
  289. /**
  290. * Parse/validate input value. See self::get_input_value()
  291. * Performs stripslashes() and charset conversion if necessary
  292. *
  293. * @param string Input value
  294. * @param boolean Allow HTML tags in field value
  295. * @param string Charset to convert into
  296. *
  297. * @return string Parsed value
  298. */
  299. public static function parse_input_value($value, $allow_html=FALSE, $charset=NULL)
  300. {
  301. global $OUTPUT;
  302. if (empty($value)) {
  303. return $value;
  304. }
  305. if (is_array($value)) {
  306. foreach ($value as $idx => $val) {
  307. $value[$idx] = self::parse_input_value($val, $allow_html, $charset);
  308. }
  309. return $value;
  310. }
  311. // strip single quotes if magic_quotes_sybase is enabled
  312. if (ini_get('magic_quotes_sybase')) {
  313. $value = str_replace("''", "'", $value);
  314. }
  315. // strip slashes if magic_quotes enabled
  316. else if (get_magic_quotes_gpc() || get_magic_quotes_runtime()) {
  317. $value = stripslashes($value);
  318. }
  319. // remove HTML tags if not allowed
  320. if (!$allow_html) {
  321. $value = strip_tags($value);
  322. }
  323. $output_charset = is_object($OUTPUT) ? $OUTPUT->get_charset() : null;
  324. // remove invalid characters (#1488124)
  325. if ($output_charset == 'UTF-8') {
  326. $value = rcube_charset::clean($value);
  327. }
  328. // convert to internal charset
  329. if ($charset && $output_charset) {
  330. $value = rcube_charset::convert($value, $output_charset, $charset);
  331. }
  332. return $value;
  333. }
  334. /**
  335. * Convert array of request parameters (prefixed with _)
  336. * to a regular array with non-prefixed keys.
  337. *
  338. * @param int $mode Source to get value from (GPC)
  339. * @param string $ignore PCRE expression to skip parameters by name
  340. *
  341. * @return array Hash array with all request parameters
  342. */
  343. public static function request2param($mode = null, $ignore = 'task|action')
  344. {
  345. $out = array();
  346. $src = $mode == self::INPUT_GET ? $_GET : ($mode == self::INPUT_POST ? $_POST : $_REQUEST);
  347. foreach ($src as $key => $value) {
  348. $fname = $key[0] == '_' ? substr($key, 1) : $key;
  349. if ($ignore && !preg_match('/^(' . $ignore . ')$/', $fname)) {
  350. $out[$fname] = self::get_input_value($key, $mode);
  351. }
  352. }
  353. return $out;
  354. }
  355. /**
  356. * Convert the given string into a valid HTML identifier
  357. * Same functionality as done in app.js with rcube_webmail.html_identifier()
  358. */
  359. public static function html_identifier($str, $encode=false)
  360. {
  361. if ($encode) {
  362. return rtrim(strtr(base64_encode($str), '+/', '-_'), '=');
  363. }
  364. else {
  365. return asciiwords($str, true, '_');
  366. }
  367. }
  368. /**
  369. * Create an edit field for inclusion on a form
  370. *
  371. * @param string col field name
  372. * @param string value field value
  373. * @param array attrib HTML element attributes for field
  374. * @param string type HTML element type (default 'text')
  375. *
  376. * @return string HTML field definition
  377. */
  378. public static function get_edit_field($col, $value, $attrib, $type = 'text')
  379. {
  380. static $colcounts = array();
  381. $fname = '_'.$col;
  382. $attrib['name'] = $fname . ($attrib['array'] ? '[]' : '');
  383. $attrib['class'] = trim($attrib['class'] . ' ff_' . $col);
  384. if ($type == 'checkbox') {
  385. $attrib['value'] = '1';
  386. $input = new html_checkbox($attrib);
  387. }
  388. else if ($type == 'textarea') {
  389. $attrib['cols'] = $attrib['size'];
  390. $input = new html_textarea($attrib);
  391. }
  392. else if ($type == 'select') {
  393. $input = new html_select($attrib);
  394. $input->add('---', '');
  395. $input->add(array_values($attrib['options']), array_keys($attrib['options']));
  396. }
  397. else if ($attrib['type'] == 'password') {
  398. $input = new html_passwordfield($attrib);
  399. }
  400. else {
  401. if ($attrib['type'] != 'text' && $attrib['type'] != 'hidden') {
  402. $attrib['type'] = 'text';
  403. }
  404. $input = new html_inputfield($attrib);
  405. }
  406. // use value from post
  407. if (isset($_POST[$fname])) {
  408. $postvalue = self::get_input_value($fname, self::INPUT_POST, true);
  409. $value = $attrib['array'] ? $postvalue[intval($colcounts[$col]++)] : $postvalue;
  410. }
  411. $out = $input->show($value);
  412. return $out;
  413. }
  414. /**
  415. * Replace all css definitions with #container [def]
  416. * and remove css-inlined scripting
  417. *
  418. * @param string CSS source code
  419. * @param string Container ID to use as prefix
  420. *
  421. * @return string Modified CSS source
  422. */
  423. public static function mod_css_styles($source, $container_id, $allow_remote=false)
  424. {
  425. $last_pos = 0;
  426. $replacements = new rcube_string_replacer;
  427. // ignore the whole block if evil styles are detected
  428. $source = self::xss_entity_decode($source);
  429. $stripped = preg_replace('/[^a-z\(:;]/i', '', $source);
  430. $evilexpr = 'expression|behavior|javascript:|import[^a]' . (!$allow_remote ? '|url\(' : '');
  431. if (preg_match("/$evilexpr/i", $stripped)) {
  432. return '/* evil! */';
  433. }
  434. // cut out all contents between { and }
  435. while (($pos = strpos($source, '{', $last_pos)) && ($pos2 = strpos($source, '}', $pos))) {
  436. $styles = substr($source, $pos+1, $pos2-($pos+1));
  437. // check every line of a style block...
  438. if ($allow_remote) {
  439. $a_styles = preg_split('/;[\r\n]*/', $styles, -1, PREG_SPLIT_NO_EMPTY);
  440. foreach ($a_styles as $line) {
  441. $stripped = preg_replace('/[^a-z\(:;]/i', '', $line);
  442. // ... and only allow strict url() values
  443. $regexp = '!url\s*\([ "\'](https?:)//[a-z0-9/._+-]+["\' ]\)!Uims';
  444. if (stripos($stripped, 'url(') && !preg_match($regexp, $line)) {
  445. $a_styles = array('/* evil! */');
  446. break;
  447. }
  448. }
  449. $styles = join(";\n", $a_styles);
  450. }
  451. $key = $replacements->add($styles);
  452. $source = substr($source, 0, $pos+1)
  453. . $replacements->get_replacement($key)
  454. . substr($source, $pos2, strlen($source)-$pos2);
  455. $last_pos = $pos+2;
  456. }
  457. // remove html comments and add #container to each tag selector.
  458. // also replace body definition because we also stripped off the <body> tag
  459. $styles = preg_replace(
  460. array(
  461. '/(^\s*<!--)|(-->\s*$)/',
  462. '/(^\s*|,\s*|\}\s*)([a-z0-9\._#\*][a-z0-9\.\-_]*)/im',
  463. '/'.preg_quote($container_id, '/').'\s+body/i',
  464. ),
  465. array(
  466. '',
  467. "\\1#$container_id \\2",
  468. $container_id,
  469. ),
  470. $source);
  471. // put block contents back in
  472. $styles = $replacements->resolve($styles);
  473. return $styles;
  474. }
  475. /**
  476. * Generate CSS classes from mimetype and filename extension
  477. *
  478. * @param string $mimetype Mimetype
  479. * @param string $filename Filename
  480. *
  481. * @return string CSS classes separated by space
  482. */
  483. public static function file2class($mimetype, $filename)
  484. {
  485. list($primary, $secondary) = explode('/', $mimetype);
  486. $classes = array($primary ? $primary : 'unknown');
  487. if ($secondary) {
  488. $classes[] = $secondary;
  489. }
  490. if (preg_match('/\.([a-z0-9]+)$/i', $filename, $m)) {
  491. $classes[] = $m[1];
  492. }
  493. return strtolower(join(" ", $classes));
  494. }
  495. /**
  496. * Decode escaped entities used by known XSS exploits.
  497. * See http://downloads.securityfocus.com/vulnerabilities/exploits/26800.eml for examples
  498. *
  499. * @param string CSS content to decode
  500. *
  501. * @return string Decoded string
  502. */
  503. public static function xss_entity_decode($content)
  504. {
  505. $out = html_entity_decode(html_entity_decode($content));
  506. $out = preg_replace_callback('/\\\([0-9a-f]{4})/i',
  507. array(self, 'xss_entity_decode_callback'), $out);
  508. $out = preg_replace('#/\*.*\*/#Ums', '', $out);
  509. return $out;
  510. }
  511. /**
  512. * preg_replace_callback callback for xss_entity_decode
  513. *
  514. * @param array $matches Result from preg_replace_callback
  515. *
  516. * @return string Decoded entity
  517. */
  518. public static function xss_entity_decode_callback($matches)
  519. {
  520. return chr(hexdec($matches[1]));
  521. }
  522. /**
  523. * Check if we can process not exceeding memory_limit
  524. *
  525. * @param integer Required amount of memory
  526. *
  527. * @return boolean True if memory won't be exceeded, False otherwise
  528. */
  529. public static function mem_check($need)
  530. {
  531. $mem_limit = parse_bytes(ini_get('memory_limit'));
  532. $memory = function_exists('memory_get_usage') ? memory_get_usage() : 16*1024*1024; // safe value: 16MB
  533. return $mem_limit > 0 && $memory + $need > $mem_limit ? false : true;
  534. }
  535. /**
  536. * Check if working in SSL mode
  537. *
  538. * @param integer $port HTTPS port number
  539. * @param boolean $use_https Enables 'use_https' option checking
  540. *
  541. * @return boolean
  542. */
  543. public static function https_check($port=null, $use_https=true)
  544. {
  545. global $RCMAIL;
  546. if (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) != 'off') {
  547. return true;
  548. }
  549. if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https') {
  550. return true;
  551. }
  552. if ($port && $_SERVER['SERVER_PORT'] == $port) {
  553. return true;
  554. }
  555. if ($use_https && isset($RCMAIL) && $RCMAIL->config->get('use_https')) {
  556. return true;
  557. }
  558. return false;
  559. }
  560. /**
  561. * Replaces hostname variables.
  562. *
  563. * @param string $name Hostname
  564. * @param string $host Optional IMAP hostname
  565. *
  566. * @return string Hostname
  567. */
  568. public static function parse_host($name, $host = '')
  569. {
  570. // %n - host
  571. $n = preg_replace('/:\d+$/', '', $_SERVER['SERVER_NAME']);
  572. // %t - host name without first part, e.g. %n=mail.domain.tld, %t=domain.tld
  573. $t = preg_replace('/^[^\.]+\./', '', $n);
  574. // %d - domain name without first part
  575. $d = preg_replace('/^[^\.]+\./', '', $_SERVER['HTTP_HOST']);
  576. // %h - IMAP host
  577. $h = $_SESSION['storage_host'] ? $_SESSION['storage_host'] : $host;
  578. // %z - IMAP domain without first part, e.g. %h=imap.domain.tld, %z=domain.tld
  579. $z = preg_replace('/^[^\.]+\./', '', $h);
  580. // %s - domain name after the '@' from e-mail address provided at login screen. Returns FALSE if an invalid email is provided
  581. if (strpos($name, '%s') !== false) {
  582. $user_email = self::get_input_value('_user', self::INPUT_POST);
  583. $user_email = self::idn_convert($user_email, true);
  584. $matches = preg_match('/(.*)@([a-z0-9\.\-\[\]\:]+)/i', $user_email, $s);
  585. if ($matches < 1 || filter_var($s[1]."@".$s[2], FILTER_VALIDATE_EMAIL) === false) {
  586. return false;
  587. }
  588. }
  589. $name = str_replace(array('%n', '%t', '%d', '%h', '%z', '%s'), array($n, $t, $d, $h, $z, $s[2]), $name);
  590. return $name;
  591. }
  592. /**
  593. * Returns remote IP address and forwarded addresses if found
  594. *
  595. * @return string Remote IP address(es)
  596. */
  597. public static function remote_ip()
  598. {
  599. $address = $_SERVER['REMOTE_ADDR'];
  600. // append the NGINX X-Real-IP header, if set
  601. if (!empty($_SERVER['HTTP_X_REAL_IP'])) {
  602. $remote_ip[] = 'X-Real-IP: ' . $_SERVER['HTTP_X_REAL_IP'];
  603. }
  604. // append the X-Forwarded-For header, if set
  605. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  606. $remote_ip[] = 'X-Forwarded-For: ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
  607. }
  608. if (!empty($remote_ip)) {
  609. $address .= '(' . implode(',', $remote_ip) . ')';
  610. }
  611. return $address;
  612. }
  613. /**
  614. * Read a specific HTTP request header.
  615. *
  616. * @param string $name Header name
  617. *
  618. * @return mixed Header value or null if not available
  619. */
  620. public static function request_header($name)
  621. {
  622. if (function_exists('getallheaders')) {
  623. $hdrs = array_change_key_case(getallheaders(), CASE_UPPER);
  624. $key = strtoupper($name);
  625. }
  626. else {
  627. $key = 'HTTP_' . strtoupper(strtr($name, '-', '_'));
  628. $hdrs = array_change_key_case($_SERVER, CASE_UPPER);
  629. }
  630. return $hdrs[$key];
  631. }
  632. /**
  633. * Explode quoted string
  634. *
  635. * @param string Delimiter expression string for preg_match()
  636. * @param string Input string
  637. *
  638. * @return array String items
  639. */
  640. public static function explode_quoted_string($delimiter, $string)
  641. {
  642. $result = array();
  643. $strlen = strlen($string);
  644. for ($q=$p=$i=0; $i < $strlen; $i++) {
  645. if ($string[$i] == "\"" && $string[$i-1] != "\\") {
  646. $q = $q ? false : true;
  647. }
  648. else if (!$q && preg_match("/$delimiter/", $string[$i])) {
  649. $result[] = substr($string, $p, $i - $p);
  650. $p = $i + 1;
  651. }
  652. }
  653. $result[] = (string) substr($string, $p);
  654. return $result;
  655. }
  656. /**
  657. * Improved equivalent to strtotime()
  658. *
  659. * @param string $date Date string
  660. *
  661. * @return int Unix timestamp
  662. */
  663. public static function strtotime($date)
  664. {
  665. // check for MS Outlook vCard date format YYYYMMDD
  666. if (preg_match('/^([12][90]\d\d)([01]\d)(\d\d)$/', trim($date), $matches)) {
  667. return mktime(0,0,0, intval($matches[2]), intval($matches[3]), intval($matches[1]));
  668. }
  669. else if (is_numeric($date)) {
  670. return $date;
  671. }
  672. // support non-standard "GMTXXXX" literal
  673. $date = preg_replace('/GMT\s*([+-][0-9]+)/', '\\1', $date);
  674. // if date parsing fails, we have a date in non-rfc format.
  675. // remove token from the end and try again
  676. while ((($ts = @strtotime($date)) === false) || ($ts < 0)) {
  677. $d = explode(' ', $date);
  678. array_pop($d);
  679. if (!$d) {
  680. break;
  681. }
  682. $date = implode(' ', $d);
  683. }
  684. return $ts;
  685. }
  686. /*
  687. * Idn_to_ascii wrapper.
  688. * Intl/Idn modules version of this function doesn't work with e-mail address
  689. */
  690. public static function idn_to_ascii($str)
  691. {
  692. return self::idn_convert($str, true);
  693. }
  694. /*
  695. * Idn_to_ascii wrapper.
  696. * Intl/Idn modules version of this function doesn't work with e-mail address
  697. */
  698. public static function idn_to_utf8($str)
  699. {
  700. return self::idn_convert($str, false);
  701. }
  702. public static function idn_convert($input, $is_utf=false)
  703. {
  704. if ($at = strpos($input, '@')) {
  705. $user = substr($input, 0, $at);
  706. $domain = substr($input, $at+1);
  707. }
  708. else {
  709. $domain = $input;
  710. }
  711. $domain = $is_utf ? idn_to_ascii($domain) : idn_to_utf8($domain);
  712. if ($domain === false) {
  713. return '';
  714. }
  715. return $at ? $user . '@' . $domain : $domain;
  716. }
  717. /**
  718. * Split the given string into word tokens
  719. *
  720. * @param string Input to tokenize
  721. * @return array List of tokens
  722. */
  723. public static function tokenize_string($str)
  724. {
  725. return explode(" ", preg_replace(
  726. array('/[\s;\/+-]+/i', '/(\d)[-.\s]+(\d)/', '/\s\w{1,3}\s/u'),
  727. array(' ', '\\1\\2', ' '),
  728. $str));
  729. }
  730. /**
  731. * Normalize the given string for fulltext search.
  732. * Currently only optimized for Latin-1 characters; to be extended
  733. *
  734. * @param string Input string (UTF-8)
  735. * @param boolean True to return list of words as array
  736. * @return mixed Normalized string or a list of normalized tokens
  737. */
  738. public static function normalize_string($str, $as_array = false)
  739. {
  740. // split by words
  741. $arr = self::tokenize_string($str);
  742. foreach ($arr as $i => $part) {
  743. if (utf8_encode(utf8_decode($part)) == $part) { // is latin-1 ?
  744. $arr[$i] = utf8_encode(strtr(strtolower(strtr(utf8_decode($part),
  745. 'ÇçäâàåéêëèïîìÅÉöôòüûùÿøØáíóúñÑÁÂÀãÃÊËÈÍÎÏÓÔõÕÚÛÙýÝ',
  746. 'ccaaaaeeeeiiiaeooouuuyooaiounnaaaaaeeeiiioooouuuyy')),
  747. array('ß' => 'ss', 'ae' => 'a', 'oe' => 'o', 'ue' => 'u')));
  748. }
  749. else
  750. $arr[$i] = mb_strtolower($part);
  751. }
  752. return $as_array ? $arr : join(" ", $arr);
  753. }
  754. }