summaryrefslogtreecommitdiff
blob: 837ffc17cb7458f59cde93a562d9b0192b0d0a70 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
<?php
declare( strict_types = 1 );

namespace MediaWiki\Extension\Translate\Synchronization;

use FileBasedMessageGroup;
use GettextFFS;
use Html;
use HTMLForm;
use LogicException;
use MediaWiki\Extension\Translate\PageTranslation\TranslatablePage;
use Message;
use MessageCollection;
use MessageGroup;
use MessageGroups;
use MessageHandle;
use Parser;
use SpecialPage;
use Status;
use Title;
use TitleFormatter;
use TranslateUtils;
use WikiPageMessageGroup;

/**
 * This special page allows exporting groups for offline translation.
 *
 * @author Niklas Laxström
 * @author Siebrand Mazeland
 * @license GPL-2.0-or-later
 * @ingroup SpecialPage TranslateSpecialPage
 */
class ExportTranslationsSpecialPage extends SpecialPage {
	/** Maximum size of a group until exporting is not allowed due to performance reasons. */
	public const MAX_EXPORT_SIZE = 10000;
	/** @var string */
	protected $language;
	/** @var string */
	protected $format;
	/** @var string */
	protected $groupId;
	/** @var TitleFormatter */
	private $titleFormatter;
	/** @var Parser */
	private $parser;
	/** @var string[] */
	private const VALID_FORMATS = [ 'export-as-po', 'export-to-file', 'export-as-csv' ];

	public function __construct( TitleFormatter $titleFormatter, Parser $parser ) {
		parent::__construct( 'ExportTranslations' );
		$this->titleFormatter = $titleFormatter;
		$this->parser = $parser;
	}

	/** @param null|string $par */
	public function execute( $par ) {
		$out = $this->getOutput();
		$request = $this->getRequest();
		$lang = $this->getLanguage();

		$this->setHeaders();

		$this->groupId = $request->getText( 'group', $par ?? '' );
		$this->language = $request->getVal( 'language', $lang->getCode() );
		$this->format = $request->getText( 'format' );

		$this->outputForm();

		if ( $this->groupId ) {
			$status = $this->checkInput();
			if ( !$status->isGood() ) {
				$out->wrapWikiTextAsInterface(
					'error',
					$status->getWikiText( false, false, $lang )
				);
				return;
			}

			$this->doExport();
		}
	}

	private function outputForm(): void {
		$fields = [
			'group' => [
				'type' => 'select',
				'name' => 'group',
				'id' => 'group',
				'label-message' => 'translate-page-group',
				'options' => $this->getGroupOptions(),
				'default' => $this->groupId,
			],
			'language' => [
				// @todo Apply ULS to this field
				'type' => 'select',
				'name' => 'language',
				'id' => 'language',
				'label-message' => 'translate-page-language',
				'options' => $this->getLanguageOptions(),
				'default' => $this->language,
			],
			'format' => [
				'type' => 'radio',
				'name' => 'format',
				'id' => 'format',
				'label-message' => 'translate-export-form-format',
				'flatlist' => true,
				'options' => $this->getFormatOptions(),
				'default' => $this->format,
			],
		];
		HTMLForm::factory( 'ooui', $fields, $this->getContext() )
			->setMethod( 'get' )
			->setWrapperLegendMsg( 'translate-page-settings-legend' )
			->setSubmitTextMsg( 'translate-submit' )
			->prepareForm()
			->displayForm( false );
	}

	private function getGroupOptions(): array {
		$selected = $this->groupId;
		$groups = MessageGroups::getAllGroups();
		uasort( $groups, [ MessageGroups::class, 'groupLabelSort' ] );

		$options = [];
		foreach ( $groups as $id => $group ) {
			if ( !$group->exists()
				|| ( MessageGroups::getPriority( $group ) === 'discouraged' && $id !== $selected )
			) {
				continue;
			}

			$options[$group->getLabel()] = $id;
		}

		return $options;
	}

	/** @return string[] */
	private function getLanguageOptions(): array {
		$languages = TranslateUtils::getLanguageNames( 'en' );
		$options = [];
		foreach ( $languages as $code => $name ) {
			$options["$code - $name"] = $code;
		}

		return $options;
	}

	/** @return string[] */
	private function getFormatOptions(): array {
		$options = [];
		foreach ( self::VALID_FORMATS as $format ) {
			// translate-taskui-export-to-file, translate-taskui-export-as-po
			$options[ $this->msg( "translate-taskui-$format" )->escaped() ] = $format;
		}
		return $options;
	}

