Example #1
0
 function action_on_translation_set($translation_set)
 {
     $po = new PO();
     $po->import_from_file($this->options['f']);
     $added = $translation_set->import($po);
     printf(_n("%s translation were added", "%s translations were added", $added), $added);
 }
Example #2
0
 function add_translate_string($entries)
 {
     //create mofile;
     $pot = new PO();
     $pot->import_from_file(dirname(__FILE__) . '/ce_alert.po', true);
     return array_merge($entries, $pot->entries);
 }
Example #3
0
function wpll_create_mofile()
{
    global $wpll_pofile, $wpll_mofile;
    include_once ABSPATH . WPINC . '/pomo/po.php';
    $po = new PO();
    if (!@$po->import_from_file($wpll_pofile)) {
        return;
    }
    foreach ($po->entries as $key => $entry) {
        if (!empty($entry->references)) {
            $entry->references = array_filter($entry->references, 'wpll_filter_references');
            if (empty($entry->references)) {
                unset($po->entries[$key]);
                continue;
            }
        }
        if (!empty($entry->translations)) {
            if ($entry->singular == $entry->translations[0]) {
                unset($po->entries[$key]);
            }
        }
    }
    $mo = new MO();
    $mo->headers = $po->headers;
    $mo->entries = $po->entries;
    $mo->export_to_file($wpll_mofile);
    die;
}
Example #4
0
function ae_fields_add_translate_string($entries)
{
    $lang_path = dirname(__FILE__) . '/lang/default.po';
    if (file_exists($lang_path)) {
        $pot = new PO();
        $pot->import_from_file($lang_path, true);
        return array_merge($entries, $pot->entries);
    }
    return $entries;
}
/**
 * Carrega um arquivo PO
 * @param string $language - codigo da linguagem
 * @param string $group - grupo que pertence a tradu��o
 * @param string <URL> $path - caminho para encontrar o arquivo
 * @return object
 */
function loadPO($language, $group = 'default', $path = false)
{
    global $cfg;
    $PO = new PO();
    $path = $path == false ? './' . $cfg['po_dir'] : $path . '/';
    $path .= $group . '.' . $language . ".po";
    if (file_exists($path)) {
        $PO->import_from_file(realpath($path));
        return $PO;
    }
    return false;
}
Example #6
0
 function action_on_translation_set($translation_set)
 {
     $po = new PO();
     $po->import_from_file($this->options['f']);
     $disable_propagating = isset($this->options['disable-propagating']);
     if ($disable_propagating) {
         add_filter('enable_propagate_translations_across_projects', '__return_false');
     }
     $added = $translation_set->import($po);
     if ($disable_propagating) {
         remove_filter('enable_propagate_translations_across_projects', '__return_false');
     }
     printf(_n("%s translation were added\n", "%s translations were added\n", $added), $added);
 }
Example #7
0
 function run()
 {
     if (!isset($this->options['p'])) {
         $this->usage();
     }
     $project = GP::$project->by_path($this->options['p']);
     if (!$project) {
         $this->error('Project not found!');
     }
     $translations = new PO();
     $translations->import_from_file($this->options['f']);
     if (!$translations) {
         $this->error('Error importing from POT file!');
     }
     GP::$original->import_for_project($project, $translations);
 }
 function test_export_po()
 {
     $set = GP::$translation_set->create(array('name' => 'Set', 'slug' => 'set', 'project_id' => 1, 'locale' => 'bg'));
     GP::$translation->create(array('original_id' => 1, 'translation_set_id' => $set->id, 'translation_0' => 'Baba', 'user_id' => 1, 'status' => 'current'));
     GP::$translation->create(array('original_id' => 2, 'translation_set_id' => $set->id, 'translation_0' => 'Dudu', 'user_id' => 1, 'status' => 'waiting'));
     $po_file = $this->temp_filename();
     file_put_contents($po_file, $set->export_as_po());
     $po = new PO();
     $po->import_from_file($po_file);
     $translated = 0;
     foreach ($po->entries as $entry) {
         if (isset($entry->translations[0]) && $entry->translations[0]) {
             $translated += 1;
         }
     }
     $this->assertEquals(1, $translated);
 }
 function load_from_file($ext_filename)
 {
     $makepot = new MakePOT();
     $source = $makepot->get_first_lines($ext_filename);
     $pot = '';
     $po = new PO();
     foreach ($this->headers as $header) {
         $string = $makepot->get_addon_header($header, $source);
         if (!$string) {
             continue;
         }
         $args = array('singular' => $string, 'extracted_comments' => $header . ' of the plugin/theme');
         $entry = new Translation_Entry($args);
         $pot .= "\n" . $po->export_entry($entry) . "\n";
     }
     return $pot;
 }
