18 public function __construct() {
19 parent::__construct();
20 $this->addDescription(
'Import translations for a CSV file' );
24 'Path to CSV file to import',
30 'The change summary when updating the translations',
37 'User ID of the user performing the import',
44 'Should the import actually be performed',
49 $this->requireExtension(
'Translate' );
52 public function execute() {
53 $csvFilePath = $this->getArg( 0 );
55 $username = $this->getOption(
'user' );
56 $summary = $this->getOption(
'summary' );
59 if ( trim( $summary ) ===
'' ) {
60 $this->fatalError(
'Please provide a non-empty "summary"' );
63 $userFactory = MediaWikiServices::getInstance()->getUserFactory();
64 $user = $userFactory->newFromName( $username );
66 if ( $user ===
null || !$user->isRegistered() ) {
67 $this->fatalError(
"User $username does not exist." );
71 $csvImporter = Services::getInstance()->getCsvTranslationImporter();
72 $status = $csvImporter->parseFile( $csvFilePath );
74 if ( $status->isOK() ) {
75 $messagesWithTranslations = $status->getValue();
77 foreach ( $messagesWithTranslations as $messageTranslations ) {
78 $translations = $messageTranslations[
'translations' ];
79 $output .=
'* ' . count( $this->filterEmptyTranslations( $translations ) ) .
80 ' translation(s) to import for ' .
81 $messageTranslations[
'messageTitle'] .
"\n";
84 $this->output( $output .
"\n" );
86 $this->error(
"Error during processing:\n" );
87 $this->error( (
string)$status );
88 $this->fatalError(
'Exiting...' );
91 if ( !$this->hasOption(
'really' ) ) {
92 $this->output(
"\nUse option --really to perform the import.\n" );
97 $this->output(
"\nProceeding with import...\n\n" );
98 $importStatus = $csvImporter->importData(
99 $status->getValue(), $user, trim( $summary ), [ $this,
'progressReporter' ]
102 if ( $importStatus->isOK() ) {
103 $this->output(
"\nSuccess: Import done\n" );
105 $this->output(
"\nImport failed. See errors:\n" );
106 $failedImportStatuses = $importStatus->getValue();
107 foreach ( $failedImportStatuses as $translationTitleText => $status ) {
108 $this->output(
"\nImport failed for $translationTitleText:\n" );
109 $this->output( $status );
118 public function progressReporter(
120 array $messageImportStatuses,
124 $paddedProcessed = str_pad( (
string)$processed, strlen( (
string)$total ),
' ', STR_PAD_LEFT );
125 $progressCounter =
"($paddedProcessed/$total)";
129 foreach ( $messageImportStatuses as $messageImportStatus ) {
130 if ( $messageImportStatus->isOK() ) {
138 "$progressCounter Imported translations for {$title->getPrefixedText()} with $failCount " .
139 "failure(s) and $successCount successful import(s) ...\n"
143 private function filterEmptyTranslations( array $translations ): array {
144 return array_filter( $translations,
'strlen' );