	private function checkInput(): Status {
		$status = Status::newGood();

		$msgGroup = MessageGroups::getGroup( $this->groupId );
		if ( $msgGroup === null ) {
			$status->fatal( 'translate-page-no-such-group' );
		} elseif ( MessageGroups::isDynamic( $msgGroup ) ) {
			$status->fatal( 'translate-export-not-supported' );
		}

		$langNames = TranslateUtils::getLanguageNames( 'en' );
		if ( !isset( $langNames[$this->language] ) ) {
			$status->fatal( 'translate-page-no-such-language' );
		}

		// Do not show this error if invalid format is specified for translatable page
		// groups as we can show a textarea box containing the translation page text
		// (however it's not currently supported for other groups).
		if (
			!$msgGroup instanceof WikiPageMessageGroup
			&& $this->format
			&& !in_array( $this->format, self::VALID_FORMATS )
		) {
			$status->fatal( 'translate-export-invalid-format' );
		}

		if ( $this->format === 'export-to-file'
			&& !$msgGroup instanceof FileBasedMessageGroup
		) {
			$status->fatal( 'translate-export-format-notsupported' );
		}

		if ( $msgGroup && !MessageGroups::isDynamic( $msgGroup ) ) {
			$size = count( $msgGroup->getKeys() );
			if ( $size > self::MAX_EXPORT_SIZE ) {
				$status->fatal(
					'translate-export-group-too-large',
					Message::numParam( self::MAX_EXPORT_SIZE )
				);
			}
		}

		return $status;
	}

	private function doExport(): void {
		$out = $this->getOutput();
		$group = MessageGroups::getGroup( $this->groupId );
		$collection = $this->setupCollection( $group );

		switch ( $this->format ) {
			case 'export-as-po':
				$out->disable();

				$ffs = null;
				if ( $group instanceof FileBasedMessageGroup ) {
					$ffs = $group->getFFS();
				}

				if ( !$ffs instanceof GettextFFS ) {
					if ( !$group instanceof FileBasedMessageGroup ) {
						$group = FileBasedMessageGroup::newFromMessageGroup( $group );
					}

					$ffs = new GettextFFS( $group );
				}

				$ffs->setOfflineMode( true );

				$filename = "{$group->getId()}_{$this->language}.po";
				$this->sendExportHeaders( $filename );

				echo $ffs->writeIntoVariable( $collection );
				break;

			case 'export-to-file':
				$out->disable();

				// This will never happen since its checked previously but add the check to keep
				// phan and IDE happy. See checkInput method
				if ( !$group instanceof FileBasedMessageGroup ) {
					throw new LogicException(
						"'export-to-file' requested for a non FileBasedMessageGroup {$group->getId()}"
					);
				}

				$filename = basename( $group->getSourceFilePath( $collection->getLanguage() ) );
				$this->sendExportHeaders( $filename );

				echo $group->getFFS()->writeIntoVariable( $collection );
				break;

			case 'export-as-csv':
				$out->disable();
				$filename = "{$group->getId()}_{$this->language}.csv";
				$this->sendExportHeaders( $filename );
				$this->exportCSV( $collection, $group->getSourceLanguage() );
				break;

			default:
				// @todo Add web viewing for groups other than WikiPageMessageGroup
				if ( !$group instanceof WikiPageMessageGroup ) {
					return;
				}

				$translatablePage = TranslatablePage::newFromTitle( $group->getTitle() );
				$translationPage = $translatablePage->getTranslationPage( $collection->getLanguage() );

				$translationPage->filterMessageCollection( $collection );
				$messages = $translationPage->extractMessages( $collection );
				$text = $translationPage->generateSourceFromTranslations( $this->parser, $messages );

				$displayTitle = $translatablePage->getPageDisplayTitle( $this->language );
				if ( $displayTitle ) {
					$text = "{{DISPLAYTITLE:$displayTitle}}$text";
				}

				$box = Html::element(
					'textarea',
					[ 'id' => 'wpTextbox', 'rows' => 40, ],
					$text
				);
				$out->addHTML( $box );

		}
	}

	private function setupCollection( MessageGroup $group ): MessageCollection {
		$collection = $group->initCollection( $this->language );

		// Don't export ignored, unless it is the source language or message documentation
		$translateDocCode = $this->getConfig()->get( 'TranslateDocumentationLanguageCode' );
		if ( $this->language !== $translateDocCode
			&& $this->language !== $group->getSourceLanguage()
		) {
			$collection->filter( 'ignored' );
		}

		$collection->loadTranslations();

		return $collection;
	}

	/** Send the appropriate response headers for the export */
	private function sendExportHeaders( string $fileName ): void {
		$response = $this->getRequest()->response();
		$response->header( 'Content-Type: text/plain; charset=UTF-8' );
		$response->header( "Content-Disposition: attachment; filename=\"$fileName\"" );
	}

	private function exportCSV( MessageCollection $collection, string $sourceLanguageCode ): void {
		$fp = fopen( 'php://output', 'w' );
		$exportingSourceLanguage = $sourceLanguageCode === $this->language;

		$header = [
			$this->msg( 'translate-export-csv-message-title' )->text(),
			$this->msg( 'translate-export-csv-definition' )->text()
		];

		if ( !$exportingSourceLanguage ) {
			$header[] = $this->language;
		}

		fputcsv( $fp, $header );

		foreach ( $collection->keys() as $messageKey => $titleValue ) {
			$message = $collection[ $messageKey ];
			$prefixedTitleText = $this->titleFormatter->getPrefixedText( $titleValue );

			$handle = new MessageHandle( Title::newFromText( $prefixedTitleText ) );
			$sourceLanguageTitle = $handle->getTitleForLanguage( $sourceLanguageCode );

			$row = [ $sourceLanguageTitle->getPrefixedText(), $message->definition() ];

			if ( !$exportingSourceLanguage ) {
				$row[] = $message->translation();
			}

			fputcsv( $fp, $row );
		}

		fclose( $fp );
	}

	protected function getGroupName() {
		return 'translation';
	}
}