예제 #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 ImportFile($strFileToImport, $strTranslatedFile = null)
 {
     if ($strTemplateFileContents = file_get_contents($strFileToImport)) {
         $arrTemplate = array();
         if (preg_match_all('/([^$]+)\\$([^\\s]+)\\s*=\\s*([\']?.*[\']?);(.*)/m', $strTemplateFileContents, $arrTemplateMatches)) {
             if ($strTranslatedFileContents = file_get_contents($strTranslatedFile)) {
                 $arrTranslationMatches = array();
                 preg_match_all('/([^$]+)\\$([^\\s]+)\\s*=\\s*([\']?.*[\']?);(.*)/m', $strTranslatedFileContents, $arrTranslationMatches);
                 foreach ($arrTranslationMatches[2] as $intKey => $strIdentifier) {
                     if (trim(preg_replace('/^\'(.*)\'$/', '\\1', $arrTranslationMatches[3][$intKey]))) {
                         $arrTranslations[$strIdentifier]['text'] = preg_replace('/^\'(.*)\'$/', '\\1', $arrTranslationMatches[3][$intKey]);
                         $arrTranslations[$strIdentifier]['context'] = $arrTranslationMatches[1][$intKey] . $arrTranslationMatches[2][$intKey] . $arrTranslationMatches[4][$intKey];
                     }
                 }
             }
             foreach ($arrTemplateMatches[2] as $intKey => $strIdentifier) {
                 if (trim(preg_replace('/^\'(.*)\'$/', '\\1', $arrTemplateMatches[3][$intKey]))) {
                     $arrTemplate[$strIdentifier]['text'] = preg_replace('/^\'(.*)\'$/', '\\1', $arrTemplateMatches[3][$intKey]);
                     $arrTemplate[$strIdentifier]['context'] = $arrTemplateMatches[1][$intKey] . $arrTemplateMatches[2][$intKey] . $arrTemplateMatches[4][$intKey];
                     if (isset($arrTranslations[$strIdentifier])) {
                         $arrTemplate[$strIdentifier]['translation'] = $arrTranslations[$strIdentifier]['text'];
                     } else {
                         $arrTemplate[$strIdentifier]['translation'] = '';
                     }
                 }
             }
             foreach ($arrTemplate as $intKey => $arrInfo) {
                 $this->AddTranslation($arrInfo['text'], null, $arrInfo['translation'], null, $arrInfo['context']);
             }
         }
     } else {
         NarroLogger::LogError(sprintf('Cannot open file "%s".', $strFileToImport));
     }
 }
예제 #3
0
 public function ExportSuggestion($strOriginal, $strTranslation, $strContext, NarroFile $objFile, NarroProject $objProject)
 {
     $strStrippedTranslation = preg_replace('/<\\/?[a-z][^>]+>/', '', $strTranslation);
     if ($strTranslation && $objFile->TypeId == NarroFileType::MozillaDtd && strstr($strStrippedTranslation, '"')) {
         NarroLogger::LogError(sprintf(t('Your translation for "%s", in "%s" includes double quote characters. Those need to be written as HTML entities, otherwise the export will not be valid. You can use &quot; instead of each double quote.'), str_replace("\n", '\\n', strlen($strOriginal) > 50 ? substr($strOriginal, 0, 50) . '...' : $strOriginal), $objFile->FilePath));
     }
     return array($strOriginal, $strTranslation, $strContext, $objFile, $objProject);
 }
 public function ImportFile($strTemplateFile, $strTranslatedFile = null)
 {
     if ($strTranslatedFile != '' && !file_exists($strTranslatedFile)) {
         NarroLogger::LogWarn(sprintf('Copying unsupported file type: %s', $strTemplateFile));
         NarroImportStatistics::$arrStatistics['Unsupported files that were copied from the source language']++;
         if (@copy($strTemplateFile, $strTranslatedFile) == false) {
             NarroLogger::LogError(sprintf('Failed to copy "%s" to "%s"', $strTemplateFile, $strTranslatedFile));
         }
     }
 }
