3 * Class for working with PO files
5 * @version $Id: po.php 718 2012-10-31 00:32:02Z nbachiyski $
10 require_once dirname(__FILE__) . '/translations.php';
12 define('PO_MAX_LINE_LEN', 79);
14 ini_set('auto_detect_line_endings', 1);
17 * Routines for working with PO files
19 if ( !class_exists( 'PO' ) ):
20 class PO extends Gettext_Translations {
22 var $comments_before_headers = '';
25 * Exports headers to a PO entry
27 * @return string msgid/msgstr PO entry for this PO file headers, doesn't contain newline at the end
29 function export_headers() {
31 foreach($this->headers as $header => $value) {
32 $header_string.= "$header: $value\n";
34 $poified = PO::poify($header_string);
35 if ($this->comments_before_headers)
36 $before_headers = $this->prepend_each_line(rtrim($this->comments_before_headers)."\n", '# ');
39 return rtrim("{$before_headers}msgid \"\"\nmsgstr $poified");
43 * Exports all entries to PO format
45 * @return string sequence of mgsgid/msgstr PO strings, doesn't containt newline at the end
47 function export_entries() {
49 return implode("\n\n", array_map(array('PO', 'export_entry'), $this->entries));
53 * Exports the whole PO file as a string
55 * @param bool $include_headers whether to include the headers in the export
56 * @return string ready for inclusion in PO file string for headers and all the enrtries
58 function export($include_headers = true) {
60 if ($include_headers) {
61 $res .= $this->export_headers();
64 $res .= $this->export_entries();
69 * Same as {@link export}, but writes the result to a file
71 * @param string $filename where to write the PO string
72 * @param bool $include_headers whether to include tje headers in the export
73 * @return bool true on success, false on error
75 function export_to_file($filename, $include_headers = true) {
76 $fh = fopen($filename, 'w');
77 if (false === $fh) return false;
78 $export = $this->export($include_headers);
79 $res = fwrite($fh, $export);
80 if (false === $res) return false;
85 * Text to include as a comment before the start of the PO contents
87 * Doesn't need to include # in the beginning of lines, these are added automatically
89 function set_comment_before_headers( $text ) {
90 $this->comments_before_headers = $text;
94 * Formats a string in PO-style
97 * @param string $string the string to format
98 * @return string the poified string
100 function poify($string) {
106 "$slash" => "$slash$slash",
107 "$quote" => "$slash$quote",
111 $string = str_replace(array_keys($replaces), array_values($replaces), $string);
113 $po = $quote.implode("${slash}n$quote$newline$quote", explode($newline, $string)).$quote;
114 // add empty string on first line for readbility
115 if (false !== strpos($string, $newline) &&
116 (substr_count($string, $newline) > 1 || !($newline === substr($string, -strlen($newline))))) {
117 $po = "$quote$quote$newline$po";
119 // remove empty strings
120 $po = str_replace("$newline$quote$quote", '', $po);
125 * Gives back the original string from a PO-formatted string
128 * @param string $string PO-formatted string
129 * @return string enascaped string
131 function unpoify($string) {
132 $escapes = array('t' => "\t", 'n' => "\n", '\\' => '\\');
133 $lines = array_map('trim', explode("\n", $string));
134 $lines = array_map(array('PO', 'trim_quotes'), $lines);
136 $previous_is_backslash = false;
137 foreach($lines as $line) {
138 preg_match_all('/./u', $line, $chars);
140 foreach($chars as $char) {
141 if (!$previous_is_backslash) {
143 $previous_is_backslash = true;
147 $previous_is_backslash = false;
148 $unpoified .= isset($escapes[$char])? $escapes[$char] : $char;
156 * Inserts $with in the beginning of every new line of $string and
157 * returns the modified string
160 * @param string $string prepend lines in this string
161 * @param string $with prepend lines with this string
163 function prepend_each_line($string, $with) {
164 $php_with = var_export($with, true);
165 $lines = explode("\n", $string);
166 // do not prepend the string on the last empty line, artefact by explode
167 if ("\n" == substr($string, -1)) unset($lines[count($lines) - 1]);
168 $res = implode("\n", array_map(create_function('$x', "return $php_with.\$x;"), $lines));
169 // give back the empty line, we ignored above
170 if ("\n" == substr($string, -1)) $res .= "\n";
175 * Prepare a text as a comment -- wraps the lines and prepends #
176 * and a special character to each line
179 * @param string $text the comment text
180 * @param string $char character to denote a special PO comment,
181 * like :, default is a space
183 function comment_block($text, $char=' ') {
184 $text = wordwrap($text, PO_MAX_LINE_LEN - 3);
185 return PO::prepend_each_line($text, "#$char ");
189 * Builds a string from the entry for inclusion in PO file
192 * @param Translation_Entry &$entry the entry to convert to po string
193 * @return false|string PO-style formatted string for the entry or
194 * false if the entry is empty
196 function export_entry(&$entry) {
197 if (is_null($entry->singular)) return false;
199 if (!empty($entry->translator_comments)) $po[] = PO::comment_block($entry->translator_comments);
200 if (!empty($entry->extracted_comments)) $po[] = PO::comment_block($entry->extracted_comments, '.');
201 if (!empty($entry->references)) $po[] = PO::comment_block(implode(' ', $entry->references), ':');
202 if (!empty($entry->flags)) $po[] = PO::comment_block(implode(", ", $entry->flags), ',');
203 if (!is_null($entry->context)) $po[] = 'msgctxt '.PO::poify($entry->context);
204 $po[] = 'msgid '.PO::poify($entry->singular);
205 if (!$entry->is_plural) {
206 $translation = empty($entry->translations)? '' : $entry->translations[0];
207 $po[] = 'msgstr '.PO::poify($translation);
209 $po[] = 'msgid_plural '.PO::poify($entry->plural);
210 $translations = empty($entry->translations)? array('', '') : $entry->translations;
211 foreach($translations as $i => $translation) {
212 $po[] = "msgstr[$i] ".PO::poify($translation);
215 return implode("\n", $po);
219 * @param string $filename
222 function import_from_file($filename) {
223 $f = fopen($filename, 'r');
224 if (!$f) return false;
227 $res = $this->read_entry($f, $lineno);
229 if ($res['entry']->singular == '') {
230 $this->set_headers($this->make_headers($res['entry']->translations[0]));
232 $this->add_entry($res['entry']);
235 PO::read_line($f, 'clear');
236 if ( false === $res ) {
239 if ( ! $this->headers && ! $this->entries ) {
248 * @return null|false|array
250 function read_entry($f, $lineno = 0) {
251 $entry = new Translation_Entry();
252 // where were we in the last step
253 // can be: comment, msgctxt, msgid, msgid_plural, msgstr, msgstr_plural
256 $is_final = create_function('$context', 'return $context == "msgstr" || $context == "msgstr_plural";');
259 $line = PO::read_line($f);
262 if ($is_final($context))
264 elseif (!$context) // we haven't read a line and eof came
272 if ($line == "\n") continue;
274 if (preg_match('/^#/', $line, $m)) {
275 // the comment is the start of a new entry
276 if ($is_final($context)) {
277 PO::read_line($f, 'put-back');
281 // comments have to be at the beginning
282 if ($context && $context != 'comment') {
286 $this->add_comment_to_entry($entry, $line);
287 } elseif (preg_match('/^msgctxt\s+(".*")/', $line, $m)) {
288 if ($is_final($context)) {
289 PO::read_line($f, 'put-back');
293 if ($context && $context != 'comment') {
296 $context = 'msgctxt';
297 $entry->context .= PO::unpoify($m[1]);
298 } elseif (preg_match('/^msgid\s+(".*")/', $line, $m)) {
299 if ($is_final($context)) {
300 PO::read_line($f, 'put-back');
304 if ($context && $context != 'msgctxt' && $context != 'comment') {
308 $entry->singular .= PO::unpoify($m[1]);
309 } elseif (preg_match('/^msgid_plural\s+(".*")/', $line, $m)) {
310 if ($context != 'msgid') {
313 $context = 'msgid_plural';
314 $entry->is_plural = true;
315 $entry->plural .= PO::unpoify($m[1]);
316 } elseif (preg_match('/^msgstr\s+(".*")/', $line, $m)) {
317 if ($context != 'msgid') {
321 $entry->translations = array(PO::unpoify($m[1]));
322 } elseif (preg_match('/^msgstr\[(\d+)\]\s+(".*")/', $line, $m)) {
323 if ($context != 'msgid_plural' && $context != 'msgstr_plural') {
326 $context = 'msgstr_plural';
327 $msgstr_index = $m[1];
328 $entry->translations[$m[1]] = PO::unpoify($m[2]);
329 } elseif (preg_match('/^".*"$/', $line)) {
330 $unpoified = PO::unpoify($line);
333 $entry->singular .= $unpoified; break;
335 $entry->context .= $unpoified; break;
337 $entry->plural .= $unpoified; break;
339 $entry->translations[0] .= $unpoified; break;
340 case 'msgstr_plural':
341 $entry->translations[$msgstr_index] .= $unpoified; break;
349 if (array() == array_filter($entry->translations, create_function('$t', 'return $t || "0" === $t;'))) {
350 $entry->translations = array();
352 return array('entry' => $entry, 'lineno' => $lineno);
356 * @staticvar string $last_line
357 * @staticvar boolean $use_last_line
359 * @param string $action
362 function read_line($f, $action = 'read') {
363 static $last_line = '';
364 static $use_last_line = false;
365 if ('clear' == $action) {
369 if ('put-back' == $action) {
370 $use_last_line = true;
373 $line = $use_last_line? $last_line : fgets($f);
374 $line = ( "\r\n" == substr( $line, -2 ) ) ? rtrim( $line, "\r\n" ) . "\n" : $line;
376 $use_last_line = false;
381 * @param Translation_Entry $entry
382 * @param string $po_comment_line
384 function add_comment_to_entry(&$entry, $po_comment_line) {
385 $first_two = substr($po_comment_line, 0, 2);
386 $comment = trim(substr($po_comment_line, 2));
387 if ('#:' == $first_two) {
388 $entry->references = array_merge($entry->references, preg_split('/\s+/', $comment));
389 } elseif ('#.' == $first_two) {
390 $entry->extracted_comments = trim($entry->extracted_comments . "\n" . $comment);
391 } elseif ('#,' == $first_two) {
392 $entry->flags = array_merge($entry->flags, preg_split('/,\s*/', $comment));
394 $entry->translator_comments = trim($entry->translator_comments . "\n" . $comment);
402 function trim_quotes($s) {
403 if ( substr($s, 0, 1) == '"') $s = substr($s, 1);
404 if ( substr($s, -1, 1) == '"') $s = substr($s, 0, -1);