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

/wp-includes/pomo/po.php

https://gitlab.com/webkod3r/tripolis
PHP | 446 lines | 316 code | 26 blank | 104 comment | 83 complexity | 0ad8053b19fc235615e1569b977c6fc6 MD5 | raw file
  1. <?php
  2. /**
  3. * Class for working with PO files
  4. *
  5. * @version $Id: po.php 1158 2015-11-20 04:31:23Z dd32 $
  6. * @package pomo
  7. * @subpackage po
  8. */
  9. require_once dirname(__FILE__) . '/translations.php';
  10. if ( ! defined( 'PO_MAX_LINE_LEN' ) ) {
  11. define('PO_MAX_LINE_LEN', 79);
  12. }
  13. ini_set('auto_detect_line_endings', 1);
  14. /**
  15. * Routines for working with PO files
  16. */
  17. if ( ! class_exists( 'PO', false ) ):
  18. class PO extends Gettext_Translations {
  19. var $comments_before_headers = '';
  20. /**
  21. * Exports headers to a PO entry
  22. *
  23. * @return string msgid/msgstr PO entry for this PO file headers, doesn't contain newline at the end
  24. */
  25. function export_headers() {
  26. $header_string = '';
  27. foreach($this->headers as $header => $value) {
  28. $header_string.= "$header: $value\n";
  29. }
  30. $poified = PO::poify($header_string);
  31. if ($this->comments_before_headers)
  32. $before_headers = $this->prepend_each_line(rtrim($this->comments_before_headers)."\n", '# ');
  33. else
  34. $before_headers = '';
  35. return rtrim("{$before_headers}msgid \"\"\nmsgstr $poified");
  36. }
  37. /**
  38. * Exports all entries to PO format
  39. *
  40. * @return string sequence of mgsgid/msgstr PO strings, doesn't containt newline at the end
  41. */
  42. function export_entries() {
  43. //TODO sorting
  44. return implode("\n\n", array_map(array('PO', 'export_entry'), $this->entries));
  45. }
  46. /**
  47. * Exports the whole PO file as a string
  48. *
  49. * @param bool $include_headers whether to include the headers in the export
  50. * @return string ready for inclusion in PO file string for headers and all the enrtries
  51. */
  52. function export($include_headers = true) {
  53. $res = '';
  54. if ($include_headers) {
  55. $res .= $this->export_headers();
  56. $res .= "\n\n";
  57. }
  58. $res .= $this->export_entries();
  59. return $res;
  60. }
  61. /**
  62. * Same as {@link export}, but writes the result to a file
  63. *
  64. * @param string $filename where to write the PO string
  65. * @param bool $include_headers whether to include tje headers in the export
  66. * @return bool true on success, false on error
  67. */
  68. function export_to_file($filename, $include_headers = true) {
  69. $fh = fopen($filename, 'w');
  70. if (false === $fh) return false;
  71. $export = $this->export($include_headers);
  72. $res = fwrite($fh, $export);
  73. if (false === $res) return false;
  74. return fclose($fh);
  75. }
  76. /**
  77. * Text to include as a comment before the start of the PO contents
  78. *
  79. * Doesn't need to include # in the beginning of lines, these are added automatically
  80. */
  81. function set_comment_before_headers( $text ) {
  82. $this->comments_before_headers = $text;
  83. }
  84. /**
  85. * Formats a string in PO-style
  86. *
  87. * @static
  88. * @param string $string the string to format
  89. * @return string the poified string
  90. */
  91. public static function poify($string) {
  92. $quote = '"';
  93. $slash = '\\';
  94. $newline = "\n";
  95. $replaces = array(
  96. "$slash" => "$slash$slash",
  97. "$quote" => "$slash$quote",
  98. "\t" => '\t',
  99. );
  100. $string = str_replace(array_keys($replaces), array_values($replaces), $string);
  101. $po = $quote.implode("${slash}n$quote$newline$quote", explode($newline, $string)).$quote;
  102. // add empty string on first line for readbility
  103. if (false !== strpos($string, $newline) &&
  104. (substr_count($string, $newline) > 1 || !($newline === substr($string, -strlen($newline))))) {
  105. $po = "$quote$quote$newline$po";
  106. }
  107. // remove empty strings
  108. $po = str_replace("$newline$quote$quote", '', $po);
  109. return $po;
  110. }
  111. /**
  112. * Gives back the original string from a PO-formatted string
  113. *
  114. * @static
  115. * @param string $string PO-formatted string
  116. * @return string enascaped string
  117. */
  118. public static function unpoify($string) {
  119. $escapes = array('t' => "\t", 'n' => "\n", 'r' => "\r", '\\' => '\\');
  120. $lines = array_map('trim', explode("\n", $string));
  121. $lines = array_map(array('PO', 'trim_quotes'), $lines);
  122. $unpoified = '';
  123. $previous_is_backslash = false;
  124. foreach($lines as $line) {
  125. preg_match_all('/./u', $line, $chars);
  126. $chars = $chars[0];
  127. foreach($chars as $char) {
  128. if (!$previous_is_backslash) {
  129. if ('\\' == $char)
  130. $previous_is_backslash = true;
  131. else
  132. $unpoified .= $char;
  133. } else {
  134. $previous_is_backslash = false;
  135. $unpoified .= isset($escapes[$char])? $escapes[$char] : $char;
  136. }
  137. }
  138. }
  139. // Standardise the line endings on imported content, technically PO files shouldn't contain \r
  140. $unpoified = str_replace( array( "\r\n", "\r" ), "\n", $unpoified );
  141. return $unpoified;
  142. }
  143. /**
  144. * Inserts $with in the beginning of every new line of $string and
  145. * returns the modified string
  146. *
  147. * @static
  148. * @param string $string prepend lines in this string
  149. * @param string $with prepend lines with this string
  150. */
  151. public static function prepend_each_line($string, $with) {
  152. $php_with = var_export($with, true);
  153. $lines = explode("\n", $string);
  154. // do not prepend the string on the last empty line, artefact by explode
  155. if ("\n" == substr($string, -1)) unset($lines[count($lines) - 1]);
  156. $res = implode("\n", array_map(create_function('$x', "return $php_with.\$x;"), $lines));
  157. // give back the empty line, we ignored above
  158. if ("\n" == substr($string, -1)) $res .= "\n";
  159. return $res;
  160. }
  161. /**
  162. * Prepare a text as a comment -- wraps the lines and prepends #
  163. * and a special character to each line
  164. *
  165. * @access private
  166. * @param string $text the comment text
  167. * @param string $char character to denote a special PO comment,
  168. * like :, default is a space
  169. */
  170. public static function comment_block($text, $char=' ') {
  171. $text = wordwrap($text, PO_MAX_LINE_LEN - 3);
  172. return PO::prepend_each_line($text, "#$char ");
  173. }
  174. /**
  175. * Builds a string from the entry for inclusion in PO file
  176. *
  177. * @static
  178. * @param Translation_Entry &$entry the entry to convert to po string
  179. * @return false|string PO-style formatted string for the entry or
  180. * false if the entry is empty
  181. */
  182. public static function export_entry(&$entry) {
  183. if ( null === $entry->singular || '' === $entry->singular ) return false;
  184. $po = array();
  185. if (!empty($entry->translator_comments)) $po[] = PO::comment_block($entry->translator_comments);
  186. if (!empty($entry->extracted_comments)) $po[] = PO::comment_block($entry->extracted_comments, '.');
  187. if (!empty($entry->references)) $po[] = PO::comment_block(implode(' ', $entry->references), ':');
  188. if (!empty($entry->flags)) $po[] = PO::comment_block(implode(", ", $entry->flags), ',');
  189. if ($entry->context) $po[] = 'msgctxt '.PO::poify($entry->context);
  190. $po[] = 'msgid '.PO::poify($entry->singular);
  191. if (!$entry->is_plural) {
  192. $translation = empty($entry->translations)? '' : $entry->translations[0];
  193. $translation = PO::match_begin_and_end_newlines( $translation, $entry->singular );
  194. $po[] = 'msgstr '.PO::poify($translation);
  195. } else {
  196. $po[] = 'msgid_plural '.PO::poify($entry->plural);
  197. $translations = empty($entry->translations)? array('', '') : $entry->translations;
  198. foreach($translations as $i => $translation) {
  199. $translation = PO::match_begin_and_end_newlines( $translation, $entry->plural );
  200. $po[] = "msgstr[$i] ".PO::poify($translation);
  201. }
  202. }
  203. return implode("\n", $po);
  204. }
  205. public static function match_begin_and_end_newlines( $translation, $original ) {
  206. if ( '' === $translation ) {
  207. return $translation;
  208. }
  209. $original_begin = "\n" === substr( $original, 0, 1 );
  210. $original_end = "\n" === substr( $original, -1 );
  211. $translation_begin = "\n" === substr( $translation, 0, 1 );
  212. $translation_end = "\n" === substr( $translation, -1 );
  213. if ( $original_begin ) {
  214. if ( ! $translation_begin ) {
  215. $translation = "\n" . $translation;
  216. }
  217. } elseif ( $translation_begin ) {
  218. $translation = ltrim( $translation, "\n" );
  219. }
  220. if ( $original_end ) {
  221. if ( ! $translation_end ) {
  222. $translation .= "\n";
  223. }
  224. } elseif ( $translation_end ) {
  225. $translation = rtrim( $translation, "\n" );
  226. }
  227. return $translation;
  228. }
  229. /**
  230. * @param string $filename
  231. * @return boolean
  232. */
  233. function import_from_file($filename) {
  234. $f = fopen($filename, 'r');
  235. if (!$f) return false;
  236. $lineno = 0;
  237. while (true) {
  238. $res = $this->read_entry($f, $lineno);
  239. if (!$res) break;
  240. if ($res['entry']->singular == '') {
  241. $this->set_headers($this->make_headers($res['entry']->translations[0]));
  242. } else {
  243. $this->add_entry($res['entry']);
  244. }
  245. }
  246. PO::read_line($f, 'clear');
  247. if ( false === $res ) {
  248. return false;
  249. }
  250. if ( ! $this->headers && ! $this->entries ) {
  251. return false;
  252. }
  253. return true;
  254. }
  255. /**
  256. * @param resource $f
  257. * @param int $lineno
  258. * @return null|false|array
  259. */
  260. function read_entry($f, $lineno = 0) {
  261. $entry = new Translation_Entry();
  262. // where were we in the last step
  263. // can be: comment, msgctxt, msgid, msgid_plural, msgstr, msgstr_plural
  264. $context = '';
  265. $msgstr_index = 0;
  266. $is_final = create_function('$context', 'return $context == "msgstr" || $context == "msgstr_plural";');
  267. while (true) {
  268. $lineno++;
  269. $line = PO::read_line($f);
  270. if (!$line) {
  271. if (feof($f)) {
  272. if ($is_final($context))
  273. break;
  274. elseif (!$context) // we haven't read a line and eof came
  275. return null;
  276. else
  277. return false;
  278. } else {
  279. return false;
  280. }
  281. }
  282. if ($line == "\n") continue;
  283. $line = trim($line);
  284. if (preg_match('/^#/', $line, $m)) {
  285. // the comment is the start of a new entry
  286. if ($is_final($context)) {
  287. PO::read_line($f, 'put-back');
  288. $lineno--;
  289. break;
  290. }
  291. // comments have to be at the beginning
  292. if ($context && $context != 'comment') {
  293. return false;
  294. }
  295. // add comment
  296. $this->add_comment_to_entry($entry, $line);
  297. } elseif (preg_match('/^msgctxt\s+(".*")/', $line, $m)) {
  298. if ($is_final($context)) {
  299. PO::read_line($f, 'put-back');
  300. $lineno--;
  301. break;
  302. }
  303. if ($context && $context != 'comment') {
  304. return false;
  305. }
  306. $context = 'msgctxt';
  307. $entry->context .= PO::unpoify($m[1]);
  308. } elseif (preg_match('/^msgid\s+(".*")/', $line, $m)) {
  309. if ($is_final($context)) {
  310. PO::read_line($f, 'put-back');
  311. $lineno--;
  312. break;
  313. }
  314. if ($context && $context != 'msgctxt' && $context != 'comment') {
  315. return false;
  316. }
  317. $context = 'msgid';
  318. $entry->singular .= PO::unpoify($m[1]);
  319. } elseif (preg_match('/^msgid_plural\s+(".*")/', $line, $m)) {
  320. if ($context != 'msgid') {
  321. return false;
  322. }
  323. $context = 'msgid_plural';
  324. $entry->is_plural = true;
  325. $entry->plural .= PO::unpoify($m[1]);
  326. } elseif (preg_match('/^msgstr\s+(".*")/', $line, $m)) {
  327. if ($context != 'msgid') {
  328. return false;
  329. }
  330. $context = 'msgstr';
  331. $entry->translations = array(PO::unpoify($m[1]));
  332. } elseif (preg_match('/^msgstr\[(\d+)\]\s+(".*")/', $line, $m)) {
  333. if ($context != 'msgid_plural' && $context != 'msgstr_plural') {
  334. return false;
  335. }
  336. $context = 'msgstr_plural';
  337. $msgstr_index = $m[1];
  338. $entry->translations[$m[1]] = PO::unpoify($m[2]);
  339. } elseif (preg_match('/^".*"$/', $line)) {
  340. $unpoified = PO::unpoify($line);
  341. switch ($context) {
  342. case 'msgid':
  343. $entry->singular .= $unpoified; break;
  344. case 'msgctxt':
  345. $entry->context .= $unpoified; break;
  346. case 'msgid_plural':
  347. $entry->plural .= $unpoified; break;
  348. case 'msgstr':
  349. $entry->translations[0] .= $unpoified; break;
  350. case 'msgstr_plural':
  351. $entry->translations[$msgstr_index] .= $unpoified; break;
  352. default:
  353. return false;
  354. }
  355. } else {
  356. return false;
  357. }
  358. }
  359. if (array() == array_filter($entry->translations, create_function('$t', 'return $t || "0" === $t;'))) {
  360. $entry->translations = array();
  361. }
  362. return array('entry' => $entry, 'lineno' => $lineno);
  363. }
  364. /**
  365. * @staticvar string $last_line
  366. * @staticvar boolean $use_last_line
  367. *
  368. * @param resource $f
  369. * @param string $action
  370. * @return boolean
  371. */
  372. function read_line($f, $action = 'read') {
  373. static $last_line = '';
  374. static $use_last_line = false;
  375. if ('clear' == $action) {
  376. $last_line = '';
  377. return true;
  378. }
  379. if ('put-back' == $action) {
  380. $use_last_line = true;
  381. return true;
  382. }
  383. $line = $use_last_line? $last_line : fgets($f);
  384. $line = ( "\r\n" == substr( $line, -2 ) ) ? rtrim( $line, "\r\n" ) . "\n" : $line;
  385. $last_line = $line;
  386. $use_last_line = false;
  387. return $line;
  388. }
  389. /**
  390. * @param Translation_Entry $entry
  391. * @param string $po_comment_line
  392. */
  393. function add_comment_to_entry(&$entry, $po_comment_line) {
  394. $first_two = substr($po_comment_line, 0, 2);
  395. $comment = trim(substr($po_comment_line, 2));
  396. if ('#:' == $first_two) {
  397. $entry->references = array_merge($entry->references, preg_split('/\s+/', $comment));
  398. } elseif ('#.' == $first_two) {
  399. $entry->extracted_comments = trim($entry->extracted_comments . "\n" . $comment);
  400. } elseif ('#,' == $first_two) {
  401. $entry->flags = array_merge($entry->flags, preg_split('/,\s*/', $comment));
  402. } else {
  403. $entry->translator_comments = trim($entry->translator_comments . "\n" . $comment);
  404. }
  405. }
  406. /**
  407. * @param string $s
  408. * @return sring
  409. */
  410. public static function trim_quotes($s) {
  411. if ( substr($s, 0, 1) == '"') $s = substr($s, 1);
  412. if ( substr($s, -1, 1) == '"') $s = substr($s, 0, -1);
  413. return $s;
  414. }
  415. }
  416. endif;