Aleksander Machniak
2015-02-27 5aa1d2005bb01f9f7f6bb2275dc467f7b7b368f4
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)
102 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'rcube_pear_error');
103
4e17e6 104
a0109c 105
6d969b 106 /**
f11541 107  * Similar function as in_array() but case-insensitive
6d969b 108  *
0c2596 109  * @param string $needle    Needle value
A 110  * @param array  $heystack  Array to search in
111  *
6d969b 112  * @return boolean True if found, False if not
f11541 113  */
4e17e6 114 function in_array_nocase($needle, $haystack)
6d969b 115 {
0c2596 116     $needle = mb_strtolower($needle);
be9840 117     foreach ((array)$haystack as $value) {
0c2596 118         if ($needle === mb_strtolower($value)) {
A 119             return true;
120         }
121     }
9e54e6 122
0c2596 123     return false;
6d969b 124 }
4e17e6 125
T 126
6d969b 127 /**
0c2596 128  * Parse a human readable string for a number of bytes.
6d969b 129  *
0c2596 130  * @param string $str  Input string
A 131  *
47f072 132  * @return float Number of bytes
6d969b 133  */
86df15 134 function parse_bytes($str)
6d969b 135 {
0c2596 136     if (is_numeric($str)) {
A 137         return floatval($str);
86df15 138     }
T 139
0c2596 140     if (preg_match('/([0-9\.]+)\s*([a-z]*)/i', $str, $regs)) {
A 141         $bytes = floatval($regs[1]);
142         switch (strtolower($regs[2])) {
143         case 'g':
144         case 'gb':
145             $bytes *= 1073741824;
146             break;
147         case 'm':
148         case 'mb':
149             $bytes *= 1048576;
150             break;
151         case 'k':
152         case 'kb':
153             $bytes *= 1024;
154             break;
7145e0 155         }
A 156     }
0c2596 157
A 158     return floatval($bytes);
7145e0 159 }
86df15 160
0c2596 161
6d969b 162 /**
T 163  * Make sure the string ends with a slash
164  */
bac7d1 165 function slashify($str)
6d969b 166 {
bac7d1 167   return unslashify($str).'/';
6d969b 168 }
bac7d1 169
T 170
6d969b 171 /**
e8be30 172  * Remove slashes at the end of the string
6d969b 173  */
bac7d1 174 function unslashify($str)
6d969b 175 {
e8be30 176   return preg_replace('/\/+$/', '', $str);
6d969b 177 }
9fee0e 178
T 179
6d969b 180 /**
5d66a4 181  * Returns number of seconds for a specified offset string.
6d969b 182  *
5d66a4 183  * @param string $str  String representation of the offset (e.g. 20min, 5h, 2days, 1week)
0c2596 184  *
5d66a4 185  * @return int Number of seconds
6d969b 186  */
5d66a4 187 function get_offset_sec($str)
9e54e6 188 {
5d66a4 189     if (preg_match('/^([0-9]+)\s*([smhdw])/i', $str, $regs)) {
A 190         $amount = (int) $regs[1];
0c2596 191         $unit   = strtolower($regs[2]);
734584 192     }
bf13ba 193     else {
5d66a4 194         $amount = (int) $str;
0c2596 195         $unit   = 's';
bf13ba 196     }
734584 197
0c2596 198     switch ($unit) {
A 199     case 'w':
200         $amount *= 7;
201     case 'd':
202         $amount *= 24;
203     case 'h':
204         $amount *= 60;
205     case 'm':
206         $amount *= 60;
207     }
208
5d66a4 209     return $amount;
A 210 }
211
212
213 /**
214  * Create a unix timestamp with a specified offset from now.
215  *
216  * @param string $offset_str  String representation of the offset (e.g. 20min, 5h, 2days)
217  * @param int    $factor      Factor to multiply with the offset
218  *
219  * @return int Unix timestamp
220  */
221 function get_offset_time($offset_str, $factor=1)
222 {
223     return time() + get_offset_sec($offset_str) * $factor;
734584 224 }
T 225
0501b6 226
T 227 /**
0c2596 228  * Truncate string if it is longer than the allowed length.
A 229  * Replace the middle or the ending part of a string with a placeholder.
0501b6 230  *
0c2596 231  * @param string $str         Input string
A 232  * @param int    $maxlength   Max. length
233  * @param string $placeholder Replace removed chars with this
234  * @param bool   $ending      Set to True if string should be truncated from the end
235  *
236  * @return string Abbreviated string
0501b6 237  */
0c2596 238 function abbreviate_string($str, $maxlength, $placeholder='...', $ending=false)
0501b6 239 {
0c2596 240     $length = mb_strlen($str);
0501b6 241
0c2596 242     if ($length > $maxlength) {
A 243         if ($ending) {
244             return mb_substr($str, 0, $maxlength) . $placeholder;
245         }
246
247         $placeholder_length = mb_strlen($placeholder);
248         $first_part_length  = floor(($maxlength - $placeholder_length)/2);
249         $second_starting_location = $length - $maxlength + $first_part_length + $placeholder_length;
250
251         $str = mb_substr($str, 0, $first_part_length) . $placeholder . mb_substr($str, $second_starting_location);
252     }
253
254     return $str;
0501b6 255 }
T 256
257
b54121 258 /**
0c2596 259  * Get all keys from array (recursive).
A 260  *
261  * @param array $array  Input array
262  *
263  * @return array List of array keys
f52c93 264  */
T 265 function array_keys_recursive($array)
266 {
0c2596 267     $keys = array();
9e54e6 268
e8be30 269     if (!empty($array) && is_array($array)) {
0c2596 270         foreach ($array as $key => $child) {
A 271             $keys[] = $key;
272             foreach (array_keys_recursive($child) as $val) {
273                 $keys[] = $val;
274             }
275         }
f52c93 276     }
0c2596 277
A 278     return $keys;
279 }
280
281
282 /**
283  * Remove all non-ascii and non-word chars except ., -, _
284  */
285 function asciiwords($str, $css_id = false, $replace_with = '')
286 {
287     $allowed = 'a-z0-9\_\-' . (!$css_id ? '\.' : '');
288     return preg_replace("/[^$allowed]/i", $replace_with, $str);
289 }
290
291
292 /**
a04a74 293  * Check if a string contains only ascii characters
AM 294  *
295  * @param string $str           String to check
296  * @param bool   $control_chars Includes control characters
297  *
298  * @return bool
299  */
300 function is_ascii($str, $control_chars = true)
301 {
302     $regexp = $control_chars ? '/[^\x00-\x7F]/' : '/[^\x20-\x7E]/';
303     return preg_match($regexp, $str) ? false : true;
304 }
305
306
307 /**
0c2596 308  * Compose a valid representation of name and e-mail address
A 309  *
310  * @param string $email  E-mail address
311  * @param string $name   Person name
312  *
313  * @return string Formatted string
314  */
315 function format_email_recipient($email, $name = '')
316 {
317     $email = trim($email);
318
319     if ($name && $name != $email) {
320         // Special chars as defined by RFC 822 need to in quoted string (or escaped).
321         if (preg_match('/[\(\)\<\>\\\.\[\]@,;:"]/', $name)) {
322             $name = '"'.addcslashes($name, '"').'"';
323         }
324
325         return "$name <$email>";
326     }
327
328     return $email;
f52c93 329 }
T 330
331
332 /**
6ab936 333  * Format e-mail address
AM 334  *
335  * @param string $email E-mail address
336  *
337  * @return string Formatted e-mail address
338  */
339 function format_email($email)
340 {
341     $email = trim($email);
342     $parts = explode('@', $email);
343     $count = count($parts);
344
345     if ($count > 1) {
346         $parts[$count-1] = mb_strtolower($parts[$count-1]);
347
348         $email = implode('@', $parts);
349     }
350
351     return $email;
352 }
353
354
355 /**
a07926 356  * Fix version number so it can be used correctly in version_compare()
AM 357  *
358  * @param string $version Version number string
359  *
360  * @param return Version number string
361  */
362 function version_parse($version)
363 {
364     return str_replace(
365         array('-stable', '-git'),
366         array('.0', '.99'),
367         $version);
368 }
369
370
371 /**
ee258c 372  * mbstring replacement functions
A 373  */
8f6a46 374 if (!extension_loaded('mbstring'))
A 375 {
ee258c 376     function mb_strlen($str)
A 377     {
0c2596 378         return strlen($str);
ee258c 379     }
A 380
381     function mb_strtolower($str)
382     {
383         return strtolower($str);
384     }
385
386     function mb_strtoupper($str)
387     {
388         return strtoupper($str);
389     }
390
391     function mb_substr($str, $start, $len=null)
392     {
393         return substr($str, $start, $len);
394     }
395
396     function mb_strpos($haystack, $needle, $offset=0)
397     {
398         return strpos($haystack, $needle, $offset);
399     }
400
401     function mb_strrpos($haystack, $needle, $offset=0)
402     {
403         return strrpos($haystack, $needle, $offset);
404     }
405 }
406
e99991 407 /**
A 408  * intl replacement functions
409  */
410
411 if (!function_exists('idn_to_utf8'))
412 {
9e4246 413     function idn_to_utf8($domain)
e99991 414     {
A 415         static $idn, $loaded;
416
417         if (!$loaded) {
418             $idn = new Net_IDNA2();
419             $loaded = true;
420         }
421
e8d5bd 422         if ($idn && $domain && preg_match('/(^|\.)xn--/i', $domain)) {
e99991 423             try {
A 424                 $domain = $idn->decode($domain);
425             }
426             catch (Exception $e) {
427             }
428         }
429         return $domain;
430     }
431 }
432
433 if (!function_exists('idn_to_ascii'))
434 {
9e4246 435     function idn_to_ascii($domain)
e99991 436     {
A 437         static $idn, $loaded;
438
439         if (!$loaded) {
440             $idn = new Net_IDNA2();
441             $loaded = true;
442         }
443
444         if ($idn && $domain && preg_match('/[^\x20-\x7E]/', $domain)) {
445             try {
446                 $domain = $idn->encode($domain);
447             }
448             catch (Exception $e) {
449             }
450         }
451         return $domain;
452     }
453 }
454
0c2596 455 /**
A 456  * Use PHP5 autoload for dynamic class loading
457  *
458  * @todo Make Zend, PEAR etc play with this
459  * @todo Make our classes conform to a more straight forward CS.
460  */
461 function rcube_autoload($classname)
462 {
463     $filename = preg_replace(
464         array(
465             '/Mail_(.+)/',
466             '/Net_(.+)/',
467             '/Auth_(.+)/',
468             '/^html_.+/',
a98a4f 469             '/^rcube(.*)/'
0c2596 470         ),
A 471         array(
472             'Mail/\\1',
473             'Net/\\1',
474             'Auth/\\1',
2187b2 475             'Roundcube/html',
a98a4f 476             'Roundcube/rcube\\1'
0c2596 477         ),
A 478         $classname
479     );
480
481     if ($fp = @fopen("$filename.php", 'r', true)) {
482         fclose($fp);
1aceb9 483         include_once "$filename.php";
0c2596 484         return true;
A 485     }
486
487     return false;
488 }
489
490 /**
491  * Local callback function for PEAR errors
492  */
493 function rcube_pear_error($err)
494 {
e17dec 495     $msg = sprintf("ERROR: %s (%s)", $err->getMessage(), $err->getCode());
AM 496
497     if ($info = $err->getUserinfo()) {
498         $msg .= ': ' . $info;
499     }
500
501     error_log($msg, 0);
0c2596 502 }