PageRenderTime 64ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/framework/thirdparty/Zend/Translate/Adapter.php

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