Adapter.php 34 KB

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