示例#1
0
 private function CreateExportArchive($strTranslationPath, $strArchive)
 {
     if (file_exists($strArchive)) {
         unlink($strArchive);
     }
     $arrFiles = NarroUtils::ListDirectory($strTranslationPath, null, null, null, true);
     $objZipFile = new ZipArchive();
     if ($objZipFile->open($strArchive, ZipArchive::OVERWRITE) === TRUE) {
         foreach ($arrFiles as $strFileName) {
             if ($strTranslationPath == $strFileName) {
                 continue;
             }
             if (is_dir($strFileName)) {
                 $objZipFile->addEmptyDir(str_replace($strTranslationPath . '/', '', $strFileName));
             } elseif (is_file($strFileName)) {
                 $objZipFile->addFile($strFileName, str_replace($strTranslationPath . '/', '', $strFileName));
             }
         }
     } else {
         NarroLogger::LogError(sprintf('Failed to create a new archive %s', $strArchive));
         return false;
     }
     $objZipFile->close();
     if (file_exists($strArchive)) {
         chmod($strArchive, 0666);
     } else {
         NarroLogger::LogError(sprintf('Failed to create an archive %s', $strArchive));
         return false;
     }
     return true;
 }
 public function __construct(NarroProject $objProject, NarroLanguage $objLanguage, $objParentObject, $strControlId = null)
 {
     // Call the Parent
     try {
         parent::__construct($objParentObject, $strControlId);
     } catch (QCallerException $objExc) {
         $objExc->IncrementOffset();
         throw $objExc;
     }
     $this->objProject = $objProject;
     $this->objLanguage = $objLanguage;
     $this->pnlTranslationSource = new QTabs($this);
     $objDirectoryPanel = new NarroDirectorySourcePanel($objProject, $objLanguage, $this->pnlTranslationSource);
     $objDirectoryPanel->Directory = $this->objProject->DefaultTranslationPath;
     new NarroUploadSourcePanel($objProject, $objLanguage, $this->pnlTranslationSource);
     new NarroWebSourcePanel($objProject, $objLanguage, $this->pnlTranslationSource);
     new NarroProjectSourcePanel($objProject, $objLanguage, $this->pnlTranslationSource);
     new NarroLanguageSourcePanel($objProject, $objLanguage, $this->pnlTranslationSource);
     if (NarroUtils::CanExec('/usr/bin/hg --help')) {
         new NarroMercurialSourcePanel($objProject, $objLanguage, $this->pnlTranslationSource);
     }
     if (NarroUtils::CanExec('/usr/bin/svn --help')) {
         new NarroSvnSourcePanel($objProject, $objLanguage, $this->pnlTranslationSource);
     }
     $this->pnlTranslationSource->Headers = array(t('On this server'), t('On my computer'), t('On the web'), t('Another project'), t('Another language'), t('Mercurial'), t('SVN'));
 }
 public function __get($strName)
 {
     switch ($strName) {
         case "Directory":
             if ($this->chkCopyFilesToDefaultDirectory->Checked && __IMPORT_PATH__ . '/' . $this->objProject->ProjectId . '/' . $this->objLanguage->LanguageCode != $this->txtDirectory->Text) {
                 if (file_exists(__IMPORT_PATH__ . '/' . $this->objProject->ProjectId . '/' . $this->objLanguage->LanguageCode)) {
                     NarroUtils::RecursiveDelete(__IMPORT_PATH__ . '/' . $this->objProject->ProjectId . '/' . $this->objLanguage->LanguageCode . '/*');
                 } else {
                     mkdir(__IMPORT_PATH__ . '/' . $this->objProject->ProjectId . '/' . $this->objLanguage->LanguageCode, 0777);
                 }
                 NarroUtils::RecursiveCopy($this->txtDirectory->Text, __IMPORT_PATH__ . '/' . $this->objProject->ProjectId . '/' . $this->objLanguage->LanguageCode);
                 NarroUtils::RecursiveChmod(__IMPORT_PATH__ . '/' . $this->objProject->ProjectId . '/' . $this->objLanguage->LanguageCode);
             }
             return $this->txtDirectory->Text;
         default:
             try {
                 return parent::__get($strName);
                 break;
             } catch (QCallerException $objExc) {
                 $objExc->IncrementOffset();
                 throw $objExc;
             }
     }
 }
示例#4
0
文件: projects.php 项目: Jobava/narro
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any
 * later version.
 *
 * This program 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 General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with this program; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */
require_once dirname(__FILE__) . '/configuration/prepend.inc.php';
/**
 * This page is used to clean stale form states if FileFormStateHandler is used
 */
