Aleksander Machniak
2015-05-27 1cb6e91e998d861c8e6b67cfc9bf83108331ca50
commit | author | age
4e17e6 1 <?php
T 2
3 /*
4  +-----------------------------------------------------------------------+
e019f2 5  | This file is part of the Roundcube PHP suite                          |
2f8b10 6  | Copyright (C) 2005-2015, The Roundcube Dev Team                       |
7fe381 7  |                                                                       |
T 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.                     |
4e17e6 11  |                                                                       |
T 12  | CONTENTS:                                                             |
f707fe 13  |   Roundcube Framework Initialization                                  |
4e17e6 14  +-----------------------------------------------------------------------+
T 15  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
f707fe 16  | Author: Aleksander Machniak <alec@alec.pl>                            |
4e17e6 17  +-----------------------------------------------------------------------+
T 18 */
19
20
6d969b 21 /**
f707fe 22  * Roundcube Framework Initialization
9e54e6 23  *
9ab346 24  * @package    Framework
AM 25  * @subpackage Core
6d969b 26  */
f707fe 27
AM 28 $config = array(
3d5eea 29     'error_reporting'         => E_ALL & ~E_NOTICE & ~E_STRICT,
f707fe 30     // Some users are not using Installer, so we'll check some
AM 31     // critical PHP settings here. Only these, which doesn't provide
32     // an error/warning in the logs later. See (#1486307).
33     'mbstring.func_overload'  => 0,
3d5eea 34     'magic_quotes_runtime'    => false,
AM 35     'magic_quotes_sybase'     => false, // #1488506
f707fe 36 );
589083 37
TB 38 // check these additional ini settings if not called via CLI
39 if (php_sapi_name() != 'cli') {
40     $config += array(
3d5eea 41         'suhosin.session.encrypt' => false,
AM 42         'file_uploads'            => true,
589083 43     );
TB 44 }
45
f707fe 46 foreach ($config as $optname => $optval) {
3d5eea 47     $ini_optval = filter_var(ini_get($optname), is_bool($optval) ? FILTER_VALIDATE_BOOLEAN : FILTER_VALIDATE_INT);
39b905 48     if ($optval != $ini_optval && @ini_set($optname, $optval) === false) {
fbd213 49         $error = "ERROR: Wrong '$optname' option value and it wasn't possible to set it to required value ($optval).\n"
AM 50             . "Check your PHP configuration (including php_admin_flag).";
51         if (defined('STDERR')) fwrite(STDERR, $error); else echo $error;
52         exit(1);
f707fe 53     }
AM 54 }
55
fdbe5a 56 // framework constants
3779b6 57 define('RCUBE_VERSION', '1.2-git');
a92beb 58 define('RCUBE_CHARSET', 'UTF-8');
f707fe 59
9be2f4 60 if (!defined('RCUBE_LIB_DIR')) {
0ea079 61     define('RCUBE_LIB_DIR', __DIR__ . '/');
f707fe 62 }
AM 63
9be2f4 64 if (!defined('RCUBE_INSTALL_PATH')) {
TB 65     define('RCUBE_INSTALL_PATH', RCUBE_LIB_DIR);
66 }
67
68 if (!defined('RCUBE_CONFIG_DIR')) {
592668 69     define('RCUBE_CONFIG_DIR', RCUBE_INSTALL_PATH . 'config/');
9be2f4 70 }
TB 71
72 if (!defined('RCUBE_PLUGINS_DIR')) {
73     define('RCUBE_PLUGINS_DIR', RCUBE_INSTALL_PATH . 'plugins/');
74 }
75
76 if (!defined('RCUBE_LOCALIZATION_DIR')) {
77     define('RCUBE_LOCALIZATION_DIR', RCUBE_INSTALL_PATH . 'localization/');
f707fe 78 }
AM 79
80 // set internal encoding for mbstring extension
f070da 81 if (function_exists('mb_internal_encoding')) {
a92beb 82     mb_internal_encoding(RCUBE_CHARSET);
f070da 83 }
AM 84 if (function_exists('mb_regex_encoding')) {
85     mb_regex_encoding(RCUBE_CHARSET);
f707fe 86 }
AM 87
d25ad5 88 // make sure the Roundcube lib directory is in the include_path
9f7544 89 $rcube_path = realpath(RCUBE_LIB_DIR . '..');
AM 90 $sep        = PATH_SEPARATOR;
91 $regexp     = "!(^|$sep)" . preg_quote($rcube_path, '!') . "($sep|\$)!";
92 $path       = ini_get('include_path');
93
94 if (!preg_match($regexp, $path)) {
95     set_include_path($path . PATH_SEPARATOR . $rcube_path);
d25ad5 96 }
TB 97
f707fe 98 // Register autoloader
AM 99 spl_autoload_register('rcube_autoload');
100
101 // set PEAR error handling (will also load the PEAR main class)
4ab77d 102 if (class_exists('PEAR')) {
d375b2 103     @PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'rcube_pear_error');
4ab77d 104 }
4e17e6 105
a0109c 106
6d969b 107 /**
f11541 108  * Similar function as in_array() but case-insensitive
6d969b 109  *
0c2596 110  * @param string $needle    Needle value
A 111  * @param array  $heystack  Array to search in
112  *
6d969b 113  * @return boolean True if found, False if not
f11541 114  */
4e17e6 115 function in_array_nocase($needle, $haystack)
6d969b 116 {
0c2596 117     $needle = mb_strtolower($needle);
be9840 118     foreach ((array)$haystack as $value) {
0c2596 119         if ($needle === mb_strtolower($value)) {
A 120             return true;
121         }
122     }
9e54e6 123
0c2596 124     return false;
6d969b 125 }
4e17e6 126
T 127
6d969b 128 /**
0c2596 129  * Parse a human readable string for a number of bytes.
6d969b 130  *
0c2596 131  * @param string $str  Input string
A 132  *
47f072 133  * @return float Number of bytes
6d969b 134  */
86df15 135 function parse_bytes($str)
6d969b 136 {
0c2596 137     if (is_numeric($str)) {
A 138         return floatval($str);
86df15 139     }
T 140
0c2596 141     if (preg_match('/([0-9\.]+)\s*([a-z]*)/i', $str, $regs)) {
A 142         $bytes = floatval($regs[1]);
143         switch (strtolower($regs[2])) {
144         case 'g':
145         case 'gb':
146             $bytes *= 1073741824;
147             break;
148         case 'm':
149         case 'mb':
150             $bytes *= 1048576;
151             break;
152         case 'k':
153         case 'kb':
154             $bytes *= 1024;
155             break;
7145e0 156         }
A 157     }
0c2596 158
A 159     return floatval($bytes);
7145e0 160 }
86df15 161
0c2596 162
6d969b 163 /**
T 164  * Make sure the string ends with a slash
165  */
bac7d1 166 function slashify($str)
6d969b 167 {
bac7d1 168   return unslashify($str).'/';
6d969b 169 }
bac7d1 170
T 171
6d969b 172 /**
e8be30 173  * Remove slashes at the end of the string
6d969b 174  */
bac7d1 175 function unslashify($str)
6d969b 176 {
e8be30 177   return preg_replace('/\/+$/', '', $str);
6d969b 178 }
9fee0e 179
T 180
6d969b 181 /**
5d66a4 182  * Returns number of seconds for a specified offset string.
6d969b 183  *
5d66a4 184  * @param string $str  String representation of the offset (e.g. 20min, 5h, 2days, 1week)
0c2596 185  *
5d66a4 186  * @return int Number of seconds
6d969b 187  */
5d66a4 188 function get_offset_sec($str)
9e54e6 189 {
5d66a4 190     if (preg_match('/^([0-9]+)\s*([smhdw])/i', $str, $regs)) {
A 191         $amount = (int) $regs[1];
0c2596 192         $unit   = strtolower($regs[2]);
734584 193     }
bf13ba 194     else {
5d66a4 195         $amount = (int) $str;
0c2596 196         $unit   = 's';
bf13ba 197     }
734584 198
0c2596 199     switch ($unit) {
A 200     case 'w':
201         $amount *= 7;
202     case 'd':
203         $amount *= 24;
204     case 'h':
205         $amount *= 60;
206     case 'm':
207         $amount *= 60;
208     }
209
5d66a4 210     return $amount;
A 211 }
212
213
214 /**
215  * Create a unix timestamp with a specified offset from now.
216  *
217  * @param string $offset_str  String representation of the offset (e.g. 20min, 5h, 2days)
218  * @param int    $factor      Factor to multiply with the offset
219  *
220  * @return int Unix timestamp
221  */
222 function get_offset_time($offset_str, $factor=1)
223 {
224     return time() + get_offset_sec($offset_str) * $factor;
734584 225 }
T 226
0501b6 227
T 228 /**
0c2596 229  * Truncate string if it is longer than the allowed length.
A 230  * Replace the middle or the ending part of a string with a placeholder.
0501b6 231  *
0c2596 232  * @param string $str         Input string
A 233  * @param int    $maxlength   Max. length
234  * @param string $placeholder Replace removed chars with this
235  * @param bool   $ending      Set to True if string should be truncated from the end
236  *
237  * @return string Abbreviated string
0501b6 238  */
0c2596 239 function abbreviate_string($str, $maxlength, $placeholder='...', $ending=false)
0501b6 240 {
0c2596 241     $length = mb_strlen($str);
0501b6 242
0c2596 243     if ($length > $maxlength) {
A 244         if ($ending) {
245             return mb_substr($str, 0, $maxlength) . $placeholder;
246         }
247
248         $placeholder_length = mb_strlen($placeholder);
249         $first_part_length  = floor(($maxlength - $placeholder_length)/2);
250         $second_starting_location = $length - $maxlength + $first_part_length + $placeholder_length;
251
252         $str = mb_substr($str, 0, $first_part_length) . $placeholder . mb_substr($str, $second_starting_location);
253     }
254
255     return $str;
0501b6 256 }
T 257
258
b54121 259 /**
0c2596 260  * Get all keys from array (recursive).
A 261  *
262  * @param array $array  Input array
263  *
264  * @return array List of array keys
f52c93 265  */
T 266 function array_keys_recursive($array)
267 {
0c2596 268     $keys = array();
9e54e6 269
e8be30 270     if (!empty($array) && is_array($array)) {
0c2596 271         foreach ($array as $key => $child) {
A 272             $keys[] = $key;
273             foreach (array_keys_recursive($child) as $val) {
274                 $keys[] = $val;
275             }
276         }
f52c93 277     }
0c2596 278
A 279     return $keys;
280 }
281
282
283 /**
284  * Remove all non-ascii and non-word chars except ., -, _
285  */
286 function asciiwords($str, $css_id = false, $replace_with = '')
287 {
288     $allowed = 'a-z0-9\_\-' . (!$css_id ? '\.' : '');
289     return preg_replace("/[^$allowed]/i", $replace_with, $str);
290 }
291
292
293 /**
a04a74 294  * Check if a string contains only ascii characters
AM 295  *
296  * @param string $str           String to check
297  * @param bool   $control_chars Includes control characters
298  *
299  * @return bool
300  */
301 function is_ascii($str, $control_chars = true)
302 {
303     $regexp = $control_chars ? '/[^\x00-\x7F]/' : '/[^\x20-\x7E]/';
304     return preg_match($regexp, $str) ? false : true;
305 }
306
307
308 /**
0c2596 309  * Compose a valid representation of name and e-mail address
A 310  *
311  * @param string $email  E-mail address
312  * @param string $name   Person name
313  *
314  * @return string Formatted string
315  */
316 function format_email_recipient($email, $name = '')
317 {
318     $email = trim($email);
319
320     if ($name && $name != $email) {
321         // Special chars as defined by RFC 822 need to in quoted string (or escaped).
322         if (preg_match('/[\(\)\<\>\\\.\[\]@,;:"]/', $name)) {
323             $name = '"'.addcslashes($name, '"').'"';
324         }
325
326         return "$name <$email>";
327     }
328
329     return $email;
f52c93 330 }
T 331
332
333 /**
6ab936 334  * Format e-mail address
AM 335  *
336  * @param string $email E-mail address
337  *
338  * @return string Formatted e-mail address
339  */
340 function format_email($email)
341 {
342     $email = trim($email);
343     $parts = explode('@', $email);
344     $count = count($parts);
345
346     if ($count > 1) {
347         $parts[$count-1] = mb_strtolower($parts[$count-1]);
348
349         $email = implode('@', $parts);
350     }
351
352     return $email;
353 }
354
355
356 /**
a07926 357  * Fix version number so it can be used correctly in version_compare()
AM 358  *
359  * @param string $version Version number string
360  *
361  * @param return Version number string
362  */
363 function version_parse($version)
364 {
365     return str_replace(
366         array('-stable', '-git'),
367         array('.0', '.99'),
368         $version);
369 }
370
371
372 /**
ee258c 373  * mbstring replacement functions
A 374  */
8f6a46 375 if (!extension_loaded('mbstring'))
A 376 {
ee258c 377     function mb_strlen($str)
A 378     {
0c2596 379         return strlen($str);
ee258c 380     }
A 381
382     function mb_strtolower($str)
383     {
384         return strtolower($str);
385     }
386
387     function mb_strtoupper($str)
388     {
389         return strtoupper($str);
390     }
391
392     function mb_substr($str, $start, $len=null)
393     {
394         return substr($str, $start, $len);
395     }
396
397     function mb_strpos($haystack, $needle, $offset=0)
398     {
399         return strpos($haystack, $needle, $offset);
400     }
401
402     function mb_strrpos($haystack, $needle, $offset=0)
403     {
404         return strrpos($haystack, $needle, $offset);
405     }
406 }
407
e99991 408 /**
A 409  * intl replacement functions
410  */
411
412 if (!function_exists('idn_to_utf8'))
413 {
9e4246 414     function idn_to_utf8($domain)
e99991 415     {
A 416         static $idn, $loaded;
417
418         if (!$loaded) {
419             $idn = new Net_IDNA2();
420             $loaded = true;
421         }
422
e8d5bd 423         if ($idn && $domain && preg_match('/(^|\.)xn--/i', $domain)) {
e99991 424             try {
A 425                 $domain = $idn->decode($domain);
426             }
427             catch (Exception $e) {
428             }
429         }
430         return $domain;
431     }
432 }
433
434 if (!function_exists('idn_to_ascii'))
435 {
9e4246 436     function idn_to_ascii($domain)
e99991 437     {
A 438         static $idn, $loaded;
439
440         if (!$loaded) {
441             $idn = new Net_IDNA2();
442             $loaded = true;
443         }
444
445         if ($idn && $domain && preg_match('/[^\x20-\x7E]/', $domain)) {
446             try {
447                 $domain = $idn->encode($domain);
448             }
449             catch (Exception $e) {
450             }
451         }
452         return $domain;
453     }
454 }
455
0c2596 456 /**
A 457  * Use PHP5 autoload for dynamic class loading
458  *
459  * @todo Make Zend, PEAR etc play with this
460  * @todo Make our classes conform to a more straight forward CS.
461  */
462 function rcube_autoload($classname)
463 {
464     $filename = preg_replace(
465         array(
466             '/Mail_(.+)/',
467             '/Net_(.+)/',
468             '/Auth_(.+)/',
469             '/^html_.+/',
a98a4f 470             '/^rcube(.*)/'
0c2596 471         ),
A 472         array(
473             'Mail/\\1',
474             'Net/\\1',
475             'Auth/\\1',
2187b2 476             'Roundcube/html',
a98a4f 477             'Roundcube/rcube\\1'
0c2596 478         ),
A 479         $classname
480     );
481
482     if ($fp = @fopen("$filename.php", 'r', true)) {
483         fclose($fp);
1aceb9 484         include_once "$filename.php";
0c2596 485         return true;
A 486     }
487
488     return false;
489 }
490
491 /**
492  * Local callback function for PEAR errors
493  */
494 function rcube_pear_error($err)
495 {
e17dec 496     $msg = sprintf("ERROR: %s (%s)", $err->getMessage(), $err->getCode());
AM 497
498     if ($info = $err->getUserinfo()) {
499         $msg .= ': ' . $info;
500     }
501
502     error_log($msg, 0);
0c2596 503 }