Example #10
0
 /**
  * POT generator
  *
  * @param string $project "woocommerce" or "woocommerce-admin"
  * @return bool true on success, false on error
  */
 public function generate_pot($project = 'woocommerce')
 {
     // Unknown project
     if (empty($this->projects[$project])) {
         return false;
     }
     // Project config
     $config = $this->projects[$project];
     // Extract translatable strings from the WooCommerce plugin
     $originals = $this->extractor->extract_from_directory($this->woocommerce_path, $config['excludes'], $config['includes']);
     // Build POT file
     $pot = new PO();
     $pot->entries = $originals->entries;
     $pot->set_header('Project-Id-Version', 'WooCommerce ' . $this->woocommerce_version() . ' ' . $config['title']);
     $pot->set_header('Report-Msgid-Bugs-To', 'https://github.com/woothemes/woocommerce/issues');
     $pot->set_header('POT-Creation-Date', gmdate('Y-m-d H:i:s+00:00'));
     $pot->set_header('MIME-Version', '1.0');
     $pot->set_header('Content-Type', 'text/plain; charset=UTF-8');
     $pot->set_header('Content-Transfer-Encoding', '8bit');
     $pot->set_header('PO-Revision-Date', gmdate('Y') . '-MO-DA HO:MI+ZONE');
     $pot->set_header('Last-Translator', 'FULL NAME <EMAIL@ADDRESS>');
     $pot->set_header('Language-Team', 'LANGUAGE <EMAIL@ADDRESS>');
     // Write POT file
     $result = $pot->export_to_file($config['file']);
     // Add plugin header
     if ($project == 'woocommerce-admin') {
         $potextmeta = new PotExtMeta();
         $potextmeta->append($this->woocommerce_path . 'woocommerce.php', $config['file']);
     }
     return $result;
 }
Example #11
0
 /**
  * Store a newly created resource in storage.
  * POST /po
  *
  * @return Response
  */
 public function store()
 {
     $validator = Validator::make(Input::all(), PO::$rules);
     if ($validator->fails()) {
         return Redirect::to('PO')->withErrors($validator)->withInput(Input::all());
     } else {
         $PO = new PO();
         $PO->no_PO = Input::get('no_PO');
         $PO->tgl_PO = Input::get('tgl_PO');
         $PO->no_SPPB = Input::get('no_SPPB');
         $PO->id_supp = Input::get('id_supp');
         $PO->ship_to = Input::get('ship_to');
         $PO->city = Input::get('city');
         $PO->save();
         Session::flash('message', 'Successfully created PO!');
         return Redirect::to('PO');
     }
 }
Example #12
0
 function export_as_po()
 {
     if (!isset($this->project) || !$this->project) {
         $this->project = GP::$project->get($this->project_id);
     }
     // TODO: rename locale column to locale_slug and use freely $this->locale as the locale object
     $locale = GP_Locales::by_slug($this->locale);
     $po = new PO();
     // TODO: add more meta data in the project: language team, report URL
     // TODO: last updated for a translation set
     $po->set_header('PO-Revision-Date', gmdate('Y-m-d H:i:s+0000'));
     $po->set_header('MIME-Version', '1.0');
     $po->set_header('Content-Type', 'text/plain; charset=UTF-8');
     $po->set_header('Content-Transfer-Encoding', '8bit');
     $po->set_header('Plural-Forms', "nplurals={$locale->nplurals}; plural={$locale->plural_expression};");
     $po->set_header('X-Generator', 'GlotPress/' . gp_get_option('version'));
     $entries = GP::$translation->for_translation($this->project, $this, 'no-limit', array('status' => 'current'));
     foreach ($entries as $entry) {
         $po->add_entry($entry);
     }
     $po->set_header('Project-Id-Version', $this->project->name);
     return $po->export();
 }
Example #13
0
 /**
  * POT generator
  *
  * @param string $project "redux" or "redux-admin"
  * @return bool true on success, false on error
  */
 public function generate_pot($project = 'redux')
 {
     // Unknown project
     if (empty($this->projects[$project])) {
         return false;
     }
     // Project config
     $config = $this->projects[$project];
     // Extract translatable strings from the ReduxFramework plugin
     $originals = $this->extractor->extract_from_directory($this->redux_path, $config['excludes'], $config['includes']);
     // Build POT file
     $pot = new PO();
     $pot->entries = $originals->entries;
     $pot->set_header('Project-Id-Version', 'Redux Framework ' . $this->redux_version() . ' ' . $config['title']);
     $pot->set_header('Report-Msgid-Bugs-To', 'https://github.com/ReduxFramework/ReduxFramework/issues');
     $pot->set_header('POT-Creation-Date', gmdate('Y-m-d H:i:s+00:00'));
     $pot->set_header('MIME-Version', '1.0');
     $pot->set_header('Content-Type', 'text/plain; charset=UTF-8');
     $pot->set_header('Content-Transfer-Encoding', '8bit');
     $pot->set_header('PO-Revision-Date', gmdate('Y') . '-MO-DA HO:MI+ZONE');
     $pot->set_header('Last-Translator', 'Dovy Paukstys <*****@*****.**>');
     $pot->set_header('Language-Team', 'ReduxFramework <*****@*****.**>');
     $pot->set_header('Language', 'en_US');
     $pot->set_header('Plural-Forms', 'nplurals=2; plural=(n != 1);');
     $pot->set_header('esc_html_x;_c;_nc', '');
     $pot->set_header('_nx_noop;_ex;esc_attr__;esc_attr_e;esc_attr_x;esc_html__;esc_html_e;', '');
     $pot->set_header('X-Poedit-KeywordsList', '__;_e;__ngettext;_n;__ngettext_noop;_n_noop;_x;_nx;');
     $pot->set_header('X-Poedit-Basepath', '../../');
     $pot->set_header('X-Poedit-SourceCharset', 'UTF-8');
     $pot->set_header('X-Poedit-SearchPath-0', 'ReduxCore');
     $pot->set_header('X-Poedit-SearchPath-1', 'ReduxCore/languages');
     $pot->set_header('X-Poedit-SearchPath-2', '.');
     // Write POT file
     $result = $pot->export_to_file($config['file']);
     // Add plugin header
     if ($project == 'redux-admin') {
         $potextmeta = new PotExtMeta();
         $potextmeta->append($this->redux_path . 'redux-framework.php', $config['file']);
     }
     return $result;
 }
Example #14
0
 function test_import_from_file()
 {
     $po = new PO();
     $res = $po->import_from_file('data/simple.po');
     $this->assertEquals(true, $res);
     $this->assertEquals(array('Project-Id-Version' => 'WordPress 2.6-bleeding', 'Plural-Forms' => 'nplurals=2; plural=n != 1;'), $po->headers);
     $simple_entry = new Translation_Entry(array('singular' => 'moon'));
     $this->assertEquals($simple_entry, $po->entries[$simple_entry->key()]);
     $all_types_entry = new Translation_Entry(array('singular' => 'strut', 'plural' => 'struts', 'context' => 'brum', 'translations' => array('ztrut0', 'ztrut1', 'ztrut2')));
     $this->assertEquals($all_types_entry, $po->entries[$all_types_entry->key()]);
     $multiple_line_entry = new Translation_Entry(array('singular' => 'The first thing you need to do is tell Blogger to let WordPress access your account. You will be sent back here after providing authorization.', 'translations' => array("baba\ndyadogugu")));
     $this->assertEquals($multiple_line_entry, $po->entries[$multiple_line_entry->key()]);
     $multiple_line_all_types_entry = new Translation_Entry(array('context' => 'context', 'singular' => 'singular', 'plural' => 'plural', 'translations' => array('translation0', 'translation1', 'translation2')));
     $this->assertEquals($multiple_line_all_types_entry, $po->entries[$multiple_line_all_types_entry->key()]);
     $comments_entry = new Translation_Entry(array('singular' => 'a', 'translator_comments' => "baba\nbrubru", 'references' => array('wp-admin/x.php:111', 'baba:333', 'baba'), 'extracted_comments' => "translators: buuu", 'flags' => array('fuzzy')));
     $this->assertEquals($comments_entry, $po->entries[$comments_entry->key()]);
     $end_quote_entry = new Translation_Entry(array('singular' => 'a"'));
     $this->assertEquals($end_quote_entry, $po->entries[$end_quote_entry->key()]);
 }
Example #15
0
 /**
  * Import a file into the translation set
  *
  * ## OPTIONS
  *
  * <project>
  * : Project path
  *
  * <locale>
  * : Locale to export
  *
  * <file>
  * : File to import
  *
  * [--set=<set>]
  * : Translation set slug; default is "default"
  *
  * [--disable-propagating]
  * : If set, propagation will be disabled.
  */
 public function import($args, $assoc_args)
 {
     $set_slug = isset($assoc_args['set']) ? $assoc_args['set'] : 'default';
     $translation_set = $this->get_translation_set($args[0], $args[1], $set_slug);
     if (is_wp_error($translation_set)) {
         WP_CLI::error($translation_set->get_error_message());
     }
     $po = new PO();
     $imported = $po->import_from_file($args[2]);
     if (!$imported) {
         WP_CLI::error(__("Couldn't load translations from file!", 'glotpress'));
     }
     $disable_propagating = isset($assoc_args['disable-propagating']);
     if ($disable_propagating) {
         add_filter('gp_enable_propagate_translations_across_projects', '__return_false');
     }
     $added = $translation_set->import($po);
     if ($disable_propagating) {
         remove_filter('gp_enable_propagate_translations_across_projects', '__return_false');
     }
     /* translators: %s: Number of imported translations */
     WP_CLI::line(sprintf(_n('%s translation was added', '%s translations were added', $added, 'glotpress'), $added));
 }
Example #16
0
 /**
  * @dataProvider data_match_begin_and_end_newlines
  */
 function test_match_begin_and_end_newlines($original, $translation, $expected_translation, $message)
 {
     $this->assertEquals($expected_translation, PO::match_begin_and_end_newlines($translation, $original), $message);
 }
 /**
  * Configura a linguagem padr�o
  */
 private function GetLanguage()
 {
     $mysql = new MysqlConsulta($this->cfg);
     $this->language['language_default'] = $mysql->getLanguagefromCOUNTRY($this->cfg['ID_COUNTRY']);
     //--> en,pt-br,ja,it
     $this->language['language'] = $mysql->ListLanguages($this->language['language_default']);
     if (isset($this->perfil->user_language)) {
         $this->language['language_default'] = $this->perfil->user_language;
         $this->language['language'] = $mysql->ListLanguages($this->perfil->user_language);
     }
     if (isset($_GET['q'])) {
         $query = getLanguageURL($_GET['q']);
         if ($query[1]) {
             $this->language['language_default'] = $query[1];
             $this->language['language'] = $mysql->ListLanguages($query[1]);
         }
         $_GET['q'] = $query[0];
     }
     if ($this->language['language']->language != language_default()->language) {
         $this->language['translate'] = $mysql->getTranslate($this->language['language']->language);
         if (!$this->language['translate']) {
             $po = loadPO($this->language['language']->language);
             if ($po == false) {
                 //@todo mensagem de errooooo
                 $message = _t("File not found a standard language for this request.");
                 setMessage($message, 'error');
             }
             insertTranslation($po);
         } else {
             $po = new PO();
             $po->set_headers($this->language['translate']->headers);
             $po->merge_with($this->language['translate']);
             //@todo = verificar esta requisições de texto, se a função de tradução não irá cumprir o mesmo papel
         }
         $this->language['translate'] = $po;
     }
 }
Example #18
0
	function read_entry($f, $lineno = 0) {
		$entry = new Translation_Entry();
						$context = '';
		$msgstr_index = 0;
		$is_final = create_function('$context', 'return $context == "msgstr" || $context == "msgstr_plural";');
		while (true) {
			$lineno++;
			$line = PO::read_line($f);
			if (!$line)  {
				if (feof($f)) {
					if ($is_final($context))
						break;
					elseif (!$context) 						return null;
					else
						return false;
				} else {
					return false;
				}
			}
			if ($line == "\n") continue;
			$line = trim($line);
			if (preg_match('/^#/', $line, $m)) {
								if ($is_final($context)) {
					PO::read_line($f, 'put-back');
					$lineno--;
					break;
				}
								if ($context && $context != 'comment') {
					return false;
				}
								$this->add_comment_to_entry($entry, $line);
			} elseif (preg_match('/^msgctxt\s+(".*")/', $line, $m)) {
				if ($is_final($context)) {
					PO::read_line($f, 'put-back');
					$lineno--;
					break;
				}
				if ($context && $context != 'comment') {
					return false;
				}
				$context = 'msgctxt';
				$entry->context .= PO::unpoify($m[1]);
			} elseif (preg_match('/^msgid\s+(".*")/', $line, $m)) {
				if ($is_final($context)) {
					PO::read_line($f, 'put-back');
					$lineno--;
					break;
				}
				if ($context && $context != 'msgctxt' && $context != 'comment') {
					return false;
				}
				$context = 'msgid';
				$entry->singular .= PO::unpoify($m[1]);
			} elseif (preg_match('/^msgid_plural\s+(".*")/', $line, $m)) {
				if ($context != 'msgid') {
					return false;
				}
				$context = 'msgid_plural';
				$entry->is_plural = true;
				$entry->plural .= PO::unpoify($m[1]);
			} elseif (preg_match('/^msgstr\s+(".*")/', $line, $m)) {
				if ($context != 'msgid') {
					return false;
				}
				$context = 'msgstr';
				$entry->translations = array(PO::unpoify($m[1]));
			} elseif (preg_match('/^msgstr\[(\d+)\]\s+(".*")/', $line, $m)) {
				if ($context != 'msgid_plural' && $context != 'msgstr_plural') {
					return false;
				}
				$context = 'msgstr_plural';
				$msgstr_index = $m[1];
				$entry->translations[$m[1]] = PO::unpoify($m[2]);
			} elseif (preg_match('/^".*"$/', $line)) {
				$unpoified = PO::unpoify($line);
				switch ($context) {
					case 'msgid':
						$entry->singular .= $unpoified; break;
					case 'msgctxt':
						$entry->context .= $unpoified; break;
					case 'msgid_plural':
						$entry->plural .= $unpoified; break;
					case 'msgstr':
						$entry->translations[0] .= $unpoified; break;
					case 'msgstr_plural':
						$entry->translations[$msgstr_index] .= $unpoified; break;
					default:
						return false;
				}
			} else {
				return false;
			}
		}
		if (array() == array_filter($entry->translations, create_function('$t', 'return $t || "0" === $t;'))) {
			$entry->translations = array();
		}
		return array('entry' => $entry, 'lineno' => $lineno);
	}
Example #19
0
 function read_entry($f, $lineno = 0)
 {
     $entry = new Translation_Entry();
     // where were we in the last step
     // can be: comment, msgctxt, msgid, msgid_plural, msgstr, msgstr_plural
     $context = '';
     $msgstr_index = 0;
     $is_final = create_function('$context', 'return $context == "msgstr" || $context == "msgstr_plural";');
     while (true) {
         $lineno++;
         $line = PO::read_line($f);
         if (!$line) {
             if (feof($f)) {
                 if ($is_final($context)) {
                     break;
                 } elseif (!$context) {
                     // we haven't read a line and eof came
                     return null;
                 } else {
                     return false;
                 }
             } else {
                 return false;
             }
         }
         if ($line == "\n") {
             continue;
         }
         $line = trim($line);
         if (preg_match('/^#/', $line, $m)) {
             // the comment is the start of a new entry
             if ($is_final($context)) {
                 PO::read_line($f, 'put-back');
                 $lineno--;
                 break;
             }
             // comments have to be at the beginning
             if ($context && $context != 'comment') {
                 return false;
             }
             // add comment
             $this->add_comment_to_entry($entry, $line);
         } elseif (preg_match('/^msgctxt\\s+(".*")/', $line, $m)) {
             if ($is_final($context)) {
                 PO::read_line($f, 'put-back');
                 $lineno--;
                 break;
             }
             if ($context && $context != 'comment') {
                 return false;
             }
             $context = 'msgctxt';
             $entry->context .= PO::unpoify($m[1]);
         } elseif (preg_match('/^msgid\\s+(".*")/', $line, $m)) {
             if ($is_final($context)) {
                 PO::read_line($f, 'put-back');
                 $lineno--;
                 break;
             }
             if ($context && $context != 'msgctxt' && $context != 'comment') {
                 return false;
             }
             $context = 'msgid';
             $entry->singular .= PO::unpoify($m[1]);
         } elseif (preg_match('/^msgid_plural\\s+(".*")/', $line, $m)) {
             if ($context != 'msgid') {
                 return false;
             }
             $context = 'msgid_plural';
             $entry->is_plural = true;
             $entry->plural .= PO::unpoify($m[1]);
         } elseif (preg_match('/^msgstr\\s+(".*")/', $line, $m)) {
             if ($context != 'msgid') {
                 return false;
             }
             $context = 'msgstr';
             $entry->translations = array(PO::unpoify($m[1]));
         } elseif (preg_match('/^msgstr\\[(\\d+)\\]\\s+(".*")/', $line, $m)) {
             if ($context != 'msgid_plural' && $context != 'msgstr_plural') {
                 return false;
             }
             $context = 'msgstr_plural';
             $msgstr_index = $m[1];
             $entry->translations[$m[1]] = PO::unpoify($m[2]);
         } elseif (preg_match('/^".*"$/', $line)) {
             $unpoified = PO::unpoify($line);
             switch ($context) {
                 case 'msgid':
                     $entry->singular .= $unpoified;
                     break;
                 case 'msgctxt':
                     $entry->context .= $unpoified;
                     break;
                 case 'msgid_plural':
                     $entry->plural .= $unpoified;
                     break;
                 case 'msgstr':
                     $entry->translations[0] .= $unpoified;
                     break;
                 case 'msgstr_plural':
                     $entry->translations[$msgstr_index] .= $unpoified;
                     break;
                 default:
                     return false;
             }
         } else {
             return false;
         }
     }
     if (array() == array_filter($entry->translations, create_function('$t', 'return $t || "0" === $t;'))) {
         $entry->translations = array();
     }
     return array('entry' => $entry, 'lineno' => $lineno);
 }
 function command_extract()
 {
     $args = func_get_args();
     $pot_filename = $args[0];
     if (isset($args[1]) && is_array($args[1])) {
         $filenames = $args[1];
     } else {
         $filenames = array_slice($args, 1);
     }
     $global_name = '__entries_' . mt_rand(1, 1000);
     $GLOBALS[$global_name] = array();
     foreach ($filenames as $filename) {
         $tokens = token_get_all(file_get_contents($filename));
         $aggregator = $this->make_string_aggregator($global_name, $filename);
         $this->walk_tokens($tokens, array($this, 'ignore_token'), array($this, 'ignore_token'), $aggregator);
     }
     $potf = '-' == $pot_filename ? STDOUT : @fopen($pot_filename, 'a');
     if (false === $potf) {
         $this->cli_die("Couldn't open pot file: {$pot_filename}");
     }
     foreach ($GLOBALS[$global_name] as $item) {
         @(list($string, $comment_id, $filename, $line_number) = $item);
         $filename = isset($filename) ? preg_replace('|^\\./|', '', $filename) : '';
         $ref_line_number = isset($line_number) ? ":{$line_number}" : '';
         $args = array('singular' => $string, 'extracted_comments' => "Not gettexted string {$comment_id}", 'references' => array("{$filename}{$ref_line_number}"));
         $entry = new Translation_Entry($args);
         fwrite($potf, "\n" . PO::export_entry($entry) . "\n");
     }
     if ('-' != $pot_filename) {
         fclose($potf);
     }
     return true;
 }
Example #21
0
 /**
  * Builds a string from the entry for inclusion in PO file
  *
  * @static
  * @param object &$entry the entry to convert to po string
  * @return string|bool PO-style formatted string for the entry or
  * 	false if the entry is empty
  */
 function export_entry(&$entry)
 {
     if (is_null($entry->singular)) {
         return false;
     }
     $po = array();
     if (!empty($entry->translator_comments)) {
         $po[] = PO::comment_block($entry->translator_comments);
     }
     if (!empty($entry->extracted_comments)) {
         $po[] = PO::comment_block($entry->extracted_comments, '.');
     }
     if (!empty($entry->references)) {
         $po[] = PO::comment_block(implode(' ', $entry->references), ':');
     }
     if (!empty($entry->flags)) {
         $po[] = PO::comment_block(implode("\n", $entry->flags), ',');
     }
     if (!is_null($entry->context)) {
         $po[] = 'msgctxt ' . PO::poify($entry->context);
     }
     $po[] = 'msgid ' . PO::poify($entry->singular);
     if (!$entry->is_plural) {
         $translation = empty($entry->translations) ? '' : $entry->translations[0];
         $po[] = 'msgstr ' . PO::poify($translation);
     } else {
         $po[] = 'msgid_plural ' . PO::poify($entry->plural);
         $translations = empty($entry->translations) ? array('', '') : $entry->translations;
         foreach ($translations as $i => $translation) {
             $po[] = "msgstr[{$i}] " . PO::poify($translation);
         }
     }
     return implode("\n", $po);
 }
Example #22
0
 /**
  * Import a file into the translation set
  *
  * ## OPTIONS
  *
  * <project>
  * : Project path
  *
  * <locale>
  * : Locale to export
  *
  * <file>
  * : File to import
  *
  * [--set=<set>]
  * : Translation set slug; default is "default"
  */
 public function import($args, $assoc_args)
 {
     $set_slug = isset($assoc_args['set']) ? $assoc_args['set'] : 'default';
     $translation_set = $this->get_translation_set($args[0], $args[1], $set_slug);
     if (is_wp_error($translation_set)) {
         WP_CLI::error($translation_set->get_error_message());
     }
     $po = new PO();
     $imported = $po->import_from_file($args[2]);
     if (!$imported) {
         WP_CLI::error(__("Couldn't load translations from file!", 'glotpress'));
     }
     $added = $translation_set->import($po);
     /* translators: %s: Number of imported translations */
     WP_CLI::line(sprintf(_n('%s translation was added', '%s translations were added', $added, 'glotpress'), $added));
 }
 public function compilePot()
 {
     $this->prepareExport();
     $path = $this->getPath();
     $pot_file = $this->getPotFile();
     $this->makePot($path, $pot_file);
     // remove headers
     $po = new \PO();
     $po->import_from_file($pot_file);
     $po->export_to_file($pot_file, false);
 }
/**
 * Translate strings to the page language or a given language.
 *
 * Human-readable text that will be displayed somewhere within a page should
 * be run through the t() function.
 *
 * Examples:
 * @code
 * if (!$info || !$info['extension']) {
 * form_set_error('picture_upload', t('The uploaded file was not an image.'));
 * }
 *
 * $form['submit'] = array(
 * '#type' => 'submit',
 * '#value' => t('Log in'),
 * );
 * @endcode
 *
 * Any text within t() can be extracted by translators and changed into
 * the equivalent text in their native language.
 *
 * Special variables called "placeholders" are used to signal dynamic
 * information in a string which should not be translated. Placeholders
 * can also be used for text that may change from time to time (such as
 * link paths) to be changed without requiring updates to translations.
 *
 * For example:
 * @code
 * $output = t('There are currently %members and %visitors online.', array(
 * '%members' => format_plural($total_users, '1 user', '@count users'),
 * '%visitors' => format_plural($guests->count, '1 guest', '@count guests')));
 * @endcode
 *
 * There are three styles of placeholders:
 * - !variable, which indicates that the text should be inserted as-is. This is
 * useful for inserting variables into things like e-mail.
 * @code
 * $message[] = t("If you don't want to receive such e-mails, you can change your settings at !url.", array('!url' => url("user/$account->uid", array('absolute' => TRUE))));
 * @endcode
 *
 * - @variable, which indicates that the text should be run through
 * check_plain, to escape HTML characters. Use this for any output that's
 * displayed within a Drupal page.
 * @code
 * drupal_set_title($title = t("@name's blog", array('@name' => $account->name)));
 * @endcode
 *
 * - %variable, which indicates that the string should be HTML escaped and
 * highlighted with theme_placeholder() which shows up by default as
 * <em>emphasized</em>.
 * @code
 * $message = t('%name-from sent %name-to an e-mail.', array('%name-from' => $user->name, '%name-to' => $account->name));
 * @endcode
 *
 * When using t(), try to put entire sentences and strings in one t() call.
 * This makes it easier for translators, as it provides context as to what
 * each word refers to. HTML markup within translation strings is allowed, but
 * should be avoided if possible. The exception are embedded links; link
 * titles add a context for translators, so should be kept in the main string.
 *
 * Here is an example of incorrect usage of t():
 * @code
 * $output .= t('<p>Go to the @contact-page.</p>', array('@contact-page' => l(t('contact page'), 'contact')));
 * @endcode
 *
 * Here is an example of t() used correctly:
 * @code
 * $output .= '<p>'. t('Go to the <a href="@contact-page">contact page</a>.', array('@contact-page' => url('contact'))) .'</p>';
 * @endcode
 *
 * Avoid escaping quotation marks wherever possible.
 *
 * Incorrect:
 * @code
 * $output .= t('Don\'t click me.');
 * @endcode
 *
 * Correct:
 * @code
 * $output .= t("Don't click me.");
 * @endcode
 *
 * Because t() is designed for handling code-based strings, in almost all
 * cases, the actual string and not a variable must be passed through t().
 *
 * Extraction of translations is done based on the strings contained in t()
 * calls. If a variable is passed through t(), the content of the variable
 * cannot be extracted from the file for translation.
 *
 * Incorrect:
 * @code
 * $message = 'An error occurred.';
 * drupal_set_message(t($message), 'error');
 * $output .= t($message);
 * @endcode
 *
 * Correct:
 * @code
 * $message = t('An error occurred.');
 * drupal_set_message($message, 'error');
 * $output .= $message;
 * @endcode
 *
 * The only case in which variables can be passed safely through t() is when
 * code-based versions of the same strings will be passed through t() (or
 * otherwise extracted) elsewhere.
 *
 * In some cases, modules may include strings in code that can't use t()
 * calls. For example, a module may use an external PHP application that
 * produces strings that are loaded into variables in Drupal for output.
 * In these cases, module authors may include a dummy file that passes the
 * relevant strings through t(). This approach will allow the strings to be
 * extracted.
 *
 * Sample external (non-Drupal) code:
 * @code
 * class Time {
 * public $yesterday = 'Yesterday';
 * public $today = 'Today';
 * public $tomorrow = 'Tomorrow';
 * }
 * @endcode
 *
 * Sample dummy file.
 * @code
 * // Dummy function included in example.potx.inc.
 * function example_potx() {
 * $strings = array(
 * t('Yesterday'),
 * t('Today'),
 * t('Tomorrow'),
 * );
 * // No return value needed, since this is a dummy function.
 * }
 * @endcode
 *
 * Having passed strings through t() in a dummy function, it is then
 * okay to pass variables through t().
 *
 * Correct (if a dummy file was used):
 * @code
 * $time = new Time();
 * $output .= t($time->today);
 * @endcode
 *
 * However tempting it is, custom data from user input or other non-code
 * sources should not be passed through t(). Doing so leads to the following
 * problems and errors:
 * - The t() system doesn't support updates to existing strings. When user
 * data is updated, the next time it's passed through t() a new record is
 * created instead of an update. The database bloats over time and any
 * existing translations are orphaned with each update.
 * - The t() system assumes any data it receives is in English. User data may
 * be in another language, producing translation errors.
 * - The "Built-in interface" text group in the locale system is used to
 * produce translations for storage in .po files. When non-code strings are
 * passed through t(), they are added to this text group, which is rendered
 * inaccurate since it is a mix of actual interface strings and various user
 * input strings of uncertain origin.
 *
 * Incorrect:
 * @code
 * $item = item_load();
 * $output .= check_plain(t($item['title']));
 * @endcode
 *
 * Instead, translation of these data can be done through the locale system,
 * either directly or through helper functions provided by contributed
 * modules.
 * @see hook_locale()
 *
 * During installation, st() is used in place of t(). Code that may be called
 * during installation or during normal operation should use the get_t()
 * helper function.
 * @see st()
 * @see get_t()
 *
 * @param $string
 * A string containing the English string to translate.
 * @param $args
 * An associative array of replacements to make after translation. Incidences
 * of any key in this array are replaced with the corresponding value. Based
 * on the first character of the key, the value is escaped and/or themed:
 * - !variable: inserted as is
 * - @variable: escape plain text to HTML (check_plain)
 * - %variable: escape text and theme as a placeholder for user-submitted
 * content (check_plain + theme_placeholder)
 * @param $langcode
 * Optional language code to translate to a language other than what is used
 * to display the page.
 * @return
 * The translated string.
 */
function _t($string, $args = array(), $langcode = NULL, $reset = FALSE)
{
    global $language, $cfg;
    static $locale_t = NULL;
    //@TODO se quiser fazer texto custom
    if ($reset) {
        // Reset in-memory cache.
        $locale_t = NULL;
    }
    if (!isset($string)) {
        // Return all cached strings if no string was specified
        return $locale_t;
    }
    $langcode = isset($langcode) ? $langcode : $language['language']->language;
    //@TODO verificr se esta consumindo muita memoria qualquer coisa cachear
    if (isset($language['translate'])) {
        $po = new PO();
        $po->merge_with($language['translate']);
        $string = $po->translate($string);
    }
    if (empty($args)) {
        return $string;
    } else {
        // Transform arguments before inserting them.
        foreach ($args as $key => $value) {
            switch ($key[0]) {
                case '@':
                    // Escaped only.
                    $args[$key] = check_plain($value);
                    break;
                case '%':
                default:
                    //@todo Escaped and placeholder.
                    //$args[$key] = theme('placeholder', $value);
                    break;
                case '!':
                    // Pass-through.
            }
        }
        return strtr($string, $args);
    }
}
Example #25
0
 function add_translate_string($entries)
 {
     $pot = new PO();
     $pot->import_from_file(dirname(__FILE__) . '/default.po', true);
     return array_merge($entries, $pot->entries);
 }
Example #26
0
 /**
  * Write an empty POT file containing all strings found
  *
  * @param string $file File to write to
  */
 public function writePot($file)
 {
     $output = "# Copyright (C) " . date("Y") . " Next Buzz" . PHP_EOL . "msgid \"\"" . PHP_EOL . "msgstr \"\"" . PHP_EOL . "\"Project-Id-Version: buzz-seo\\n\"" . PHP_EOL . "\"POT-Creation-Date: " . date("Y-m-d H:i:sO") . "\\n\"" . PHP_EOL . "\"MIME-Version: 1.0\\n\"" . PHP_EOL . "\"Content-Type: text/plain; charset=UTF-8\\n\"" . PHP_EOL . "\"Content-Transfer-Encoding: 8bit\\n\"" . PHP_EOL . "\"PO-Revision-Date: 2014-MO-DA HO:MI+ZONE\\n\"" . PHP_EOL . "\"Language-Team: Next Buzz, Bas de Kort <*****@*****.**>\\n\"" . PHP_EOL . PHP_EOL;
     require_once ABSPATH . '/wp-includes/pomo/po.php';
     $poifyString = new \PO();
     foreach ($this->findings as $translatable => $locations) {
         $output .= "#:";
         foreach ($locations as $line => $location) {
             $output .= " " . $location . ":" . $line;
         }
         $output .= PHP_EOL . "msgid " . $poifyString->poify(StringParser::factory($translatable)->trimMultiline()) . PHP_EOL . "msgstr \"\"" . PHP_EOL . PHP_EOL;
     }
     file_put_contents($file, $output);
 }
 function xgettext($project, $dir, $output_file, $placeholders = array(), $excludes = array(), $includes = array())
 {
     $meta = array_merge($this->meta['default'], $this->meta[$project]);
     $placeholders = array_merge($meta, $placeholders);
     $meta['output'] = $this->realpath_missing($output_file);
     $placeholders['year'] = date('Y');
     $placeholder_keys = array_map(create_function('$x', 'return "{".$x."}";'), array_keys($placeholders));
     $placeholder_values = array_values($placeholders);
     foreach ($meta as $key => $value) {
         $meta[$key] = str_replace($placeholder_keys, $placeholder_values, $value);
     }
     $originals = $this->extractor->extract_from_directory($dir, $excludes, $includes);
     $pot = new PO();
     $pot->entries = $originals->entries;
     $pot->set_header('Project-Id-Version', $meta['package-name'] . ' ' . $meta['package-version']);
     $pot->set_header('Report-Msgid-Bugs-To', $meta['msgid-bugs-address']);
     $pot->set_header('POT-Creation-Date', gmdate('Y-m-d H:i:s+00:00'));
     $pot->set_header('MIME-Version', '1.0');
     $pot->set_header('Content-Type', 'text/plain; charset=UTF-8');
     $pot->set_header('Content-Transfer-Encoding', '8bit');
     $pot->set_header('PO-Revision-Date', date('Y') . '-MO-DA HO:MI+ZONE');
     $pot->set_header('Last-Translator', 'FULL NAME <EMAIL@ADDRESS>');
     $pot->set_header('Language-Team', 'LANGUAGE <*****@*****.**>');
     $pot->set_comment_before_headers($meta['comments']);
     $pot->export_to_file($output_file);
     return true;
 }
Example #28
0
	function test_import_from_file_with_windows_line_endings_should_work_as_with_unix_line_endings() {
		$po = new PO();
		$this->assertTrue( $po->import_from_file( DIR_TESTDATA . '/pomo/windows-line-endings.po' ) );
		$this->assertEquals( 1, count( $po->entries ) );
	}
Example #29
0
 function updatePot(&$POs, $msg)
 {
     foreach ($POs as $po) {
         $t = $msg[$po->num];
         $po->str = PO::undecorate($t);
     }
 }
 /**
  * Save the PO file and compile corresponding MO file.
  *
  * @since 1.2.0 Removed .bak creation, added destination directory generating.
  * @since 1.0.0
  *
  * @uses \PO::export_to_file() to save the updated PO file.
  * @uses \MO::export_to_file() to compile the MO file.
  *
  * @param string $file Optional The file path/name to use.
  */
 public function export($file = null)
 {
     // Override file property with provided filename
     if ($file) {
         $this->filename = $file;
     }
     // Fail if no filename is available
     if (!$this->filename) {
         throw new Exception('No path specified to save to.');
     }
     // Load necessary libraries
     require_once ABSPATH . WPINC . '/pomo/mo.php';
     $mo = new \MO();
     // Create the .po and .mo filenames appropriately
     if (substr($this->filename, -3) == '.po') {
         // .po extension exists...
         $po_file = $this->filename;
         // ...replace with .mo
         $mo_file = substr($this->filename, 0, -3) . '.mo';
     } else {
         // No extension, add each
         $po_file = $this->filename . '.po';
         $mo_file = $this->filename . '.mo';
     }
     // Copy all properties from the PO interface to the MO one
     foreach (get_object_vars($this->po) as $key => $val) {
         $mo->{$key} = $val;
     }
     // Ensure the parent directory exists
     wp_mkdir_p(dirname($po_file));
     // Export the PO file
     $this->po->export_to_file($po_file);
     // Compile the MO file
     $mo->export_to_file($mo_file);
 }