File: NLS.php

package info (click to toggle)
horde3 3.1.3-4etch7
  • links: PTS
  • area: main
  • in suites: etch
  • size: 22,876 kB
  • ctags: 18,071
  • sloc: php: 75,151; xml: 2,979; sql: 1,069; makefile: 79; sh: 64
file content (526 lines) | stat: -rw-r--r-- 16,783 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
<?php
/**
 * The NLS:: class provides Native Language Support. This includes common
 * methods for handling language detection and selection, timezones, and
 * hostname->country lookups.
 *
 * $Horde: framework/NLS/NLS.php,v 1.82.4.13 2006/01/24 07:50:26 selsky Exp $
 *
 * Copyright 1999-2006 Jon Parise <jon@horde.org>
 * Copyright 1999-2006 Chuck Hagenbuch <chuck@horde.org>
 * Copyright 2002-2006 Jan Schneider <jan@horde.org>
 * Copyright 2003-2006 Michael Slusarz <slusarz@bigworm.colorado.edu>
 *
 * See the enclosed file COPYING for license information (LGPL). If you
 * did not receive this file, see http://www.fsf.org/copyleft/lgpl.html.
 *
 * @author  Jon Parise <jon@horde.org>
 * @author  Chuck Hagenbuch <chuck@horde.org>
 * @author  Jan Schneider <jan@horde.org>
 * @author  Michael Slusarz <slusarz@bigworm.colorado.edu>
 * @since   Horde 3.0
 * @package Horde_NLS
 */
class NLS {

    /**
     * Selects the most preferred language for the current client session.
     *
     * @return string  The selected language abbreviation.
     */
    function select()
    {
        global $nls, $prefs;

        $lang = Util::getFormData('new_lang');

        /* First, check if language pref is locked and, if so, set it to its
           value */
        if (isset($prefs) && $prefs->isLocked('language')) {
            $language = $prefs->getValue('language');
        /* Check if the user selected a language from the login screen */
        // backport security patch for sarge
        // See http://bugs.debian.org/434045 and http://bugs.horde.org/ticket/?id=4816
        } elseif (!empty($lang) && NLS::isValid($lang)) {
            $language = $lang;
        /* Check if we have a language set in a cookie */
        } elseif (isset($_SESSION['horde_language'])) {
            $language = $_SESSION['horde_language'];
        /* Use site-wide default, if one is defined */
        } elseif (!empty($nls['defaults']['language'])) {
            $language = $nls['defaults']['language'];
        /* Try browser-accepted languages. */
        } elseif (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
            /* The browser supplies a list, so return the first valid one. */
            $browser_langs = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
            foreach ($browser_langs as $lang) {
                /* Strip quality value for language */
                if (($pos = strpos($lang, ';')) !== false) {
                    $lang = substr($lang, 0, $pos);
                }
                $lang = NLS::_map(trim($lang));
                if (NLS::isValid($lang)) {
                    $language = $lang;
                    break;
                }
                /* In case no full match, save best guess based on prefix */
                if (!isset($partial_lang) &&
                    NLS::isValid(NLS::_map(substr($lang, 0, 2)))) {
                    $partial_lang = NLS::_map(substr($lang, 0, 2));
                }
            }
        }

        if (!isset($language)) {
            if (isset($partial_lang)) {
                $language = $partial_lang;
            } else {
                /* No dice auto-detecting, default to US English. */
                $language = 'en_US';
            }
        }

        return basename($language);
    }

