gettext.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. <?php
  2. /*
  3. Copyright (c) 2003, 2009 Danilo Segan <[email protected]>.
  4. Copyright (c) 2005 Nico Kaiser <[email protected]>
  5. This file is part of PHP-gettext.
  6. PHP-gettext is free software; you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation; either version 2 of the License, or
  9. (at your option) any later version.
  10. PHP-gettext is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. GNU General Public License for more details.
  14. You should have received a copy of the GNU General Public License
  15. along with PHP-gettext; if not, write to the Free Software
  16. Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  17. */
  18. /**
  19. * Provides a simple gettext replacement that works independently from
  20. * the system's gettext abilities.
  21. * It can read MO files and use them for translating strings.
  22. * The files are passed to gettext_reader as a Stream (see streams.php)
  23. *
  24. * This version has the ability to cache all strings and translations to
  25. * speed up the string lookup.
  26. * While the cache is enabled by default, it can be switched off with the
  27. * second parameter in the constructor (e.g. whenusing very large MO files
  28. * that you don't want to keep in memory)
  29. */
  30. class gettext_reader {
  31. //public:
  32. var $error = 0; // public variable that holds error code (0 if no error)
  33. //private:
  34. var $BYTEORDER = 0; // 0: low endian, 1: big endian
  35. var $STREAM = NULL;
  36. var $short_circuit = false;
  37. var $enable_cache = false;
  38. var $originals = NULL; // offset of original table
  39. var $translations = NULL; // offset of translation table
  40. var $pluralheader = NULL; // cache header field for plural forms
  41. var $total = 0; // total string count
  42. var $table_originals = NULL; // table for original strings (offsets)
  43. var $table_translations = NULL; // table for translated strings (offsets)
  44. var $cache_translations = NULL; // original -> translation mapping
  45. /* Methods */
  46. /**
  47. * Reads a 32bit Integer from the Stream
  48. *
  49. * @access private
  50. * @return Integer from the Stream
  51. */
  52. function readint() {
  53. if ($this->BYTEORDER == 0) {
  54. // low endian
  55. $input=unpack('V', $this->STREAM->read(4));
  56. return array_shift($input);
  57. } else {
  58. // big endian
  59. $input=unpack('N', $this->STREAM->read(4));
  60. return array_shift($input);
  61. }
  62. }
  63. function read($bytes) {
  64. return $this->STREAM->read($bytes);
  65. }
  66. /**
  67. * Reads an array of Integers from the Stream
  68. *
  69. * @param int count How many elements should be read
  70. * @return Array of Integers
  71. */
  72. function readintarray($count) {
  73. if ($this->BYTEORDER == 0) {
  74. // low endian
  75. return unpack('V'.$count, $this->STREAM->read(4 * $count));
  76. } else {
  77. // big endian
  78. return unpack('N'.$count, $this->STREAM->read(4 * $count));
  79. }
  80. }
  81. /**
  82. * Constructor
  83. *
  84. * @param object Reader the StreamReader object
  85. * @param boolean enable_cache Enable or disable caching of strings (default on)
  86. */
  87. function gettext_reader($Reader, $enable_cache = true) {
  88. // If there isn't a StreamReader, turn on short circuit mode.
  89. if (! $Reader || isset($Reader->error) ) {
  90. $this->short_circuit = true;
  91. return;
  92. }
  93. // Caching can be turned off
  94. $this->enable_cache = $enable_cache;
  95. $MAGIC1 = "\x95\x04\x12\xde";
  96. $MAGIC2 = "\xde\x12\x04\x95";
  97. $this->STREAM = $Reader;
  98. $magic = $this->read(4);
  99. if ($magic == $MAGIC1) {
  100. $this->BYTEORDER = 1;
  101. } elseif ($magic == $MAGIC2) {
  102. $this->BYTEORDER = 0;
  103. } else {
  104. $this->error = 1; // not MO file
  105. return false;
  106. }
  107. // FIXME: Do we care about revision? We should.
  108. $revision = $this->readint();
  109. $this->total = $this->readint();
  110. $this->originals = $this->readint();
  111. $this->translations = $this->readint();
  112. }
  113. /**
  114. * Loads the translation tables from the MO file into the cache
  115. * If caching is enabled, also loads all strings into a cache
  116. * to speed up translation lookups
  117. *
  118. * @access private
  119. */
  120. function load_tables() {
  121. if (is_array($this->cache_translations) &&
  122. is_array($this->table_originals) &&
  123. is_array($this->table_translations))
  124. return;
  125. /* get original and translations tables */
  126. if (!is_array($this->table_originals)) {
  127. $this->STREAM->seekto($this->originals);
  128. $this->table_originals = $this->readintarray($this->total * 2);
  129. }
  130. if (!is_array($this->table_translations)) {
  131. $this->STREAM->seekto($this->translations);
  132. $this->table_translations = $this->readintarray($this->total * 2);
  133. }
  134. if ($this->enable_cache) {
  135. $this->cache_translations = array ();
  136. /* read all strings in the cache */
  137. for ($i = 0; $i < $this->total; $i++) {
  138. $this->STREAM->seekto($this->table_originals[$i * 2 + 2]);
  139. $original = $this->STREAM->read($this->table_originals[$i * 2 + 1]);
  140. $this->STREAM->seekto($this->table_translations[$i * 2 + 2]);
  141. $translation = $this->STREAM->read($this->table_translations[$i * 2 + 1]);
  142. $this->cache_translations[$original] = $translation;
  143. }
  144. }
  145. }
  146. /**
  147. * Returns a string from the "originals" table
  148. *
  149. * @access private
  150. * @param int num Offset number of original string
  151. * @return string Requested string if found, otherwise ''
  152. */
  153. function get_original_string($num) {
  154. $length = $this->table_originals[$num * 2 + 1];
  155. $offset = $this->table_originals[$num * 2 + 2];
  156. if (! $length)
  157. return '';
  158. $this->STREAM->seekto($offset);
  159. $data = $this->STREAM->read($length);
  160. return (string)$data;
  161. }
  162. /**
  163. * Returns a string from the "translations" table
  164. *
  165. * @access private
  166. * @param int num Offset number of original string
  167. * @return string Requested string if found, otherwise ''
  168. */
  169. function get_translation_string($num) {
  170. $length = $this->table_translations[$num * 2 + 1];
  171. $offset = $this->table_translations[$num * 2 + 2];
  172. if (! $length)
  173. return '';
  174. $this->STREAM->seekto($offset);
  175. $data = $this->STREAM->read($length);
  176. return (string)$data;
  177. }
  178. /**
  179. * Binary search for string
  180. *
  181. * @access private
  182. * @param string string
  183. * @param int start (internally used in recursive function)
  184. * @param int end (internally used in recursive function)
  185. * @return int string number (offset in originals table)
  186. */
  187. function find_string($string, $start = -1, $end = -1) {
  188. if (($start == -1) or ($end == -1)) {
  189. // find_string is called with only one parameter, set start end end
  190. $start = 0;
  191. $end = $this->total;
  192. }
  193. if (abs($start - $end) <= 1) {
  194. // We're done, now we either found the string, or it doesn't exist
  195. $txt = $this->get_original_string($start);
  196. if ($string == $txt)
  197. return $start;
  198. else
  199. return -1;
  200. } else if ($start > $end) {
  201. // start > end -> turn around and start over
  202. return $this->find_string($string, $end, $start);
  203. } else {
  204. // Divide table in two parts
  205. $half = (int)(($start + $end) / 2);
  206. $cmp = strcmp($string, $this->get_original_string($half));
  207. if ($cmp == 0)
  208. // string is exactly in the middle => return it
  209. return $half;
  210. else if ($cmp < 0)
  211. // The string is in the upper half
  212. return $this->find_string($string, $start, $half);
  213. else
  214. // The string is in the lower half
  215. return $this->find_string($string, $half, $end);
  216. }
  217. }
  218. /**
  219. * Translates a string
  220. *
  221. * @access public
  222. * @param string string to be translated
  223. * @return string translated string (or original, if not found)
  224. */
  225. function translate($string) {
  226. if ($this->short_circuit)
  227. return $string;
  228. $this->load_tables();
  229. if ($this->enable_cache) {
  230. // Caching enabled, get translated string from cache
  231. if (array_key_exists($string, $this->cache_translations))
  232. return $this->cache_translations[$string];
  233. else
  234. return $string;
  235. } else {
  236. // Caching not enabled, try to find string
  237. $num = $this->find_string($string);
  238. if ($num == -1)
  239. return $string;
  240. else
  241. return $this->get_translation_string($num);
  242. }
  243. }
  244. /**
  245. * Sanitize plural form expression for use in PHP eval call.
  246. *
  247. * @access private
  248. * @return string sanitized plural form expression
  249. */
  250. function sanitize_plural_expression($expr) {
  251. // Get rid of disallowed characters.
  252. $expr = preg_replace('@[^a-zA-Z0-9_:;\(\)\?\|\&=!<>+*/\%-]@', '', $expr);
  253. // Add parenthesis for tertiary '?' operator.
  254. $expr .= ';';
  255. $res = '';
  256. $p = 0;
  257. for ($i = 0; $i < strlen($expr); $i++) {
  258. $ch = $expr[$i];
  259. switch ($ch) {
  260. case '?':
  261. $res .= ' ? (';
  262. $p++;
  263. break;
  264. case ':':
  265. $res .= ') : (';
  266. break;
  267. case ';':
  268. $res .= str_repeat( ')', $p) . ';';
  269. $p = 0;
  270. break;
  271. default:
  272. $res .= $ch;
  273. }
  274. }
  275. return $res;
  276. }
  277. /**
  278. * Parse full PO header and extract only plural forms line.
  279. *
  280. * @access private
  281. * @return string verbatim plural form header field
  282. */
  283. function extract_plural_forms_header_from_po_header($header) {
  284. if (preg_match("/(^|\n)plural-forms: ([^\n]*)\n/i", $header, $regs))
  285. $expr = $regs[2];
  286. else
  287. $expr = "nplurals=2; plural=n == 1 ? 0 : 1;";
  288. return $expr;
  289. }
  290. /**
  291. * Get possible plural forms from MO header
  292. *
  293. * @access private
  294. * @return string plural form header
  295. */
  296. function get_plural_forms() {
  297. // lets assume message number 0 is header
  298. // this is true, right?
  299. $this->load_tables();
  300. // cache header field for plural forms
  301. if (! is_string($this->pluralheader)) {
  302. if ($this->enable_cache) {
  303. $header = $this->cache_translations[""];
  304. } else {
  305. $header = $this->get_translation_string(0);
  306. }
  307. $expr = $this->extract_plural_forms_header_from_po_header($header);
  308. $this->pluralheader = $this->sanitize_plural_expression($expr);
  309. }
  310. return $this->pluralheader;
  311. }
  312. /**
  313. * Detects which plural form to take
  314. *
  315. * @access private
  316. * @param n count
  317. * @return int array index of the right plural form
  318. */
  319. function select_string($n) {
  320. $string = $this->get_plural_forms();
  321. $string = str_replace('nplurals',"\$total",$string);
  322. $string = str_replace("n",$n,$string);
  323. $string = str_replace('plural',"\$plural",$string);
  324. $total = 0;
  325. $plural = 0;
  326. eval("$string");
  327. if ($plural >= $total) $plural = $total - 1;
  328. return $plural;
  329. }
  330. /**
  331. * Plural version of gettext
  332. *
  333. * @access public
  334. * @param string single
  335. * @param string plural
  336. * @param string number
  337. * @return translated plural form
  338. */
  339. function ngettext($single, $plural, $number) {
  340. if ($this->short_circuit) {
  341. if ($number != 1)
  342. return $plural;
  343. else
  344. return $single;
  345. }
  346. // find out the appropriate form
  347. $select = $this->select_string($number);
  348. // this should contains all strings separated by NULLs
  349. $key = $single . chr(0) . $plural;
  350. if ($this->enable_cache) {
  351. if (! array_key_exists($key, $this->cache_translations)) {
  352. return ($number != 1) ? $plural : $single;
  353. } else {
  354. $result = $this->cache_translations[$key];
  355. $list = explode(chr(0), $result);
  356. return $list[$select];
  357. }
  358. } else {
  359. $num = $this->find_string($key);
  360. if ($num == -1) {
  361. return ($number != 1) ? $plural : $single;
  362. } else {
  363. $result = $this->get_translation_string($num);
  364. $list = explode(chr(0), $result);
  365. return $list[$select];
  366. }
  367. }
  368. }
  369. function pgettext($context, $msgid) {
  370. $key = $context . chr(4) . $msgid;
  371. $ret = $this->translate($key);
  372. if (strpos($ret, "\004") !== FALSE) {
  373. return $msgid;
  374. } else {
  375. return $ret;
  376. }
  377. }
  378. function npgettext($context, $singular, $plural, $number) {
  379. $key = $context . chr(4) . $singular;
  380. $ret = $this->ngettext($key, $plural, $number);
  381. if (strpos($ret, "\004") !== FALSE) {
  382. return $singular;
  383. } else {
  384. return $ret;
  385. }
  386. }
  387. }
  388. ?>