Adapter.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  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-2009 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. * @version $Id: Date.php 2498 2006-12-23 22:13:38Z thomas $
  21. */
  22. /**
  23. * @see Zend_Locale
  24. */
  25. require_once 'Zend/Locale.php';
  26. /**
  27. * Basic adapter class for each translation source adapter
  28. *
  29. * @category Zend
  30. * @package Zend_Translate
  31. * @subpackage Zend_Translate_Adapter
  32. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  33. * @license http://framework.zend.com/license/new-bsd New BSD License
  34. */
  35. abstract class Zend_Translate_Adapter {
  36. /**
  37. * Shows if locale detection is in automatic level
  38. * @var boolean
  39. */
  40. private $_automatic = true;
  41. /**
  42. * Internal cache for all adapters
  43. * @var Zend_Cache_Core
  44. */
  45. protected static $_cache = null;
  46. /**
  47. * Scans for the locale within the name of the directory
  48. * @constant integer
  49. */
  50. const LOCALE_DIRECTORY = 'directory';
  51. /**
  52. * Scans for the locale within the name of the file
  53. * @constant integer
  54. */
  55. const LOCALE_FILENAME = 'filename';
  56. /**
  57. * Array with all options, each adapter can have own additional options
  58. * 'clear' => clears already loaded data when adding new files
  59. * 'scan' => searches for translation files using the LOCALE constants
  60. * 'locale' => the actual set locale to use
  61. * @var array
  62. */
  63. protected $_options = array(
  64. 'clear' => false,
  65. 'disableNotices' => false,
  66. 'ignore' => '.',
  67. 'locale' => 'auto',
  68. 'log' => null,
  69. 'logMessage' => "Untranslated message within '%locale%': %message%",
  70. 'logUntranslated' => false,
  71. 'scan' => null
  72. );
  73. /**
  74. * Translation table
  75. * @var array
  76. */
  77. protected $_translate = array();
  78. /**
  79. * Generates the adapter
  80. *
  81. * @param string|array $data Translation data or filename for this adapter
  82. * @param string|Zend_Locale $locale (optional) Locale/Language to set, identical with Locale
  83. * identifiers see Zend_Locale for more information
  84. * @param array $options (optional) Options for the adaptor
  85. * @throws Zend_Translate_Exception
  86. * @return void
  87. */
  88. public function __construct($data, $locale = null, array $options = array())
  89. {
  90. if (isset(self::$_cache)) {
  91. $id = 'Zend_Translate_' . $this->toString() . '_Options';
  92. $result = self::$_cache->load($id);
  93. if ($result) {
  94. $this->_options = unserialize($result);
  95. }
  96. }
  97. if (($locale === "auto") or ($locale === null)) {
  98. $this->_automatic = true;
  99. } else {
  100. $this->_automatic = false;
  101. }
  102. $this->addTranslation($data, $locale, $options);
  103. if ($this->getLocale() !== (string) $locale) {
  104. $this->setLocale($locale);
  105. }
  106. }
  107. /**
  108. * Add translation data
  109. *
  110. * It may be a new language or additional data for existing language
  111. * If $clear parameter is true, then translation data for specified
  112. * language is replaced and added otherwise
  113. *
  114. * @param array|string $data Translation data
  115. * @param string|Zend_Locale $locale (optional) Locale/Language to add data for, identical
  116. * with locale identifier, see Zend_Locale for more information
  117. * @param array $options (optional) Option for this Adapter
  118. * @throws Zend_Translate_Exception
  119. * @return Zend_Translate_Adapter Provides fluent interface
  120. */
  121. public function addTranslation($data, $locale = null, array $options = array())
  122. {
  123. try {
  124. $locale = Zend_Locale::findLocale($locale);
  125. } catch (Zend_Locale_Exception $e) {
  126. require_once 'Zend/Translate/Exception.php';
  127. throw new Zend_Translate_Exception("The given Language '{$locale}' does not exist");
  128. }
  129. $originate = (string) $locale;
  130. $this->setOptions($options);
  131. if (is_string($data) and is_dir($data)) {
  132. $data = realpath($data);
  133. $prev = '';
  134. foreach (new RecursiveIteratorIterator(
  135. new RecursiveDirectoryIterator($data, RecursiveDirectoryIterator::KEY_AS_PATHNAME),
  136. RecursiveIteratorIterator::SELF_FIRST) as $directory => $info) {
  137. $file = $info->getFilename();
  138. if (strpos($directory, DIRECTORY_SEPARATOR . $this->_options['ignore']) !== false) {
  139. // ignore files matching first characters from option 'ignore' and all files below
  140. continue;
  141. }
  142. if ($info->isDir()) {
  143. // pathname as locale
  144. if (($this->_options['scan'] === self::LOCALE_DIRECTORY) and (Zend_Locale::isLocale($file, true, false))) {
  145. if (strlen($prev) <= strlen($file)) {
  146. $locale = $file;
  147. $prev = (string) $locale;
  148. }
  149. }
  150. } else if ($info->isFile()) {
  151. // filename as locale
  152. if ($this->_options['scan'] === self::LOCALE_FILENAME) {
  153. $filename = explode('.', $file);
  154. array_pop($filename);
  155. $filename = implode('.', $filename);
  156. if (Zend_Locale::isLocale((string) $filename, true, false)) {
  157. $locale = (string) $filename;
  158. } else {
  159. $parts = explode('.', $file);
  160. $parts2 = array();
  161. foreach($parts as $token) {
  162. $parts2 += explode('_', $token);
  163. }
  164. $parts = array_merge($parts, $parts2);
  165. $parts2 = array();
  166. foreach($parts as $token) {
  167. $parts2 += explode('-', $token);
  168. }
  169. $parts = array_merge($parts, $parts2);
  170. $parts = array_unique($parts);
  171. $prev = '';
  172. foreach($parts as $token) {
  173. if (Zend_Locale::isLocale($token, true, false)) {
  174. if (strlen($prev) <= strlen($token)) {
  175. $locale = $token;
  176. $prev = $token;
  177. }
  178. }
  179. }
  180. }
  181. }
  182. try {
  183. $this->_addTranslationData($info->getPathname(), (string) $locale, $this->_options);
  184. if ((isset($this->_translate[(string) $locale]) === true) and (count($this->_translate[(string) $locale]) > 0)) {
  185. $this->setLocale($locale);
  186. }
  187. } catch (Zend_Translate_Exception $e) {
  188. // ignore failed sources while scanning
  189. }
  190. }
  191. }
  192. } else {
  193. $this->_addTranslationData($data, (string) $locale, $this->_options);
  194. if ((isset($this->_translate[(string) $locale]) === true) and (count($this->_translate[(string) $locale]) > 0)) {
  195. $this->setLocale($locale);
  196. }
  197. }
  198. if ((isset($this->_translate[$originate]) === true) and (count($this->_translate[$originate]) > 0) and ($originate !== (string) $locale)) {
  199. $this->setLocale($originate);
  200. }
  201. return $this;
  202. }
  203. /**
  204. * Sets new adapter options
  205. *
  206. * @param array $options Adapter options
  207. * @throws Zend_Translate_Exception
  208. * @return Zend_Translate_Adapter Provides fluent interface
  209. */
  210. public function setOptions(array $options = array())
  211. {
  212. $change = false;
  213. $locale = null;
  214. foreach ($options as $key => $option) {
  215. if ($key == 'locale') {
  216. $locale = $option;
  217. } else if ((isset($this->_options[$key]) and ($this->_options[$key] != $option)) or
  218. !isset($this->_options[$key])) {
  219. if (($key == 'log') && !($option instanceof Zend_Log)) {
  220. require_once 'Zend/Translate/Exception.php';
  221. throw new Zend_Translate_Exception('Instance of Zend_Log expected for option log');
  222. }
  223. $this->_options[$key] = $option;
  224. $change = true;
  225. }
  226. }
  227. if ($locale !== null) {
  228. $this->setLocale($option);
  229. }
  230. if (isset(self::$_cache) and ($change == true)) {
  231. $id = 'Zend_Translate_' . $this->toString() . '_Options';
  232. self::$_cache->save( serialize($this->_options), $id, array('Zend_Translate'));
  233. }
  234. return $this;
  235. }
  236. /**
  237. * Returns the adapters name and it's options
  238. *
  239. * @param string|null $optionKey String returns this option
  240. * null returns all options
  241. * @return integer|string|array|null
  242. */
  243. public function getOptions($optionKey = null)
  244. {
  245. if ($optionKey === null) {
  246. return $this->_options;
  247. }
  248. if (isset($this->_options[$optionKey]) === true) {
  249. return $this->_options[$optionKey];
  250. }
  251. return null;
  252. }
  253. /**
  254. * Gets locale
  255. *
  256. * @return Zend_Locale|string|null
  257. */
  258. public function getLocale()
  259. {
  260. return $this->_options['locale'];
  261. }
  262. /**
  263. * Sets locale
  264. *
  265. * @param string|Zend_Locale $locale Locale to set
  266. * @throws Zend_Translate_Exception
  267. * @return Zend_Translate_Adapter Provides fluent interface
  268. */
  269. public function setLocale($locale)
  270. {
  271. if (($locale === "auto") or ($locale === null)) {
  272. $this->_automatic = true;
  273. } else {
  274. $this->_automatic = false;
  275. }
  276. try {
  277. $locale = Zend_Locale::findLocale($locale);
  278. } catch (Zend_Locale_Exception $e) {
  279. require_once 'Zend/Translate/Exception.php';
  280. throw new Zend_Translate_Exception("The given Language ({$locale}) does not exist");
  281. }
  282. if (!isset($this->_translate[$locale])) {
  283. $temp = explode('_', $locale);
  284. if (!isset($this->_translate[$temp[0]]) and !isset($this->_translate[$locale])) {
  285. if (!$this->_options['disableNotices']) {
  286. if ($this->_options['log']) {
  287. $this->_options['log']->notice("The language '{$locale}' has to be added before it can be used.");
  288. } else {
  289. trigger_error("The language '{$locale}' has to be added before it can be used.", E_USER_NOTICE);
  290. }
  291. }
  292. }
  293. $locale = $temp[0];
  294. }
  295. if (empty($this->_translate[$locale])) {
  296. if (!$this->_options['disableNotices']) {
  297. if ($this->_options['log']) {
  298. $this->_options['log']->notice("No translation for the language '{$locale}' available.");
  299. } else {
  300. trigger_error("No translation for the language '{$locale}' available.", E_USER_NOTICE);
  301. }
  302. }
  303. }
  304. if ($this->_options['locale'] != $locale) {
  305. $this->_options['locale'] = $locale;
  306. if (isset(self::$_cache)) {
  307. $id = 'Zend_Translate_' . $this->toString() . '_Options';
  308. self::$_cache->save( serialize($this->_options), $id, array('Zend_Translate'));
  309. }
  310. }
  311. return $this;
  312. }
  313. /**
  314. * Returns the available languages from this adapter
  315. *
  316. * @return array
  317. */
  318. public function getList()
  319. {
  320. $list = array_keys($this->_translate);
  321. $result = null;
  322. foreach($list as $value) {
  323. if (!empty($this->_translate[$value])) {
  324. $result[$value] = $value;
  325. }
  326. }
  327. return $result;
  328. }
  329. /**
  330. * Returns all available message ids from this adapter
  331. * If no locale is given, the actual language will be used
  332. *
  333. * @param string|Zend_Locale $locale (optional) Language to return the message ids from
  334. * @return array
  335. */
  336. public function getMessageIds($locale = null)
  337. {
  338. if (empty($locale) or !$this->isAvailable($locale)) {
  339. $locale = $this->_options['locale'];
  340. }
  341. return array_keys($this->_translate[(string) $locale]);
  342. }
  343. /**
  344. * Returns all available translations from this adapter
  345. * If no locale is given, the actual language will be used
  346. * If 'all' is given the complete translation dictionary will be returned
  347. *
  348. * @param string|Zend_Locale $locale (optional) Language to return the messages from
  349. * @return array
  350. */
  351. public function getMessages($locale = null)
  352. {
  353. if ($locale === 'all') {
  354. return $this->_translate;
  355. }
  356. if ((empty($locale) === true) or ($this->isAvailable($locale) === false)) {
  357. $locale = $this->_options['locale'];
  358. }
  359. return $this->_translate[(string) $locale];
  360. }
  361. /**
  362. * Is the wished language available ?
  363. *
  364. * @see Zend_Locale
  365. * @param string|Zend_Locale $locale Language to search for, identical with locale identifier,
  366. * @see Zend_Locale for more information
  367. * @return boolean
  368. */
  369. public function isAvailable($locale)
  370. {
  371. $return = isset($this->_translate[(string) $locale]);
  372. return $return;
  373. }
  374. /**
  375. * Load translation data
  376. *
  377. * @param mixed $data
  378. * @param string|Zend_Locale $locale
  379. * @param array $options (optional)
  380. * @return array
  381. */
  382. abstract protected function _loadTranslationData($data, $locale, array $options = array());
  383. /**
  384. * Internal function for adding translation data
  385. *
  386. * It may be a new language or additional data for existing language
  387. * If $clear parameter is true, then translation data for specified
  388. * language is replaced and added otherwise
  389. *
  390. * @see Zend_Locale
  391. * @param array|string $data Translation data
  392. * @param string|Zend_Locale $locale Locale/Language to add data for, identical with locale identifier,
  393. * @see Zend_Locale for more information
  394. * @param array $options (optional) Option for this Adapter
  395. * @throws Zend_Translate_Exception
  396. * @return Zend_Translate_Adapter Provides fluent interface
  397. */
  398. private function _addTranslationData($data, $locale, array $options = array())
  399. {
  400. try {
  401. $locale = Zend_Locale::findLocale($locale);
  402. } catch (Zend_Locale_Exception $e) {
  403. require_once 'Zend/Translate/Exception.php';
  404. throw new Zend_Translate_Exception("The given Language '{$locale}' does not exist");
  405. }
  406. if ($options['clear'] || !isset($this->_translate[$locale])) {
  407. $this->_translate[$locale] = array();
  408. }
  409. $read = true;
  410. if (isset(self::$_cache)) {
  411. $id = 'Zend_Translate_' . preg_replace('/[^a-zA-Z0-9_]/', '_', $data) . '_' . $this->toString();
  412. $result = self::$_cache->load($id);
  413. if ($result) {
  414. $temp = unserialize($result);
  415. $read = false;
  416. }
  417. }
  418. if ($read) {
  419. $temp = $this->_loadTranslationData($data, $locale, $options);
  420. }
  421. if (empty($temp)) {
  422. $temp = array();
  423. }
  424. $keys = array_keys($temp);
  425. foreach($keys as $key) {
  426. if (!isset($this->_translate[$key])) {
  427. $this->_translate[$key] = array();
  428. }
  429. $this->_translate[$key] = $this->_translate[$key] + $temp[$key];
  430. }
  431. if ($this->_automatic === true) {
  432. $find = new Zend_Locale($locale);
  433. $browser = $find->getEnvironment() + $find->getBrowser();
  434. arsort($browser);
  435. foreach($browser as $language => $quality) {
  436. if (isset($this->_translate[$language])) {
  437. $this->_options['locale'] = $language;
  438. break;
  439. }
  440. }
  441. }
  442. if (($read) and (isset(self::$_cache))) {
  443. $id = 'Zend_Translate_' . preg_replace('/[^a-zA-Z0-9_]/', '_', $data) . '_' . $this->toString();
  444. self::$_cache->save( serialize($temp), $id, array('Zend_Translate'));
  445. }
  446. return $this;
  447. }
  448. /**
  449. * Translates the given string
  450. * returns the translation
  451. *
  452. * @see Zend_Locale
  453. * @param string $messageId Translation string
  454. * @param string|Zend_Locale $locale (optional) Locale/Language to use, identical with
  455. * locale identifier, @see Zend_Locale for more information
  456. * @return string
  457. */
  458. public function translate($messageId, $locale = null)
  459. {
  460. if ($locale === null) {
  461. $locale = $this->_options['locale'];
  462. }
  463. if (!Zend_Locale::isLocale($locale, true, false)) {
  464. if (!Zend_Locale::isLocale($locale, false, false)) {
  465. // language does not exist, return original string
  466. $this->_log($messageId, $locale);
  467. return $messageId;
  468. }
  469. $locale = new Zend_Locale($locale);
  470. }
  471. $locale = (string) $locale;
  472. if ((is_string($messageId) || is_numeric($messageId))
  473. && isset($this->_translate[$locale])
  474. && is_array($this->_translate[$locale])
  475. && isset($this->_translate[$locale][$messageId])
  476. ) {
  477. // return original translation
  478. return $this->_translate[$locale][$messageId];
  479. } else if (strlen($locale) != 2) {
  480. // faster than creating a new locale and separate the leading part
  481. $locale = substr($locale, 0, -strlen(strrchr($locale, '_')));
  482. if ((is_string($messageId) || is_numeric($messageId))
  483. && isset($this->_translate[$locale][$messageId])
  484. ) {
  485. // return regionless translation (en_US -> en)
  486. return $this->_translate[$locale][$messageId];
  487. }
  488. }
  489. $this->_log($messageId, $locale);
  490. return $messageId;
  491. }
  492. /**
  493. * Logs a message when the log option is set
  494. *
  495. * @param string $message Message to log
  496. * @param String $locale Locale to log
  497. */
  498. protected function _log($message, $locale) {
  499. if ($this->_options['logUntranslated']) {
  500. $message = str_replace('%message%', $message, $this->_options['logMessage']);
  501. $message = str_replace('%locale%', $locale, $message);
  502. if ($this->_options['log']) {
  503. $this->_options['log']->notice($message);
  504. } else {
  505. trigger_error($message, E_USER_NOTICE);
  506. }
  507. }
  508. }
  509. /**
  510. * Translates the given string
  511. * returns the translation
  512. *
  513. * @param string $messageId Translation string
  514. * @param string|Zend_Locale $locale (optional) Locale/Language to use, identical with locale
  515. * identifier, @see Zend_Locale for more information
  516. * @return string
  517. */
  518. public function _($messageId, $locale = null)
  519. {
  520. return $this->translate($messageId, $locale);
  521. }
  522. /**
  523. * Checks if a string is translated within the source or not
  524. * returns boolean
  525. *
  526. * @param string $messageId Translation string
  527. * @param boolean $original (optional) Allow translation only for original language
  528. * when true, a translation for 'en_US' would give false when it can
  529. * be translated with 'en' only
  530. * @param string|Zend_Locale $locale (optional) Locale/Language to use, identical with locale identifier,
  531. * see Zend_Locale for more information
  532. * @return boolean
  533. */
  534. public function isTranslated($messageId, $original = false, $locale = null)
  535. {
  536. if (($original !== false) and ($original !== true)) {
  537. $locale = $original;
  538. $original = false;
  539. }
  540. if ($locale === null) {
  541. $locale = $this->_options['locale'];
  542. }
  543. if (!Zend_Locale::isLocale($locale, true, false)) {
  544. if (!Zend_Locale::isLocale($locale, false, false)) {
  545. // language does not exist, return original string
  546. $this->_log($messageId, $locale);
  547. return false;
  548. }
  549. $locale = new Zend_Locale();
  550. }
  551. $locale = (string) $locale;
  552. if (isset($this->_translate[$locale][$messageId]) === true) {
  553. // return original translation
  554. return true;
  555. } else if ((strlen($locale) != 2) and ($original === false)) {
  556. // faster than creating a new locale and separate the leading part
  557. $locale = substr($locale, 0, -strlen(strrchr($locale, '_')));
  558. if (isset($this->_translate[$locale][$messageId]) === true) {
  559. // return regionless translation (en_US -> en)
  560. return true;
  561. }
  562. }
  563. // No translation found, return original
  564. $this->_log($messageId, $locale);
  565. return false;
  566. }
  567. /**
  568. * Returns the set cache
  569. *
  570. * @return Zend_Cache_Core The set cache
  571. */
  572. public static function getCache()
  573. {
  574. return self::$_cache;
  575. }
  576. /**
  577. * Sets a cache for all Zend_Translate_Adapters
  578. *
  579. * @param Zend_Cache_Core $cache Cache to store to
  580. */
  581. public static function setCache(Zend_Cache_Core $cache)
  582. {
  583. self::$_cache = $cache;
  584. }
  585. /**
  586. * Returns true when a cache is set
  587. *
  588. * @return boolean
  589. */
  590. public static function hasCache()
  591. {
  592. if (self::$_cache !== null) {
  593. return true;
  594. }
  595. return false;
  596. }
  597. /**
  598. * Removes any set cache
  599. *
  600. * @return void
  601. */
  602. public static function removeCache()
  603. {
  604. self::$_cache = null;
  605. }
  606. /**
  607. * Clears all set cache data
  608. *
  609. * @return void
  610. */
  611. public static function clearCache()
  612. {
  613. require_once 'Zend/Cache.php';
  614. self::$_cache->clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array('Zend_Translate'));
  615. }
  616. /**
  617. * Returns the adapter name
  618. *
  619. * @return string
  620. */
  621. abstract public function toString();
  622. }