NarroUtils::CleanStaleFormStates();
class NarroProjectListForm extends NarroForm
{
    /**
     * The main tab is the tab panel, used to group panels in a tabbed control for easy access
     * @var QTabPanel
     */
    protected $pnlTab;
    /**
     * This is the project list panel
     * @see includes/narro/panel/NarroProjectListPanel.class.php
     * @var NarroProjectListPanel
     */
    protected $pnlProjectList;
    protected $pnlTop;
    protected function Form_Create()
 public function ExportFile($strTemplateFile, $strTranslatedFile)
 {
     $intTime = time();
     $arrSourceKey = $this->FileAsArray($strTemplateFile);
     $intElapsedTime = time() - $intTime;
     if ($intElapsedTime > 0) {
         // NarroLogger::LogDebug(sprintf('Preprocessing %s took %d seconds.', $this->objFile->FileName, $intElapsedTime));
     }
     // NarroLogger::LogDebug(sprintf('Found %d contexts in file %s.', count($arrSourceKey), $this->objFile->FileName));
     if (is_array($arrSourceKey)) {
         $arrSourceKey = $this->GetAccessKeys($arrSourceKey);
         $arrTranslation = $this->GetTranslations($arrSourceKey);
         $hndTranslationFile = fopen($strTranslatedFile, 'w');
         if ($this->objProject->GetPreferenceValueByName('Export translators and reviewers in the file header as a comment') == 'Yes') {
             $arrUsers = array();
             foreach ($this->objFile->GetTranslatorArray($this->objTargetLanguage->LanguageId) as $objUser) {
                 $arrUsers[] = sprintf("# %s <%s>", $objUser->RealName, $objUser->Email);
             }
             if (count($arrUsers)) {
                 fwrite($hndTranslationFile, sprintf("# Translator(s):\n#\n%s\n#\n", join("\n", $arrUsers)));
             }
             $arrUsers = array();
             foreach ($this->objFile->GetReviewerArray($this->objTargetLanguage->LanguageId) as $objUser) {
                 $arrUsers[] = sprintf("# %s <%s>", $objUser->RealName, $objUser->Email);
             }
             if (count($arrUsers)) {
                 fwrite($hndTranslationFile, sprintf("# Reviewer(s):\n#\n%s\n#\n", join("\n", $arrUsers)));
             }
         }
         if ($this->objFile->Header) {
             fwrite($hndTranslationFile, $this->objFile->Header);
         }
         foreach ($arrSourceKey as $strContext => $objEntity) {
             if (isset($arrTranslation[$strContext])) {
                 fwrite($hndTranslationFile, $objEntity->BeforeValue . $arrTranslation[$strContext] . $objEntity->AfterValue);
             } else {
                 fwrite($hndTranslationFile, $objEntity->BeforeValue . $objEntity->Value . $objEntity->AfterValue);
             }
         }
         fclose($hndTranslationFile);
         NarroUtils::Chmod($strTranslatedFile, 0666);
         return true;
     } else {
         NarroLogger::LogWarn(sprintf('Found a empty template (%s), copying the original', $strTemplateFile));
         copy($strTemplateFile, $strTranslatedFile);
         NarroUtils::Chmod($strTranslatedFile, 0666);
         return false;
     }
 }
 public function btnTest_Click()
 {
     NarroProject::RegisterPreference('Mercurial commit path', false, 0, 'text', 'The url to commit this project to mercurial.', '');
     NarroProject::RegisterPreference('Username for Mercurial', false, 0, 'text', '', '');
     $this->objProject->SetPreferenceValueByName('Mercurial commit path', $this->txtRepositoryUrl->Text);
     $this->objProject->SetPreferenceValueByName('Username for Mercurial', $this->txtUsername->Text);
     $this->objProject->Save();
     $strSSHKey = sprintf('%s/mercurial_%d_%s_%d', __TMP_PATH__, QApplication::$User->UserId, QApplication::$TargetLanguage->LanguageCode, $this->objProject->ProjectId);
     $strProcLogFile = __TMP_PATH__ . '/' . $this->objProject->ProjectId . '-' . QApplication::$TargetLanguage->LanguageCode . '-mercurial.log';
     copy($this->fileSSHPrivateKey->File, $strSSHKey);
     chmod($strSSHKey, 0600);
     file_put_contents($strSSHKey . '_hgrc', sprintf("[paths]\n" . "default = %s\n" . "\n" . "[ui]\n" . "ssh = ssh -i %s -o StrictHostKeyChecking=no -l %s\n" . "username = %s\n", $this->txtRepositoryUrl->Text, $strSSHKey, $this->txtUsername->Text, $this->txtCommitUsername->Text));
     $mixProcess = exec(sprintf('export HOME=%s;export HGRCPATH=%s; hg clone %s %s_mercurial;cd %s_mercurial; cp -f -R %s/* .; hg addremove; hg diff -w --nodates > %s_diff; hg commit -m "%s" %s; hg outgoing', __TMP_PATH__, $strSSHKey . '_hgrc', escapeshellarg($this->txtRepositoryUrl->Text), $strSSHKey, $strSSHKey, escapeshellarg($this->objProject->DefaultTranslationPath), $strSSHKey, escapeshellarg($this->txtCommitMessage->Text), $this->pnlPatchViewer && count($this->pnlPatchViewer->SelectedFiles) ? join(" ", $this->pnlPatchViewer->SelectedFiles) : ""), $arrOutput);
     $this->lblOutput->Text = join("\n", $arrOutput);
     $this->Form->RemoveControl($this->pnlPatchViewer->ControlId);
     $this->pnlPatchViewer = new NarroPatchViewerPanel($strSSHKey . '_diff', $this);
     unlink($strSSHKey);
     unlink($strSSHKey . '_hgrc');
     unlink($strSSHKey . '_diff');
     NarroUtils::RecursiveDelete($strSSHKey . '_mercurial');
     $this->btnCommit->Display = true;
     $this->chkForce->Display = true;
 }
 public function ExportFile($strTemplate, $strTranslatedFile)
 {
     $hndExportFile = fopen($strTranslatedFile, 'w');
     if (!$hndExportFile) {
         NarroLogger::LogError(sprintf('Cannot create or write to "%s".', $strTranslatedFile));
         return false;
     }
     if ($this->objProject->GetPreferenceValueByName('Export translators and reviewers in the file header as a comment') == 'Yes') {
         $arrUsers = array();
         foreach ($this->objFile->GetTranslatorArray($this->objTargetLanguage->LanguageId) as $objUser) {
             $arrUsers[] = sprintf("# %s <%s>", $objUser->RealName, $objUser->Email);
         }
         if (count($arrUsers)) {
             fwrite($hndExportFile, sprintf("# Translator(s):\n#\n%s\n#\n", join("\n", $arrUsers)));
         }
         $arrUsers = array();
         foreach ($this->objFile->GetReviewerArray($this->objTargetLanguage->LanguageId) as $objUser) {
             $arrUsers[] = sprintf("# %s <%s>", $objUser->RealName, $objUser->Email);
         }
         if (count($arrUsers)) {
             fwrite($hndExportFile, sprintf("# Reviewer(s):\n#\n%s\n#\n", join("\n", $arrUsers)));
         }
     }
     $arrTemplateFile = $this->getFieldGroups($strTemplate);
     $intTotalContexts = count($arrTemplateFile);
     $intCurrentContext = 0;
     foreach ($arrTemplateFile as $strIndex => $arrTemplateFields) {
         $intCurrentContext++;
         NarroProgress::SetProgressPerFile($intCurrentContext / $intTotalContexts * 100, $this->objProject->ProjectId, 'export');
         $this->objCurrentContext = null;
         if (!is_null($arrTemplateFields['MsgId'])) {
             $arrTemplateFields['MsgId'] = str_replace('\\"', '"', $arrTemplateFields['MsgId']);
         }
         if (!is_null($arrTemplateFields['MsgStr'])) {
             $arrTemplateFields['MsgStr'] = str_replace('\\"', '"', $arrTemplateFields['MsgStr']);
         }
         if (!is_null($arrTemplateFields['MsgPluralId'])) {
             $arrTemplateFields['MsgPluralId'] = str_replace('\\"', '"', $arrTemplateFields['MsgPluralId']);
         }
         if (isset($arrTemplateFields['MsgPluralId'])) {
             for ($intPluralId = 0; $intPluralId < $this->objTargetLanguage->Plurals; $intPluralId++) {
                 $arrTemplateFields['MsgStr' . $intPluralId] = str_replace('\\"', '"', $arrTemplateFields['MsgStr' . $intPluralId]);
             }
         }
         /**
          * if it's not a plural, just add msgid and msgstr
          */
         if (is_null($arrTemplateFields['MsgPluralId'])) {
             /**
              * Leave the header alone
              */
             if ($arrTemplateFields['MsgId'] == '' && strstr($arrTemplateFields['MsgStr'], 'Project-Id-Version')) {
                 /**
                  * This is the header
                  */
                 /**
                  * unset the flag, if is set
                  */
                 unset($arrTemplateFields['Flag']);
                 /**
                  * At import, we concatenate strings on more than one lines, so now we have to restore it
                  */
                 $arrTemplateFields['MsgStr'] = str_replace('\\n', '\\n"' . "\n" . '"', $arrTemplateFields['MsgStr']);
                 /**
                  * There's an extra " at the end, remove it
                  */
                 $arrTemplateFields['MsgStr'] = trim(preg_replace('/"$/', '', $arrTemplateFields['MsgStr']));
                 if (strstr($arrTemplateFields['MsgStr'], '"Plural-Forms')) {
                     /**
                      * the plural declaration is there, try to replace it
                      */
                     $arrTemplateFields['MsgStr'] = preg_replace('/"Plural-Forms:[^"]+"/mi', $this->objTargetLanguage->PluralForm, $arrTemplateFields['MsgStr']);
                 } else {
                     /**
                      * the plural declaration isn't there, try to change it
                      */
                     $arrTemplateFields['MsgStr'] .= "\n" . $this->objTargetLanguage->PluralForm;
                 }
                 /**
                  * There's an extra " at the end, remove it
                  */
                 $arrTemplateFields['MsgStr'] = trim(preg_replace('/"$/', '', $arrTemplateFields['MsgStr']));
                 $strGeneratorLine = sprintf('X-Generator: Narro %s on %s\\n', NARRO_VERSION, __HTTP_URL__ . __VIRTUAL_DIRECTORY__ . __SUBDIRECTORY__);
                 if (strstr($arrTemplateFields['MsgStr'], '"X-Generator:')) {
                     $arrTemplateFields['MsgStr'] = $strGeneratorLine;
                 } else {
                     $arrTemplateFields['MsgStr'] .= '"' . "\n" . '"' . $strGeneratorLine;
                 }
                 $strProjectLine = sprintf('Project-Id-Version: %s\\n', $this->objProject->ProjectName);
                 if (strstr($arrTemplateFields['MsgStr'], 'Project-Id-Version:')) {
                     $arrTemplateFields['MsgStr'] = preg_replace('/Project\\-Id\\-Version:[^"]+/mi', $strProjectLine, $arrTemplateFields['MsgStr']);
                 } else {
                     $arrTemplateFields['MsgStr'] .= '"' . "\n" . '"' . $strProjectLine;
                 }
                 $strCharsetLine = sprintf('Content-Type: text/plain; charset=%s\\n', $this->objTargetLanguage->Encoding);
                 if (strstr($arrTemplateFields['MsgStr'], '"Content-Type:')) {
                     $arrTemplateFields['MsgStr'] = preg_replace('/Content\\-Type:[^"]+/mi', $strCharsetLine, $arrTemplateFields['MsgStr']);
                 } else {
                     $arrTemplateFields['MsgStr'] .= '"' . "\n" . '"' . $strCharsetLine;
                 }
                 $strTranslatorLine = sprintf('Last-Translator: %s <%s>\\n', QApplication::$User->RealName, QApplication::$User->Email);
                 if (strstr($arrTemplateFields['MsgStr'], '"Last-Translator:')) {
                     $arrTemplateFields['MsgStr'] = preg_replace('/Last\\-Translator:[^"]+/mi', $strTranslatorLine, $arrTemplateFields['MsgStr']);
                 } else {
                     $arrTemplateFields['MsgStr'] .= '"' . "\n" . '"' . $strTranslatorLine;
                 }
                 $strLanguageLine = sprintf('Language-Team: %s <*****@*****.**>\\n', $this->objTargetLanguage->LanguageName);
                 if (strstr($arrTemplateFields['MsgStr'], '"Language-Team:')) {
                     $arrTemplateFields['MsgStr'] = preg_replace('/Language\\-Team:[^"]+/mi', $strLanguageLine, $arrTemplateFields['MsgStr']);
                 } else {
                     $arrTemplateFields['MsgStr'] .= '"' . "\n" . '"' . $strLanguageLine;
                 }
                 $strRevisionLine = sprintf('PO-Revision-Date: %s\\n', date('Y-m-d H:iO'));
                 if (strstr($arrTemplateFields['MsgStr'], '"PO-Revision-Date:')) {
                     $arrTemplateFields['MsgStr'] = preg_replace('/PO\\-Revision\\-Date:[^"]+/mi', $strRevisionLine, $arrTemplateFields['MsgStr']);
                 } else {
                     $arrTemplateFields['MsgStr'] .= '"' . "\n" . '"' . $strRevisionLine;
                 }
                 if (!strstr($arrTemplateFields['MsgStr'], '"MIME-Version')) {
                     $arrTemplateFields['MsgStr'] .= '"' . "\n" . '"MIME-Version: 1.0\\n';
                 }
                 if (!strstr($arrTemplateFields['MsgStr'], '"Content-Type')) {
                     $arrTemplateFields['MsgStr'] .= '"' . "\n" . '"Content-Type: text/plain; charset=UTF-8\\n';
                 }
                 if (!strstr($arrTemplateFields['MsgStr'], '"Content-Transfer-Encoding')) {
                     $arrTemplateFields['MsgStr'] .= '"' . "\n" . '"Content-Transfer-Encoding: 8bit\\n';
                 }
                 if (!strstr($arrTemplateFields['MsgStr'], '"Plural-Forms')) {
                     $arrTemplateFields['MsgStr'] .= '"' . "\n" . $this->objTargetLanguage->PluralForm . "\n" . '"';
                 }
             } else {
                 $arrTemplateFields['MsgStr'] = $this->GetTranslation($this->stripAccessKey($arrTemplateFields['MsgId']), $this->getAccessKey($arrTemplateFields['MsgId']), $this->getAccessKeyPrefix($arrTemplateFields['MsgId']), null, null, $arrTemplateFields['Context']);
             }
         } else {
             /**
              * if it's a plural, add the pluralid with all the msgstr's available
              * the first one is added with msgid/msgstr[0] (this is the singular)
              * the next ones are added with plural id, so in fact they will be tied to the same text
              */
             $strSingularText = $arrTemplateFields['MsgId'];
             if (!is_null($arrTemplateFields['MsgStr0'])) {
                 $arrTemplateFields['MsgStr0'] = $this->GetTranslation($this->stripAccessKey($arrTemplateFields['MsgId']), $this->getAccessKey($arrTemplateFields['MsgId']), $this->getAccessKeyPrefix($arrTemplateFields['MsgId']), null, null, $arrTemplateFields['Context'] . "\nThis text has plurals.");
             }
             for ($intPluralId = 1; $intPluralId < $this->objTargetLanguage->Plurals; $intPluralId++) {
                 $arrTemplateFields['MsgStr' . $intPluralId] = $this->GetTranslation($this->stripAccessKey($arrTemplateFields['MsgPluralId']), $this->getAccessKey($arrTemplateFields['MsgPluralId']), $this->getAccessKeyPrefix($arrTemplateFields['MsgPluralId']), null, null, $arrTemplateFields['Context'] . "\nThis is plural form {$intPluralId} for the text \"" . $strSingularText . "\".");
             }
         }
         if (isset($arrTemplateFields['TranslatorComment']) && !is_null($arrTemplateFields['TranslatorComment'])) {
             fputs($hndExportFile, $arrTemplateFields['TranslatorComment']);
         }
         if (isset($arrTemplateFields['ExtractedComment']) && !is_null($arrTemplateFields['ExtractedComment'])) {
             fputs($hndExportFile, $arrTemplateFields['ExtractedComment']);
         }
         if (isset($arrTemplateFields['Reference']) && !is_null($arrTemplateFields['Reference'])) {
             fputs($hndExportFile, $arrTemplateFields['Reference']);
         }
         if (isset($arrTemplateFields['Flag']) && !is_null($arrTemplateFields['Flag'])) {
             fputs($hndExportFile, $arrTemplateFields['Flag']);
         }
         if (isset($arrTemplateFields['PreviousContext']) && !is_null($arrTemplateFields['PreviousContext'])) {
             fputs($hndExportFile, $arrTemplateFields['PreviousContext']);
         }
         if (isset($arrTemplateFields['PreviousUntranslated']) && !is_null($arrTemplateFields['PreviousUntranslated'])) {
             fputs($hndExportFile, $arrTemplateFields['PreviousUntranslated']);
         }
         if (isset($arrTemplateFields['PreviousUntranslatedPlural']) && !is_null($arrTemplateFields['PreviousUntranslatedPlural'])) {
             fputs($hndExportFile, $arrTemplateFields['PreviousUntranslatedPlural']);
         }
         if (isset($arrTemplateFields['MsgContext']) && !is_null($arrTemplateFields['MsgContext'])) {
             fputs($hndExportFile, sprintf('msgctxt "%s"' . "\n", str_replace('"', '\\"', $arrTemplateFields['MsgContext'])));
         }
         if (isset($arrTemplateFields['MsgId']) && !is_null($arrTemplateFields['MsgId'])) {
             /**
              * If we're exporting a translation that is not approved, mark it as fuzzy
              */
             if ($this->objCurrentContext instanceof NarroContextInfo && !$this->objCurrentContext->ValidSuggestionId && isset($arrTemplateFields['MsgStr']) && $arrTemplateFields['MsgStr'] != '') {
                 NarroImportStatistics::$arrStatistics['Texts exported as fuzzy because they are not approved']++;
                 fputs($hndExportFile, "#, fuzzy\n");
             }
             fputs($hndExportFile, sprintf('msgid "%s"' . "\n", str_replace('"', '\\"', $arrTemplateFields['MsgId'])));
         }
         if (isset($arrTemplateFields['MsgPluralId']) && !is_null($arrTemplateFields['MsgPluralId'])) {
             fputs($hndExportFile, sprintf('msgid_plural "%s"' . "\n", str_replace('"', '\\"', $arrTemplateFields['MsgPluralId'])));
         }
         if (!is_null($arrTemplateFields['MsgStr'])) {
             /**
              * put the header as it is
              */
             if ($arrTemplateFields['MsgId'] == '' && strstr($arrTemplateFields['MsgStr'], 'Project-Id-Version')) {
                 fputs($hndExportFile, sprintf('msgstr "%s"' . "\n", $arrTemplateFields['MsgStr']));
             } else {
                 fputs($hndExportFile, sprintf('msgstr "%s"' . "\n", str_replace(array('"', "\n"), array('\\"', '"' . "\n" . '"'), $arrTemplateFields['MsgStr'])));
             }
         }
         for ($intPluralId = 0; $intPluralId < $this->objTargetLanguage->Plurals; $intPluralId++) {
             if (!is_null($arrTemplateFields['MsgStr' . $intPluralId])) {
                 fputs($hndExportFile, sprintf('msgstr[%d] "%s"' . "\n", $intPluralId, str_replace(array('"', "\n"), array('\\"', '"' . "\n" . '"'), $arrTemplateFields['MsgStr' . $intPluralId])));
             }
         }
         fputs($hndExportFile, "\n");
     }
     fclose($hndExportFile);
     @chmod($strTranslatedFile, 0666);
     /**
      * Try to format the file
      * @todo add php replacement for msgcat
      */
     if (file_exists($strTranslatedFile . '~')) {
         unlink($strTranslatedFile . '~');
     }
     NarroUtils::Exec(sprintf('msgcat %s -w 80 -o %s~', escapeshellarg($strTranslatedFile), escapeshellarg($strTranslatedFile)), $arrOutput, $arrError, $intRetVal, false, null, __TMP_PATH__, true);
     if (file_exists($strTranslatedFile . '~')) {
         unlink($strTranslatedFile);
         copy($strTranslatedFile . '~', $strTranslatedFile);
     }
     if (file_exists($strTranslatedFile . '~')) {
         unlink($strTranslatedFile . '~');
     }
     NarroUtils::Exec(sprintf('msgfmt -cv "%s"', $strTranslatedFile), $arrOutput, $arrError, $intRetVal);
     if ($intRetVal != 0) {
         NarroLogger::LogError(sprintf('Not exporting %s because it has errors: %s', $this->objFile->FilePath, join("\n", $arrOutput)));
         unlink($strTranslatedFile);
     } else {
         @chmod($strTranslatedFile, 0666);
     }
 }
 public function btnImport_Click($strFormId, $strControlId, $strParameter)
 {
     if (!QApplication::HasPermissionForThisLang('Can import project', $this->objProject->ProjectId)) {
         return false;
     }
     $strProcLogFile = __TMP_PATH__ . '/' . $this->objProject->ProjectId . '-' . QApplication::$TargetLanguage->LanguageCode . '-import-process.log';
     $strProcPidFile = __TMP_PATH__ . '/' . $this->objProject->ProjectId . '-' . QApplication::$TargetLanguage->LanguageCode . '-import-process.pid';
     $strProgressFile = __TMP_PATH__ . '/import-' . $this->objProject->ProjectId . '-' . QApplication::$TargetLanguage->LanguageCode;
     if ($strParameter == 1) {
         if (NarroUtils::IsProcessRunning('import', $this->objProject->ProjectId)) {
             $this->objImportProgress->Translated = NarroProgress::GetProgress($this->objProject->ProjectId, 'import');
             $this->objImportProgress->MarkAsModified();
         } else {
             $this->lblImport->Text = t('Import finished.');
             if (QApplication::$UseAjax) {
                 QApplication::ExecuteJavaScript('if (typeof lastImportId != \'undefined\') clearInterval(lastImportId)');
             }
             if (file_exists($strProcLogFile) && filesize($strProcLogFile)) {
                 NarroLogger::LogInfo(sprintf('There are messages from the background process: %s', file_get_contents($strProcLogFile)));
             }
             if (file_exists($strProcLogFile)) {
                 unlink($strProcLogFile);
             }
             if (file_exists($strProcPidFile)) {
                 unlink($strProcPidFile);
             }
             if (file_exists($strProgressFile)) {
                 unlink($strProgressFile);
             }
             $this->lblImport->Visible = true;
             $this->btnImport->Visible = true;
             $this->btnKillProcess->Visible = false;
             $this->objImportProgress->Translated = 0;
             $this->objImportProgress->Visible = false;
         }
         $this->pnlLogViewer->MarkAsModified();
     } elseif ($strParameter == 2) {
         $this->pnlLogViewer->ProjectId = $this->objProject->ProjectId;
         $this->pnlLogViewer->LanguageId = QApplication::GetLanguageId();
         $this->pnlLogViewer->DateStart = QDateTime::Now();
         NarroProgress::ClearProgressFileName($this->objProject->ProjectId, 'import');
         set_time_limit(0);
         if (file_exists($strProcLogFile)) {
             unlink($strProcLogFile);
         }
         if (file_exists($strProcPidFile)) {
             unlink($strProcPidFile);
         }
         if (file_exists($strProgressFile)) {
             unlink($strProgressFile);
         }
         $objNarroImporter = new NarroProjectImporter();
         /**
          * Get boolean options
          */
         $objNarroImporter->CheckEqual = true;
         $objNarroImporter->Approve = $this->chkApproveImportedTranslations->Checked;
         $objNarroImporter->ApproveAlreadyApproved = !$this->chkApproveOnlyNotApproved->Checked;
         $objNarroImporter->OnlySuggestions = !$this->chkImportSourceTexts->Checked;
         $objNarroImporter->Project = $this->objProject;
         $objNarroImporter->ImportUnchangedFiles = $this->chkImportUnchangedFiles->Checked;
         $objNarroImporter->User = QApplication::$User;
         $objNarroImporter->TargetLanguage = QApplication::$TargetLanguage;
         $objNarroImporter->SourceLanguage = NarroLanguage::LoadByLanguageCode(NarroLanguage::SOURCE_LANGUAGE_CODE);
         try {
             $objNarroImporter->TranslationPath = $this->pnlTranslationsSource->Directory;
             $objNarroImporter->TemplatePath = $this->objProject->DefaultTemplatePath;
         } catch (Exception $objEx) {
             NarroLogger::LogError(sprintf('An error occurred during import: %s', $objEx->getMessage()));
             $this->lblImport->Text = sprintf(t('Import failed: %s'), $objEx->getMessage());
             return false;
         }
         try {
             $objNarroImporter->ImportProject();
         } catch (Exception $objEx) {
             NarroLogger::LogError(sprintf('An error occurred during import: %s', $objEx->getMessage()));
             $this->lblImport->Text = sprintf(t('Import failed: %s'), $objEx->getMessage());
         }
         $this->lblImport->Visible = true;
         $this->btnImport->Visible = true;
         $this->btnKillProcess->Visible = false;
         $this->objImportProgress->Visible = false;
         $this->pnlLogViewer->MarkAsModified();
     } else {
         $this->pnlLogViewer->ProjectId = $this->objProject->ProjectId;
         $this->pnlLogViewer->LanguageId = QApplication::GetLanguageId();
         $this->pnlLogViewer->DateStart = QDateTime::Now();
         NarroProgress::ClearProgressFileName($this->objProject->ProjectId, 'import');
         $this->pnlLogViewer->MarkAsModified();
         $this->btnImport->Visible = false;
         $this->btnKillProcess->Visible = QApplication::HasPermission('Administrator', $this->objProject, QApplication::$TargetLanguage->LanguageCode) && !$this->btnImport->Visible;
         $this->objImportProgress->Visible = true;
         $this->objImportProgress->Translated = 0;
         $this->lblImport->Text = '';
         try {
             $strCommand = sprintf(__PHP_CLI_PATH__ . ' ' . escapeshellarg(sprintf('%s/includes/narro/importer/narro-cli.php', __DOCROOT__ . __SUBDIRECTORY__)) . ' --import --minloglevel 3 --project %d --user %d --check-equal ' . ($this->chkApproveImportedTranslations->Checked ? '--approve ' : '') . ($this->chkImportUnchangedFiles->Checked ? '--import-unchanged-files ' : '') . ($this->chkApproveOnlyNotApproved->Checked ? '' : '--approve-already-approved ') . (!$this->chkImportSourceTexts->Checked || !QApplication::HasPermission('Can import project', $this->objProject->ProjectId) ? '--only-suggestions ' : '') . ' --template-lang %s --translation-lang %s --template-directory %s --translation-directory %s', (int) $this->objProject->ProjectId, (int) QApplication::$User->UserId, escapeshellarg(NarroLanguage::SOURCE_LANGUAGE_CODE), escapeshellarg(QApplication::$TargetLanguage->LanguageCode), escapeshellarg($this->objProject->DefaultTemplatePath), escapeshellarg($this->pnlTranslationsSource->Directory));
         } catch (Exception $objEx) {
             NarroLogger::LogError(sprintf('An error occurred during import: %s', $objEx->getMessage()));
             $this->lblImport->Text = sprintf(t('Import failed: %s'), $objEx->getMessage());
             $this->lblImport->Visible = true;
             $this->btnImport->Visible = true;
             $this->btnKillProcess->Visible = QApplication::HasPermission('Administrator', $this->objProject, QApplication::$TargetLanguage->LanguageCode) && !$this->btnImport->Visible;
             $this->objImportProgress->Translated = 0;
             $this->objImportProgress->Visible = false;
             $this->pnlLogViewer->MarkAsModified();
             return false;
         }
         if (file_exists($strProcLogFile) && is_writable($strProcLogFile)) {
             unlink($strProcLogFile);
         }
         NarroUtils::Exec($strCommand, $arrOutput, $arrError, $intRetVal, true);
         if ($intRetVal == 0) {
             if (QApplication::$UseAjax) {
                 QApplication::ExecuteJavaScript(sprintf('lastImportId = setInterval("qc.pA(\'%s\', \'%s\', \'QClickEvent\', \'1\')", %d);', $strFormId, $strControlId, 2000));
             } else {
                 $this->btnImport_Click($strFormId, $strControlId, 1);
             }
         } else {
             $this->objImportProgress->Visible = false;
             NarroLogger::LogError('Failed to launch a background process, there will be no progress displayed, and it might take a while, please wait for more messages');
             $this->pnlLogViewer->MarkAsModified();
             /**
              * try importing without launching a background process
              */
             if (QApplication::$UseAjax) {
                 QApplication::ExecuteJavaScript(sprintf('lastImportId = setTimeout("qc.pA(\'%s\', \'%s\', \'QClickEvent\', \'2\')", %d);', $strFormId, $strControlId, 2000));
             } else {
                 $this->btnImport_Click($strFormId, $strControlId, 2);
             }
         }
     }
 }
示例#9
0
    }
    NarroLogger::LogInfo(sprintf('Source language is %s', $objNarroImporter->SourceLanguage->LanguageName));
    $objNarroImporter->Project = $objProject;
    $objNarroImporter->User = $objUser;
    if (array_search('--template-directory', $argv) !== false) {
        $objNarroImporter->TemplatePath = $argv[array_search('--template-directory', $argv) + 1];
    } else {
        $objNarroImporter->TemplatePath = $objNarroImporter->Project->DefaultTemplatePath;
    }
    if (array_search('--translation-directory', $argv) !== false) {
        $objNarroImporter->TranslationPath = $argv[array_search('--translation-directory', $argv) + 1];
    } else {
        $objNarroImporter->TranslationPath = $objNarroImporter->Project->DefaultTranslationPath;
    }
    try {
        $intPid = NarroUtils::IsProcessRunning('export', $objNarroImporter->Project->ProjectId);
        if ($intPid && $intPid != getmypid()) {
            NarroLogger::LogInfo(sprintf('An export process is already running for this project with pid %d', $intPid));
        }
        $strProcPidFile = __TMP_PATH__ . '/' . $objNarroImporter->Project->ProjectId . '-' . $objNarroImporter->TargetLanguage->LanguageCode . '-export-process.pid';
        if (file_exists($strProcPidFile)) {
            unlink($strProcPidFile);
        }
        file_put_contents($strProcPidFile, getmypid());
        chmod($strProcPidFile, 0666);
        $objNarroImporter->ExportProject();
    } catch (Exception $objEx) {
        NarroLogger::LogError(sprintf('An error occurred during export: %s', $objEx->getMessage()));
        exit;
    }
}
 public function btnDelete_Click($strFormId, $strControlId, $strParameter)
 {
     if (!QApplication::HasPermission('Can delete project', $this->objProject->ProjectId)) {
         QApplication::Redirect(NarroLink::ProjectList());
     }
     $objDatabase = QApplication::$Database[1];
     try {
         $strQuery = sprintf("DELETE FROM narro_context_info USING narro_context_info LEFT JOIN narro_context ON narro_context_info.context_id=narro_context.context_id WHERE narro_context_info.language_id=%d AND narro_context.project_id=%d", QApplication::GetLanguageId(), $this->objProject->ProjectId);
         $objDatabase->NonQuery($strQuery);
         $strQuery = sprintf("DELETE FROM `narro_context` WHERE project_id = %d", $this->objProject->ProjectId);
         $objDatabase->NonQuery($strQuery);
         $strQuery = sprintf("DELETE FROM `narro_file` WHERE project_id = %d", $this->objProject->ProjectId);
         $objDatabase->NonQuery($strQuery);
         $strQuery = sprintf("DELETE FROM `narro_user_role` WHERE project_id = %d", $this->objProject->ProjectId);
         $objDatabase->NonQuery($strQuery);
         $intProjectId = $this->objProject->ProjectId;
         $this->objProject->Delete();
         NarroUtils::RecursiveDelete(__IMPORT_PATH__ . '/' . $intProjectId);
         NarroUtils::RecursiveDelete(sprintf('%s/project-%d-hg', __NARRO_DATA__ . '/mozilla-build', $intProjectId));
         NarroUtils::RecursiveDelete(sprintf('%s/project-%d-obj', __NARRO_DATA__ . '/mozilla-build', $intProjectId));
     } catch (Exception $objEx) {
         $this->lblMessage->Text = $objEx->getMessage();
         return false;
     }
     QApplication::Redirect(NarroLink::ProjectList());
 }
 public function ExportFile($strTemplate, $strTranslatedFile)
 {
     $hndExportFile = fopen($strTranslatedFile, 'w');
     if (!$hndExportFile) {
         NarroLogger::LogWarn(sprintf('Cannot create or write to "%s".', $strTranslatedFile));
         return false;
     }
     $arrTemplateFile = $this->getFieldGroups($strTemplate);
     foreach ($arrTemplateFile as $strContext => $arrTemplateFields) {
         if (!is_null($arrTemplateFields['MsgId'])) {
             $arrTemplateFields['MsgId'] = str_replace('\\"', '"', $arrTemplateFields['MsgId']);
         }
         if (!is_null($arrTemplateFields['MsgStr'])) {
             $arrTemplateFields['MsgStr'] = str_replace('\\"', '"', $arrTemplateFields['MsgStr']);
         }
         if (!is_null($arrTemplateFields['MsgPluralId'])) {
             $arrTemplateFields['MsgPluralId'] = str_replace('\\"', '"', $arrTemplateFields['MsgPluralId']);
         }
         if (isset($arrTemplateFields['MsgPluralId'])) {
             for ($intPluralId = 0; $intPluralId < $this->objTargetLanguage->Plurals; $intPluralId++) {
                 $arrTemplateFields['MsgStr' . $intPluralId] = str_replace('\\"', '"', $arrTemplateFields['MsgStr' . $intPluralId]);
             }
         }
         /**
          * if it's not a plural, just add msgid and msgstr
          */
         if (is_null($arrTemplateFields['MsgPluralId'])) {
             /**
              * Leave the header alone
              */
             if ($arrTemplateFields['MsgId'] == '' && strstr($arrTemplateFields['MsgStr'], 'Project-Id-Version')) {
                 /**
                  * This is the header
                  */
                 /**
                  * unset the flag, if is set
                  */
                 unset($arrTemplateFields['Flag']);
                 /**
                  * At import, we concatenate strings on more than one lines, so no we have to restore it
                  */
                 $arrTemplateFields['MsgStr'] = str_replace('\\n', '\\n"' . "\n" . '"', $arrTemplateFields['MsgStr']);
                 /**
                  * There's an extra " at the end, remove it
                  */
                 $arrTemplateFields['MsgStr'] = trim(preg_replace('/"$/', '', $arrTemplateFields['MsgStr']));
                 if (strstr($arrTemplateFields['MsgStr'], '"Plural-Forms')) {
                     /**
                      * the plural declaration is there, try to replace it
                      */
                     $arrTemplateFields['MsgStr'] = preg_replace('/"Plural-Forms:[^"]+"/mi', $this->objTargetLanguage->PluralForm, $arrTemplateFields['MsgStr']);
                 } else {
                     /**
                      * the plural declaration isn't there, try to change it
                      */
                     $arrTemplateFields['MsgStr'] .= "\n" . $this->objTargetLanguage->PluralForm;
                 }
                 /**
                  * There's an extra " at the end, remove it
                  */
                 $arrTemplateFields['MsgStr'] = trim(preg_replace('/"$/', '', $arrTemplateFields['MsgStr']));
                 $strGeneratorLine = sprintf('X-Generator: Narro %s on %s\\n', NARRO_VERSION, __HTTP_URL__ . __VIRTUAL_DIRECTORY__ . __SUBDIRECTORY__);
                 if (strstr($arrTemplateFields['MsgStr'], '"X-Generator:')) {
                     $arrTemplateFields['MsgStr'] = preg_replace('/X\\-Generator:[^"]+/mi', $strGeneratorLine, $arrTemplateFields['MsgStr']);
                 } else {
                     $arrTemplateFields['MsgStr'] .= '"' . "\n" . '"' . $strGeneratorLine;
                 }
                 $strProjectLine = sprintf('Project-Id-Version: %s\\n', $this->objProject->ProjectName);
                 if (strstr($arrTemplateFields['MsgStr'], 'Project-Id-Version:')) {
                     $arrTemplateFields['MsgStr'] = preg_replace('/Project\\-Id\\-Version:[^"]+/mi', $strProjectLine, $arrTemplateFields['MsgStr']);
                 } else {
                     $arrTemplateFields['MsgStr'] .= '"' . "\n" . '"' . $strProjectLine;
                 }
                 $strCharsetLine = sprintf('Content-Type: text/plain; charset=%s\\n', $this->objTargetLanguage->Encoding);
                 if (strstr($arrTemplateFields['MsgStr'], '"Content-Type:')) {
                     $arrTemplateFields['MsgStr'] = preg_replace('/Content\\-Type:[^"]+/mi', $strCharsetLine, $arrTemplateFields['MsgStr']);
                 } else {
                     $arrTemplateFields['MsgStr'] .= '"' . "\n" . '"' . $strCharsetLine;
                 }
                 $strTranslatorLine = sprintf('Last-Translator: %s <%s>\\n', QApplication::$User->RealName, QApplication::$User->Email);
                 if (strstr($arrTemplateFields['MsgStr'], '"Last-Translator:')) {
                     $arrTemplateFields['MsgStr'] = preg_replace('/Last\\-Translator:[^"]+/mi', $strTranslatorLine, $arrTemplateFields['MsgStr']);
                 } else {
                     $arrTemplateFields['MsgStr'] .= '"' . "\n" . '"' . $strTranslatorLine;
                 }
                 $strLanguageLine = sprintf('Language-Team: %s <*****@*****.**>\\n', $this->objTargetLanguage->LanguageName);
                 if (strstr($arrTemplateFields['MsgStr'], '"Language-Team:')) {
                     $arrTemplateFields['MsgStr'] = preg_replace('/Language\\-Team:[^"]+/mi', $strLanguageLine, $arrTemplateFields['MsgStr']);
                 } else {
                     $arrTemplateFields['MsgStr'] .= '"' . "\n" . '"' . $strLanguageLine;
                 }
                 $strRevisionLine = sprintf('PO-Revision-Date: %s\\n', date('Y-m-d H:iO'));
                 if (strstr($arrTemplateFields['MsgStr'], '"PO-Revision-Date:')) {
                     $arrTemplateFields['MsgStr'] = preg_replace('/PO\\-Revision\\-Date:[^"]+/mi', $strRevisionLine, $arrTemplateFields['MsgStr']);
                 } else {
                     $arrTemplateFields['MsgStr'] .= '"' . "\n" . '"' . $strRevisionLine;
                 }
             } else {
                 $arrTemplateFields['MsgStr'] = $this->GetTranslation($this->stripAccessKey($arrTemplateFields['MsgStr']), $this->getAccessKey($arrTemplateFields['MsgStr']), $this->getAccessKeyPrefix($arrTemplateFields['MsgStr']), null, null, $arrTemplateFields['Context']);
             }
         } else {
             /**
              * if it's a plural, add the pluralid with all the msgstr's available
              * the first one is added with msgid/msgstr[0] (this is the singular)
              * the next ones are added with plural id, so in fact they will be tied to the same text
              */
             $strSingularText = $arrTemplateFields['MsgStr0'];
             if (!is_null($arrTemplateFields['MsgStr0'])) {
                 $arrTemplateFields['MsgStr0'] = $this->GetTranslation($this->stripAccessKey($arrTemplateFields['MsgStr0']), $this->getAccessKey($arrTemplateFields['MsgStr0']), $this->getAccessKeyPrefix($arrTemplateFields['MsgStr0']), null, null, $arrTemplateFields['Context'] . "\nThis text has plurals.");
             }
             $strPluralText = $arrTemplateFields['MsgStr1'];
             for ($intPluralId = 1; $intPluralId < $this->objTargetLanguage->Plurals; $intPluralId++) {
                 $arrTemplateFields['MsgStr' . $intPluralId] = $this->GetTranslation($this->stripAccessKey($strPluralText), $this->getAccessKey($strPluralText), $this->getAccessKeyPrefix($strPluralText), null, null, $arrTemplateFields['Context'] . "\nThis is plural form {$intPluralId} for the text \"" . $strSingularText . "\".");
             }
         }
         if (!is_null($arrTemplateFields['TranslatorComment'])) {
             fputs($hndExportFile, $arrTemplateFields['TranslatorComment']);
         }
         if (!is_null($arrTemplateFields['ExtractedComment'])) {
             fputs($hndExportFile, $arrTemplateFields['ExtractedComment']);
         }
         if (!is_null($arrTemplateFields['Reference'])) {
             fputs($hndExportFile, $arrTemplateFields['Reference']);
         }
         if (!is_null($arrTemplateFields['Flag'])) {
             fputs($hndExportFile, $arrTemplateFields['Flag']);
         }
         if (!is_null($arrTemplateFields['PreviousContext'])) {
             fputs($hndExportFile, $arrTemplateFields['PreviousContext']);
         }
         if (!is_null($arrTemplateFields['PreviousUntranslated'])) {
             fputs($hndExportFile, $arrTemplateFields['PreviousUntranslated']);
         }
         if (!is_null($arrTemplateFields['PreviousUntranslatedPlural'])) {
             fputs($hndExportFile, $arrTemplateFields['PreviousUntranslatedPlural']);
         }
         if (!is_null($arrTemplateFields['MsgContext'])) {
             fputs($hndExportFile, sprintf('msgctxt "%s"' . "\n", str_replace('"', '\\"', $arrTemplateFields['MsgContext'])));
         }
         if (!is_null($arrTemplateFields['MsgId'])) {
             fputs($hndExportFile, sprintf('msgid "%s"' . "\n", str_replace('"', '\\"', $arrTemplateFields['MsgId'])));
         }
         if (!is_null($arrTemplateFields['MsgPluralId'])) {
             fputs($hndExportFile, sprintf('msgid_plural "%s"' . "\n", str_replace('"', '\\"', $arrTemplateFields['MsgPluralId'])));
         }
         if (!is_null($arrTemplateFields['MsgStr'])) {
             /**
              * put the header as it is
              */
             if ($arrTemplateFields['MsgId'] == '' && strstr($arrTemplateFields['MsgStr'], 'Project-Id-Version')) {
                 fputs($hndExportFile, sprintf('msgstr "%s"' . "\n", $arrTemplateFields['MsgStr']));
             } else {
                 fputs($hndExportFile, sprintf('msgstr "%s"' . "\n", str_replace(array('"', "\n"), array('\\"', '"' . "\n" . '"'), $arrTemplateFields['MsgStr'])));
             }
         }
         for ($intPluralId = 0; $intPluralId < $this->objTargetLanguage->Plurals; $intPluralId++) {
             if (!is_null($arrTemplateFields['MsgStr' . $intPluralId])) {
                 fputs($hndExportFile, sprintf('msgstr[%d] "%s"' . "\n", $intPluralId, str_replace(array('"', "\n"), array('\\"', '"' . "\n" . '"'), $arrTemplateFields['MsgStr' . $intPluralId])));
             }
         }
         fputs($hndExportFile, "\n");
         if ($arrTemplateFields['MsgId'] == '') {
             fputs($hndExportFile, $strLine);
         }
     }
     fclose($hndExportFile);
     chmod($strTranslatedFile, 0666);
     /**
      * Try to format the file
      * @todo add php replacement for msgcat
      */
     if (file_exists($strTranslatedFile . '~')) {
         unlink($strTranslatedFile . '~');
     }
     NarroUtils::Exec(sprintf('msgcat %s -w 80 -o %s~', escapeshellarg($strTranslatedFile), escapeshellarg($strTranslatedFile)), $arrOutput, $arrError, $intRetVal, false, null, __TMP_PATH__, true);
     if (file_exists($strTranslatedFile . '~')) {
         unlink($strTranslatedFile);
         copy($strTranslatedFile . '~', $strTranslatedFile);
     }
     unlink($strTranslatedFile . '~');
     chmod($strTranslatedFile, 0666);
 }