    /**
     * Sets the language.
     *
     * @param string $lang  The language abbreviation.
     */
    function setLang($lang = null)
    {
        include_once HORDE_BASE . '/config/nls.php';

        if (empty($lang) || !NLS::isValid($lang)) {
            $lang = NLS::select();
        }

        if (isset($GLOBALS['language'])) {
            if ($GLOBALS['language'] == $lang) {
                return;
            } else {
                $GLOBALS['registry']->clearCache();
            }
        }

        $GLOBALS['language'] = $lang;
        $_SESSION['horde_language'] = $lang;

        /* First try language with the current charset. */
        $lang_charset = $lang . '.' . NLS::getCharset();
        if ($lang_charset != setlocale(LC_ALL, $lang_charset)) {
            /* Next try language with its default charset. */
            global $nls;
            $charset = !empty($nls['charsets'][$lang]) ? $nls['charsets'][$lang] : 'ISO-8859-1';
            $lang_charset = $lang . '.' . $charset;
            NLS::_cachedCharset(0, $charset);
            if ($lang_charset != setlocale(LC_ALL, $lang_charset)) {
                /* At last try language solely. */
                $lang_charset = $lang;
                setlocale(LC_ALL, $lang_charset);
            }
        }
        @putenv('LANG=' . $lang_charset);
        @putenv('LANGUAGE=' . $lang_charset);
    }

    /**
     * Sets the gettext domain.
     *
     * @param string $app        The application name.
     * @param string $directory  The directory where the application's
     *                           LC_MESSAGES directory resides.
     * @param string $charset    The charset.
     */
    function setTextdomain($app, $directory, $charset)
    {
        bindtextdomain($app, $directory);
        textdomain($app);

        /* The existence of this function depends on the platform. */
        if (function_exists('bind_textdomain_codeset')) {
            NLS::_cachedCharset(0, bind_textdomain_codeset($app, $charset));
        }

        if (!headers_sent()) {
            header('Content-Type: text/html; charset=' . $charset);
        }
    }

    /**
     * Determines whether the supplied language is valid.
     *
     * @param string $language  The abbreviated name of the language.
     *
     * @return boolean  True if the language is valid, false if it's not
     *                  valid or unknown.
     */
    function isValid($language)
    {
        return !empty($GLOBALS['nls']['languages'][$language]);
    }

    /**
     * Maps languages with common two-letter codes (such as nl) to the
     * full gettext code (in this case, nl_NL). Returns the language
     * unmodified if it isn't an alias.
     *
     * @access private
     *
     * @param string $language  The language code to map.
     *
     * @return string  The mapped language code.
     */

    function _map($language)
    {
        require_once 'Horde/String.php';

        $aliases = &$GLOBALS['nls']['aliases'];

        // Translate the $language to get broader matches.
        // (eg. de-DE should match de_DE)
        $trans_lang = str_replace('-', '_', $language);
        $lang_parts = explode('_', $trans_lang);
        $trans_lang = String::lower($lang_parts[0]);
        if (isset($lang_parts[1])) {
            $trans_lang .= '_' . String::upper($lang_parts[1]);
        }

        // See if we get a match for this
        if (!empty($aliases[$trans_lang])) {
            return $aliases[$trans_lang];
        }

        // If we get that far down, the language cannot be found.
        // Return $trans_lang.
        return $trans_lang;
    }

    /**
     * Returns the charset for the current language.
     *
     * @param boolean $original  If true returns the original charset of the
     *                           translation, the actually used one otherwise.
     *
     * @return string  The character set that should be used with the current
     *                 locale settings.
     */
    function getCharset($original = false)
    {
        global $language, $nls;

        /* Get cached results. */
        $cacheKey = intval($original);
        $charset = NLS::_cachedCharset($cacheKey);
        if (!is_null($charset)) {
            return $charset;
        }

        if ($original) {
            $charset = empty($nls['charsets'][$language]) ? 'ISO-8859-1' : $nls['charsets'][$language];
        } else {
            require_once 'Horde/Browser.php';
            $browser = &Browser::singleton();

            if ($browser->hasFeature('utf') &&
                (Util::extensionExists('iconv') ||
                 Util::extensionExists('mbstring'))) {
                $charset = 'UTF-8';
            }
        }

        if (is_null($charset)) {
            $charset = NLS::getExternalCharset();
        }

        NLS::_cachedCharset($cacheKey, $charset);
        return $charset;
    }