예제 #5
0
 public function ImportFile($strFileToImport, $strTranslatedFile = null)
 {
     if ($strFileContents = file_get_contents($strFileToImport)) {
         if (preg_match_all('/<flowPara[^>]+>([^<]+)<\\/flowPara>/', $strFileContents, $arrMatches)) {
             foreach ($arrMatches[0] as $intKey => $strContext) {
                 if (trim($arrMatches[1][$intKey]) != '') {
                     $this->AddTranslation($this->objFile, $arrMatches[1][$intKey], null, null, null, $strContext);
                 }
             }
         }
     } else {
         NarroLogger::LogError(sprintf('Cannot open file "%s".', $strFileToImport));
     }
 }
예제 #6
0
 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;
 }
 public function ExportFile($strTemplateFile, $strTranslatedFile)
 {
     $strTemplateContents = file_get_contents($strTemplateFile);
     if (!$strTemplateContents) {
         NarroLogger::LogWarn(sprintf('Found a empty template (%s), copying the original', $strTemplateFile));
         copy($strTemplateFile, $strTranslatedFile);
         chmod($strTranslatedFile, 0666);
         return false;
     }
     if (strstr($strTemplateContents, '#define MOZ_LANGPACK_CONTRIBUTORS')) {
         $strTemplateContents = preg_replace('/^#\\s+#define MOZ_LANGPACK_CONTRIBUTORS.*$/m', '#define MOZ_LANGPACK_CONTRIBUTORS <em:contributor>Joe Solon</em:contributor> <em:contributor>Suzy Solon</em:contributor>', $strTemplateContents);
     }
     $arrTemplateContents = explode("\n", $strTemplateContents);
     $strComment = '';
     foreach ($arrTemplateContents as $intPos => $strLine) {
         if (preg_match('/^#define\\s+([^\\s]+)\\s+(.+)$/s', trim($strLine), $arrMatches)) {
             $arrTemplate[trim($arrMatches[1])] = trim($arrMatches[2]);
             $arrTemplateLines[trim($arrMatches[1])] = $arrMatches[0];
             $arrTemplateComment[trim($arrMatches[1])] = $strComment;
             $strComment = '';
         } elseif (trim($strLine) != '' && $strLine[0] != '#') {
             // NarroLogger::LogDebug(sprintf('Skipped line "%s" from the template "%s".', $strLine, $this->objFile->FileName));
         } elseif ($strLine[0] == '#') {
             $strComment .= "\n" . $strLine;
         }
     }
     $strTranslateContents = '';
     if (count($arrTemplate) < 1) {
         return false;
     }
     $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) {
         if ($objNarroContextInfo->ValidSuggestionId > 0) {
             $arrTranslation[$objNarroContextInfo->Context->Context] = $this->GetExportedSuggestion($objNarroContextInfo);
             if ($arrTranslation[$objNarroContextInfo->Context->Context] === false) {
                 $arrTranslation[$objNarroContextInfo->Context->Context] = $objNarroContextInfo->Context->Text->TextValue;
             }
             if ($objNarroContextInfo->Context->TextAccessKey) {
                 if ($objNarroContextInfo->SuggestionAccessKey) {
                     $strAccessKey = $objNarroContextInfo->SuggestionAccessKey;
                 } else {
                     $strAccessKey = $objNarroContextInfo->Context->TextAccessKey;
                 }
                 $arrTranslation[$objNarroContextInfo->Context->Context] = preg_replace('/' . $strAccessKey . '/', '&' . $strAccessKey, $arrTranslation[$objNarroContextInfo->Context->Context], 1);
                 NarroImportStatistics::$arrStatistics['Texts that have access keys']++;
             } else {
                 NarroImportStatistics::$arrStatistics["Texts that don't have access keys"]++;
             }
         } else {
             // NarroLogger::LogDebug(sprintf('In file "%s", the context "%s" does not have a valid suggestion.', $this->objFile->FileName, $objNarroContextInfo->Context->Context));
             NarroImportStatistics::$arrStatistics['Texts without valid suggestions']++;
             NarroImportStatistics::$arrStatistics['Texts kept as original']++;
         }
     }
     $strTranslateContents = $strTemplateContents;
     foreach ($arrTemplate as $strKey => $strOriginalText) {
         if (isset($arrTranslation[$strKey])) {
             $arrResult = QApplication::$PluginHandler->ExportSuggestion($strOriginalText, $arrTranslation[$strKey], $strKey, $this->objFile, $this->objProject);
             if ($arrResult[1] != '' && $arrResult[0] == $strOriginalText && $arrResult[2] == $strKey && $arrResult[3] == $this->objFile && $arrResult[4] == $this->objProject) {
                 $arrTranslation[$strKey] = $arrResult[1];
             } else {
                 NarroLogger::LogWarn(sprintf('The plugin "%s" returned an unexpected result while processing the suggestion "%s": %s', QApplication::$PluginHandler->CurrentPluginName, $arrTranslation[$strKey], var_export($arrResult, true)));
             }
             if (strstr($strTranslateContents, sprintf('#define %s %s', $strKey, $strOriginalText))) {
                 $strTranslateContents = str_replace(sprintf('#define %s %s', $strKey, $strOriginalText), sprintf('#define %s %s', $strKey, $arrTranslation[$strKey]), $strTranslateContents);
             } else {
                 NarroLogger::LogWarn(sprintf('Can\'t find "%s" in the file "%s"'), $strKey . $strGlue . $strOriginalText, $this->objFile->FileName);
             }
             if (strstr($arrTranslation[$strKey], "\n")) {
                 NarroLogger::LogWarn(sprintf('Skpping translation "%s" because it has a newline in it'), $arrTranslation[$strKey]);
                 continue;
             }
         } else {
             // NarroLogger::LogDebug(sprintf('Couldn\'t find the key "%s" in the translations, using the original text.', $strKey, $this->objFile->FileName));
             NarroImportStatistics::$arrStatistics['Texts kept as original']++;
             if ($this->blnSkipUntranslated == true) {
             }
             if ($this->blnSkipUntranslated == true) {
                 if (isset($arrTemplateComment[$strKey]) && $arrTemplateComment[$strKey] != '') {
                     $strTranslateContents = str_replace($arrTemplateComment[$strKey] . "\n", "\n", $strTranslateContents);
                     $strTranslateContents = str_replace(sprintf("#define %s %s\n", $strKey, $strOriginalText), '', $strTranslateContents);
                 }
             }
         }
     }
     if (file_exists($strTranslatedFile) && !is_writable($strTranslatedFile) && !unlink($strTranslatedFile)) {
         NarroLogger::LogError(sprintf('Can\'t delete the file "%s"', $strTranslatedFile));
     }
     if (!file_put_contents($strTranslatedFile, $strTranslateContents)) {
         NarroLogger::LogError(sprintf('Can\'t write to file "%s"', $strTranslatedFile));
     }
     @chmod($strTranslatedFile, 0666);
 }
