/
habarilocale.php
494 lines (445 loc) · 14.4 KB
/
habarilocale.php
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
<?php
/**
* @package Habari
*
*/
/**
* Habari Locale Class
*
* Provides translation services.
*
*/
class HabariLocale
{
private static $uselocale = false;
private static $messages = array();
private static $plural_function;
private static $locale;
/**
* Sets the locale for Habari.
*
* @param string $locale A language code like 'en' or 'en-us' or 'x-klingon', will be lowercased
*/
public static function set( $locale = null )
{
if ( $locale == null ) {
return;
}
self::$locale = strtolower( $locale );
self::$uselocale = self::load_domain( 'habari' );
}
/**
* Return the current locale
* @static
* @return string The current locale.
*/
public static function get()
{
return self::$locale;
}
/**
* Set system locale.
*
* The problem is that every platform has its own way to designate a locale,
* so for German you could have 'de', 'de_DE', 'de_DE.UTF-8', 'de_DE.UTF-8@euro'
* (Linux) or 'DEU' (Windows), etc.
*
* @todo: This setting should probably be stored in the language files.
*
* @param string... $locale The locale(s) to set. They will be tried in order.
* @return string the locale that was picked, or false if an error occurred
*/
public static function set_system_locale()
{
if ( func_num_args() == 0 ) return;
$args = func_get_args();
array_unshift( $args, LC_ALL );
return call_user_func_array( 'setlocale', $args );
}
/**
* Load translations for a given domain and base directory for a pluggable object.
* Translations are stored in gettext-style .mo files.
* The internal workings of the file format are not entirely meant to be understood.
*
* @link http://www.gnu.org/software/gettext/manual/html_node/gettext_136.html GNU Gettext Manual: Description of the MO file format
* @param string $domain the domain to load
* @param string $base_dir the base directory in which to find the translation files
* @return boolean true if data was successfully loaded, false otherwise
*/
public static function load_pluggable_domain( $domain, $base_dir )
{
$file = $base_dir . '/locale/' . self::$locale . '/LC_MESSAGES/' . $domain . '.mo';
return self::load_file( $domain, $file );
}
/**
* Load translations for a given domain.
* Translations are stored in gettext-style .mo files.
* The internal workings of the file format are not entirely meant to be understood.
*
* @link http://www.gnu.org/software/gettext/manual/html_node/gettext_136.html GNU Gettext Manual: Description of the MO file format
* @param string $domain the domain to load
* @return boolean true if data was successfully loaded, false otherwise
*/
private static function load_domain( $domain )
{
$file_end = self::$locale . '/LC_MESSAGES/' . $domain . '.mo';
if ( file_exists( Site::get_dir( 'config' ) . '/locale/' . $file_end ) ) {
$file = Site::get_dir( 'config' ) . '/locale/' . $file_end;
}
else if ( file_exists( HABARI_PATH . '/user/locale/' . $file_end ) ) {
$file = HABARI_PATH . '/user/locale/' . $file_end;
}
else if ( file_exists( HABARI_PATH . '/3rdparty/locale/' . $file_end ) ) {
$file = HABARI_PATH . '/3rdparty/locale/' . $file_end;
}
else {
$file = HABARI_PATH . '/system/locale/' . $file_end;
}
return self::load_file( $domain, $file );
}
/**
* function list_all
* Retrieves an array of the Habari locales that are installed
*
* @return array. An array of Habari locales in the installation
*/
public static function list_all()
{
$localedirs = array( HABARI_PATH . '/system/locale/', HABARI_PATH . '/3rdparty/locale/', HABARI_PATH . '/user/locale/' );
if ( Site::CONFIG_LOCAL != Site::$config_type ) {
// include site-specific locales
$localedirs[] = Site::get_dir( 'config' ) . '/locale/';
}
$dirs = array();
foreach ( $localedirs as $localedir ) {
if ( file_exists( $localedir ) ) {
$dirs = array_merge( $dirs, Utils::glob( $localedir . '*', GLOB_ONLYDIR | GLOB_MARK ) );
}
}
$dirs = array_filter( $dirs, function( $a ) {return file_exists($a . "LC_MESSAGES/habari.mo"); } );
$locales = array_map( 'basename', $dirs );
ksort( $locales );
return $locales;
}
/**
* Load translations from a given file.
*
* @param string $domain the domain to load the data into
* @param string $file the file name
* @return boolean true if data was successfully loaded, false otherwise
*/
private static function load_file( $domain, $file )
{
if ( ! file_exists( $file ) ) {
Error::raise( _t( 'No translations found for locale %s, domain %s!', array( self::$locale, $domain ) ) );
return false;
}
if ( filesize( $file ) < 24 ) {
Error::raise( _t( 'Invalid .MO file for locale %s, domain %s!', array( self::$locale, $domain ) ) );
return false;
}
$fp = fopen( $file, 'rb' );
$data = fread( $fp, filesize( $file ) );
fclose( $fp );
// determine endianness
$little_endian = true;
list(,$magic) = unpack( 'V1', substr( $data, 0, 4 ) );
switch ( $magic & 0xFFFFFFFF ) {
case (int)0x950412de:
$little_endian = true;
break;
case (int)0xde120495:
$little_endian = false;
break;
default:
Error::raise( _t( 'Invalid magic number 0x%08x in %s!', array( $magic, $file ) ) );
return false;
}
$revision = substr( $data, 4, 4 );
if ( $revision != 0 ) {
Error::raise( _t( 'Unknown revision number %d in %s!', array( $revision, $file ) ) );
return false;
}
$l = $little_endian ? 'V' : 'N';
if ( $data && strlen( $data ) >= 20 ) {
$header = substr( $data, 8, 12 );
$header = unpack( "{$l}1msgcount/{$l}1msgblock/{$l}1transblock", $header );
if ( $header['msgblock'] + ($header['msgcount'] - 1 ) * 8 > filesize( $file ) ) {
Error::raise( _t( 'Message count (%d) out of bounds in %s!', array( $header['msgcount'], $file ) ) );
return false;
}
$lo = "{$l}1length/{$l}1offset";
for ( $msgindex = 0; $msgindex < $header['msgcount']; $msgindex++ ) {
$msginfo = unpack( $lo, substr( $data, $header['msgblock'] + $msgindex * 8, 8 ) );
$msgids = explode( "\0", substr( $data, $msginfo['offset'], $msginfo['length'] ) );
$transinfo = unpack( $lo, substr( $data, $header['transblock'] + $msgindex * 8, 8 ) );
$transids = explode( "\0", substr( $data, $transinfo['offset'], $transinfo['length'] ) );
self::$messages[$domain][$msgids[0]] = array(
$msgids,
$transids,
);
}
}
// setup plural functionality
self::$plural_function = self::get_plural_function( self::$messages[$domain][''][1][0] );
// only use locale if we actually read something
return ( count( self::$messages ) > 0 );
}
private static function get_plural_function( $header )
{
if ( preg_match( '/plural-forms: (.*?)\n/i', $header, $matches ) && preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $matches[1], $matches ) ) {
// sanitize
$nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
$plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
$body = str_replace(
array( 'plural', 'n', '$n$plurals', ),
array( '$plural', '$n', '$nplurals', ),
'nplurals='. $nplurals . '; plural=' . $plural
);
// add parens
// important since PHP's ternary evaluates from left to right
$body .= ';';
$res = '';
$p = 0;
for ( $i = 0; $i < strlen( $body ); $i++ ) {
$ch = $body[$i];
switch ( $ch ) {
case '?':
$res .= ' ? (';
$p++;
break;
case ':':
$res .= ') : (';
break;
case ';':
$res .= str_repeat( ')', $p ) . ';';
$p = 0;
break;
default:
$res .= $ch;
}
}
$body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
$fn = create_function(
'$n',
$body
);
}
else {
// default: one plural form for all cases but n==1 (english)
$fn = create_function(
'$n',
'$nplurals=2;$plural=($n==1?0:1);return ($plural>=$nplurals?$nplurals-1:$plural);'
);
}
return $fn;
}
/**
* DO NOT USE THIS FUNCTION.
* This function is only to be used by the test case for the Locale class!
*/
public static function __run_plural_test( $header )
{
$fn = self::get_plural_function( $header );
$res = '';
for ( $n = 0; $n < 200; $n++ ) {
$res .= $fn( $n );
}
return $res;
}
/**
* DO NOT USE THIS FUNCTION.
* This function is only to be used by the test case for the Locale class!
*/
public static function __run_loadfile_test( $filename )
{
return self::load_file( 'test', $filename );
}
/**
* Echo a version of the string translated into the current locale
* @param string $text The text to echo translated
* @param string $domain (optional) The domain to search for the message
*/
public static function _e()
{
$args = func_get_args();
echo call_user_func_array( array( 'HabariLocale', '_t' ), $args );
}
/**
* Return a version of the string translated into the current locale
*
* @param string $text The text to echo translated
* @param string $domain (optional) The domain to search for the message
* @return string The translated string
*/
public static function _t( $text, $args = array(), $domain = 'habari' )
{
if ( is_string( $args ) ) {
$domain = $args;
}
if ( isset( self::$messages[$domain][$text] ) ) {
$t = self::$messages[$domain][$text][1][0];
}
else {
$t = $text;
}
if ( !empty( $args ) && is_array( $args ) ) {
array_unshift( $args, $t );
$t = call_user_func_array( 'sprintf', $args );
}
return $t;
}
/**
* Return the entire message catalog for a domain as an array
*
* @static
* @param string $domain (optional) The domain to return
* @return array The array of locale messages
*/
public static function get_messages($domain = 'habari')
{
return self::$messages[$domain];
}
/**
* Given a string translated into the current locale, return the untranslated string.
*
* @param string $text The translated string
* @param string $domain (optional) The domain to search for the message
* @return string The untranslated string
*/
public static function _u( $text, $domain = 'habari' )
{
$t = $text;
foreach ( self::$messages[$domain] as $msg ) {
if ( $text == $msg[1][0] ) {
$t = $msg[0][0];
break;
}
}
return $t;
}
/**
* Echo singular or plural version of the string, translated into the current locale, based on the count provided
*
* @param string $singular The singular form
* @param string $plural The plural form
* @param string $count The count
* @param string $domain (optional) The domain to search for the message
*/
public static function _ne( $singular, $plural, $count, $domain = 'habari' )
{
echo self::_n( $singular, $plural, $count, $domain );
}
/**
* Return a singular or plural string translated into the current locale based on the count provided
*
* @param string $singular The singular form
* @param string $plural The plural form
* @param string $count The count
* @param string $domain (optional) The domain to search for the message
* @return string The appropriately translated string
*/
public static function _n( $singular, $plural, $count, $domain = 'habari' )
{
if ( isset( self::$messages[$domain][$singular] ) ) {
// XXX workaround, but direct calling doesn't work
$fn = self::$plural_function;
$n = $fn( $count );
if ( isset( self::$messages[$domain][$singular][1][$n] ) ) {
return self::$messages[$domain][$singular][1][$n];
}
}
// fall-through else for both cases
return ( $count == 1 ? $singular : $plural );
}
/**
* Return a translated value of a SimpleXml object value based on the locale and namespace
*
* @param SimpleXMLElement $parent The parent node of the node we are translating
* @param SimpleXMLElement $child The child node we're trying to translate
* @param string The namespace to use for the lang attribute of the node to be translated
* @param string $locale The locale we want to translate into
* @return nothing. Translations are done in place
* @todo These defaults may need tweaked. It seems there should be a better way to do this whole thing
*/
public static function translate_xml( $parent, $child, $ns = 'http://www.w3.org/XML/1998/namespace', $locale = null )
{
$use = null;
// Set the locale
if( !isset( $locale ) ) {
$locale = self::$locale;
}
// Loop through the child elements
foreach( $child as $el ) {
$attr = $el->attributes( $ns );
foreach( $attr as $key => $value ) {
// Found one with the language of the current locale
if ( $key == 'lang' && $value == $locale ) {
$use = (string)$el;
}
}
}
// If a translation for the element is found, use it instead of the default value
if ( ! empty( $use ) ) {
$name = $child->getName();
unset( $parent->$name );
$parent->addChild( $name, $use );
}
}
}
/**
* Echo a version of the string translated into the current locale, alias for HabariLocale::_e()
*
* @param string $text The text to translate
*/
function _e( $text, $args = array(), $domain = 'habari' )
{
return HabariLocale::_e( $text, $args, $domain );
}
/**
* function _ne
* Echo singular or plural version of the string, translated into the current locale, based on the count provided,
* alias for HabariLocale::_ne()
* @param string $singular The singular form
* @param string $plural The plural form
* @param string $count The count
*/
function _ne( $singular, $plural, $count, $domain = 'habari' )
{
return HabariLocale::_ne( $singular, $plural, $count, $domain );
}
/**
* Return a version of the string translated into the current locale, alias for HabariLocale::_t()
*
* @param string $text The text to translate
* @return string The translated string
*/
function _t( $text, $args = array(), $domain = 'habari' )
{
return HabariLocale::_t( $text, $args, $domain );
}
/**
* Return a singular or plural string translated into the current locale based on the count provided
*
* @param string $singular The singular form
* @param string $plural The plural form
* @param string $count The count
* @return string The appropriately translated string
*/
function _n( $singular, $plural, $count, $domain = 'habari' )
{
return HabariLocale::_n( $singular, $plural, $count, $domain );
}
/**
* Given a string translated into the current locale, return the untranslated version of the string.
* Alias for HabariLocale::_u()
*
* @param string $text The translated string
* @param string $domain (optional) The domain to search for the message
* @return string The untranslated string
*/
function _u( $text, $domain = 'habari' )
{
return HabariLocale::_u( $text, $domain );
}
?>