    /**
     * Returns the current charset of the environment
     *
     * @return string  The character set that should be used with the current
     *                 locale settings.
     */
    function getExternalCharset()
    {
        global $language, $nls;

        /* Get cached results. */
        $charset = NLS::_cachedCharset(2);
        if (!is_null($charset)) {
            return $charset;
        }

        $lang_charset = setlocale(LC_ALL, 0);
        if (strpos($lang_charset, ';') === false &&
            strpos($lang_charset, '/') === false) {
            $lang_charset = explode('.', $lang_charset);
            if ((count($lang_charset) == 2) && !empty($lang_charset[1])) {
                NLS::_cachedCharset(2, $lang_charset[1]);
                return $lang_charset[1];
            }
        }

        return (!empty($nls['charsets'][$language])) ? $nls['charsets'][$language] : 'ISO-8859-1';
    }

    /**
     * Sets or returns the charset used under certain conditions.
     *
     * @access private
     *
     * @param integer $index   The ID of a cache slot. 0 for the UI charset, 1
     *                         for the translation charset and 2 for the
     *                         external charset.
     * @param string $charset  If specified, this charset will be stored in the
     *                         given cache slot. Otherwise the content of the
     *                         specified cache slot will be returned.
     */
    function _cachedCharset($index, $charset = null)
    {
        static $cache;

        if (!isset($cache)) {
            $cache = array();
        }

        if ($charset == null) {
            return isset($cache[$index]) ? $cache[$index] : null;
        } else {
            $cache[$index] = $charset;
        }
    }

    /**
     * Returns the charset to use for outgoing emails.
     *
     * @return string  The preferred charset for outgoing mails based on
     *                 the user's preferences and the current language.
     */
    function getEmailCharset()
    {
        global $prefs, $language, $nls;

        $charset = $prefs->getValue('sending_charset');
        if (!empty($charset)) {
            return $charset;
        }
        return isset($nls['emails'][$language]) ? $nls['emails'][$language] :
               (isset($nls['charsets'][$language]) ? $nls['charsets'][$language] : 'ISO-8859-1');
    }

    /**
     * Check to see if character set is valid for htmlspecialchars() calls.
     *
     * @param string $charset  The character set to check.
     *
     * @return boolean  Is charset valid for the current system?
     */
    function checkCharset($charset)
    {
        static $check;

        if (is_null($charset) || empty($charset)) {
            return false;
        }

        if (isset($check[$charset])) {
            return $check[$charset];
        } elseif (!isset($check)) {
            $check = array();
        }

        $valid = true;

        ini_set('track_errors', 1);
        @htmlspecialchars('', ENT_COMPAT, $charset);
        if (isset($php_errormsg)) {
            $valid = false;
        }
        ini_restore('track_errors');

        $check[$charset] = $valid;

        return $valid;
    }

   /**
     * Sets the charset.
     * In general, the applied charset is automatically determined by browser
     * language and browser capabilities and there's no need to manually call
     * setCharset. However for headless (RPC) operations the charset may be
     * set manually to ensure correct character conversion in the backend.
     *
     * @param string $charset  If specified, this charset will be stored in the
     *                         given cache slot.
     *
     * @param integer $index   The ID of a cache slot. 0 for the UI charset, 1
     *                         for the translation charset and 2 for the
     *                         external charset. Defaults to 0: this is the
     *                         charset returned by getCharset and used for
     *                         conversion.
     */

    function setCharset($charset,$index = 0)
    {
        NLS::_cachedCharset($index, $charset);
    }

    /**
     * Sets the current timezone, if available.
     */
    function setTimeZone()
    {
        global $prefs;

        $tz = $prefs->getValue('timezone');
        if (!empty($tz)) {
            @putenv('TZ=' . $tz);
        }
    }