예제 #8
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;
 }
예제 #9
0
 public function Save($blnForceInsert = false, $blnForceUpdate = false)
 {
     $this->intSuggestionWordCount = NarroString::WordCount($this->strSuggestionValue);
     $this->intSuggestionCharCount = mb_strlen($this->strSuggestionValue);
     $this->strSuggestionValueMd5 = md5($this->strSuggestionValue);
     if (!isset($this->blnIsImported)) {
         $this->blnIsImported = false;
     }
     if (!$this->__blnRestored || $blnForceInsert) {
         $this->dttCreated = QDateTime::Now();
     } else {
         $this->dttModified = QDateTime::Now();
     }
     parent::Save($blnForceInsert, $blnForceUpdate);
     /**
      * Update all context infos with the has suggestion property
      */
     $arrContextInfo = NarroContextInfo::QueryArray(QQ::AndCondition(QQ::Equal(QQN::NarroContextInfo()->Context->TextId, $this->intTextId), QQ::Equal(QQN::NarroContextInfo()->LanguageId, $this->intLanguageId), QQ::Equal(QQN::NarroContextInfo()->HasSuggestions, 0)));
     foreach ($arrContextInfo as $objOneContextInfo) {
         $objOneContextInfo->HasSuggestions = 1;
         $objOneContextInfo->Modified = QDateTime::Now();
         try {
             $objOneContextInfo->Save();
         } catch (Exception $objEx) {
             NarroLogger::LogWarn($objEx->getMessage());
         }
     }
 }
