1: <?php
  2:   3:   4:   5:   6:   7:   8:   9:  10:  11:  12:  13:  14:  15:  16:  17: 
 18: 
 19: App::uses('CakePlugin', 'Core');
 20: App::uses('L10n', 'I18n');
 21: App::uses('Multibyte', 'I18n');
 22: App::uses('CakeSession', 'Model/Datasource');
 23: 
 24:  25:  26:  27:  28: 
 29: class I18n {
 30: 
 31:  32:  33:  34:  35: 
 36:     public $l10n = null;
 37: 
 38:  39:  40:  41:  42: 
 43:     public static $defaultDomain = 'default';
 44: 
 45:  46:  47:  48:  49: 
 50:     public $domain = null;
 51: 
 52:  53:  54:  55:  56: 
 57:     public $category = 'LC_MESSAGES';
 58: 
 59:  60:  61:  62:  63: 
 64:     protected $_lang = null;
 65: 
 66:  67:  68:  69:  70: 
 71:     protected $_domains = array();
 72: 
 73:  74:  75:  76:  77:  78: 
 79:     protected $_noLocale = false;
 80: 
 81:  82:  83:  84:  85: 
 86:     protected $_categories = array(
 87:         'LC_ALL', 'LC_COLLATE', 'LC_CTYPE', 'LC_MONETARY', 'LC_NUMERIC', 'LC_TIME', 'LC_MESSAGES'
 88:     );
 89: 
 90:  91:  92:  93:  94:  95:  96:  97:  98:  99: 100: 101: 102: 
103: 104: 105: 106: 107: 
108:     const LC_ALL = 0;
109: 
110: 111: 112: 113: 114: 
115:     const LC_COLLATE = 1;
116: 
117: 118: 119: 120: 121: 
122:     const LC_CTYPE = 2;
123: 
124: 125: 126: 127: 128: 
129:     const LC_MONETARY = 3;
130: 
131: 132: 133: 134: 135: 
136:     const LC_NUMERIC = 4;
137: 
138: 139: 140: 141: 142: 
143:     const LC_TIME = 5;
144: 
145: 146: 147: 148: 149: 
150:     const LC_MESSAGES = 6;
151: 
152: 153: 154: 155: 156: 
157:     protected $_escape = null;
158: 
159: 160: 161: 
162:     public function __construct() {
163:         $this->l10n = new L10n();
164:     }
165: 
166: 167: 168: 169: 170: 
171:     public static function getInstance() {
172:         static $instance = array();
173:         if (!$instance) {
174:             $instance[0] = new I18n();
175:         }
176:         return $instance[0];
177:     }
178: 
179: 180: 181: 182: 183: 184: 185: 186: 187: 188: 189: 190: 191: 192: 193: 194: 
195:     public static function translate($singular, $plural = null, $domain = null, $category = self::LC_MESSAGES,
196:         $count = null, $language = null, $context = null
197:     ) {
198:         $_this = I18n::getInstance();
199: 
200:         if (strpos($singular, "\r\n") !== false) {
201:             $singular = str_replace("\r\n", "\n", $singular);
202:         }
203:         if ($plural !== null && strpos($plural, "\r\n") !== false) {
204:             $plural = str_replace("\r\n", "\n", $plural);
205:         }
206: 
207:         if (is_numeric($category)) {
208:             $_this->category = $_this->_categories[$category];
209:         }
210: 
211:         if (empty($language)) {
212:             if (CakeSession::started()) {
213:                 $language = CakeSession::read('Config.language');
214:             }
215:             if (empty($language)) {
216:                 $language = Configure::read('Config.language');
217:             }
218:         }
219: 
220:         if (($_this->_lang && $_this->_lang !== $language) || !$_this->_lang) {
221:             $lang = $_this->l10n->get($language);
222:             $_this->_lang = $lang;
223:         }
224: 
225:         if ($domain === null) {
226:             $domain = static::$defaultDomain;
227:         }
228:         if ($domain === '') {
229:             throw new CakeException(__d('cake_dev', 'You cannot use "" as a domain.'));
230:         }
231: 
232:         $_this->domain = $domain . '_' . $_this->l10n->lang;
233: 
234:         if (!isset($_this->_domains[$domain][$_this->_lang])) {
235:             $_this->_domains[$domain][$_this->_lang] = Cache::read($_this->domain, '_cake_core_');
236:         }
237: 
238:         if (!isset($_this->_domains[$domain][$_this->_lang][$_this->category])) {
239:             $_this->_bindTextDomain($domain);
240:             Cache::write($_this->domain, $_this->_domains[$domain][$_this->_lang], '_cake_core_');
241:         }
242: 
243:         if ($_this->category === 'LC_TIME') {
244:             return $_this->_translateTime($singular, $domain);
245:         }
246: 
247:         if (!isset($count)) {
248:             $plurals = 0;
249:         } elseif (!empty($_this->_domains[$domain][$_this->_lang][$_this->category]["%plural-c"]) && $_this->_noLocale === false) {
250:             $header = $_this->_domains[$domain][$_this->_lang][$_this->category]["%plural-c"];
251:             $plurals = $_this->_pluralGuess($header, $count);
252:         } else {
253:             if ($count != 1) {
254:                 $plurals = 1;
255:             } else {
256:                 $plurals = 0;
257:             }
258:         }
259: 
260:         if (!empty($_this->_domains[$domain][$_this->_lang][$_this->category][$singular][$context])) {
261:             if (($trans = $_this->_domains[$domain][$_this->_lang][$_this->category][$singular][$context]) ||
262:                 ($plurals) && ($trans = $_this->_domains[$domain][$_this->_lang][$_this->category][$plural][$context])
263:             ) {
264:                 if (is_array($trans)) {
265:                     if (isset($trans[$plurals])) {
266:                         $trans = $trans[$plurals];
267:                     } else {
268:                         trigger_error(
269:                             __d('cake_dev',
270:                                 'Missing plural form translation for "%s" in "%s" domain, "%s" locale. ' .
271:                                 ' Check your po file for correct plurals and valid Plural-Forms header.',
272:                                 $singular,
273:                                 $domain,
274:                                 $_this->_lang
275:                             ),
276:                             E_USER_WARNING
277:                         );
278:                         $trans = $trans[0];
279:                     }
280:                 }
281:                 if (strlen($trans)) {
282:                     return $trans;
283:                 }
284:             }
285:         }
286: 
287:         if (!empty($plurals)) {
288:             return $plural;
289:         }
290:         return $singular;
291:     }
292: 
293: 294: 295: 296: 297: 
298:     public static function clear() {
299:         $self = I18n::getInstance();
300:         $self->_domains = array();
301:     }
302: 
303: 304: 305: 306: 307: 
308:     public static function domains() {
309:         $self = I18n::getInstance();
310:         return $self->_domains;
311:     }
312: 
313: 314: 315: 316: 317: 318: 319: 320: 321: 
322:     protected function _pluralGuess($header, $n) {
323:         if (!is_string($header) || $header === "nplurals=1;plural=0;" || !isset($header[0])) {
324:             return 0;
325:         }
326: 
327:         if ($header === "nplurals=2;plural=n!=1;") {
328:             return $n != 1 ? 1 : 0;
329:         } elseif ($header === "nplurals=2;plural=n>1;") {
330:             return $n > 1 ? 1 : 0;
331:         }
332: 
333:         if (strpos($header, "plurals=3")) {
334:             if (strpos($header, "100!=11")) {
335:                 if (strpos($header, "10<=4")) {
336:                     return $n % 10 == 1 && $n % 100 != 11 ? 0 : ($n % 10 >= 2 && $n % 10 <= 4 && ($n % 100 < 10 || $n % 100 >= 20) ? 1 : 2);
337:                 } elseif (strpos($header, "100<10")) {
338:                     return $n % 10 == 1 && $n % 100 != 11 ? 0 : ($n % 10 >= 2 && ($n % 100 < 10 || $n % 100 >= 20) ? 1 : 2);
339:                 }
340:                 return $n % 10 == 1 && $n % 100 != 11 ? 0 : ($n != 0 ? 1 : 2);
341:             } elseif (strpos($header, "n==2")) {
342:                 return $n == 1 ? 0 : ($n == 2 ? 1 : 2);
343:             } elseif (strpos($header, "n==0")) {
344:                 return $n == 1 ? 0 : ($n == 0 || ($n % 100 > 0 && $n % 100 < 20) ? 1 : 2);
345:             } elseif (strpos($header, "n>=2")) {
346:                 return $n == 1 ? 0 : ($n >= 2 && $n <= 4 ? 1 : 2);
347:             } elseif (strpos($header, "10>=2")) {
348:                 return $n == 1 ? 0 : ($n % 10 >= 2 && $n % 10 <= 4 && ($n % 100 < 10 || $n % 100 >= 20) ? 1 : 2);
349:             }
350:             return $n % 10 == 1 ? 0 : ($n % 10 == 2 ? 1 : 2);
351:         } elseif (strpos($header, "plurals=4")) {
352:             if (strpos($header, "100==2")) {
353:                 return $n % 100 == 1 ? 0 : ($n % 100 == 2 ? 1 : ($n % 100 == 3 || $n % 100 == 4 ? 2 : 3));
354:             } elseif (strpos($header, "n>=3")) {
355:                 return $n == 1 ? 0 : ($n == 2 ? 1 : ($n == 0 || ($n >= 3 && $n <= 10) ? 2 : 3));
356:             } elseif (strpos($header, "100>=1")) {
357:                 return $n == 1 ? 0 : ($n == 0 || ($n % 100 >= 1 && $n % 100 <= 10) ? 1 : ($n % 100 >= 11 && $n % 100 <= 20 ? 2 : 3));
358:             }
359:         } elseif (strpos($header, "plurals=5")) {
360:             return $n == 1 ? 0 : ($n == 2 ? 1 : ($n >= 3 && $n <= 6 ? 2 : ($n >= 7 && $n <= 10 ? 3 : 4)));
361:         } elseif (strpos($header, "plurals=6")) {
362:             return $n == 0 ? 0 :
363:                 ($n == 1 ? 1 :
364:                 ($n == 2 ? 2 :
365:                 ($n % 100 >= 3 && $n % 100 <= 10 ? 3 :
366:                 ($n % 100 >= 11 ? 4 : 5))));
367:         }
368: 
369:         return 0;
370:     }
371: 
372: 373: 374: 375: 376: 377: 
378:     protected function _bindTextDomain($domain) {
379:         $this->_noLocale = true;
380:         $core = true;
381:         $merge = array();
382:         $searchPaths = App::path('locales');
383:         $plugins = CakePlugin::loaded();
384: 
385:         if (!empty($plugins)) {
386:             foreach ($plugins as $plugin) {
387:                 $pluginDomain = Inflector::underscore($plugin);
388:                 if ($pluginDomain === $domain) {
389:                     $searchPaths[] = CakePlugin::path($plugin) . 'Locale' . DS;
390:                     if (!Configure::read('I18n.preferApp')) {
391:                         $searchPaths = array_reverse($searchPaths);
392:                     }
393:                     break;
394:                 }
395:             }
396:         }
397: 
398:         foreach ($searchPaths as $directory) {
399:             foreach ($this->l10n->languagePath as $lang) {
400:                 $localeDef = $directory . $lang . DS . $this->category;
401:                 if (is_file($localeDef)) {
402:                     $definitions = static::loadLocaleDefinition($localeDef);
403:                     if ($definitions !== false) {
404:                         $this->_domains[$domain][$this->_lang][$this->category] = $definitions;
405:                         $this->_noLocale = false;
406:                         return $domain;
407:                     }
408:                 }
409: 
410:                 if ($core) {
411:                     $app = $directory . $lang . DS . $this->category . DS . 'core';
412:                     $translations = false;
413: 
414:                     if (is_file($app . '.mo')) {
415:                         $translations = static::loadMo($app . '.mo');
416:                     }
417:                     if ($translations === false && is_file($app . '.po')) {
418:                         $translations = static::loadPo($app . '.po');
419:                     }
420: 
421:                     if ($translations !== false) {
422:                         $this->_domains[$domain][$this->_lang][$this->category] = $translations;
423:                         $merge[$domain][$this->_lang][$this->category] = $this->_domains[$domain][$this->_lang][$this->category];
424:                         $this->_noLocale = false;
425:                         $core = null;
426:                     }
427:                 }
428: 
429:                 $file = $directory . $lang . DS . $this->category . DS . $domain;
430:                 $translations = false;
431: 
432:                 if (is_file($file . '.mo')) {
433:                     $translations = static::loadMo($file . '.mo');
434:                 }
435:                 if ($translations === false && is_file($file . '.po')) {
436:                     $translations = static::loadPo($file . '.po');
437:                 }
438: 
439:                 if ($translations !== false) {
440:                     $this->_domains[$domain][$this->_lang][$this->category] = $translations;
441:                     $this->_noLocale = false;
442:                     break 2;
443:                 }
444:             }
445:         }
446: 
447:         if (empty($this->_domains[$domain][$this->_lang][$this->category])) {
448:             $this->_domains[$domain][$this->_lang][$this->category] = array();
449:             return $domain;
450:         }
451: 
452:         if (isset($this->_domains[$domain][$this->_lang][$this->category][""])) {
453:             $head = $this->_domains[$domain][$this->_lang][$this->category][""];
454: 
455:             foreach (explode("\n", $head) as $line) {
456:                 $header = strtok($line, ':');
457:                 $line = trim(strtok("\n"));
458:                 $this->_domains[$domain][$this->_lang][$this->category]["%po-header"][strtolower($header)] = $line;
459:             }
460: 
461:             if (isset($this->_domains[$domain][$this->_lang][$this->category]["%po-header"]["plural-forms"])) {
462:                 $switch = preg_replace("/(?:[() {}\\[\\]^\\s*\\]]+)/", "", $this->_domains[$domain][$this->_lang][$this->category]["%po-header"]["plural-forms"]);
463:                 $this->_domains[$domain][$this->_lang][$this->category]["%plural-c"] = $switch;
464:                 unset($this->_domains[$domain][$this->_lang][$this->category]["%po-header"]);
465:             }
466:             $this->_domains = Hash::mergeDiff($this->_domains, $merge);
467: 
468:             if (isset($this->_domains[$domain][$this->_lang][$this->category][null])) {
469:                 unset($this->_domains[$domain][$this->_lang][$this->category][null]);
470:             }
471:         }
472: 
473:         return $domain;
474:     }
475: 
476: 477: 478: 479: 480: 481: 482: 
483:     public static function loadMo($filename) {
484:         $translations = false;
485: 
486:         
487:         
488:         if ($data = file_get_contents($filename)) {
489:             $translations = array();
490:             $header = substr($data, 0, 20);
491:             $header = unpack('L1magic/L1version/L1count/L1o_msg/L1o_trn', $header);
492:             extract($header);
493: 
494:             if ((dechex($magic) === '950412de' || dechex($magic) === 'ffffffff950412de') && !$version) {
495:                 for ($n = 0; $n < $count; $n++) {
496:                     $r = unpack("L1len/L1offs", substr($data, $o_msg + $n * 8, 8));
497:                     $msgid = substr($data, $r["offs"], $r["len"]);
498:                     unset($msgid_plural);
499:                     $context = null;
500: 
501:                     if (strpos($msgid, "\x04") !== false) {
502:                         list($context, $msgid) = explode("\x04", $msgid);
503:                     }
504:                     if (strpos($msgid, "\000")) {
505:                         list($msgid, $msgid_plural) = explode("\000", $msgid);
506:                     }
507:                     $r = unpack("L1len/L1offs", substr($data, $o_trn + $n * 8, 8));
508:                     $msgstr = substr($data, $r["offs"], $r["len"]);
509: 
510:                     if (strpos($msgstr, "\000")) {
511:                         $msgstr = explode("\000", $msgstr);
512:                     }
513: 
514:                     if ($msgid != '') {
515:                         $translations[$msgid][$context] = $msgstr;
516:                     } else {
517:                         $translations[$msgid] = $msgstr;
518:                     }
519: 
520:                     if (isset($msgid_plural)) {
521:                         $translations[$msgid_plural] =& $translations[$msgid];
522:                     }
523:                 }
524:             }
525:         }
526:         
527: 
528:         return $translations;
529:     }
530: 
531: 532: 533: 534: 535: 536: 
537:     public static function loadPo($filename) {
538:         if (!$file = fopen($filename, 'r')) {
539:             return false;
540:         }
541: 
542:         $type = 0;
543:         $translations = array();
544:         $translationKey = '';
545:         $translationContext = null;
546:         $plural = 0;
547:         $header = '';
548: 
549:         do {
550:             $line = trim(fgets($file));
551:             if ($line === '' || $line[0] === '#') {
552:                 $translationContext = null;
553: 
554:                 continue;
555:             }
556:             if (preg_match("/msgid[[:space:]]+\"(.+)\"$/i", $line, $regs)) {
557:                 $type = 1;
558:                 $translationKey = stripcslashes($regs[1]);
559:             } elseif (preg_match("/msgid[[:space:]]+\"\"$/i", $line, $regs)) {
560:                 $type = 2;
561:                 $translationKey = '';
562:             } elseif (preg_match("/msgctxt[[:space:]]+\"(.+)\"$/i", $line, $regs)) {
563:                 $translationContext = $regs[1];
564:             } elseif (preg_match("/^\"(.*)\"$/i", $line, $regs) && ($type == 1 || $type == 2 || $type == 3)) {
565:                 $type = 3;
566:                 $translationKey .= stripcslashes($regs[1]);
567:             } elseif (preg_match("/msgstr[[:space:]]+\"(.+)\"$/i", $line, $regs) && ($type == 1 || $type == 3) && $translationKey) {
568:                 $translations[$translationKey][$translationContext] = stripcslashes($regs[1]);
569:                 $type = 4;
570:             } elseif (preg_match("/msgstr[[:space:]]+\"\"$/i", $line, $regs) && ($type == 1 || $type == 3) && $translationKey) {
571:                 $type = 4;
572:                 $translations[$translationKey][$translationContext] = '';
573:             } elseif (preg_match("/^\"(.*)\"$/i", $line, $regs) && $type == 4 && $translationKey) {
574:                 $translations[$translationKey][$translationContext] .= stripcslashes($regs[1]);
575:             } elseif (preg_match("/msgid_plural[[:space:]]+\".*\"$/i", $line, $regs)) {
576:                 $type = 6;
577:             } elseif (preg_match("/^\"(.*)\"$/i", $line, $regs) && $type == 6 && $translationKey) {
578:                 $type = 6;
579:             } elseif (preg_match("/msgstr\[(\d+)\][[:space:]]+\"(.+)\"$/i", $line, $regs) && ($type == 6 || $type == 7) && $translationKey) {
580:                 $plural = $regs[1];
581:                 $translations[$translationKey][$translationContext][$plural] = stripcslashes($regs[2]);
582:                 $type = 7;
583:             } elseif (preg_match("/msgstr\[(\d+)\][[:space:]]+\"\"$/i", $line, $regs) && ($type == 6 || $type == 7) && $translationKey) {
584:                 $plural = $regs[1];
585:                 $translations[$translationKey][$translationContext][$plural] = '';
586:                 $type = 7;
587:             } elseif (preg_match("/^\"(.*)\"$/i", $line, $regs) && $type == 7 && $translationKey) {
588:                 $translations[$translationKey][$translationContext][$plural] .= stripcslashes($regs[1]);
589:             } elseif (preg_match("/msgstr[[:space:]]+\"(.+)\"$/i", $line, $regs) && $type == 2 && !$translationKey) {
590:                 $header .= stripcslashes($regs[1]);
591:                 $type = 5;
592:             } elseif (preg_match("/msgstr[[:space:]]+\"\"$/i", $line, $regs) && !$translationKey) {
593:                 $header = '';
594:                 $type = 5;
595:             } elseif (preg_match("/^\"(.*)\"$/i", $line, $regs) && $type == 5) {
596:                 $header .= stripcslashes($regs[1]);
597:             } else {
598:                 unset($translations[$translationKey][$translationContext]);
599:                 $type = 0;
600:                 $translationKey = '';
601:                 $translationContext = null;
602:                 $plural = 0;
603:             }
604:         } while (!feof($file));
605:         fclose($file);
606: 
607:         $merge[''] = $header;
608:         return array_merge($merge, $translations);
609:     }
610: 
611: 612: 613: 614: 615: 616: 
617:     public static function loadLocaleDefinition($filename) {
618:         if (!$file = fopen($filename, 'r')) {
619:             return false;
620:         }
621: 
622:         $definitions = array();
623:         $comment = '#';
624:         $escape = '\\';
625:         $currentToken = false;
626:         $value = '';
627:         $_this = I18n::getInstance();
628:         while ($line = fgets($file)) {
629:             $line = trim($line);
630:             if (empty($line) || $line[0] === $comment) {
631:                 continue;
632:             }
633:             $parts = preg_split("/[[:space:]]+/", $line);
634:             if ($parts[0] === 'comment_char') {
635:                 $comment = $parts[1];
636:                 continue;
637:             }
638:             if ($parts[0] === 'escape_char') {
639:                 $escape = $parts[1];
640:                 continue;
641:             }
642:             $count = count($parts);
643:             if ($count === 2) {
644:                 $currentToken = $parts[0];
645:                 $value = $parts[1];
646:             } elseif ($count === 1) {
647:                 $value = is_array($value) ? $parts[0] : $value . $parts[0];
648:             } else {
649:                 continue;
650:             }
651: 
652:             $len = strlen($value) - 1;
653:             if ($value[$len] === $escape) {
654:                 $value = substr($value, 0, $len);
655:                 continue;
656:             }
657: 
658:             $mustEscape = array($escape . ',', $escape . ';', $escape . '<', $escape . '>', $escape . $escape);
659:             $replacements = array_map('crc32', $mustEscape);
660:             $value = str_replace($mustEscape, $replacements, $value);
661:             $value = explode(';', $value);
662:             $_this->_escape = $escape;
663:             foreach ($value as $i => $val) {
664:                 $val = trim($val, '"');
665:                 $val = preg_replace_callback('/(?:<)?(.[^>]*)(?:>)?/', array(&$_this, '_parseLiteralValue'), $val);
666:                 $val = str_replace($replacements, $mustEscape, $val);
667:                 $value[$i] = $val;
668:             }
669:             if (count($value) === 1) {
670:                 $definitions[$currentToken] = array_pop($value);
671:             } else {
672:                 $definitions[$currentToken] = $value;
673:             }
674:         }
675: 
676:         return $definitions;
677:     }
678: 
679: 680: 681: 682: 683: 684: 685: 
686:     public static function insertArgs($translated, array $args) {
687:         $len = count($args);
688:         if ($len === 0 || ($len === 1 && $args[0] === null)) {
689:             return $translated;
690:         }
691: 
692:         if (is_array($args[0])) {
693:             $args = $args[0];
694:         }
695: 
696:         $translated = preg_replace('/(?<!%)%(?![%\'\-+bcdeEfFgGosuxX\d\.])/', '%%', $translated);
697:         return vsprintf($translated, $args);
698:     }
699: 
700: 701: 702: 703: 704: 705: 
706:     protected function _parseLiteralValue($string) {
707:         $string = $string[1];
708:         if (substr($string, 0, 2) === $this->_escape . 'x') {
709:             $delimiter = $this->_escape . 'x';
710:             return implode('', array_map('chr', array_map('hexdec', array_filter(explode($delimiter, $string)))));
711:         }
712:         if (substr($string, 0, 2) === $this->_escape . 'd') {
713:             $delimiter = $this->_escape . 'd';
714:             return implode('', array_map('chr', array_filter(explode($delimiter, $string))));
715:         }
716:         if ($string[0] === $this->_escape && isset($string[1]) && is_numeric($string[1])) {
717:             $delimiter = $this->_escape;
718:             return implode('', array_map('chr', array_filter(explode($delimiter, $string))));
719:         }
720:         if (substr($string, 0, 3) === 'U00') {
721:             $delimiter = 'U00';
722:             return implode('', array_map('chr', array_map('hexdec', array_filter(explode($delimiter, $string)))));
723:         }
724:         if (preg_match('/U([0-9a-fA-F]{4})/', $string, $match)) {
725:             return Multibyte::ascii(array(hexdec($match[1])));
726:         }
727:         return $string;
728:     }
729: 
730: 731: 732: 733: 734: 735: 736: 
737:     protected function _translateTime($format, $domain) {
738:         if (!empty($this->_domains[$domain][$this->_lang]['LC_TIME'][$format])) {
739:             if (($trans = $this->_domains[$domain][$this->_lang][$this->category][$format])) {
740:                 return $trans;
741:             }
742:         }
743:         return $format;
744:     }
745: 
746: }
747: