Automatizando tradução i18n do seu codigo

Publicado por João Pinto Neto 15/01/2009

[ Hits: 7.467 ]

Homepage: http://joaopintoneto.com/

Download traduzir.php




Este script lê todos os arquivos de um diretório e seus subdiretórios. Dá opção para excolher um e carregar todas as entradas gettext "_()".

Sendo assim possível traduzir todas as entradas do código-fonte.

  



Esconder código-fonte

<?php
/**
 * traduzir
 *
 * traduzir is dual-licensed under
 *   the GNU Lesser General Public License, version 2.1, and
 *   the Apache License, version 2.0.
 * 
 * For the terms of the licenses, see the LICENSE-LGPL.txt and LICENSE-AL2.txt
 * files, respectively.
 *
 *
 * Copyright (C) 2009 João Pinto Neto
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License, version 2.1, as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *
 * Copyright 2007 João Pinto Neto
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package João Pinto Neto
 * @version $Id$
 * @copyright 2009 João Pinto Neto
 * @author João Pinto Neto <joaopintoneto@gmail.com>
 * @license http://opensource.org/licenses/lgpl-license.php GNU Lesser General Public License 2.1
 * @license http://opensource.org/licenses/apache2.0.php Apache License 2.0
 */

define('UNIX_EOL', "\n");
function translationHeader($project_name, $translator, $yranslator_email, $codeset) {
    return sprintf('msgid ""' . UNIX_EOL
                   .'msgstr ""' . UNIX_EOL
                   .'"Project-Id-Version: %s\n"' . UNIX_EOL
                   .'"POT-Creation-Date: \n"' . UNIX_EOL
                   .'"PO-Revision-Date: \n"' . UNIX_EOL
                   .'"Last-Translator: %s <%s>\n"' . UNIX_EOL
                   .'"Language-Team: \n"' . UNIX_EOL
                   .'"MIME-Version: 1.0\n"' . UNIX_EOL
                   .'"Content-Type: text/plain; charset=%s\n"' . UNIX_EOL
                   .'"Content-Transfer-Encoding: 8bit\n"' . UNIX_EOL . UNIX_EOL,
                   $project_name, $translator, $translator_email, $codeset);
}

function all_files($dir) {
    $files = array();
    $file_tmp = glob($dir.'*', GLOB_MARK);

    foreach ($file_tmp as $item) {
        if (substr($item, -1) != DIRECTORY_SEPARATOR)
            $files[basename($item)] = $item;
        else
            $files = array_merge($files, all_files($item));
    }

    return $files;
}

function arrayToCheckbox($array, $id) {
    $ret = '<select id="' . $id . '" name="' . $id . '">' . PHP_EOL;
    foreach ($array as $key => $value) {
        $ret .= '    <option value="' . $value . '">' . $key . '</option>' . PHP_EOL; 
    }
    return $ret .= '</select>' . PHP_EOL;
}

function parseFile($path) {
    $file = file($path);
    $ret = array();
    $out = array();
    foreach ($file as $line => $value) {
        preg_match("|\_\((.*)\)|U", $value, $out);
        if (count($out) > 0) {
            $out[] = $line;
            // $out[] = strpos($value, "_("); // Get colun position?
            $ret[] = $out;
        }
    }
    return $ret;
}
?>
<html>
<head>
<title>Ferramenta de tradução</title>
</head>
<body>
<form action="index.php" method="post">
    <input type="hidden" id="x_arquivo" name="x_arquivo" value="<?= $_POST['x_arquivo'] ? $_POST['x_arquivo'] : $_POST['arquivo'] ?>" />
    <input type="hidden" id="x_project_name" name="x_project_name" value="<?= $_POST['x_project_name'] ? $_POST['x_project_name'] : $_POST['project_name'] ?>" />
    <input type="hidden" id="x_translator" name="x_translator" value="<?= $_POST['x_translator'] ? $_POST['x_translator'] : $_POST['translator'] ?>" />
    <input type="hidden" id="x_translator_email" name="x_translator_email" value="<?= $_POST['x_translator_email'] ? $_POST['x_translator_email'] : $_POST['translator_email'] ?>" />
    <input type="hidden" id="x_codeset" name="x_codeset" value="<?= $_POST['x_codeset'] ? $_POST['x_codeset'] : $_POST['codeset'] ?>" />
    <input type="hidden" id="x_language" name="x_language" value="<?= $_POST['x_language'] ? $_POST['x_language'] : $_POST['language'] ?>" />

<?php if ($_POST['linha'] != ''): ?>
    <h1>Gerar arquivo</h1>
    <?php
        $outPO = translationHeader($_POST['x_project_name'],$_POST['x_translator'],$_POST['x_translator_email'],$_POST['x_codeset']);
        foreach ($_POST['linha'] as $linha => $valor) {
           $outPO .= '#:' . $_POST['x_arquivo'] . ':' . $linha . UNIX_EOL
                     . 'msgid "' . $_POST['linha_msgid'][$linha] . '"' . UNIX_EOL
                      . 'msgstr "' . $valor . '"' . UNIX_EOL . UNIX_EOL;
        }

        if ($_POST['x_codeset'] == 'utf-8')
            $outPO = utf8_encode($outPO);
        
        $filename_po = 'messages_'.$_POST['x_language'].'_'.time().'.po';
        if (!@file_put_contents($filename_po, $outPO))
            echo 'Erro de permissão ao tentar gerar "' . $filename_po . '"';

        echo '<a href="' . $filename_po . '">' . $filename_po . '</a>';
        //echo '<pre>'.$outPO;
    ?>
<?php elseif ($_POST['arquivo'] != ''): ?>
    <h1>Traduzindo "<?= basename($_POST['arquivo']) ?>"</h1>
    <?php foreach (parseFile($_POST['arquivo']) as $line): ?>
        <?= $line[1] ?>:
        <input name="linha_msgid[<?= $line[2] ?>]" type="hidden" value="<?= str_replace(array("\"","'"), '', $line[1]) ?>" />
        <input name="linha[<?= $line[2] ?>]" type="text" /><br />
    <?php endforeach; ?>
<?php else: ?>
    <h1>Titulo</h1>
    <fieldset>
    <legend>Configurações:</legend>
        Nome do projeto: <input type="text" id="project_name" name="project_name" /><br />
        Nome do tratutor: <input type="text" id="translator" name="translator" /><br />
        E-mail do tradutor: <input type="text" id="translator_email" name="translator_email" /><br />
        Línguagem: <input type="text" id="language" name="language" value="pt_BR" /><br />
        Tabela de caracteres:
        <select id="codeset" name="codeset">
            <option selected="selected">utf-8</option>
            <option>iso8859-1</option>
        </select><br />
    </fieldset>
    <fieldset>
        <legend>Selecione o arquivo para traduzir:</legend>
        <?php echo arrayToCheckbox(all_files('../'), 'arquivo') ?>
        </fieldset>
<?php endif; ?>

<?php if (!isset($_POST['linha'])): ?>
    <input type="submit" />
<?php endif; ?>
</form>

</body>
</html>

Scripts recomendados

Calendário em php

Loja Virtual em PHP

FormConstructor: Formulário Construído por Variável

Contador Automático v2.0

Agenda de site de Baladas


  

Comentários
[1] Comentário enviado por felipecaioba em 11/08/2010 - 19:46h

Parabéns pelo artigo. Vou testar o código e volto a comentar


Contribuir com comentário




Patrocínio

Site hospedado pelo provedor RedeHost.
Linux banner

Destaques

Artigos

Dicas

Tópicos

Top 10 do mês

Scripts