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

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