示例#12
0
 private function CreateNarroTemplate($intProjectId)
 {
     $strPoFile = __DOCROOT__ . __SUBDIRECTORY__ . '/locale/' . $this->objSourceLanguage->LanguageCode . '/narro.po';
     NarroLogger::LogInfo(sprintf('Building a narro gettext template in %s.', $strPoFile));
     $arrPermissions = NarroPermission::QueryArray(QQ::All(), QQ::Clause(QQ::OrderBy(QQN::NarroPermission()->PermissionName)));
     NarroLogger::LogInfo(sprintf('Found %d permission names to localize.', count($arrPermissions)));
     $arrRoles = NarroRole::QueryArray(QQ::All(), QQ::Clause(QQ::OrderBy(QQN::NarroRole()->RoleName)));
     NarroLogger::LogInfo(sprintf('Found %d role names to localize.', count($arrRoles)));
     $allFiles = NarroUtils::ListDirectory(realpath(dirname(__FILE__) . '/../../..'), null, '/.*\\/drafts\\/.*|.*\\/data\\/.*|.*\\/examples\\/.*|.*\\/qcubed_generated\\/.*/');
     NarroLogger::LogInfo(sprintf('Found %d php files to search for localizable messages.', count($allFiles)));
     foreach ($allFiles as $strFileName) {
         if (pathinfo($strFileName, PATHINFO_EXTENSION) != 'php') {
             continue;
         }
         $strFile = file_get_contents($strFileName);
         $strShortPath = str_ireplace(realpath(__DOCROOT__ . __SUBDIRECTORY__) . '/', '', $strFileName);
         if (strpos($strShortPath, 'data') === 0) {
             continue;
         }
         if (strpos($strShortPath, 'includes/qcubed_generated') === 0) {
             continue;
         }
         $strFile = str_replace("\\'", "&&&escapedsimplequote&&&", $strFile);
         $strFile = str_replace('\\"', "&&&escapeddoublequote&&&", $strFile);
         if ($strFile) {
             preg_match_all('/([^a-zA-Z]t|NarroApp::Translate|QApplication::Translate|__t)\\s*\\(\\s*[\']([^\']{2,})[\']\\s*\\)/', $strFile, $arrMatches);
             if (isset($arrMatches[2])) {
                 foreach ($arrMatches[2] as $intMatchNo => $strText) {
                     if (trim($strText) != '') {
                         $strText = str_replace(array("&&&escapedsimplequote&&&", "&&&escapeddoublequote&&&"), array("'", '\\"'), $strText);
                         $arrMessages[md5($strText)]['text'] = $strText;
                         $arrMessages[md5($strText)]['files'][$strShortPath] = $strShortPath;
                         $strSearchText = str_replace(array("&&&escapedsimplequote&&&", "&&&escapeddoublequote&&&"), array("'", '\\"'), $arrMatches[0][$intMatchNo]);
                         preg_match_all('/^.*' . preg_quote($strSearchText, '/') . '.*$/m', $strFile, $arrFullMatches);
                         $arrMessages[md5($strText)]['context'] = '#. ';
                         foreach ($arrFullMatches[0] as $strFullMatch) {
                             if (trim($strFullMatch)) {
                                 $arrMessages[md5($strText)]['context'] .= trim($strFullMatch) . "\n";
                             }
                         }
                     }
                 }
             }
             preg_match_all('/([^a-zA-Z]t|NarroApp::Translate|QApplication::Translate|__t)\\s*\\(\\s*[\\"]([^\\"]{2,})[\\"]\\s*\\)/', $strFile, $arrMatches);
             if (isset($arrMatches[2])) {
                 foreach ($arrMatches[2] as $intMatchNo => $strText) {
                     if (trim($strText) != '') {
                         $strText = str_replace(array("&&&escapedsimplequote&&&", "&&&escapeddoublequote&&&"), array("'", '\\"'), $strText);
                         $arrMessages[md5($strText)]['text'] = $strText;
                         $arrMessages[md5($strText)]['files'][$strShortPath] = $strShortPath;
                         $strSearchText = str_replace(array("&&&escapedsimplequote&&&", "&&&escapeddoublequote&&&"), array("'", '\\"'), $arrMatches[0][$intMatchNo]);
                         preg_match_all('/^.*' . preg_quote($strSearchText, '/') . '.*$/m', $strFile, $arrFullMatches);
                         $arrMessages[md5($strText)]['context'] = '#. ';
                         foreach ($arrFullMatches[0] as $strFullMatch) {
                             if (trim($strFullMatch)) {
                                 $arrMessages[md5($strText)]['context'] .= trim($strFullMatch) . "\n";
                             }
                         }
                     }
                 }
             }
             preg_match_all('/([^a-zA-Z]t|NarroApp::Translate|QApplication::Translate|__t)\\s*\\(\\s*[\']([^\']{2,})[\']\\s*,\\s*[\']([^\']{2,})[\']\\s*,\\s*([^\\)]+)\\s*\\)/', $strFile, $arrMatches);
             if (isset($arrMatches[2])) {
                 foreach ($arrMatches[2] as $intMatchNo => $strText) {
                     if (trim($strText) != '') {
                         $strText = str_replace(array("&&&escapedsimplequote&&&", "&&&escapeddoublequote&&&"), array("'", '\\"'), $strText);
                         $arrMessages[md5($strText)]['text'] = $strText;
                         $arrMessages[md5($strText)]['files'][$strShortPath] = $strShortPath;
                         $arrMessages[md5($strText)]['plural'] = $arrMatches[3][$intMatchNo];
                         $strSearchText = str_replace(array("&&&escapedsimplequote&&&", "&&&escapeddoublequote&&&"), array("'", '\\"'), $arrMatches[0][$intMatchNo]);
                         preg_match_all('/^.*' . preg_quote($strSearchText, '/') . '.*$/m', $strFile, $arrFullMatches);
                         $arrMessages[md5($strText)]['context'] = '#. ';
                         foreach ($arrFullMatches[0] as $strFullMatch) {
                             if (trim($strFullMatch)) {
                                 $arrMessages[md5($strText)]['context'] .= trim($strFullMatch) . "\n";
                             }
                         }
                     }
                 }
             }
             preg_match_all('/([^a-zA-Z]t|NarroApp::Translate|QApplication::Translate|__t)\\s*\\(\\s*[\\"]([^\\"]{2,})[\\"]\\s*,\\s*[\\"]([^\\"]{2,})[\\"]\\s*,\\s*([^\\)]+)\\s*\\)/', $strFile, $arrMatches);
             if (isset($arrMatches[2])) {
                 foreach ($arrMatches[2] as $intMatchNo => $strText) {
                     if (trim($strText) != '') {
                         $strText = str_replace(array("&&&escapedsimplequote&&&", "&&&escapeddoublequote&&&"), array("'", '\\"'), $strText);
                         $arrMessages[md5($strText)]['text'] = $strText;
                         $arrMessages[md5($strText)]['files'][$strShortPath] = $strShortPath;
                         $arrMessages[md5($strText)]['plural'] = $arrMatches[3][$intMatchNo];
                         $strSearchText = str_replace(array("&&&escapedsimplequote&&&", "&&&escapeddoublequote&&&"), array("'", '\\"'), $arrMatches[0][$intMatchNo]);
                         preg_match_all('/^.*' . preg_quote($strSearchText, '/') . '.*$/m', $strFile, $arrFullMatches);
                         $arrMessages[md5($strText)]['context'] = '#. ';
                         foreach ($arrFullMatches[0] as $strFullMatch) {
                             if (trim($strFullMatch)) {
                                 $arrMessages[md5($strText)]['context'] .= trim($strFullMatch) . "\n";
                             }
                         }
                     }
                 }
             }
             preg_match_all('/NarroApp::RegisterPreference\\(\\s*\'([^\']+)\'\\s*,\\s*\'[^\']+\'\\s*,\\s*\'([^\']+)\'\\s*,\\s*/', $strFile, $arrMatches);
             if (isset($arrMatches[1])) {
                 foreach ($arrMatches[1] as $intMatchNo => $strText) {
                     if (trim($strText) != '') {
                         $strText = str_replace(array("&&&escapedsimplequote&&&", "&&&escapeddoublequote&&&"), array("'", '\\"'), $strText);
                         $arrMessages[md5($strText)]['text'] = $strText;
                         $arrMessages[md5($strText)]['files'][$strShortPath] = $strShortPath;
                         $strSearchText = $arrMatches[0][$intMatchNo];
                         preg_match_all('/^.*' . preg_quote($strSearchText, '/') . '.*$/m', $strFile, $arrFullMatches);
                         $arrMessages[md5($strText)]['context'] = "#. Preference name\n";
                         foreach ($arrFullMatches[0] as $strLine) {
                             if (isset($strLine) && trim($strLine)) {
                                 $arrMessages[md5($strText)]['context'] .= trim($strLine) . "\n";
                             }
                         }
                     }
                 }
                 foreach ($arrMatches[2] as $intMatchNo => $strText) {
                     if (trim($strText) != '') {
                         $strText = str_replace(array("&&&escapedsimplequote&&&", "&&&escapeddoublequote&&&"), array("'", '\\"'), $strText);
                         $arrMessages[md5($strText)]['text'] = $strText;
                         $arrMessages[md5($strText)]['files'][$strShortPath] = $strShortPath;
                         $strSearchText = $arrMatches[0][$intMatchNo];
                         preg_match_all('/^.*' . preg_quote($strSearchText, '/') . '.*$/m', $strFile, $arrFullMatches);
                         $arrMessages[md5($strText)]['context'] = "#. Preference description\n";
                         foreach ($arrFullMatches[0] as $strLine) {
                             if (isset($strLine) && trim($strLine)) {
                                 $arrMessages[md5($strText)]['context'] .= trim($strLine) . "\n";
                             }
                         }
                     }
                 }
             }
             if (preg_match_all('/t\\(\\$[a-zA-Z]+\\-\\>LanguageName/', $strFile, $arrMatches)) {
                 if (!isset($arrLanguages)) {
                     $arrLanguages = NarroLanguage::QueryArray(QQ::All(), QQ::Clause(QQ::OrderBy(QQN::NarroLanguage()->LanguageName)));
                 }
                 $strLangContext = '#. ';
                 foreach ($arrMatches as $intMatchNo => $arrVal) {
                     $strSearchText = $arrMatches[0][$intMatchNo];
                     preg_match_all('/^.*' . preg_quote($strSearchText, '/') . '.*$/m', $strFile, $arrFullMatches);
                     foreach ($arrFullMatches[0] as $strLine) {
                         if (isset($strLine) && trim($strLine)) {
                             $strLangContext .= trim($strLine) . "\n";
                         }
                     }
                 }
                 if (is_array($arrLanguages)) {
                     foreach ($arrLanguages as $objLanguage) {
                         $arrMessages[md5($objLanguage->LanguageName)]['text'] = $objLanguage->LanguageName;
                         $arrMessages[md5($objLanguage->LanguageName)]['files'][$strShortPath] = $strShortPath;
                         $arrMessages[md5($objLanguage->LanguageName)]['context'] = $strLangContext;
                     }
                 }
             }
             if (preg_match_all('/t\\(\\$[a-zA-Z]+\\-\\>RoleName/', $strFile, $arrMatches)) {
                 $strLangContext = '#. ';
                 foreach ($arrMatches as $intMatchNo => $arrVal) {
                     $strSearchText = $arrMatches[0][$intMatchNo];
                     preg_match_all('/^.*' . preg_quote($strSearchText, '/') . '.*$/m', $strFile, $arrFullMatches);
                     foreach ($arrFullMatches[0] as $strLine) {
                         if (isset($strLine) && trim($strLine)) {
                             $strLangContext .= trim($strLine) . "\n";
                         }
                     }
                 }
                 if (is_array($arrRoles)) {
                     foreach ($arrRoles as $objRole) {
                         $arrMessages[md5($objRole->RoleName)]['text'] = $objRole->RoleName;
                         $arrMessages[md5($objRole->RoleName)]['files'][$strShortPath] = $strShortPath;
                         $arrMessages[md5($objRole->RoleName)]['context'] = $strLangContext;
                     }
                 }
             }
             if (preg_match_all('/t\\(\\$[a-zA-Z]+\\-\\>PermissionName/', $strFile, $arrMatches)) {
                 $strLangContext = '#. ';
                 foreach ($arrMatches as $intMatchNo => $arrVal) {
                     $strSearchText = $arrMatches[0][$intMatchNo];
                     preg_match_all('/^.*' . preg_quote($strSearchText, '/') . '.*$/m', $strFile, $arrFullMatches);
                     foreach ($arrFullMatches[0] as $strLine) {
                         if (isset($strLine) && trim($strLine)) {
                             $strLangContext .= trim($strLine) . "\n";
                         }
                     }
                 }
                 if (is_array($arrPermissions)) {
                     foreach ($arrPermissions as $objPermission) {
                         $arrMessages[md5($objPermission->PermissionName)]['text'] = $objPermission->PermissionName;
                         $arrMessages[md5($objPermission->PermissionName)]['files'][$strShortPath] = $strShortPath;
                         $arrMessages[md5($objPermission->PermissionName)]['context'] = $strLangContext;
                     }
                 }
             }
         }
     }
     $strPoHeader = '#, fuzzy' . "\n" . 'msgid ""' . "\n" . 'msgstr ""' . "\n" . '"Project-Id-Version: Narro ' . NARRO_VERSION . "\n" . '"Report-Msgid-Bugs-To: alexxed@gmail.com\\n"' . "\n" . '"POT-Creation-Date: ' . date('Y-d-m H:iO') . '\\n"' . "\n" . '"PO-Revision-Date: ' . date('Y-d-m H:iO') . '\\n"' . "\n" . '"Last-Translator: FULL NAME <EMAIL@ADDRESS>\\n"' . "\n" . '"Language-Team: LANGUAGE <*****@*****.**>\\n"' . "\n" . '"MIME-Version: 1.0\\n"' . "\n" . '"Content-Type: text/plain; charset=UTF-8\\n"' . "\n" . '"Content-Transfer-Encoding: 8bit\\n"' . "\n" . '"Plural-Forms: nplurals=2; plural=n != 1;\\n"' . "\n" . '"X-Generator: Narro\\n"' . "\n";
     $hndFile = fopen($strPoFile, 'w');
     if (!$hndFile) {
         NarroLogger::LogError(sprintf('Error while opening the po file "%s" for writing.', $strPoFile));
     }
     fputs($hndFile, $strPoHeader);
     // Obtain a list of columns
     foreach ($arrMessages as $key => $row) {
         $texts[$key] = $row['text'];
     }
     //array_multisort($texts, SORT_ASC, SORT_STRING, $arrMessages);
     foreach ($arrMessages as $intKey => $arrMsgData) {
         if (isset($arrMsgData['plural'])) {
             fputs($hndFile, sprintf("#: %s\nmsgid \"%s\"\nmsgid_plural \"%s\"\nmsgstr[0] \"\"\nmsgstr[1] \"\"\n\n", join(' ', array_values($arrMsgData['files'])), str_replace(array('"', "\n"), array('\\"', '\\n'), $arrMsgData['text']), str_replace(array('"', "\n"), array('\\"', '\\n'), $arrMsgData['plural'])));
         } else {
             if (!isset($arrMsgData['files'])) {
                 print_r($arrMsgData);
             } else {
                 fputs($hndFile, sprintf("%s\n#: %s\nmsgid \"%s\"\nmsgstr \"\"\n\n", isset($arrMsgData['context']) ? str_replace("\n", "\n#. ", trim($arrMsgData['context'])) . '' : '', join(' ', array_values($arrMsgData['files'])), str_replace(array('"', "\n"), array('\\"', '\\n'), $arrMsgData['text'])));
             }
         }
     }
     fclose($hndFile);
     NarroUtils::Chmod($strPoFile, 0666);
     NarroLogger::LogInfo('Wrote a new Narro template file in ' . $strPoFile);
 }
 public static function SplitFile($strFile, $strPath, $arrLocale = array(NarroLanguage::SOURCE_LANGUAGE_CODE))
 {
     $hndFile = fopen($strFile, 'r');
     if (!$hndFile) {
         NarroLogger::LogError(sprintf('Cannot open input file "%s" for reading.', $strFile));
         return false;
     }
     /**
      * read the template file line by line
      */
     while (!feof($hndFile)) {
         $strFileLine = fgets($hndFile);
         /**
          * OpenOffice uses tab separated values
          */
         $arrColumn = preg_split('/\\t/', $strFileLine);
         if (count($arrColumn) < 14) {
             continue;
         }
         if (!in_array($arrColumn[9], $arrLocale)) {
             continue;
         }
         $strFilePath = $strPath . '/' . $arrColumn[0] . '/' . str_replace('\\', '/', $arrColumn[1]) . '.sdf';
         if (!file_exists($strFilePath)) {
             if (!file_exists(dirname($strFilePath))) {
                 mkdir(dirname($strFilePath), 0777, true);
             }
         }
         $hndSplitFile = fopen($strFilePath, 'a+');
         fputs($hndSplitFile, $strFileLine);
         fclose($hndSplitFile);
     }
     NarroUtils::RecursiveChmod($strPath);
 }
