Adapter.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Translate
  17. * @subpackage Zend_Translate_Adapter
  18. * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. * @version $Id$
  21. */
  22. /**
  23. * @see Zend_Locale
  24. */
  25. require_once 'Zend/Locale.php';
  26. /**
  27. * @see Zend_Translate_Plural
  28. */
  29. require_once 'Zend/Translate/Plural.php';
  30. /**
  31. * Basic adapter class for each translation source adapter
  32. *
  33. * @category Zend
  34. * @package Zend_Translate
  35. * @subpackage Zend_Translate_Adapter
  36. * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  37. * @license http://framework.zend.com/license/new-bsd New BSD License
  38. */
  39. abstract class Zend_Translate_Adapter {
  40. /**
  41. * Shows if locale detection is in automatic level
  42. * @var boolean
  43. */
  44. private $_automatic = true;
  45. /**
  46. * Internal value to see already routed languages
  47. * @var array()
  48. */
  49. private $_routed = array();
  50. /**
  51. * Internal cache for all adapters
  52. * @var Zend_Cache_Core
  53. */
  54. protected static $_cache = null;
  55. /**
  56. * Internal value to remember if cache supports tags
  57. *
  58. * @var boolean
  59. */
  60. private static $_cacheTags = false;
  61. /**
  62. * Scans for the locale within the name of the directory
  63. * @constant integer
  64. */
  65. const LOCALE_DIRECTORY = 'directory';
  66. /**
  67. * Scans for the locale within the name of the file
  68. * @constant integer
  69. */
  70. const LOCALE_FILENAME = 'filename';
  71. /**
  72. * Array with all options, each adapter can have own additional options
  73. * 'clear' => when true, clears already loaded translations when adding new files
  74. * 'content' => content to translate or file or directory with content
  75. * 'disableNotices' => when true, omits notices from being displayed
  76. * 'ignore' => a prefix for files and directories which are not being added
  77. * 'locale' => the actual set locale to use
  78. * 'log' => a instance of Zend_Log where logs are written to
  79. * 'logMessage' => message to be logged
  80. * 'logUntranslated' => when true, untranslated messages are not logged
  81. * 'reload' => reloads the cache by reading the content again
  82. * 'scan' => searches for translation files using the LOCALE constants
  83. * 'tag' => tag to use for the cache
  84. *
  85. * @var array
  86. */
  87. protected $_options = array(
  88. 'clear' => false,
  89. 'content' => null,
  90. 'disableNotices' => false,
  91. 'ignore' => '.',
  92. 'locale' => 'auto',
  93. 'log' => null,
  94. 'logMessage' => "Untranslated message within '%locale%': %message%",
  95. 'logUntranslated' => false,
  96. 'reload' => false,
  97. 'route' => null,
  98. 'scan' => null,
  99. 'tag' => 'Zend_Translate'
  100. );
  101. /**
  102. * Translation table
  103. * @var array
  104. */
  105. protected $_translate = array();
  106. /**
  107. * Generates the adapter
  108. *
  109. * @param array|Zend_Config $options Translation options for this adapter
  110. * @throws Zend_Translate_Exception
  111. * @return void
  112. */
  113. public function __construct($options = array())
  114. {
  115. if ($options instanceof Zend_Config) {
  116. $options = $options->toArray();
  117. } else if (func_num_args() > 1) {
  118. $args = func_get_args();
  119. $options = array();
  120. $options['content'] = array_shift($args);
  121. if (!empty($args)) {
  122. $options['locale'] = array_shift($args);
  123. }
  124. if (!empty($args)) {
  125. $opt = array_shift($args);
  126. $options = array_merge($opt, $options);
  127. }
  128. } else if (!is_array($options)) {
  129. $options = array('content' => $options);
  130. }
  131. if (array_key_exists('cache', $options)) {
  132. self::setCache($options['cache']);
  133. unset($options['cache']);
  134. }
  135. if (isset(self::$_cache)) {
  136. $id = 'Zend_Translate_' . $this->toString() . '_Options';
  137. $result = self::$_cache->load($id);
  138. if ($result) {
  139. $this->_options = $result;
  140. }
  141. }
  142. if (empty($options['locale']) || ($options['locale'] === "auto")) {
  143. $this->_automatic = true;
  144. } else {
  145. $this->_automatic = false;
  146. }
  147. $locale = null;
  148. if (!empty($options['locale'])) {
  149. $locale = $options['locale'];
  150. unset($options['locale']);
  151. }
  152. $this->setOptions($options);
  153. $options['locale'] = $locale;
  154. if (!empty($options['content'])) {
  155. $this->addTranslation($options);
  156. }
  157. if ($this->getLocale() !== (string) $options['locale']) {
  158. $this->setLocale($options['locale']);
  159. }
  160. }
  161. /**
  162. * Add translations
  163. *
  164. * This may be a new language or additional content for an existing language
  165. * If the key 'clear' is true, then translations for the specified
  166. * language will be replaced and added otherwise
  167. *
  168. * @param array|Zend_Config $options Options and translations to be added
  169. * @throws Zend_Translate_Exception
  170. * @return Zend_Translate_Adapter Provides fluent interface
  171. */
  172. public function addTranslation($options = array())
  173. {
  174. if ($options instanceof Zend_Config) {
  175. $options = $options->toArray();
  176. } else if (func_num_args() > 1) {
  177. $args = func_get_args();
  178. $options = array();
  179. $options['content'] = array_shift($args);
  180. if (!empty($args)) {
  181. $options['locale'] = array_shift($args);
  182. }
  183. if (!empty($args)) {
  184. $opt = array_shift($args);
  185. $options = array_merge($opt, $options);
  186. }
  187. } else if (!is_array($options)) {
  188. $options = array('content' => $options);
  189. }
  190. $originate = null;
  191. if (!empty($options['locale'])) {
  192. $originate = (string) $options['locale'];
  193. }
  194. if ((array_key_exists('log', $options)) && !($options['log'] instanceof Zend_Log)) {
  195. require_once 'Zend/Translate/Exception.php';
  196. throw new Zend_Translate_Exception('Instance of Zend_Log expected for option log');
  197. }
  198. try {
  199. if (!($options['content'] instanceof Zend_Translate) && !($options['content'] instanceof Zend_Translate_Adapter)) {
  200. if (empty($options['locale'])) {
  201. $options['locale'] = null;
  202. }
  203. $options['locale'] = Zend_Locale::findLocale($options['locale']);
  204. }
  205. } catch (Zend_Locale_Exception $e) {
  206. require_once 'Zend/Translate/Exception.php';
  207. throw new Zend_Translate_Exception("The given Language '{$options['locale']}' does not exist", 0, $e);
  208. }
  209. $options = $options + $this->_options;
  210. if (is_string($options['content']) and is_dir($options['content'])) {
  211. $options['content'] = realpath($options['content']);
  212. $prev = '';
  213. foreach (new RecursiveIteratorIterator(
  214. new RecursiveDirectoryIterator($options['content'], RecursiveDirectoryIterator::KEY_AS_PATHNAME),
  215. RecursiveIteratorIterator::SELF_FIRST) as $directory => $info) {
  216. $file = $info->getFilename();
  217. if (is_array($options['ignore'])) {
  218. foreach ($options['ignore'] as $key => $ignore) {
  219. if (strpos($key, 'regex') !== false) {
  220. if (preg_match($ignore, $directory)) {
  221. // ignore files matching the given regex from option 'ignore' and all files below
  222. continue 2;
  223. }
  224. } else if (strpos($directory, DIRECTORY_SEPARATOR . $ignore) !== false) {
  225. // ignore files matching first characters from option 'ignore' and all files below
  226. continue 2;
  227. }
  228. }
  229. } else {
  230. if (strpos($directory, DIRECTORY_SEPARATOR . $options['ignore']) !== false) {
  231. // ignore files matching first characters from option 'ignore' and all files below
  232. continue;
  233. }
  234. }
  235. if ($info->isDir()) {
  236. // pathname as locale
  237. if (($options['scan'] === self::LOCALE_DIRECTORY) and (Zend_Locale::isLocale($file, true, false))) {
  238. $options['locale'] = $file;
  239. $prev = (string) $options['locale'];
  240. }
  241. } else if ($info->isFile()) {
  242. // filename as locale
  243. if ($options['scan'] === self::LOCALE_FILENAME) {
  244. $filename = explode('.', $file);
  245. array_pop($filename);
  246. $filename = implode('.', $filename);
  247. if (Zend_Locale::isLocale((string) $filename, true, false)) {
  248. $options['locale'] = (string) $filename;
  249. } else {
  250. $parts = explode('.', $file);
  251. $parts2 = array();
  252. foreach($parts as $token) {
  253. $parts2 += explode('_', $token);
  254. }
  255. $parts = array_merge($parts, $parts2);
  256. $parts2 = array();
  257. foreach($parts as $token) {
  258. $parts2 += explode('-', $token);
  259. }
  260. $parts = array_merge($parts, $parts2);
  261. $parts = array_unique($parts);
  262. $prev = '';
  263. foreach($parts as $token) {
  264. if (Zend_Locale::isLocale($token, true, false)) {
  265. if (strlen($prev) <= strlen($token)) {
  266. $options['locale'] = $token;
  267. $prev = $token;
  268. }
  269. }
  270. }
  271. }
  272. }
  273. try {
  274. $options['content'] = $info->getPathname();
  275. $this->_addTranslationData($options);
  276. } catch (Zend_Translate_Exception $e) {
  277. // ignore failed sources while scanning
  278. }
  279. }
  280. }
  281. } else {
  282. $this->_addTranslationData($options);
  283. }
  284. if ((isset($this->_translate[$originate]) === true) and (count($this->_translate[$originate]) > 0)) {
  285. $this->setLocale($originate);
  286. }
  287. return $this;
  288. }
  289. /**
  290. * Sets new adapter options
  291. *
  292. * @param array $options Adapter options
  293. * @throws Zend_Translate_Exception
  294. * @return Zend_Translate_Adapter Provides fluent interface
  295. */
  296. public function setOptions(array $options = array())
  297. {
  298. $change = false;
  299. $locale = null;
  300. foreach ($options as $key => $option) {
  301. if ($key == 'locale') {
  302. $locale = $option;
  303. } else if ((isset($this->_options[$key]) and ($this->_options[$key] != $option)) or
  304. !isset($this->_options[$key])) {
  305. if (($key == 'log') && !($option instanceof Zend_Log)) {
  306. require_once 'Zend/Translate/Exception.php';
  307. throw new Zend_Translate_Exception('Instance of Zend_Log expected for option log');
  308. }
  309. if ($key == 'cache') {
  310. self::setCache($option);
  311. continue;
  312. }
  313. $this->_options[$key] = $option;
  314. $change = true;
  315. }
  316. }
  317. if ($locale !== null) {
  318. $this->setLocale($locale);
  319. }
  320. if (isset(self::$_cache) and ($change == true)) {
  321. $id = 'Zend_Translate_' . $this->toString() . '_Options';
  322. if (self::$_cacheTags) {
  323. self::$_cache->save($this->_options, $id, array($this->_options['tag']));
  324. } else {
  325. self::$_cache->save($this->_options, $id);
  326. }
  327. }
  328. return $this;
  329. }
  330. /**
  331. * Returns the adapters name and it's options
  332. *
  333. * @param string|null $optionKey String returns this option
  334. * null returns all options
  335. * @return integer|string|array|null
  336. */
  337. public function getOptions($optionKey = null)
  338. {
  339. if ($optionKey === null) {
  340. return $this->_options;
  341. }
  342. if (isset($this->_options[$optionKey]) === true) {
  343. return $this->_options[$optionKey];
  344. }
  345. return null;
  346. }
  347. /**
  348. * Gets locale
  349. *
  350. * @return Zend_Locale|string|null
  351. */
  352. public function getLocale()
  353. {
  354. return $this->_options['locale'];
  355. }
  356. /**
  357. * Sets locale
  358. *
  359. * @param string|Zend_Locale $locale Locale to set
  360. * @throws Zend_Translate_Exception
  361. * @return Zend_Translate_Adapter Provides fluent interface
  362. */
  363. public function setLocale($locale)
  364. {
  365. if (($locale === "auto") or ($locale === null)) {
  366. $this->_automatic = true;
  367. } else {
  368. $this->_automatic = false;
  369. }
  370. try {
  371. $locale = Zend_Locale::findLocale($locale);
  372. } catch (Zend_Locale_Exception $e) {
  373. require_once 'Zend/Translate/Exception.php';
  374. throw new Zend_Translate_Exception("The given Language ({$locale}) does not exist", 0, $e);
  375. }
  376. if (!isset($this->_translate[$locale])) {
  377. $temp = explode('_', $locale);
  378. if (!isset($this->_translate[$temp[0]]) and !isset($this->_translate[$locale])) {
  379. if (!$this->_options['disableNotices']) {
  380. if ($this->_options['log']) {
  381. $this->_options['log']->notice("The language '{$locale}' has to be added before it can be used.");
  382. } else {
  383. trigger_error("The language '{$locale}' has to be added before it can be used.", E_USER_NOTICE);
  384. }
  385. }
  386. }
  387. $locale = $temp[0];
  388. }
  389. if (empty($this->_translate[$locale])) {
  390. if (!$this->_options['disableNotices']) {
  391. if ($this->_options['log']) {
  392. $this->_options['log']->notice("No translation for the language '{$locale}' available.");
  393. } else {
  394. trigger_error("No translation for the language '{$locale}' available.", E_USER_NOTICE);
  395. }
  396. }
  397. }
  398. if ($this->_options['locale'] != $locale) {
  399. $this->_options['locale'] = $locale;
  400. if (isset(self::$_cache)) {
  401. $id = 'Zend_Translate_' . $this->toString() . '_Options';
  402. if (self::$_cacheTags) {
  403. self::$_cache->save($this->_options, $id, array($this->_options['tag']));
  404. } else {
  405. self::$_cache->save($this->_options, $id);
  406. }
  407. }
  408. }
  409. return $this;
  410. }
  411. /**
  412. * Returns the available languages from this adapter
  413. *
  414. * @return array
  415. */
  416. public function getList()
  417. {
  418. $list = array_keys($this->_translate);
  419. $result = null;
  420. foreach($list as $value) {
  421. if (!empty($this->_translate[$value])) {
  422. $result[$value] = $value;
  423. }
  424. }
  425. return $result;
  426. }
  427. /**
  428. * Returns the message id for a given translation
  429. * If no locale is given, the actual language will be used
  430. *
  431. * @param string $message Message to get the key for
  432. * @param string|Zend_Locale $locale (optional) Language to return the message ids from
  433. * @return string|array|false
  434. */
  435. public function getMessageId($message, $locale = null)
  436. {
  437. if (empty($locale) or !$this->isAvailable($locale)) {
  438. $locale = $this->_options['locale'];
  439. }
  440. return array_search($message, $this->_translate[(string) $locale]);
  441. }
  442. /**
  443. * Returns all available message ids from this adapter
  444. * If no locale is given, the actual language will be used
  445. *
  446. * @param string|Zend_Locale $locale (optional) Language to return the message ids from
  447. * @return array
  448. */
  449. public function getMessageIds($locale = null)
  450. {
  451. if (empty($locale) or !$this->isAvailable($locale)) {
  452. $locale = $this->_options['locale'];
  453. }
  454. return array_keys($this->_translate[(string) $locale]);
  455. }
  456. /**
  457. * Returns all available translations from this adapter
  458. * If no locale is given, the actual language will be used
  459. * If 'all' is given the complete translation dictionary will be returned
  460. *
  461. * @param string|Zend_Locale $locale (optional) Language to return the messages from
  462. * @return array
  463. */
  464. public function getMessages($locale = null)
  465. {
  466. if ($locale === 'all') {
  467. return $this->_translate;
  468. }
  469. if ((empty($locale) === true) or ($this->isAvailable($locale) === false)) {
  470. $locale = $this->_options['locale'];
  471. }
  472. return $this->_translate[(string) $locale];
  473. }
  474. /**
  475. * Is the wished language available ?
  476. *
  477. * @see Zend_Locale
  478. * @param string|Zend_Locale $locale Language to search for, identical with locale identifier,
  479. * @see Zend_Locale for more information
  480. * @return boolean
  481. */
  482. public function isAvailable($locale)
  483. {
  484. $return = isset($this->_translate[(string) $locale]);
  485. return $return;
  486. }
  487. /**
  488. * Load translation data
  489. *
  490. * @param mixed $data
  491. * @param string|Zend_Locale $locale
  492. * @param array $options (optional)
  493. * @return array
  494. */
  495. abstract protected function _loadTranslationData($data, $locale, array $options = array());
  496. /**
  497. * Internal function for adding translation data
  498. *
  499. * This may be a new language or additional data for an existing language
  500. * If the options 'clear' is true, then the translation data for the specified
  501. * language is replaced and added otherwise
  502. *
  503. * @see Zend_Locale
  504. * @param array|Zend_Config $content Translation data to add
  505. * @throws Zend_Translate_Exception
  506. * @return Zend_Translate_Adapter Provides fluent interface
  507. */
  508. private function _addTranslationData($options = array())
  509. {
  510. if ($options instanceof Zend_Config) {
  511. $options = $options->toArray();
  512. } else if (func_num_args() > 1) {
  513. $args = func_get_args();
  514. $options['content'] = array_shift($args);
  515. if (!empty($args)) {
  516. $options['locale'] = array_shift($args);
  517. }
  518. if (!empty($args)) {
  519. $options += array_shift($args);
  520. }
  521. }
  522. if (($options['content'] instanceof Zend_Translate) || ($options['content'] instanceof Zend_Translate_Adapter)) {
  523. $options['usetranslateadapter'] = true;
  524. if (!empty($options['locale']) && ($options['locale'] !== 'auto')) {
  525. $options['content'] = $options['content']->getMessages($options['locale']);
  526. } else {
  527. $content = $options['content'];
  528. $locales = $content->getList();
  529. foreach ($locales as $locale) {
  530. $options['locale'] = $locale;
  531. $options['content'] = $content->getMessages($locale);
  532. $this->_addTranslationData($options);
  533. }
  534. return $this;
  535. }
  536. }
  537. try {
  538. $options['locale'] = Zend_Locale::findLocale($options['locale']);
  539. } catch (Zend_Locale_Exception $e) {
  540. require_once 'Zend/Translate/Exception.php';
  541. throw new Zend_Translate_Exception("The given Language '{$options['locale']}' does not exist", 0, $e);
  542. }
  543. if ($options['clear'] || !isset($this->_translate[$options['locale']])) {
  544. $this->_translate[$options['locale']] = array();
  545. }
  546. $read = true;
  547. if (isset(self::$_cache)) {
  548. $id = 'Zend_Translate_' . md5(serialize($options['content'])) . '_' . $this->toString();
  549. $temp = self::$_cache->load($id);
  550. if ($temp) {
  551. $read = false;
  552. }
  553. }
  554. if ($options['reload']) {
  555. $read = true;
  556. }
  557. if ($read) {
  558. if (!empty($options['usetranslateadapter'])) {
  559. $temp = array($options['locale'] => $options['content']);
  560. } else {
  561. $temp = $this->_loadTranslationData($options['content'], $options['locale'], $options);
  562. }
  563. }
  564. if (empty($temp)) {
  565. $temp = array();
  566. }
  567. $keys = array_keys($temp);
  568. foreach($keys as $key) {
  569. if (!isset($this->_translate[$key])) {
  570. $this->_translate[$key] = array();
  571. }
  572. if (array_key_exists($key, $temp) && is_array($temp[$key])) {
  573. $this->_translate[$key] = $temp[$key] + $this->_translate[$key];
  574. }
  575. }
  576. if ($this->_automatic === true) {
  577. $find = new Zend_Locale($options['locale']);
  578. $browser = $find->getEnvironment() + $find->getBrowser();
  579. arsort($browser);
  580. foreach($browser as $language => $quality) {
  581. if (isset($this->_translate[$language])) {
  582. $this->_options['locale'] = $language;
  583. break;
  584. }
  585. }
  586. }
  587. if (($read) and (isset(self::$_cache))) {
  588. $id = 'Zend_Translate_' . md5(serialize($options['content'])) . '_' . $this->toString();
  589. if (self::$_cacheTags) {
  590. self::$_cache->save($temp, $id, array($this->_options['tag']));
  591. } else {
  592. self::$_cache->save($temp, $id);
  593. }
  594. }
  595. return $this;
  596. }
  597. /**
  598. * Translates the given string
  599. * returns the translation
  600. *
  601. * @see Zend_Locale
  602. * @param string|array $messageId Translation string, or Array for plural translations
  603. * @param string|Zend_Locale $locale (optional) Locale/Language to use, identical with
  604. * locale identifier, @see Zend_Locale for more information
  605. * @return string
  606. */
  607. public function translate($messageId, $locale = null)
  608. {
  609. if ($locale === null) {
  610. $locale = $this->_options['locale'];
  611. }
  612. $plural = null;
  613. if (is_array($messageId)) {
  614. if (count($messageId) > 2) {
  615. $number = array_pop($messageId);
  616. if (!is_numeric($number)) {
  617. $plocale = $number;
  618. $number = array_pop($messageId);
  619. } else {
  620. $plocale = 'en';
  621. }
  622. $plural = $messageId;
  623. $messageId = $messageId[0];
  624. } else {
  625. $messageId = $messageId[0];
  626. }
  627. }
  628. if (!Zend_Locale::isLocale($locale, true, false)) {
  629. if (!Zend_Locale::isLocale($locale, false, false)) {
  630. // language does not exist, return original string
  631. $this->_log($messageId, $locale);
  632. // use rerouting when enabled
  633. if (!empty($this->_options['route'])) {
  634. if (array_key_exists($locale, $this->_options['route']) &&
  635. !array_key_exists($locale, $this->_routed)) {
  636. $this->_routed[$locale] = true;
  637. return $this->translate($messageId, $this->_options['route'][$locale]);
  638. }
  639. }
  640. $this->_routed = array();
  641. if ($plural === null) {
  642. return $messageId;
  643. }
  644. $rule = Zend_Translate_Plural::getPlural($number, $plocale);
  645. if (!isset($plural[$rule])) {
  646. $rule = 0;
  647. }
  648. return $plural[$rule];
  649. }
  650. $locale = new Zend_Locale($locale);
  651. }
  652. $locale = (string) $locale;
  653. if ((is_string($messageId) || is_int($messageId)) && isset($this->_translate[$locale][$messageId])) {
  654. // return original translation
  655. if ($plural === null) {
  656. $this->_routed = array();
  657. return $this->_translate[$locale][$messageId];
  658. }
  659. $rule = Zend_Translate_Plural::getPlural($number, $locale);
  660. if (isset($this->_translate[$locale][$plural[0]][$rule])) {
  661. $this->_routed = array();
  662. return $this->_translate[$locale][$plural[0]][$rule];
  663. }
  664. } else if (strlen($locale) != 2) {
  665. // faster than creating a new locale and separate the leading part
  666. $locale = substr($locale, 0, -strlen(strrchr($locale, '_')));
  667. if ((is_string($messageId) || is_int($messageId)) && isset($this->_translate[$locale][$messageId])) {
  668. // return regionless translation (en_US -> en)
  669. if ($plural === null) {
  670. $this->_routed = array();
  671. return $this->_translate[$locale][$messageId];
  672. }
  673. $rule = Zend_Translate_Plural::getPlural($number, $locale);
  674. if (isset($this->_translate[$locale][$plural[0]][$rule])) {
  675. $this->_routed = array();
  676. return $this->_translate[$locale][$plural[0]][$rule];
  677. }
  678. }
  679. }
  680. $this->_log($messageId, $locale);
  681. // use rerouting when enabled
  682. if (!empty($this->_options['route'])) {
  683. if (array_key_exists($locale, $this->_options['route']) &&
  684. !array_key_exists($locale, $this->_routed)) {
  685. $this->_routed[$locale] = true;
  686. return $this->translate($messageId, $this->_options['route'][$locale]);
  687. }
  688. }
  689. $this->_routed = array();
  690. if ($plural === null) {
  691. return $messageId;
  692. }
  693. $rule = Zend_Translate_Plural::getPlural($number, $plocale);
  694. if (!isset($plural[$rule])) {
  695. $rule = 0;
  696. }
  697. return $plural[$rule];
  698. }
  699. /**
  700. * Translates the given string using plural notations
  701. * Returns the translated string
  702. *
  703. * @see Zend_Locale
  704. * @param string $singular Singular translation string
  705. * @param string $plural Plural translation string
  706. * @param integer $number Number for detecting the correct plural
  707. * @param string|Zend_Locale $locale (Optional) Locale/Language to use, identical with
  708. * locale identifier, @see Zend_Locale for more information
  709. * @return string
  710. */
  711. public function plural($singular, $plural, $number, $locale = null)
  712. {
  713. return $this->translate(array($singular, $plural, $number), $locale);
  714. }
  715. /**
  716. * Logs a message when the log option is set
  717. *
  718. * @param string $message Message to log
  719. * @param String $locale Locale to log
  720. */
  721. protected function _log($message, $locale) {
  722. if ($this->_options['logUntranslated']) {
  723. $message = str_replace('%message%', $message, $this->_options['logMessage']);
  724. $message = str_replace('%locale%', $locale, $message);
  725. if ($this->_options['log']) {
  726. $this->_options['log']->notice($message);
  727. } else {
  728. trigger_error($message, E_USER_NOTICE);
  729. }
  730. }
  731. }
  732. /**
  733. * Translates the given string
  734. * returns the translation
  735. *
  736. * @param string $messageId Translation string
  737. * @param string|Zend_Locale $locale (optional) Locale/Language to use, identical with locale
  738. * identifier, @see Zend_Locale for more information
  739. * @return string
  740. */
  741. public function _($messageId, $locale = null)
  742. {
  743. return $this->translate($messageId, $locale);
  744. }
  745. /**
  746. * Checks if a string is translated within the source or not
  747. * returns boolean
  748. *
  749. * @param string $messageId Translation string
  750. * @param boolean $original (optional) Allow translation only for original language
  751. * when true, a translation for 'en_US' would give false when it can
  752. * be translated with 'en' only
  753. * @param string|Zend_Locale $locale (optional) Locale/Language to use, identical with locale identifier,
  754. * see Zend_Locale for more information
  755. * @return boolean
  756. */
  757. public function isTranslated($messageId, $original = false, $locale = null)
  758. {
  759. if (($original !== false) and ($original !== true)) {
  760. $locale = $original;
  761. $original = false;
  762. }
  763. if ($locale === null) {
  764. $locale = $this->_options['locale'];
  765. }
  766. if (!Zend_Locale::isLocale($locale, true, false)) {
  767. if (!Zend_Locale::isLocale($locale, false, false)) {
  768. // language does not exist, return original string
  769. return false;
  770. }
  771. $locale = new Zend_Locale($locale);
  772. }
  773. $locale = (string) $locale;
  774. if ((is_string($messageId) || is_int($messageId)) && isset($this->_translate[$locale][$messageId])) {
  775. // return original translation
  776. return true;
  777. } else if ((strlen($locale) != 2) and ($original === false)) {
  778. // faster than creating a new locale and separate the leading part
  779. $locale = substr($locale, 0, -strlen(strrchr($locale, '_')));
  780. if ((is_string($messageId) || is_int($messageId)) && isset($this->_translate[$locale][$messageId])) {
  781. // return regionless translation (en_US -> en)
  782. return true;
  783. }
  784. }
  785. // No translation found, return original
  786. return false;
  787. }
  788. /**
  789. * Returns the set cache
  790. *
  791. * @return Zend_Cache_Core The set cache
  792. */
  793. public static function getCache()
  794. {
  795. return self::$_cache;
  796. }
  797. /**
  798. * Sets a cache for all Zend_Translate_Adapters
  799. *
  800. * @param Zend_Cache_Core $cache Cache to store to
  801. */
  802. public static function setCache(Zend_Cache_Core $cache)
  803. {
  804. self::$_cache = $cache;
  805. self::_getTagSupportForCache();
  806. }
  807. /**
  808. * Returns true when a cache is set
  809. *
  810. * @return boolean
  811. */
  812. public static function hasCache()
  813. {
  814. if (self::$_cache !== null) {
  815. return true;
  816. }
  817. return false;
  818. }
  819. /**
  820. * Removes any set cache
  821. *
  822. * @return void
  823. */
  824. public static function removeCache()
  825. {
  826. self::$_cache = null;
  827. }
  828. /**
  829. * Clears all set cache data
  830. *
  831. * @param string $tag Tag to clear when the default tag name is not used
  832. * @return void
  833. */
  834. public static function clearCache($tag = null)
  835. {
  836. require_once 'Zend/Cache.php';
  837. if (self::$_cacheTags) {
  838. if ($tag == null) {
  839. $tag = 'Zend_Translate';
  840. }
  841. self::$_cache->clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array($tag));
  842. } else {
  843. self::$_cache->clean(Zend_Cache::CLEANING_MODE_ALL);
  844. }
  845. }
  846. /**
  847. * Returns the adapter name
  848. *
  849. * @return string
  850. */
  851. abstract public function toString();
  852. /**
  853. * Internal method to check if the given cache supports tags
  854. *
  855. * @param Zend_Cache $cache
  856. */
  857. private static function _getTagSupportForCache()
  858. {
  859. $backend = self::$_cache->getBackend();
  860. if ($backend instanceof Zend_Cache_Backend_ExtendedInterface) {
  861. $cacheOptions = $backend->getCapabilities();
  862. self::$_cacheTags = $cacheOptions['tags'];
  863. } else {
  864. self::$_cacheTags = false;
  865. }
  866. return self::$_cacheTags;
  867. }
  868. }