source: subversion/trunk/roundcubemail/program/include/rcube_shared.inc @ 3680

Last change on this file since 3680 was 3680, checked in by alec, 3 years ago
  • Fix forwarding of messages with winmail attachments
  • Remove some redundant code for winmail handling in get.inc, move tnef_decode() to rcube_message
  • Fix handling of uuencoded attachments in message body (#1485839)
  • Extend rc_mime_content_type() to work with string buffer
  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 15.9 KB
Line 
1<?php
2
3/*
4 +-----------------------------------------------------------------------+
5 | rcube_shared.inc                                                      |
6 |                                                                       |
7 | This file is part of the RoundCube PHP suite                          |
8 | Copyright (C) 2005-2007, RoundCube Dev. - Switzerland                 |
9 | Licensed under the GNU GPL                                            |
10 |                                                                       |
11 | CONTENTS:                                                             |
12 |   Shared functions and classes used in PHP projects                   |
13 |                                                                       |
14 +-----------------------------------------------------------------------+
15 | Author: Thomas Bruederli <roundcube@gmail.com>                        |
16 +-----------------------------------------------------------------------+
17
18 $Id$
19
20*/
21
22
23/**
24 * RoundCube shared functions
25 *
26 * @package Core
27 */
28
29
30/**
31 * Send HTTP headers to prevent caching this page
32 */
33function send_nocacheing_headers()
34{
35  if (headers_sent())
36    return;
37
38  header("Expires: ".gmdate("D, d M Y H:i:s")." GMT");
39  header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
40  header("Cache-Control: private, must-revalidate, post-check=0, pre-check=0");
41  header("Pragma: no-cache");
42  // Request browser to disable DNS prefetching (CVE-2010-0464)
43  header("X-DNS-Prefetch-Control: off");
44 
45  // We need to set the following headers to make downloads work using IE in HTTPS mode.
46  if (rcube_https_check()) {
47    header('Pragma: ');
48    header('Cache-Control: ');
49  }
50}
51
52
53/**
54 * Send header with expire date 30 days in future
55 *
56 * @param int Expiration time in seconds
57 */
58function send_future_expire_header($offset=2600000)
59{
60  if (headers_sent())
61    return;
62
63  header("Expires: ".gmdate("D, d M Y H:i:s", mktime()+$offset)." GMT");
64  header("Cache-Control: max-age=$offset");
65  header("Pragma: ");
66}
67
68
69/**
70 * Check request for If-Modified-Since and send an according response.
71 * This will terminate the current script if headers match the given values
72 *
73 * @param int Modified date as unix timestamp
74 * @param string Etag value for caching
75 */
76function send_modified_header($mdate, $etag=null, $skip_check=false)
77{
78  if (headers_sent())
79    return;
80   
81  $iscached = false;
82  $etag = $etag ? "\"$etag\"" : null;
83
84  if (!$skip_check)
85  {
86    if ($_SERVER['HTTP_IF_MODIFIED_SINCE'] && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $mdate)
87      $iscached = true;
88 
89    if ($etag)
90      $iscached = ($_SERVER['HTTP_IF_NONE_MATCH'] == $etag);
91  }
92 
93  if ($iscached)
94    header("HTTP/1.x 304 Not Modified");
95  else
96    header("Last-Modified: ".gmdate("D, d M Y H:i:s", $mdate)." GMT");
97 
98  header("Cache-Control: private, must-revalidate, max-age=0");
99  header("Expires: ");
100  header("Pragma: ");
101 
102  if ($etag)
103    header("Etag: $etag");
104 
105  if ($iscached)
106    {
107    ob_end_clean();
108    exit;
109    }
110}
111
112
113/**
114 * Similar function as in_array() but case-insensitive
115 *
116 * @param mixed Needle value
117 * @param array Array to search in
118 * @return boolean True if found, False if not
119 */
120function in_array_nocase($needle, $haystack)
121{
122  $needle = mb_strtolower($needle);
123  foreach ($haystack as $value)
124    if ($needle===mb_strtolower($value))
125      return true;
126 
127  return false;
128}
129
130
131/**
132 * Find out if the string content means TRUE or FALSE
133 *
134 * @param string Input value
135 * @return boolean Imagine what!
136 */
137function get_boolean($str)
138{
139  $str = strtolower($str);
140  if (in_array($str, array('false', '0', 'no', 'nein', ''), TRUE))
141    return FALSE;
142  else
143    return TRUE;
144}
145
146
147/**
148 * Parse a human readable string for a number of bytes
149 *
150 * @param string Input string
151 * @return float Number of bytes
152 */
153function parse_bytes($str)
154{
155  if (is_numeric($str))
156    return floatval($str);
157
158  if (preg_match('/([0-9\.]+)\s*([a-z]*)/i', $str, $regs))
159  {
160    $bytes = floatval($regs[1]);
161    switch (strtolower($regs[2]))
162    {
163      case 'g':
164      case 'gb':
165        $bytes *= 1073741824;
166        break;
167      case 'm':
168      case 'mb':
169        $bytes *= 1048576;
170        break;
171      case 'k':
172      case 'kb':
173        $bytes *= 1024;
174        break;
175    }
176  }
177
178  return floatval($bytes);
179}
180   
181/**
182 * Create a human readable string for a number of bytes
183 *
184 * @param int Number of bytes
185 * @return string Byte string
186 */
187function show_bytes($bytes)
188{
189  if ($bytes > 1073741824)
190  {
191    $gb = $bytes/1073741824;
192    $str = sprintf($gb>=10 ? "%d " : "%.1f ", $gb) . rcube_label('GB');
193  }
194  else if ($bytes > 1048576)
195  {
196    $mb = $bytes/1048576;
197    $str = sprintf($mb>=10 ? "%d " : "%.1f ", $mb) . rcube_label('MB');
198  }
199  else if ($bytes > 1024)
200    $str = sprintf("%d ",  round($bytes/1024)) . rcube_label('KB');
201  else
202    $str = sprintf('%d ', $bytes) . rcube_label('B');
203
204  return $str;
205}
206
207
208/**
209 * Convert paths like ../xxx to an absolute path using a base url
210 *
211 * @param string Relative path
212 * @param string Base URL
213 * @return string Absolute URL
214 */
215function make_absolute_url($path, $base_url)
216{
217  $host_url = $base_url;
218  $abs_path = $path;
219 
220  // check if path is an absolute URL
221  if (preg_match('/^[fhtps]+:\/\//', $path))
222    return $path;
223
224  // cut base_url to the last directory
225  if (strrpos($base_url, '/')>7)
226  {
227    $host_url = substr($base_url, 0, strpos($base_url, '/'));
228    $base_url = substr($base_url, 0, strrpos($base_url, '/'));
229  }
230
231  // $path is absolute
232  if ($path{0}=='/')
233    $abs_path = $host_url.$path;
234  else
235  {
236    // strip './' because its the same as ''
237    $path = preg_replace('/^\.\//', '', $path);
238
239    if (preg_match_all('/\.\.\//', $path, $matches, PREG_SET_ORDER))
240      foreach ($matches as $a_match)
241      {
242        if (strrpos($base_url, '/'))
243          $base_url = substr($base_url, 0, strrpos($base_url, '/'));
244       
245        $path = substr($path, 3);
246      }
247
248    $abs_path = $base_url.'/'.$path;
249  }
250   
251  return $abs_path;
252}
253
254/**
255 * Wrapper function for wordwrap
256 */
257function rc_wordwrap($string, $width=75, $break="\n", $cut=false)
258{
259  $para = explode($break, $string);
260  $string = '';
261  while (count($para)) {
262    $line = array_shift($para);
263    if ($line[0] == '>') {
264      $string .= $line.$break;
265      continue;
266    }
267    $list = explode(' ', $line);
268    $len = 0;
269    while (count($list)) {
270      $line = array_shift($list);
271      $l = mb_strlen($line);
272      $newlen = $len + $l + ($len ? 1 : 0);
273
274      if ($newlen <= $width) {
275        $string .= ($len ? ' ' : '').$line;
276        $len += (1 + $l);
277      } else {
278        if ($l > $width) {
279          if ($cut) {
280            $start = 0;
281            while ($l) {
282              $str = mb_substr($line, $start, $width);
283              $strlen = mb_strlen($str);
284              $string .= ($len ? $break : '').$str;
285              $start += $strlen;
286              $l -= $strlen;
287              $len = $strlen;
288            }
289          } else {
290                $string .= ($len ? $break : '').$line;
291            if (count($list)) $string .= $break;
292            $len = 0;
293          }
294        } else {
295          $string .= $break.$line;
296          $len = $l;
297        }
298      }
299    }
300    if (count($para)) $string .= $break;
301  }
302  return $string;
303}
304
305/**
306 * Read a specific HTTP request header
307 *
308 * @access static
309 * @param  string $name Header name
310 * @return mixed  Header value or null if not available
311 */
312function rc_request_header($name)
313{
314  if (function_exists('getallheaders'))
315  {
316    $hdrs = array_change_key_case(getallheaders(), CASE_UPPER);
317    $key  = strtoupper($name);
318  }
319  else
320  {
321    $key  = 'HTTP_' . strtoupper(strtr($name, '-', '_'));
322    $hdrs = array_change_key_case($_SERVER, CASE_UPPER);
323  }
324
325  return $hdrs[$key];
326  }
327
328
329/**
330 * Make sure the string ends with a slash
331 */
332function slashify($str)
333{
334  return unslashify($str).'/';
335}
336
337
338/**
339 * Remove slash at the end of the string
340 */
341function unslashify($str)
342{
343  return preg_replace('/\/$/', '', $str);
344}
345 
346
347/**
348 * Delete all files within a folder
349 *
350 * @param string Path to directory
351 * @return boolean True on success, False if directory was not found
352 */
353function clear_directory($dir_path)
354{
355  $dir = @opendir($dir_path);
356  if(!$dir) return FALSE;
357
358  while ($file = readdir($dir))
359    if (strlen($file)>2)
360      unlink("$dir_path/$file");
361
362  closedir($dir);
363  return TRUE;
364}
365
366
367/**
368 * Create a unix timestamp with a specified offset from now
369 *
370 * @param string String representation of the offset (e.g. 20min, 5h, 2days)
371 * @param int Factor to multiply with the offset
372 * @return int Unix timestamp
373 */
374function get_offset_time($offset_str, $factor=1)
375  {
376  if (preg_match('/^([0-9]+)\s*([smhdw])/i', $offset_str, $regs))
377  {
378    $amount = (int)$regs[1];
379    $unit = strtolower($regs[2]);
380  }
381  else
382  {
383    $amount = (int)$offset_str;
384    $unit = 's';
385  }
386   
387  $ts = mktime();
388  switch ($unit)
389  {
390    case 'w':
391      $amount *= 7;
392    case 'd':
393      $amount *= 24;
394    case 'h':
395      $amount *= 60;
396    case 'm':
397      $amount *= 60;
398    case 's':
399      $ts += $amount * $factor;
400  }
401
402  return $ts;
403}
404
405
406/**
407 * Replace the middle part of a string with ...
408 * if it is longer than the allowed length
409 *
410 * @param string Input string
411 * @param int    Max. length
412 * @param string Replace removed chars with this
413 * @return string Abbreviated string
414 */
415function abbreviate_string($str, $maxlength, $place_holder='...')
416{
417  $length = mb_strlen($str);
418 
419  if ($length > $maxlength)
420  {
421    $place_holder_length = mb_strlen($place_holder);
422    $first_part_length = floor(($maxlength - $place_holder_length)/2);
423    $second_starting_location = $length - $maxlength + $first_part_length + $place_holder_length;
424    $str = mb_substr($str, 0, $first_part_length) . $place_holder . mb_substr($str, $second_starting_location);
425  }
426
427  return $str;
428}
429
430/**
431 * A method to guess the mime_type of an attachment.
432 *
433 * @param string $path      Path to the file.
434 * @param string $name      File name (with suffix)
435 * @param string $failover  Mime type supplied for failover.
436 * @param string $is_stream Set to True if $path contains file body
437 *
438 * @return string
439 * @author Till Klampaeckel <till@php.net>
440 * @see    http://de2.php.net/manual/en/ref.fileinfo.php
441 * @see    http://de2.php.net/mime_content_type
442 */
443function rc_mime_content_type($path, $name, $failover = 'application/octet-stream', $is_stream=false)
444{
445    $mime_type = null;
446    $mime_magic = rcmail::get_instance()->config->get('mime_magic');
447    $mime_ext = @include(RCMAIL_CONFIG_DIR . '/mimetypes.php');
448    $suffix = $name ? substr($name, strrpos($name, '.')+1) : '*';
449
450    // use file name suffix with hard-coded mime-type map
451    if (is_array($mime_ext)) {
452        $mime_type = $mime_ext[$suffix];
453    }
454    // try fileinfo extension if available
455    if (!$mime_type && function_exists('finfo_open')) {
456        if ($finfo = finfo_open(FILEINFO_MIME, $mime_magic)) {
457            if ($is_stream)
458                $mime_type = finfo_buffer($finfo, $path);
459            else
460                $mime_type = finfo_file($finfo, $path);
461            finfo_close($finfo);
462        }
463    }
464    // try PHP's mime_content_type
465    if (!$mime_type && !$is_stream && function_exists('mime_content_type')) {
466      $mime_type = @mime_content_type($path);
467    }
468    // fall back to user-submitted string
469    if (!$mime_type) {
470        $mime_type = $failover;
471    }
472
473    return $mime_type;
474}
475
476/**
477 * A method to guess encoding of a string.
478 *
479 * @param string $string        String.
480 * @param string $failover      Default result for failover.
481 *
482 * @return string
483 */
484function rc_detect_encoding($string, $failover='')
485{
486    if (!function_exists('mb_detect_encoding')) {
487        return $failover;
488    }
489
490    // FIXME: the order is important, because sometimes
491    // iso string is detected as euc-jp and etc.
492    $enc = array(
493      'UTF-8', 'SJIS', 'BIG5', 'GB2312',
494      'ISO-8859-1', 'ISO-8859-2', 'ISO-8859-3', 'ISO-8859-4',
495      'ISO-8859-5', 'ISO-8859-6', 'ISO-8859-7', 'ISO-8859-8', 'ISO-8859-9',
496      'ISO-8859-10', 'ISO-8859-13', 'ISO-8859-14', 'ISO-8859-15', 'ISO-8859-16',
497      'WINDOWS-1252', 'WINDOWS-1251', 'EUC-JP', 'EUC-TW', 'KOI8-R',
498      'ISO-2022-KR', 'ISO-2022-JP'
499    );
500
501    $result = mb_detect_encoding($string, join(',', $enc));
502
503    return $result ? $result : $failover;
504}
505
506/**
507 * Removes non-unicode characters from input
508 *
509 * @param mixed $input String or array.
510 * @return string
511 */
512function rc_utf8_clean($input)
513{
514  // handle input of type array
515  if (is_array($input)) {
516    foreach ($input as $idx => $val)
517      $input[$idx] = rc_utf8_clean($val);
518    return $input;
519  }
520 
521  if (!is_string($input) || $input == '')
522    return $input;
523
524  // iconv/mbstring are much faster (especially with long strings)
525  if (function_exists('mb_convert_encoding') && ($res = mb_convert_encoding($input, 'UTF-8', 'UTF-8')) !== false)
526    return $res;
527
528  if (function_exists('iconv') && ($res = @iconv('UTF-8', 'UTF-8//IGNORE', $input)) !== false)
529    return $res;
530
531  $regexp = '/^('.
532//    '[\x00-\x7F]'.                                  // UTF8-1
533    '|[\xC2-\xDF][\x80-\xBF]'.                      // UTF8-2
534    '|\xE0[\xA0-\xBF][\x80-\xBF]'.                  // UTF8-3
535    '|[\xE1-\xEC][\x80-\xBF][\x80-\xBF]'.           // UTF8-3
536    '|\xED[\x80-\x9F][\x80-\xBF]'.                  // UTF8-3
537    '|[\xEE-\xEF][\x80-\xBF][\x80-\xBF]'.           // UTF8-3
538    '|\xF0[\x90-\xBF][\x80-\xBF][\x80-\xBF]'.       // UTF8-4
539    '|[\xF1-\xF3][\x80-\xBF][\x80-\xBF][\x80-\xBF]'.// UTF8-4
540    '|\xF4[\x80-\x8F][\x80-\xBF][\x80-\xBF]'.       // UTF8-4
541    ')$/';
542 
543  $seq = '';
544  $out = '';
545
546  for ($i = 0, $len = strlen($input); $i < $len; $i++) {
547    $chr = $input[$i];
548    $ord = ord($chr);
549    // 1-byte character
550    if ($ord <= 0x7F) {
551      if ($seq)
552        $out .= preg_match($regexp, $seq) ? $seq : '';
553      $seq = '';
554      $out .= $chr;
555    // first (or second) byte of multibyte sequence
556    } else if ($ord >= 0xC0) {
557      if (strlen($seq)>1) {
558        $out .= preg_match($regexp, $seq) ? $seq : '';
559        $seq = '';
560      } else if ($seq && ord($seq) < 0xC0) {
561        $seq = '';
562      }
563      $seq .= $chr;
564    // next byte of multibyte sequence
565    } else if ($seq) {
566      $seq .= $chr;
567    }
568  }
569
570  if ($seq)
571    $out .= preg_match($regexp, $seq) ? $seq : '';
572
573  return $out;
574}
575
576
577/**
578 * Convert a variable into a javascript object notation
579 *
580 * @param mixed Input value
581 * @return string Serialized JSON string
582 */
583function json_serialize($input)
584{
585  $input = rc_utf8_clean($input);
586
587  // sometimes even using rc_utf8_clean() the input contains invalid UTF-8 sequences
588  // that's why we have @ here
589  return @json_encode($input);
590}
591
592
593/**
594 * Explode quoted string
595 *
596 * @param string Delimiter expression string for preg_match()
597 * @param string Input string
598 */
599function rcube_explode_quoted_string($delimiter, $string)
600{
601  $result = array();
602  $strlen = strlen($string);
603
604  for ($q=$p=$i=0; $i < $strlen; $i++) {
605    if ($string[$i] == "\"" && $string[$i-1] != "\\") {
606      $q = $q ? false : true;
607    }
608    else if (!$q && preg_match("/$delimiter/", $string[$i])) {
609      $result[] = substr($string, $p, $i - $p);
610      $p = $i + 1;
611    }
612  }
613 
614  $result[] = substr($string, $p);
615  return $result;
616}
617
618
619/**
620 * Get all keys from array (recursive)
621 *
622 * @param array Input array
623 * @return array
624 */
625function array_keys_recursive($array)
626{
627  $keys = array();
628 
629  if (!empty($array))
630    foreach ($array as $key => $child) {
631      $keys[] = $key;
632      if ($children = array_keys_recursive($child))
633        $keys = array_merge($keys, $children);
634    }
635  return $keys;
636}
637
638
639/**
640 * mbstring replacement functions
641 */
642
643if (!extension_loaded('mbstring'))
644{
645    function mb_strlen($str)
646    {
647        return strlen($str);
648    }
649
650    function mb_strtolower($str)
651    {
652        return strtolower($str);
653    }
654
655    function mb_strtoupper($str)
656    {
657        return strtoupper($str);
658    }
659
660    function mb_substr($str, $start, $len=null)
661    {
662        return substr($str, $start, $len);
663    }
664
665    function mb_strpos($haystack, $needle, $offset=0)
666    {
667        return strpos($haystack, $needle, $offset);
668    }
669
670    function mb_strrpos($haystack, $needle, $offset=0)
671    {
672        return strrpos($haystack, $needle, $offset);
673    }
674}
675
676?>
Note: See TracBrowser for help on using the repository browser.