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;
 }
 protected function FileAsArray($strFile, $blnNoHeader = false)
 {
     $intTime = time();
     if (!file_exists($strFile)) {
         NarroLogger::LogInfo(sprintf(t('%s does not exist'), $strFile));
         return false;
     }
     $strFileContent = file_get_contents($strFile);
     if (!$strFileContent) {
         NarroLogger::LogInfo(sprintf(t('%s is empty'), $strFile));
         return false;
     }
     $strFileContent = $this->PreProcessFile($strFileContent);
     $arrFile = explode("\n", $strFileContent);
     unset($strFileContent);
     $arrKeys = array();
     $strPreviousLines = '';
     $strFileHeader = '';
     foreach ($arrFile as $intPos => $strLine) {
         if ($this->blnIsHeader) {
             $this->objFile->Header = $strPreviousLines;
             $this->objFile->Save();
             $this->blnIsHeader = false;
             $strPreviousLines = '';
         }
         $strPreProcessedLine = $this->PreProcessLine($strLine);
         $strLineToProcess = $strPreviousLines . $strPreProcessedLine;
         $mixResult = $this->ProcessLine($strLineToProcess);
         if ($mixResult instanceof NarroFileEntity) {
             $strLastKey = $mixResult->Key;
             $arrKeys[$mixResult->Key] = $mixResult;
             $strPreviousLines = '';
             $this->blnFirstEntityFound = true;
         } else {
             $strPreviousLines = $strPreviousLines . $strLine . "\n";
         }
     }
     if (!$this->blnHeaderFound) {
         $this->objFile->Header = null;
         $this->objFile->Save();
     }
     foreach ($arrKeys as $strKey => $objEntity) {
         /* @var $objEntity NarroFileEntity */
         if (isset($strLastKey) && $strKey != $strLastKey) {
             $arrKeys[$strKey]->AfterValue .= "\n";
         }
     }
     if (isset($strLastKey) && $strPreviousLines) {
         $arrKeys[$strLastKey]->AfterValue .= "\n" . $strPreviousLines;
     }
     // NarroLogger::LogDebug(sprintf('Converted file to array in %s second(s)', (time() - $intTime)));
     return $arrKeys;
 }
Beispiel #3
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;
    }
}
 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;
 }
Beispiel #5
0
                    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));
Beispiel #6
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;
         }
     }
 }
 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 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);
             }
         }
     }
 }
 public function btnKillProcess_Click($strFormId, $strControlId, $strParameter)
 {
     $strProcLogFile = __TMP_PATH__ . '/' . $this->objProject->ProjectId . '-' . QApplication::$TargetLanguage->LanguageCode . '-export-process.log';
     $strProcPidFile = __TMP_PATH__ . '/' . $this->objProject->ProjectId . '-' . QApplication::$TargetLanguage->LanguageCode . '-export-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::LogInfo('Process killed');
         } else {
             NarroLogger::LogInfo('Failed to kill process');
         }
         if (file_exists($strProcLogFile) && filesize($strProcLogFile)) {
             NarroLogger::LogInfo(sprintf('There are messages from the background process: %s', file_get_contents($strProcLogFile)));
         }
         $this->pnlLogViewer->MarkAsModified();
     }
 }