    /**
     * Get the locale info returned by localeconv(), but cache it, to
     * avoid repeated calls.
     *
     * @return array  The results of localeconv().
     */
    function getLocaleInfo()
    {
        static $lc_info;

        if (!isset($lc_info)) {
            $lc_info = localeconv();
        }

        return $lc_info;
    }

    /**
     * Get the language info returned by nl_langinfo(), but cache it, to
     * avoid repeated calls.
     *
     * @since Horde 3.1
     *
     * @param const $item  The langinfo item to return.
     *
     * @return array  The results of nl_langinfo().
     */
    function getLangInfo($item)
    {
        static $nl_info = array();

        if (!isset($nl_info[$item])) {
            $nl_info[$item] = nl_langinfo($item);
        }

        return $nl_info[$item];
    }

    /**
     * Get country information from a hostname or IP address.
     *
     * @param string $host  The hostname or IP address.
     *
     * @return mixed  On success, return an array with the following entries:
     *                'code'  =>  Country Code
     *                'name'  =>  Country Name
     *                On failure, return false.
     */
    function getCountryByHost($host)
    {
        global $conf;

        /* List of generic domains that we know is not in the country TLD
           list. See: http://www.iana.org/gtld/gtld.htm */
        $generic = array(
            'aero', 'biz', 'com', 'coop', 'edu', 'gov', 'info', 'int', 'mil',
            'museum', 'name', 'net', 'org', 'pro'
        );

        $checkHost = $host;
        if (preg_match('/^\d+\.\d+\.\d+\.\d+$/', $host)) {
            $checkHost = @gethostbyaddr($host);
        }

        /* Get the TLD of the hostname. */
        $pos = strrpos($checkHost, '.');
        if ($pos === false) {
            return false;
        }
        $domain = String::lower(substr($checkHost, $pos + 1));

        /* Try lookup via TLD first. */
        if (!in_array($domain, $generic)) {
            require 'Horde/NLS/tld.php';
            if (isset($tld[$domain])) {
                return array('code' => $domain, 'name' => $tld[$domain]);
            }
        }

        /* Try GeoIP lookup next. */
        if (!empty($conf['geoip']['datafile'])) {
            require_once 'Horde/NLS/GeoIP.php';
            $geoip = &NLS_GeoIP::singleton($conf['geoip']['datafile']);
            $id = $geoip->countryIdByName($checkHost);
            if (!empty($id)) {
                return array('code' => String::lower($GLOBALS['GEOIP_COUNTRY_CODES'][$id]), 'name' => $GLOBALS['GEOIP_COUNTRY_NAMES'][$id]);
            }
        }

        return false;
    }

    /**
     * Returns a Horde image link to the country flag.
     *
     * @param string $host  The hostname or IP address.
     *
     * @return string  The image URL, or the empty string on error.
     */
    function generateFlagImageByHost($host)
    {
        global $registry;

        $data = NLS::getCountryByHost($host);
        if ($data !== false) {
            $img = $data['code'] . '.png';
            if (file_exists($registry->get('themesfs', 'horde') . '/graphics/flags/' . $img)) {
                return Horde::img($img, $data['name'], array('title' => $data['name']), $registry->getImageDir('horde') . '/flags');
            } else {
                return '[' . $data['name'] . ']';
            }
        }

        return '';
    }

    /**
     * Returns either a specific or all ISO-3166 country names.
     *
     * @param string $code  The ISO 3166 country code.
     *
     * @return mixed  If a country code has been requested will return the
     *                corresponding country name. If empty will return an
     *                array of all the country codes and their names.
     */
    function &getCountryISO($code = '')
    {
        static $countries = array();
        if (empty($countries)) {
            require_once 'Horde/NLS/countries.php';
        }
        if (empty($code)) {
            return $countries;
        } elseif (isset($countries[$code])) {
            return $countries[$code];
        }
        return false;
    }

}