예제 #10
0
 public static function InitializeLogging($intProjectId = null)
 {
     NarroLogger::$intProjectId = self::GetProjectId();
     NarroLogger::$intLanguageId = self::GetLanguageId();
     NarroLogger::$intUserId = self::GetUserId();
 }
 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);
 }
 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;
     }
 }
예제 #13
0
 public static function SetProgress($intValue, $intProjectId, $strOperation, $intFilesToProcess = 0, $intProgressPerFile = 0)
 {
     if ($intFilesToProcess == 0) {
         $intFilesToProcess = self::GetFilesToProcess($intProjectId, $strOperation);
     }
     if ($intProgressPerFile == 0) {
         $intProgressPerFile = self::GetProgressPerFile($intProjectId, $strOperation);
     }
     if ($intValue == 0) {
         $intValue = self::GetProgressPerProject($intProjectId, $strOperation);
     }
     if (!@file_put_contents(self::GetProgressFileName($intProjectId, $strOperation), $intFilesToProcess . ',' . $intValue . ',' . $intProgressPerFile)) {
         NarroLogger::LogWarn(sprintf('Can\'t write progress file %s', self::GetProgressFileName($intProjectId, $strOperation)));
     }
     @chmod(self::GetProgressFileName($intProjectId, $strOperation), 0666);
 }
예제 #14
0
파일: export_all.php 프로젝트: Jobava/narro
                    return false;
                }
                NarroLogger::LogInfo(sprintf('Source language is %s', $objNarroImporter->SourceLanguage->LanguageName));
                $objNarroImporter->Project = $objProject;
                $objNarroImporter->User = $objUser;
                $objNarroImporter->TemplatePath = $objNarroImporter->Project->DefaultTemplatePath;
                $objNarroImporter->TranslationPath = $objNarroImporter->Project->DefaultTranslationPath;
                $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();
                unlink($strProcPidFile);
            } catch (Exception $objEx) {
                printf("\n%s: %s\n", $objEx->getMessage(), $objEx->getTraceAsString());
                NarroLogger::LogError(sprintf('An error occurred during export: %s', $objEx->getMessage()));
                continue;
            }
        }
    }
}
$objDateSpan = new QDateTimeSpan(time() - $intStartTime);
printf("Export started %s ago, finished in %d seconds\n", $objDateSpan->SimpleDisplay(), time() - $intStartTime);
NarroLogger::LogInfo(sprintf('Export started %s ago, finished in %d seconds', $objDateSpan->SimpleDisplay(), time() - $intStartTime));
예제 #15
0
파일: narro-cli.php 프로젝트: Jobava/narro
    }
    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;
    }
}
예제 #16
0
 public function btnKillProcess_Click($strFormId, $strControlId, $strParameter)
 {
     $strProcLogFile = __TMP_PATH__ . '/' . $this->objProject->ProjectId . '-' . QApplication::$TargetLanguage->LanguageCode . '-import-process.log';
     $strProcPidFile = __TMP_PATH__ . '/' . $this->objProject->ProjectId . '-' . QApplication::$TargetLanguage->LanguageCode . '-import-process.pid';
     if (!file_exists($strProcPidFile)) {
         NarroLogger::LogError('Could not find a pid file for the background process.');
         $this->pnlLogViewer->MarkAsModified();
         return false;
     }
     $intPid = file_get_contents($strProcPidFile);
     if (is_numeric(trim($intPid))) {
         $mixProcess = proc_open(sprintf('kill -9 %d', $intPid), array(2 => array("file", $strProcLogFile, 'a')), $foo);
         if ($mixProcess) {
             proc_close($mixProcess);
             NarroLogger::LogError('Process killed');
         } else {
             NarroLogger::LogError('Failed to kill process');
         }
         if (file_exists($strProcLogFile) && filesize($strProcLogFile)) {
             NarroLogger::LogWarn(sprintf('There are messages from the background process: %s', file_get_contents($strProcLogFile)));
         }
         $this->pnlLogViewer->MarkAsModified();
     }
 }