示例#14
0
 public function btnTest_Click()
 {
     if ($this->RepositorySetup() == 0) {
         $mixProcess = NarroUtils::Exec(sprintf('svn diff > %s_diff', $this->strSSHKey), $arrOutput, $arrError, $intRetVal, false, array('SVN_SSH' => sprintf('ssh -o StrictHostKeyChecking=no -l %s -p 22 -i %s', escapeshellarg($this->txtUsername->Text), $this->strSSHKey), 'HOME' => __TMP_PATH__), $this->strSSHKey . '_svn', true);
     } else {
         $this->lblOutput->Text = join("\n", $arrOutput);
     }
     $this->Form->RemoveControl($this->pnlPatchViewer->ControlId);
     NarroPatchViewerPanel::$strFileExpression = '/^\\-\\-\\-\\s([^\\(]+).*$/';
     $this->pnlPatchViewer = new NarroPatchViewerPanel($this->strSSHKey . '_diff', $this);
     unlink($this->strSSHKey);
     unlink($this->strSSHKey . '_diff');
     NarroUtils::RecursiveDelete($this->strSSHKey . '_svn');
     $this->btnCommit->Display = true;
 }
示例#15
0
 protected function GetWorkingDirectory($strCheckoutCommand = null)
 {
     $this->strWorkingDirectory = sprintf('%s/upload-u_%d-l_%s-p_%d', __TMP_PATH__, QApplication::GetUserId(), $this->objLanguage->LanguageCode, $this->objProject->ProjectId);
     $this->CleanWorkingDirectory();
     if (!$this instanceof NarroMercurialSourcePanel) {
         mkdir($this->strWorkingDirectory);
     }
     $strCommand = sprintf($strCheckoutCommand, escapeshellarg($this->txtRepository->Text), escapeshellarg($this->strWorkingDirectory));
     NarroLogger::LogInfo(sprintf('Running "%s"', $strCommand));
     $strProcLogFile = __TMP_PATH__ . '/' . $this->objProject->ProjectId . '-' . $this->objLanguage->LanguageCode . '-vcs.log';
     if (file_exists($strProcLogFile) && is_writable($strProcLogFile)) {
         unlink($strProcLogFile);
     }
     chdir(__TMP_PATH__);
     $mixProcess = proc_open("{$strCommand}", array(1 => array("file", $strProcLogFile, 'a'), 2 => array("file", $strProcLogFile, 'a')), $foo);
     $status = proc_get_status($mixProcess);
     while ($status['running']) {
         $status = proc_get_status($mixProcess);
     }
     proc_close($mixProcess);
     if (!file_exists($this->strWorkingDirectory)) {
         throw new Exception(sprintf('The working directory "%s" does not exist, probably the checkout command failed', $this->strWorkingDirectory));
     }
     chmod($this->strWorkingDirectory, 0777);
     if (file_exists($strProcLogFile)) {
         NarroLogger::LogInfo(file_get_contents($strProcLogFile));
     }
     NarroUtils::RecursiveDelete($this->strWorkingDirectory . '/.hg');
     foreach (NarroUtils::SearchDirectoryByName($this->strWorkingDirectory, '.svn') as $strSvnDir) {
         NarroUtils::RecursiveDelete($strSvnDir);
     }
     $arrSearchResult = NarroUtils::SearchDirectoryByName($this->strWorkingDirectory, $this->objLanguage->LanguageCode);
     if ($arrSearchResult == false) {
         $arrSearchResult = NarroUtils::SearchDirectoryByName($this->strWorkingDirectory, $this->objLanguage->LanguageCode . '-' . $this->objLanguage->CountryCode);
     }
     if ($arrSearchResult == false) {
         $arrSearchResult = NarroUtils::SearchDirectoryByName($this->strWorkingDirectory, $this->objLanguage->LanguageCode . '_' . $this->objLanguage->CountryCode);
     }
     NarroUtils::RecursiveChmod($this->strWorkingDirectory);
     if (is_array($arrSearchResult) && count($arrSearchResult) == 1) {
         NarroLogger::LogWarn(sprintf('Path changed from "%s" to "%s" because a directory named "%s" was found deeper in the given path.', $this->strWorkingDirectory, $arrSearchResult[0], $this->objLanguage->LanguageCode));
         $this->strWorkingDirectory = $arrSearchResult[0];
     }
     if ($this->chkCopyFilesToDefaultDirectory->Checked) {
         if (file_exists(__IMPORT_PATH__ . '/' . $this->objProject->ProjectId . '/' . $this->objLanguage->LanguageCode)) {
             NarroUtils::RecursiveDelete(__IMPORT_PATH__ . '/' . $this->objProject->ProjectId . '/' . $this->objLanguage->LanguageCode . '/*');
         } else {
             mkdir(__IMPORT_PATH__ . '/' . $this->objProject->ProjectId . '/' . $this->objLanguage->LanguageCode, 0777, true);
         }
         NarroUtils::RecursiveCopy($this->strWorkingDirectory, __IMPORT_PATH__ . '/' . $this->objProject->ProjectId . '/' . $this->objLanguage->LanguageCode);
         NarroUtils::RecursiveChmod(__IMPORT_PATH__ . '/' . $this->objProject->ProjectId . '/' . $this->objLanguage->LanguageCode);
     }
     return $this->strWorkingDirectory;
 }
