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

Last change on this file since 1998 was 1998, checked in by thomasb, 5 years ago

Improve vcard import (#1485502); try utf-8 first in charset detection

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 13.6 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, no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
41  header("Pragma: no-cache");
42 
43  // We need to set the following headers to make downloads work using IE in HTTPS mode.
44  if (isset($_SERVER['HTTPS'])) {
45    header('Pragma: ');
46    header('Cache-Control: ');
47  }
48}
49
50
51/**
52 * Send header with expire date 30 days in future
53 *
54 * @param int Expiration time in seconds
55 */
56function send_future_expire_header($offset=2600000)
57{
58  if (headers_sent())
59    return;
60
61  header("Expires: ".gmdate("D, d M Y H:i:s", mktime()+$offset)." GMT");
62  header("Cache-Control: max-age=$offset");
63  header("Pragma: ");
64}
65
66
67/**
68 * Check request for If-Modified-Since and send an according response.
69 * This will terminate the current script if headers match the given values
70 *
71 * @param int Modified date as unix timestamp
72 * @param string Etag value for caching
73 */
74function send_modified_header($mdate, $etag=null, $skip_check=false)
75{
76  if (headers_sent())
77    return;
78   
79  $iscached = false;
80  $etag = $etag ? "\"$etag\"" : null;
81
82  if (!$skip_check)
83  {
84    if ($_SERVER['HTTP_IF_MODIFIED_SINCE'] && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $mdate)
85      $iscached = true;
86 
87    if ($etag)
88      $iscached = ($_SERVER['HTTP_IF_NONE_MATCH'] == $etag);
89  }
90 
91  if ($iscached)
92    header("HTTP/1.x 304 Not Modified");
93  else
94    header("Last-Modified: ".gmdate("D, d M Y H:i:s", $mdate)." GMT");
95 
96  header("Cache-Control: max-age=0");
97  header("Expires: ");
98  header("Pragma: ");
99 
100  if ($etag)
101    header("Etag: $etag");
102 
103  if ($iscached)
104    {
105    ob_end_clean();
106    exit;
107    }
108}
109
110
111/**
112 * Returns whether an $str is a reserved word for any of the version of Javascript or ECMAScript
113 * @param str String to check
114 * @return boolean True if $str is a reserver word, False if not
115 */
116function is_js_reserved_word($str)
117{
118  return in_array($str, array(
119    // ECMASript ver 4 reserved words
120    'as','break','case','catch','class','const','continue',
121    'default','delete','do','else','export','extends','false','finally','for','function',
122    'if','import','in','instanceof','is','namespace','new','null','package','private',
123    'public','return','super','switch','this','throw','true','try','typeof','use','var',
124    'void','while','with',
125    // ECMAScript ver 4 future reserved words
126    'abstract','debugger','enum','goto','implements','interface','native','protected',
127    'synchronized','throws','transient','volatile',
128    // special meaning in some contexts
129    'get','set',
130    // were reserved in ECMAScript ver 3
131    'boolean','byte','char','double','final','float','int','long','short','static'
132  ));
133}
134
135
136/**
137 * Convert a variable into a javascript object notation
138 *
139 * @param mixed Input value
140 * @return string Serialized JSON string
141 */
142function json_serialize($var)
143{
144  if (is_object($var))
145    $var = get_object_vars($var);
146
147  if (is_array($var))
148  {
149    // empty array
150    if (!sizeof($var))
151      return '[]';
152    else
153    {
154      $keys_arr = array_keys($var);
155      $is_assoc = $have_numeric = 0;
156
157      for ($i=0; $i<sizeof($keys_arr); ++$i)
158      {
159        if (is_numeric($keys_arr[$i]))
160          $have_numeric = 1;
161        if (!is_numeric($keys_arr[$i]) || $keys_arr[$i] != $i)
162          $is_assoc = 1;
163        if ($is_assoc && $have_numeric)
164          break;
165      }
166     
167      $brackets = $is_assoc ? '{}' : '[]';
168      $pairs = array();
169
170      foreach ($var as $key => $value)
171      {
172        // enclose key with quotes if it is not variable-name conform
173        if (!ereg("^[_a-zA-Z]{1}[_a-zA-Z0-9]*$", $key) || is_js_reserved_word($key))
174          $key = "'$key'";
175
176        $pairs[] = sprintf("%s%s", $is_assoc ? "$key:" : '', json_serialize($value));
177      }
178
179      return $brackets{0} . implode(',', $pairs) . $brackets{1};
180    }
181  }
182  else if (is_numeric($var) && strval(intval($var)) === strval($var))
183    return $var;
184  else if (is_bool($var))
185    return $var ? '1' : '0';
186  else
187    return "'".JQ($var)."'";
188
189}
190
191
192/**
193 * Function to convert an array to a javascript array
194 * Actually an alias function for json_serialize()
195 * @deprecated
196 */
197function array2js($arr, $type='')
198{
199  return json_serialize($arr);
200}
201
202
203/**
204 * Similar function as in_array() but case-insensitive
205 *
206 * @param mixed Needle value
207 * @param array Array to search in
208 * @return boolean True if found, False if not
209 */
210function in_array_nocase($needle, $haystack)
211{
212  $needle = rc_strtolower($needle);
213  foreach ($haystack as $value)
214    if ($needle===rc_strtolower($value))
215      return true;
216 
217  return false;
218}
219
220
221/**
222 * Find out if the string content means TRUE or FALSE
223 *
224 * @param string Input value
225 * @return boolean Imagine what!
226 */
227function get_boolean($str)
228{
229  $str = strtolower($str);
230  if(in_array($str, array('false', '0', 'no', 'nein', ''), TRUE))
231    return FALSE;
232  else
233    return TRUE;
234}
235
236
237/**
238 * Parse a human readable string for a number of bytes
239 *
240 * @param string Input string
241 * @return int Number of bytes
242 */
243function parse_bytes($str)
244{
245  if (is_numeric($str))
246    return intval($str);
247   
248  if (preg_match('/([0-9]+)([a-z])/i', $str, $regs))
249  {
250    $bytes = floatval($regs[1]);
251    switch (strtolower($regs[2]))
252    {
253      case 'g':
254        $bytes *= 1073741824;
255        break;
256      case 'm':
257        $bytes *= 1048576;
258        break;
259      case 'k':
260        $bytes *= 1024;
261        break;
262    }
263  }
264
265  return intval($bytes);
266}
267   
268/**
269 * Create a human readable string for a number of bytes
270 *
271 * @param int Number of bytes
272 * @return string Byte string
273 */
274function show_bytes($bytes)
275{
276  if ($bytes > 1073741824)
277  {
278    $gb = $bytes/1073741824;
279    $str = sprintf($gb>=10 ? "%d " : "%.1f ", $gb) . rcube_label('GB');
280  }
281  else if ($bytes > 1048576)
282  {
283    $mb = $bytes/1048576;
284    $str = sprintf($mb>=10 ? "%d " : "%.1f ", $mb) . rcube_label('MB');
285  }
286  else if ($bytes > 1024)
287    $str = sprintf("%d ",  round($bytes/1024)) . rcube_label('KB');
288  else
289    $str = sprintf('%d ', $bytes) . rcube_label('B');
290
291  return $str;
292}
293
294
295/**
296 * Convert paths like ../xxx to an absolute path using a base url
297 *
298 * @param string Relative path
299 * @param string Base URL
300 * @return string Absolute URL
301 */
302function make_absolute_url($path, $base_url)
303{
304  $host_url = $base_url;
305  $abs_path = $path;
306 
307  // check if path is an absolute URL
308  if (preg_match('/^[fhtps]+:\/\//', $path))
309    return $path;
310
311  // cut base_url to the last directory
312  if (strpos($base_url, '/')>7)
313  {
314    $host_url = substr($base_url, 0, strpos($base_url, '/'));
315    $base_url = substr($base_url, 0, strrpos($base_url, '/'));
316  }
317
318  // $path is absolute
319  if ($path{0}=='/')
320    $abs_path = $host_url.$path;
321  else
322  {
323    // strip './' because its the same as ''
324    $path = preg_replace('/^\.\//', '', $path);
325
326    if (preg_match_all('/\.\.\//', $path, $matches, PREG_SET_ORDER))
327      foreach ($matches as $a_match)
328      {
329        if (strrpos($base_url, '/'))
330          $base_url = substr($base_url, 0, strrpos($base_url, '/'));
331       
332        $path = substr($path, 3);
333      }
334
335    $abs_path = $base_url.'/'.$path;
336  }
337   
338  return $abs_path;
339}
340
341
342/**
343 * Wrapper function for strlen
344 */
345function rc_strlen($str)
346{
347  if (function_exists('mb_strlen'))
348    return mb_strlen($str);
349  else
350    return strlen($str);
351}
352 
353/**
354 * Wrapper function for strtolower
355 */
356function rc_strtolower($str)
357{
358  if (function_exists('mb_strtolower'))
359    return mb_strtolower($str);
360  else
361    return strtolower($str);
362}
363
364/**
365 * Wrapper function for substr
366 */
367function rc_substr($str, $start, $len=null)
368{
369  if (function_exists('mb_substr'))
370    return mb_substr($str, $start, $len);
371  else
372    return substr($str, $start, $len);
373}
374
375/**
376 * Wrapper function for strpos
377 */
378function rc_strpos($haystack, $needle, $offset=0)
379{
380  if (function_exists('mb_strpos'))
381    return mb_strpos($haystack, $needle, $offset);
382  else
383    return strpos($haystack, $needle, $offset);
384}
385
386/**
387 * Wrapper function for strrpos
388 */
389function rc_strrpos($haystack, $needle, $offset=0)
390{
391  if (function_exists('mb_strrpos'))
392    return mb_strrpos($haystack, $needle, $offset);
393  else
394    return strrpos($haystack, $needle, $offset);
395}
396
397
398/**
399 * Read a specific HTTP request header
400 *
401 * @access static
402 * @param  string $name Header name
403 * @return mixed  Header value or null if not available
404 */
405function rc_request_header($name)
406{
407  if (function_exists('getallheaders'))
408  {
409    $hdrs = array_change_key_case(getallheaders(), CASE_UPPER);
410    $key  = strtoupper($name);
411  }
412  else
413  {
414    $key  = 'HTTP_' . strtoupper(strtr($name, '-', '_'));
415    $hdrs = array_change_key_case($_SERVER, CASE_UPPER);
416  }
417
418  return $hdrs[$key];
419  }
420
421
422/**
423 * Replace the middle part of a string with ...
424 * if it is longer than the allowed length
425 *
426 * @param string Input string
427 * @param int    Max. length
428 * @param string Replace removed chars with this
429 * @return string Abbreviated string
430 */
431function abbreviate_string($str, $maxlength, $place_holder='...')
432{
433  $length = rc_strlen($str);
434  $first_part_length = floor($maxlength/2) - rc_strlen($place_holder);
435 
436  if ($length > $maxlength)
437  {
438    $second_starting_location = $length - $maxlength + $first_part_length + 1;
439    $str = rc_substr($str, 0, $first_part_length) . $place_holder . rc_substr($str, $second_starting_location, $length);
440  }
441
442  return $str;
443}
444
445
446/**
447 * Make sure the string ends with a slash
448 */
449function slashify($str)
450{
451  return unslashify($str).'/';
452}
453
454
455/**
456 * Remove slash at the end of the string
457 */
458function unslashify($str)
459{
460  return preg_replace('/\/$/', '', $str);
461}
462 
463
464/**
465 * Delete all files within a folder
466 *
467 * @param string Path to directory
468 * @return boolean True on success, False if directory was not found
469 */
470function clear_directory($dir_path)
471{
472  $dir = @opendir($dir_path);
473  if(!$dir) return FALSE;
474
475  while ($file = readdir($dir))
476    if (strlen($file)>2)
477      unlink("$dir_path/$file");
478
479  closedir($dir);
480  return TRUE;
481}
482
483
484/**
485 * Create a unix timestamp with a specified offset from now
486 *
487 * @param string String representation of the offset (e.g. 20min, 5h, 2days)
488 * @param int Factor to multiply with the offset
489 * @return int Unix timestamp
490 */
491function get_offset_time($offset_str, $factor=1)
492  {
493  if (preg_match('/^([0-9]+)\s*([smhdw])/i', $offset_str, $regs))
494  {
495    $amount = (int)$regs[1];
496    $unit = strtolower($regs[2]);
497  }
498  else
499  {
500    $amount = (int)$offset_str;
501    $unit = 's';
502  }
503   
504  $ts = mktime();
505  switch ($unit)
506  {
507    case 'w':
508      $amount *= 7;
509    case 'd':
510      $amount *= 24;
511    case 'h':
512      $amount *= 60;
513    case 'm':
514      $amount *= 60;
515    case 's':
516      $ts += $amount * $factor;
517  }
518
519  return $ts;
520}
521
522
523/**
524 * A method to guess the mime_type of an attachment.
525 *
526 * @param string $path     Path to the file.
527 * @param string $failover Mime type supplied for failover.
528 *
529 * @return string
530 * @author Till Klampaeckel <till@php.net>
531 * @see    http://de2.php.net/manual/en/ref.fileinfo.php
532 * @see    http://de2.php.net/mime_content_type
533 */
534function rc_mime_content_type($path, $failover = 'application/octet-stream')
535{
536    $mime_type = null;
537    $mime_magic = rcmail::get_instance()->config->get('mime_magic');
538
539    if (!extension_loaded('fileinfo')) {
540        @dl('fileinfo.' . PHP_SHLIB_SUFFIX);
541    }
542
543    if (function_exists('finfo_open')) {
544        if ($finfo = finfo_open(FILEINFO_MIME, $mime_magic)) {
545            $mime_type = finfo_file($finfo, $path);
546            finfo_close($finfo);
547        }
548    }
549    if (!$mime_type && function_exists('mime_content_type')) {
550      $mime_type = mime_content_type($path);
551    }
552   
553    if (!$mime_type) {
554        $mime_type = $failover;
555    }
556
557    return $mime_type;
558}
559
560
561/**
562 * A method to guess encoding of a string.
563 *
564 * @param string $string        String.
565 * @param string $failover      Default result for failover.
566 *
567 * @return string
568 */
569function rc_detect_encoding($string, $failover='')
570{
571    if (!function_exists('mb_detect_encoding')) {
572        return $failover;
573    }
574
575    // FIXME: the order is important, because sometimes
576    // iso string is detected as euc-jp and etc.
577    $enc = array(
578      'UTF-8', 'SJIS', 'BIG5', 'GB2312',
579      'ISO-8859-1', 'ISO-8859-2', 'ISO-8859-3', 'ISO-8859-4',
580      'ISO-8859-5', 'ISO-8859-6', 'ISO-8859-7', 'ISO-8859-8', 'ISO-8859-9',
581      'ISO-8859-10', 'ISO-8859-13', 'ISO-8859-14', 'ISO-8859-15', 'ISO-8859-16',
582      'WINDOWS-1252', 'WINDOWS-1251', 'EUC-JP', 'EUC-TW', 'KOI8-R',
583      'ISO-2022-KR', 'ISO-2022-JP'
584    );
585
586    $result = mb_detect_encoding($string, join(',', $enc));
587
588    return $result ? $result : $failover;
589}
590
591?>
Note: See TracBrowser for help on using the repository browser.