예제 #17
0
 /**
  * Get the most voted suggestion for a context
  *
  * @param integer $intContextId
  * @param integer $intTextId
  * @param integer $intUserId
  * @return NarroSuggestion
  */
 public function GetMostVotedSuggestion($intContextId, $intTextId, $intUserId)
 {
     $strQuery = sprintf('SELECT
                 narro_suggestion_vote.suggestion_id, SUM(vote_value) as votes
             FROM
                 narro_suggestion_vote, narro_suggestion
             WHERE
                 narro_suggestion_vote.suggestion_id=narro_suggestion.suggestion_id AND
                 narro_suggestion.text_id=%d AND
                 narro_suggestion.language_id=%d
             GROUP BY narro_suggestion_vote.suggestion_id
             ORDER BY votes DESC
             LIMIT 1', $intTextId, $this->objTargetLanguage->LanguageId);
     if (!($objDbResult = NarroSuggestion::GetDatabase()->Query($strQuery))) {
         NarroLogger::LogError('db_query failed. $strQuery=' . $strQuery);
         return false;
     } else {
         if ($objDbResult->CountRows()) {
             $arrDbRow = $objDbResult->FetchArray();
             return NarroSuggestion::Load($arrDbRow['suggestion_id']);
         } else {
             // NarroLogger::LogDebug(sprintf('There are no votes recorded for context_id=%d', $intContextId));
             return false;
         }
     }
 }
예제 #18
0
 /**
  *
  * A better version of exec()
  * @param string $strCommand The command to run
  * @param array $arrOutput An array where you'll get the output
  * @param array $arrError An array where you'll get the errors
  * @param integer $intRetVal The return value of the command
  * @param boolean $blnInBackground Whether to launch the command in background
  * @param array $env Associative array with environment variables
  * @param string $cwd The directory to switch to before running the command
  * @param boolean $blnLogErrors Whether to log the errors in the database
  *
  * @return boolean
  */
 public static function Exec($strCommand, &$arrOutput, &$arrError, &$intRetVal, $blnInBackground = false, $env = null, $cwd = null, $blnLogErrors = true)
 {
     $process = proc_open($strCommand . ($blnInBackground ? ' &' : ''), array(1 => array("pipe", 'w'), 2 => array("pipe", 'w')), $pipes, $cwd, $env);
     if (!$blnInBackground) {
         if (is_resource($process)) {
             $arrOutput = explode("\n", stream_get_contents($pipes[1]));
             fclose($pipes[1]);
             $arrError = explode("\n", stream_get_contents($pipes[2]));
             fclose($pipes[2]);
             // It is important that you close any pipes before calling
             // proc_close in order to avoid a deadlock
             $intRetVal = proc_close($process);
             if ($intRetVal != 0 && $blnLogErrors) {
                 NarroLogger::LogError(sprintf('Running "%s" in "%s" returned %d', $strCommand, is_null($cwd) ? getcwd() : $cwd, $intRetVal));
                 foreach ($arrOutput as $strOutput) {
                     NarroLogger::LogInfo($strOutput);
                 }
                 foreach ($arrError as $strOutput) {
                     NarroLogger::LogError($strOutput);
                 }
                 return false;
             }
             NarroLogger::LogDebug(sprintf('Running "%s" in "%s"', $strCommand, is_null($cwd) ? getcwd() : $cwd));
             return true;
         } else {
             return false;
         }
     } else {
         if (is_resource($process)) {
             return true;
         } else {
             return false;
         }
     }
 }
 /**
  * A translation here consists of the project, file, text, translation, context, plurals, approval, ignore equals
  *
  * @param string $strOriginal the original text
  * @param string $strOriginalAccKey access key for the original text
  * @param string $strTranslation the translated text from the import file (can be empty)
  * @param string $strOriginalAccKey access key for the translated text
  * @param string $strContext the context where the text/translation appears in the file
  * @param string $intPluralForm if this is a plural, what plural form is it (0 singular, 1 plural form 1, and so on)
  * @param string $strComment a comment from the imported file
  *
  * @return string valid suggestion
  */
 protected function GetTranslation($strOriginal, $strOriginalAccKey = null, $strOriginalAccKeyPrefix = null, $strTranslation, $strTranslationAccKey = null, $strContext, $strComment = null)
 {
     $objNarroContextInfo = NarroContextInfo::QuerySingle(QQ::AndCondition(QQ::Equal(QQN::NarroContextInfo()->Context->ProjectId, $this->objProject->ProjectId), QQ::Equal(QQN::NarroContextInfo()->Context->FileId, $this->objFile->FileId), QQ::Equal(QQN::NarroContextInfo()->Context->ContextMd5, md5(trim($strContext))), QQ::Equal(QQN::NarroContextInfo()->Context->Text->TextValueMd5, md5($strOriginal)), QQ::Equal(QQN::NarroContextInfo()->LanguageId, $this->objTargetLanguage->LanguageId)));
     if ($objNarroContextInfo instanceof NarroContextInfo) {
         $strSuggestionValue = $this->GetExportedSuggestion($objNarroContextInfo);
         $arrResult = QApplication::$PluginHandler->ExportSuggestion($strOriginal, $strSuggestionValue, $strContext, $this->objFile, $this->objProject);
         if ($arrResult[1] != '' && $arrResult[0] == $strOriginal && $arrResult[2] == $strContext && $arrResult[3] == $this->objFile && $arrResult[4] == $this->objProject) {
             $strSuggestionValue = $arrResult[1];
         } else {
             NarroLogger::LogWarn(sprintf('The plugin "%s" returned an unexpected result while processing the suggestion "%s": %s', QApplication::$PluginHandler->CurrentPluginName, $strTranslation, $strTranslation));
         }
         if (!is_null($strOriginalAccKey) && !is_null($strOriginalAccKeyPrefix)) {
             /**
              * @todo don't export if there's no valid access key
              */
             $strTextWithAccKey = NarroString::Replace($objNarroContextInfo->SuggestionAccessKey, $strOriginalAccKeyPrefix . $objNarroContextInfo->SuggestionAccessKey, $strSuggestionValue, 1);
             return $strTextWithAccKey;
         } else {
             return $strSuggestionValue;
         }
     } else {
         /**
          * leave it untranslated
          */
         return $strOriginal;
     }
 }
예제 #20
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 function ImportFile($strTemplateFile, $strTranslatedFile = null)
 {
     $intTime = time();
     if ($strTranslatedFile) {
         $arrTransKey = $this->FileAsArray($strTranslatedFile, false);
     }
     $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);
         if (isset($arrTransKey)) {
             $arrTransKey = $this->GetAccessKeys($arrTransKey);
         }
         foreach ($arrSourceKey as $strKey => $objEntity) {
             /* @var $objEntity NarroFileEntity */
             // if it's a matched access key or command key, keep going
             if (isset($objEntity->LabelCtx)) {
                 continue;
             }
             if (strstr($objEntity->Comment, 'DONT_TRANSLATE') !== false) {
                 continue;
             }
             $this->AddTranslation($objEntity->Value, $objEntity->AccessKey, isset($arrTransKey[$strKey]) ? $arrTransKey[$strKey]->Value : null, isset($arrTransKey[$strKey]) ? isset($arrTransKey[$strKey]->AccessKey) ? $arrTransKey[$strKey]->AccessKey : null : null, trim($strKey), isset($objEntity->AccessKeyCtx) ? trim($objEntity->Comment) . "\n" . trim($arrSourceKey[$objEntity->AccessKeyCtx]->Comment) : trim($objEntity->Comment), $objEntity->CommandKey, isset($arrTransKey[$strKey]) ? isset($arrTransKey[$strKey]->CommandKey) ? $arrTransKey[$strKey]->CommandKey : null : null);
         }
     } else {
         NarroLogger::LogWarn(sprintf('Found a empty template (%s), copying the original', $strTemplateFile));
         copy($strTemplateFile, $strTranslatedFile);
         chmod($strTranslatedFile, 0666);
     }
 }