示例#16
0
 public function Save($blnForceInsert = false, $blnForceUpdate = false)
 {
     $blnNew = !$this->__blnRestored || $blnForceInsert;
     $objProjectProgress = NarroProjectProgress::LoadByProjectIdLanguageId($this->intProjectId, QApplication::GetLanguageId());
     if (is_array($this->arrPreferences)) {
         foreach ($this->arrPreferences as $strName => $strValue) {
             if (self::$AvailablePreferences[$strName]['global'] == false) {
                 if ($objProjectProgress) {
                     $objProjectProgress->SetPreferenceValueByName($strName, $strValue);
                 }
             } else {
                 $arrGlobalPreferences[$strName] = $strValue;
             }
         }
     }
     if (isset($arrGlobalPreferences)) {
         $this->strData = serialize($arrGlobalPreferences);
     }
     if ($objProjectProgress) {
         $objProjectProgress->Save();
     }
     $mixResult = parent::Save($blnForceInsert, $blnForceUpdate);
     if ($blnNew) {
         if (!file_exists(__IMPORT_PATH__ . '/' . $this->ProjectId)) {
             @mkdir(__IMPORT_PATH__ . '/' . $this->ProjectId, 0777, true);
             NarroUtils::RecursiveChmod(__IMPORT_PATH__ . '/' . $this->ProjectId);
         }
         if (!file_exists($this->DefaultTemplatePath)) {
             @mkdir($this->DefaultTemplatePath, 0777, true);
             NarroUtils::RecursiveChmod($this->DefaultTemplatePath);
         }
         foreach (NarroLanguage::LoadAll() as $objLanguage) {
             $objProjectProgress = new NarroProjectProgress();
             $objProjectProgress->LanguageId = $objLanguage->LanguageId;
             $objProjectProgress->ProjectId = $this->ProjectId;
             $objProjectProgress->Active = $this->Active;
             $objProjectProgress->TotalTextCount = 0;
             $objProjectProgress->ApprovedTextCount = 0;
             $objProjectProgress->FuzzyTextCount = 0;
             $objProjectProgress->ProgressPercent = 0;
             $objProjectProgress->Active = $this->Active;
             $objProjectProgress->LastModified = QDateTime::Now();
             $objProjectProgress->Save();
             if (!file_exists($this->DefaultTranslationPath)) {
                 @mkdir($this->DefaultTranslationPath, 0777, true);
             }
             NarroUtils::RecursiveChmod($this->DefaultTranslationPath, 0666, 0777);
         }
     }
     return $mixResult;
 }
 protected function GetWorkingDirectory()
 {
     if (!file_exists($this->fileSource->File)) {
         throw new Exception('You have to upload a file');
     }
     $this->strWorkingDirectory = sprintf('%s/upload-u_%d-l_%s-p_%d', __TMP_PATH__, QApplication::GetUserId(), $this->objLanguage->LanguageCode, $this->objProject->ProjectId);
     $this->CleanWorkingDirectory();
     mkdir($this->strWorkingDirectory);
     chmod($this->strWorkingDirectory, 0777);
     switch (strtolower(pathinfo($this->fileSource->File, PATHINFO_EXTENSION))) {
         case 'zip':
         case 'xpi':
             NarroLogger::LogInfo(sprintf('Trying to uncompress %s', $this->fileSource->FileName));
             $objZipFile = new ZipArchive();
             $intErrCode = $objZipFile->open($this->fileSource->File);
             if ($intErrCode === TRUE) {
                 $objZipFile->extractTo($this->strWorkingDirectory);
                 $objZipFile->close();
                 NarroLogger::LogInfo(sprintf('Sucessfully uncompressed %s.', $this->fileSource->FileName));
             } else {
                 switch ($intErrCode) {
                     case ZIPARCHIVE::ER_NOZIP:
                         $strError = 'Not a zip archive';
                         break;
                     default:
                         $strError = 'Error code: ' . $intErrCode;
                 }
                 $this->fileSource->File = '';
                 throw new Exception(sprintf('Failed to uncompress %s: %s', $this->fileSource->File, $strError));
             }
             break;
         case 'dtd':
         case 'properties':
         case 'ini':
         case 'inc':
         case 'po':
         case 'sdf':
         case 'svg':
         case 'dpo':
         case 'srt':
         case 'php':
             copy($this->fileSource->File, $this->strWorkingDirectory . '/' . $this->fileSource->FileName);
             chmod($this->strWorkingDirectory . '/' . $this->fileSource->FileName, 0666);
             NarroLogger::LogInfo(sprintf('Single file uploaded, copied %s to %s', $this->fileSource->FileName, $this->strWorkingDirectory));
             break;
         default:
             throw new Exception(sprintf('Unsupported file type uploaded'));
     }
     if (file_exists($this->fileSource->File)) {
         unlink($this->fileSource->File);
     }
     $this->fileSource->btnDelete_Click();
     $arrSearchResult = NarroUtils::SearchDirectoryByName($this->strWorkingDirectory, $this->objLanguage->LanguageCode);
     if ($arrSearchResult == false) {
         $arrSearchResult = NarroUtils::SearchDirectoryByName($this->strWorkingDirectory, $this->objLanguage->LanguageCode . '-' . $this->objLanguage->CountryCode);
     }
     if ($arrSearchResult == false) {
         $arrSearchResult = NarroUtils::SearchDirectoryByName($this->strWorkingDirectory, $this->objLanguage->LanguageCode . '_' . $this->objLanguage->CountryCode);
     }
     NarroUtils::RecursiveChmod($this->strWorkingDirectory);
     if (is_array($arrSearchResult) && count($arrSearchResult) == 1) {
         NarroLogger::LogWarn(sprintf('Path changed from "%s" to "%s" because a directory named "%s" was found deeper in the given path.', $this->strWorkingDirectory, $arrSearchResult[0], $this->objLanguage->LanguageCode));
         $this->strWorkingDirectory = $arrSearchResult[0];
     }
     if ($this->chkCopyFilesToDefaultDirectory->Checked) {
         if (file_exists(__IMPORT_PATH__ . '/' . $this->objProject->ProjectId . '/' . $this->objLanguage->LanguageCode)) {
             NarroUtils::RecursiveDelete(__IMPORT_PATH__ . '/' . $this->objProject->ProjectId . '/' . $this->objLanguage->LanguageCode . '/*');
         } else {
             mkdir(__IMPORT_PATH__ . '/' . $this->objProject->ProjectId . '/' . $this->objLanguage->LanguageCode, 0777);
         }
         NarroUtils::RecursiveCopy($this->strWorkingDirectory, __IMPORT_PATH__ . '/' . $this->objProject->ProjectId . '/' . $this->objLanguage->LanguageCode);
         NarroUtils::RecursiveChmod(__IMPORT_PATH__ . '/' . $this->objProject->ProjectId . '/' . $this->objLanguage->LanguageCode);
     }
     return $this->strWorkingDirectory;
 }
