PageRenderTime 45ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/Translate/Adapter.php

https://bitbucket.org/jfrubiom/zendframework-1.x
PHP | 995 lines | 597 code | 115 blank | 283 comment | 169 complexity | 43dfdeddf2b2d69a3a57e9a9d476e10e MD5 | raw file
  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-2012 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 24593 2012-01-05 20:35:02Z matthew $
  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-2012 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. if (!Zend_Locale::isLocale($locale, true, false)) {
  641. if (!Zend_Locale::isLocale($locale, false, false)) {
  642. // language does not exist, return original string
  643. $this->_log($messageId, $locale);
  644. // use rerouting when enabled
  645. if (!empty($this->_options['route'])) {
  646. if (array_key_exists($locale, $this->_options['route']) &&
  647. !array_key_exists($locale, $this->_routed)) {
  648. $this->_routed[$locale] = true;
  649. return $this->translate($messageId, $this->_options['route'][$locale]);
  650. }
  651. }
  652. $this->_routed = array();
  653. if ($plural === null) {
  654. return $messageId;
  655. }
  656. $rule = Zend_Translate_Plural::getPlural($number, $plocale);
  657. if (!isset($plural[$rule])) {
  658. $rule = 0;
  659. }
  660. return $plural[$rule];
  661. }
  662. $locale = new Zend_Locale($locale);
  663. }
  664. $locale = (string) $locale;
  665. if ((is_string($messageId) || is_int($messageId)) && isset($this->_translate[$locale][$messageId])) {
  666. // return original translation
  667. if ($plural === null) {
  668. $this->_routed = array();
  669. return $this->_translate[$locale][$messageId];
  670. }
  671. $rule = Zend_Translate_Plural::getPlural($number, $locale);
  672. if (isset($this->_translate[$locale][$plural[0]][$rule])) {
  673. $this->_routed = array();
  674. return $this->_translate[$locale][$plural[0]][$rule];
  675. }
  676. } else if (strlen($locale) != 2) {
  677. // faster than creating a new locale and separate the leading part
  678. $locale = substr($locale, 0, -strlen(strrchr($locale, '_')));
  679. if ((is_string($messageId) || is_int($messageId)) && isset($this->_translate[$locale][$messageId])) {
  680. // return regionless translation (en_US -> en)
  681. if ($plural === null) {
  682. $this->_routed = array();
  683. return $this->_translate[$locale][$messageId];
  684. }
  685. $rule = Zend_Translate_Plural::getPlural($number, $locale);
  686. if (isset($this->_translate[$locale][$plural[0]][$rule])) {
  687. $this->_routed = array();
  688. return $this->_translate[$locale][$plural[0]][$rule];
  689. }
  690. }
  691. }
  692. $this->_log($messageId, $locale);
  693. // use rerouting when enabled
  694. if (!empty($this->_options['route'])) {
  695. if (array_key_exists($locale, $this->_options['route']) &&
  696. !array_key_exists($locale, $this->_routed)) {
  697. $this->_routed[$locale] = true;
  698. return $this->translate($messageId, $this->_options['route'][$locale]);
  699. }
  700. }
  701. $this->_routed = array();
  702. if ($plural === null) {
  703. return $messageId;
  704. }
  705. $rule = Zend_Translate_Plural::getPlural($number, $plocale);
  706. if (!isset($plural[$rule])) {
  707. $rule = 0;
  708. }
  709. return $plural[$rule];
  710. }
  711. /**
  712. * Translates the given string using plural notations
  713. * Returns the translated string
  714. *
  715. * @see Zend_Locale
  716. * @param string $singular Singular translation string
  717. * @param string $plural Plural translation string
  718. * @param integer $number Number for detecting the correct plural
  719. * @param string|Zend_Locale $locale (Optional) Locale/Language to use, identical with
  720. * locale identifier, @see Zend_Locale for more information
  721. * @return string
  722. */
  723. public function plural($singular, $plural, $number, $locale = null)
  724. {
  725. return $this->translate(array($singular, $plural, $number), $locale);
  726. }
  727. /**
  728. * Logs a message when the log option is set
  729. *
  730. * @param string $message Message to log
  731. * @param String $locale Locale to log
  732. */
  733. protected function _log($message, $locale) {
  734. if ($this->_options['logUntranslated']) {
  735. $message = str_replace('%message%', $message, $this->_options['logMessage']);
  736. $message = str_replace('%locale%', $locale, $message);
  737. if ($this->_options['log']) {
  738. $this->_options['log']->log($message, $this->_options['logPriority']);
  739. } else {
  740. trigger_error($message, E_USER_NOTICE);
  741. }
  742. }
  743. }
  744. /**
  745. * Translates the given string
  746. * returns the translation
  747. *
  748. * @param string $messageId Translation string
  749. * @param string|Zend_Locale $locale (optional) Locale/Language to use, identical with locale
  750. * identifier, @see Zend_Locale for more information
  751. * @return string
  752. */
  753. public function _($messageId, $locale = null)
  754. {
  755. return $this->translate($messageId, $locale);
  756. }
  757. /**
  758. * Checks if a string is translated within the source or not
  759. * returns boolean
  760. *
  761. * @param string $messageId Translation string
  762. * @param boolean $original (optional) Allow translation only for original language
  763. * when true, a translation for 'en_US' would give false when it can
  764. * be translated with 'en' only
  765. * @param string|Zend_Locale $locale (optional) Locale/Language to use, identical with locale identifier,
  766. * see Zend_Locale for more information
  767. * @return boolean
  768. */
  769. public function isTranslated($messageId, $original = false, $locale = null)
  770. {
  771. if (($original !== false) and ($original !== true)) {
  772. $locale = $original;
  773. $original = false;
  774. }
  775. if ($locale === null) {
  776. $locale = $this->_options['locale'];
  777. }
  778. if (!Zend_Locale::isLocale($locale, true, false)) {
  779. if (!Zend_Locale::isLocale($locale, false, false)) {
  780. // language does not exist, return original string
  781. return false;
  782. }
  783. $locale = new Zend_Locale($locale);
  784. }
  785. $locale = (string) $locale;
  786. if ((is_string($messageId) || is_int($messageId)) && isset($this->_translate[$locale][$messageId])) {
  787. // return original translation
  788. return true;
  789. } else if ((strlen($locale) != 2) and ($original === false)) {
  790. // faster than creating a new locale and separate the leading part
  791. $locale = substr($locale, 0, -strlen(strrchr($locale, '_')));
  792. if ((is_string($messageId) || is_int($messageId)) && isset($this->_translate[$locale][$messageId])) {
  793. // return regionless translation (en_US -> en)
  794. return true;
  795. }
  796. }
  797. // No translation found, return original
  798. return false;
  799. }
  800. /**
  801. * Returns the set cache
  802. *
  803. * @return Zend_Cache_Core The set cache
  804. */
  805. public static function getCache()
  806. {
  807. return self::$_cache;
  808. }
  809. /**
  810. * Sets a cache for all Zend_Translate_Adapters
  811. *
  812. * @param Zend_Cache_Core $cache Cache to store to
  813. */
  814. public static function setCache(Zend_Cache_Core $cache)
  815. {
  816. self::$_cache = $cache;
  817. self::_getTagSupportForCache();
  818. }
  819. /**
  820. * Returns true when a cache is set
  821. *
  822. * @return boolean
  823. */
  824. public static function hasCache()
  825. {
  826. if (self::$_cache !== null) {
  827. return true;
  828. }
  829. return false;
  830. }
  831. /**
  832. * Removes any set cache
  833. *
  834. * @return void
  835. */
  836. public static function removeCache()
  837. {
  838. self::$_cache = null;
  839. }
  840. /**
  841. * Clears all set cache data
  842. *
  843. * @param string $tag Tag to clear when the default tag name is not used
  844. * @return void
  845. */
  846. public static function clearCache($tag = null)
  847. {
  848. require_once 'Zend/Cache.php';
  849. if (self::$_cacheTags) {
  850. if ($tag == null) {
  851. $tag = 'Zend_Translate';
  852. }
  853. self::$_cache->clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array($tag));
  854. } else {
  855. self::$_cache->clean(Zend_Cache::CLEANING_MODE_ALL);
  856. }
  857. }
  858. /**
  859. * Returns the adapter name
  860. *
  861. * @return string
  862. */
  863. abstract public function toString();
  864. /**
  865. * Internal method to check if the given cache supports tags
  866. *
  867. * @param Zend_Cache $cache
  868. */
  869. private static function _getTagSupportForCache()
  870. {
  871. $backend = self::$_cache->getBackend();
  872. if ($backend instanceof Zend_Cache_Backend_ExtendedInterface) {
  873. $cacheOptions = $backend->getCapabilities();
  874. self::$_cacheTags = $cacheOptions['tags'];
  875. } else {
  876. self::$_cacheTags = false;
  877. }
  878. return self::$_cacheTags;
  879. }
  880. }