예제 #22
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;
     }
 }
 /**
  * A translation here consists of the project, file, text, translation, context, plurals, approval, ignore equals
  *
  * @param string $strOriginal the original text
  * @param string $strOriginalAccKey access key for the original text
  * @param string $strTranslation the translated text from the import file (can be empty)
  * @param string $strOriginalAccKey access key for the translated text
  * @param string $strContext the context where the text/translation appears in the file
  * @param string $intPluralForm if this is a plural, what plural form is it (0 singular, 1 plural form 1, and so on)
  * @param string $strComment a comment from the imported file
  *
  * @return string valid suggestion
  */
 protected function GetTranslation($strOriginal, $strOriginalAccKey = null, $strOriginalAccKeyPrefix = null, $strTranslation, $strTranslationAccKey = null, $strContext, $strComment = null)
 {
     /**
      * The contexts are trimmed at import to avoid useless white space contexts, so we need to trim it when searching for it as well
      */
     $strContext = trim($strContext);
     if ($strContext != '') {
         $objNarroContextInfo = NarroContextInfo::QuerySingle(QQ::AndCondition(QQ::Equal(QQN::NarroContextInfo()->Context->ProjectId, $this->objProject->ProjectId), QQ::Equal(QQN::NarroContextInfo()->Context->FileId, $this->objFile->FileId), QQ::Equal(QQN::NarroContextInfo()->Context->Active, 1), QQ::Equal(QQN::NarroContextInfo()->Context->File->Active, 1), QQ::Equal(QQN::NarroContextInfo()->Context->TextAccessKey, $strOriginalAccKey), QQ::Equal(QQN::NarroContextInfo()->Context->ContextMd5, md5($strContext)), QQ::Equal(QQN::NarroContextInfo()->Context->Text->TextValueMd5, md5($strOriginal)), QQ::Equal(QQN::NarroContextInfo()->LanguageId, $this->objTargetLanguage->LanguageId)));
     } else {
         $objNarroContextInfo = NarroContextInfo::QuerySingle(QQ::AndCondition(QQ::Equal(QQN::NarroContextInfo()->Context->ProjectId, $this->objProject->ProjectId), QQ::Equal(QQN::NarroContextInfo()->Context->FileId, $this->objFile->FileId), QQ::Equal(QQN::NarroContextInfo()->Context->Active, 1), QQ::Equal(QQN::NarroContextInfo()->Context->File->Active, 1), QQ::Equal(QQN::NarroContextInfo()->Context->TextAccessKey, $strOriginalAccKey), QQ::Equal(QQN::NarroContextInfo()->Context->Text->TextValueMd5, md5($strOriginal)), QQ::Equal(QQN::NarroContextInfo()->LanguageId, $this->objTargetLanguage->LanguageId)));
     }
     if ($objNarroContextInfo instanceof NarroContextInfo) {
         $this->objCurrentContext = $objNarroContextInfo;
         $strSuggestionValue = $this->GetExportedSuggestion($objNarroContextInfo);
         if ($strSuggestionValue !== false) {
             $arrResult = QApplication::$PluginHandler->ExportSuggestion($strOriginal, $strSuggestionValue, $strContext, $this->objFile, $this->objProject);
             if ($arrResult[1] != '' && $arrResult[0] == $strOriginal && $arrResult[2] == $strContext && $arrResult[3] == $this->objFile && $arrResult[4] == $this->objProject) {
                 $strSuggestionValue = $arrResult[1];
             } else {
                 NarroLogger::LogWarn(sprintf('The plugin "%s" returned an unexpected result while processing the suggestion "%s": %s', QApplication::$PluginHandler->CurrentPluginName, $strSuggestionValue, join(';', $arrResult)));
             }
             if (!is_null($strOriginalAccKey) && !is_null($strOriginalAccKeyPrefix)) {
                 /**
                  * @todo don't export if there's no valid access key
                  */
                 $strTextWithAccKey = NarroString::Replace($objNarroContextInfo->SuggestionAccessKey, $strOriginalAccKeyPrefix . $objNarroContextInfo->SuggestionAccessKey, $strSuggestionValue, 1);
                 return $strTextWithAccKey;
             } else {
                 return $strSuggestionValue;
             }
         } else {
             // NarroLogger::LogDebug(sprintf('No translation found for the text "%s", while searching for context "%s"', $strOriginal, $strContext));
             return '';
         }
     } else {
         NarroLogger::LogError(sprintf('No context found for the text "%s", while searching for context "%s"', $strOriginal, $strContext));
         return '';
     }
 }