PageRenderTime 49ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/program/lib/Roundcube/rcube_utils.php

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