示例#18
0
 public static function Reset()
 {
     NarroUtils::RecursiveDelete(__CACHE__ . '/*');
 }
示例#19
0
 public function ExportFile($strTemplateFile, $strTranslatedFile)
 {
     $arrSourceKey = $this->FileAsArray($strTemplateFile);
     $intElapsedTime = time() - $intTime;
     if ($intElapsedTime > 0) {
         // NarroLogger::LogDebug(sprintf('Preprocessing %s took %d seconds.', $this->objFile->FileName, $intElapsedTime));
     }
     // NarroLogger::LogDebug(sprintf('Found %d contexts in file %s.', count($arrSourceKey), $this->objFile->FileName));
     if (is_array($arrSourceKey)) {
         $arrTranslationObjects = NarroContextInfo::QueryArray(QQ::AndCondition(QQ::Equal(QQN::NarroContextInfo()->Context->FileId, $this->objFile->FileId), QQ::Equal(QQN::NarroContextInfo()->LanguageId, $this->objTargetLanguage->LanguageId), QQ::Equal(QQN::NarroContextInfo()->Context->Active, 1)));
         foreach ($arrTranslationObjects as $objNarroContextInfo) {
             $strTranslation = $this->GetExportedSuggestion($objNarroContextInfo);
             if (isset($arrSourceKey[$objNarroContextInfo->Context->Context])) {
                 $arrSourceKey[$objNarroContextInfo->Context->Context]->Value = $strTranslation;
             } else {
                 if ($this->blnSkipUntranslated == false) {
                     $arrSourceKey[$objNarroContextInfo->Context->Context]->Value = $objNarroContextInfo->Context->Text->TextValue;
                 } else {
                     unset($arrTranslation[$objNarroContextInfo->Context->Context]);
                 }
             }
         }
         $hndTranslationFile = fopen($strTranslatedFile, 'w');
         foreach ($arrSourceKey as $strContext => $objEntity) {
             /* @var $objEntity NarroFileEntity */
             fwrite($hndTranslationFile, $objEntity->Key . "\n");
             fwrite($hndTranslationFile, $objEntity->Comment . "\n");
             fwrite($hndTranslationFile, $objEntity->Value . "\n\n");
         }
         fclose($hndTranslationFile);
         NarroUtils::Chmod($strTranslatedFile, 0666);
         return true;
     } else {
         NarroLogger::LogWarn(sprintf('Found a empty template (%s), copying the original', $strTemplateFile));
         copy($strTemplateFile, $strTranslatedFile);
         NarroUtils::Chmod($strTranslatedFile, 0666);
         return false;
     }
 }
 public function btnExport_Click($strFormId, $strControlId, $strParameter)
 {
     if (!QApplication::HasPermissionForThisLang('Can export project', $this->objProject->ProjectId)) {
         return false;
     }
     $strProcLogFile = __TMP_PATH__ . '/' . $this->objProject->ProjectId . '-' . QApplication::$TargetLanguage->LanguageCode . '-export-process.log';
     if ($strParameter == 1) {
         if (NarroUtils::IsProcessRunning('export', $this->objProject->ProjectId)) {
             $this->objExportProgress->Translated = NarroProgress::GetProgress($this->objProject->ProjectId, 'export');
             $this->objExportProgress->MarkAsModified();
         } else {
             $this->lblExport->Text = t('Export finished.');
             if (QApplication::$UseAjax) {
                 QApplication::ExecuteJavaScript('if (typeof lastExportId != \'undefined\') clearInterval(lastExportId)');
             }
             if (file_exists($strProcLogFile) && filesize($strProcLogFile)) {
                 NarroLogger::LogInfo(sprintf('There are messages from the background process: %s', file_get_contents($strProcLogFile)));
             }
             $this->lblExport->Visible = true;
             $this->btnExport->Visible = true;
             $this->btnKillProcess->Visible = false;
             $this->objExportProgress->Translated = 0;
             $this->objExportProgress->Visible = false;
             QApplication::$PluginHandler->DisplayExportMessage($this->objProject);
             if (is_array(QApplication::$PluginHandler->PluginReturnValues)) {
                 foreach (QApplication::$PluginHandler->PluginReturnValues as $strPluginName => $mixReturnValue) {
                     if (count($mixReturnValue) == 2 && $mixReturnValue[0] instanceof NarroProject && is_string($mixReturnValue[1]) && $mixReturnValue[1] != '') {
                         $this->lblExport->Text .= sprintf('<br /><span class="info"><b>%s</b>: %s</span>', $strPluginName, nl2br($mixReturnValue[1]));
                     }
                 }
             }
         }
         $this->pnlLogViewer->MarkAsModified();
     } elseif ($strParameter == 2) {
         $this->pnlLogViewer->DateStart = QDateTime::Now();
         $this->pnlLogViewer->ProjectId = $this->objProject->ProjectId;
         $this->pnlLogViewer->LanguageId = QApplication::GetLanguageId();
         NarroProgress::ClearProgressFileName($this->objProject->ProjectId, 'import');
         set_time_limit(0);
         if ($this->chkCleanDirectory->Checked) {
             NarroUtils::RecursiveDelete($this->objProject->DefaultTranslationPath . '/*');
         }
         $objNarroImporter = new NarroProjectImporter();
         /**
          * Get boolean options
          */
         $objNarroImporter->ExportedSuggestion = $this->lstExportSuggestionType->SelectedValue;
         $objNarroImporter->Project = $this->objProject;
         $objNarroImporter->ExportAuthorList = $this->txtAuthor->Text;
         $objNarroImporter->User = QApplication::$User;
         $objNarroImporter->TargetLanguage = QApplication::$TargetLanguage;
         $objNarroImporter->SourceLanguage = NarroLanguage::LoadByLanguageCode(NarroLanguage::SOURCE_LANGUAGE_CODE);
         try {
             $objNarroImporter->TranslationPath = $this->objProject->DefaultTranslationPath;
             $objNarroImporter->TemplatePath = $this->objProject->DefaultTemplatePath;
         } catch (Exception $objEx) {
             NarroLogger::LogError(sprintf('An error occurred during export: %s', $objEx->getMessage()));
             $this->lblExport->Text = t('Export failed.');
         }
         try {
             $objNarroImporter->ExportProject();
         } catch (Exception $objEx) {
             NarroLogger::LogError(sprintf('An error occurred during export: %s', $objEx->getMessage()));
             $this->lblExport->Text = t('Export failed.');
         }
         $this->lblExport->Visible = true;
         $this->btnExport->Visible = true;
         $this->btnKillProcess->Visible = false;
         $this->objExportProgress->Visible = false;
         $this->pnlLogViewer->MarkAsModified();
     } else {
         $this->pnlLogViewer->DateStart = QDateTime::Now();
         $this->pnlLogViewer->ProjectId = $this->objProject->ProjectId;
         $this->pnlLogViewer->LanguageId = QApplication::GetLanguageId();
         if ($this->chkCleanDirectory->Checked) {
             NarroUtils::RecursiveDelete($this->objProject->DefaultTranslationPath . '/*');
         }
         $this->btnExport->Visible = false;
         $this->btnKillProcess->Visible = $this->btnKillProcess->Visible = QApplication::HasPermission('Administrator', $this->objProject, QApplication::$TargetLanguage->LanguageCode);
         $this->objExportProgress->Visible = true;
         $this->objExportProgress->Translated = 0;
         $this->lblExport->Text = '';
         try {
             $strCommand = sprintf('%s %s --export --project %d --user %d --template-lang %s --translation-lang %s --template-directory %s --translation-directory %s --exported-suggestion %d --export-author-list %s', __PHP_CLI_PATH__, escapeshellarg(sprintf('%s/includes/narro/importer/narro-cli.php', __DOCROOT__ . __SUBDIRECTORY__)), (int) $this->objProject->ProjectId, (int) QApplication::$User->UserId, escapeshellarg(NarroLanguage::SOURCE_LANGUAGE_CODE), escapeshellarg(QApplication::$TargetLanguage->LanguageCode), escapeshellarg($this->objProject->DefaultTemplatePath), escapeshellarg($this->objProject->DefaultTranslationPath), (int) $this->lstExportSuggestionType->SelectedValue, escapeshellarg($this->txtAuthor->Text));
         } catch (Exception $objEx) {
             NarroLogger::LogError(sprintf('An error occurred during export: %s', $objEx->getMessage()));
             $this->lblExport->Text = t('Export failed.');
             $this->lblExport->Visible = true;
             $this->btnExport->Visible = true;
             $this->btnKillProcess->Visible = false;
             $this->objExportProgress->Translated = 0;
             $this->objExportProgress->Visible = false;
             $this->pnlLogViewer->MarkAsModified();
             return false;
         }
         if (file_exists($strProcLogFile) && is_writable($strProcLogFile)) {
             unlink($strProcLogFile);
         }
         $mixProcess = proc_open("{$strCommand} &", array(2 => array("file", $strProcLogFile, 'a')), $foo);
         if ($mixProcess) {
             if (QApplication::$UseAjax) {
                 QApplication::ExecuteJavaScript(sprintf('lastExportId = setInterval("qc.pA(\'%s\', \'%s\', \'QClickEvent\', \'1\')", %d);', $strFormId, $strControlId, 2000));
             } else {
                 $this->btnExport_Click($strFormId, $strControlId, 1);
             }
         } else {
             $this->objExportProgress->Visible = false;
             NarroLogger::LogError('Failed to launch a background process, there will be no progress displayed, and it might take a while, please wait for more messages');
             $this->pnlLogViewer->MarkAsModified();
             /**
              * try exporting without launching a background process
              */
             if (QApplication::$UseAjax) {
                 QApplication::ExecuteJavaScript(sprintf('lastExportId = setTimeout("qc.pA(\'%s\', \'%s\', \'QClickEvent\', \'2\')", %d);', $strFormId, $strControlId, 2000));
             } else {
                 $this->btnExport_Click($strFormId, $strControlId, 2);
             }
         }
     }
 }