summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/Translate/specials/SpecialImportTranslations.php
blob: fcdd1ace0a3f3aeef893bc5cd03319c857c1030c (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
<?php
/**
 * Contains logic for special page Special:ImportTranslations.
 *
 * @file
 * @author Niklas Laxström
 * @author Siebrand Mazeland
 * @license GPL-2.0-or-later
 */

/**
 * Special page to import Gettext (.po) files exported using Translate extension.
 * Does not support generic Gettext files.
 *
 * @ingroup SpecialPage TranslateSpecialPage
 */
class SpecialImportTranslations extends SpecialPage {
	/**
	 * Set up and fill some dependencies.
	 */
	public function __construct() {
		parent::__construct( 'ImportTranslations', 'translate-import' );
	}

	public function doesWrites() {
		return true;
	}

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

	/**
	 * Special page entry point.
	 * @param null|string $parameters
	 * @throws PermissionsError
	 */
	public function execute( $parameters ) {
		$this->setHeaders();

		// Security and validity checks
		if ( !$this->userCanExecute( $this->getUser() ) ) {
			$this->displayRestrictionError();

			return;
		}

		if ( !$this->getRequest()->wasPosted() ) {
			$this->outputForm();

			return;
		}

		if ( !$this->getUser()->matchEditToken( $this->getRequest()->getVal( 'token' ) ) ) {
			$this->getOutput()->addWikiMsg( 'session_fail_preview' );
			$this->outputForm();

			return;
		}

		if ( $this->getRequest()->getCheck( 'process' ) ) {
			$data = $this->getCachedData();
			if ( !$data ) {
				$this->getOutput()->addWikiMsg( 'session_fail_preview' );
				$this->outputForm();

				return;
			}
		} else {
			/**
			 * Proceed to loading and parsing if possible
			 * @todo: use a Status object instead?
			 */
			$file = null;
			$msg = $this->loadFile( $file );
			if ( $this->checkError( $msg ) ) {
				return;
			}

			$msg = $this->parseFile( $file );
			if ( $this->checkError( $msg ) ) {
				return;
			}

			$data = $msg[1];
			$this->setCachedData( $data );
		}

		$messages = $data['MESSAGES'];
		$group = $data['METADATA']['group'];
		$code = $data['METADATA']['code'];

		if ( !MessageGroups::exists( $group ) ) {
			$errorWrap = "<div class='error'>\n$1\n</div>";
			$this->getOutput()->wrapWikiMsg( $errorWrap, 'translate-import-err-stale-group' );

			return;
		}

		$importer = new MessageWebImporter( $this->getPageTitle(), $group, $code );
		$alldone = $importer->execute( $messages );

		if ( $alldone ) {
			$this->deleteCachedData();
		}
	}

	/**
	 * Checks for error state from the return value of loadFile and parseFile
	 * functions. Prints the error and the form and returns true if there is an
	 * error. Returns false and does nothing if there is no error.
	 * @param array $msg
	 * @return bool
	 */
	protected function checkError( $msg ) {
		// Give grep a chance to find the usages:
		// translate-import-err-dl-failed, translate-import-err-ul-failed,
		// translate-import-err-invalid-title, translate-import-err-no-such-file,
		// translate-import-err-stale-group, translate-import-err-no-headers,
		// translate-import-err-warnings
		if ( $msg[0] !== 'ok' ) {
			$errorWrap = "<div class='error'>\n$1\n</div>";
			$msg[0] = 'translate-import-err-' . $msg[0];
			$this->getOutput()->wrapWikiMsg( $errorWrap, $msg );
			$this->outputForm();

			return true;
		}

		return false;
	}

	/**
	 * Constructs and outputs file input form with supported methods.
	 */
	protected function outputForm() {
		$this->getOutput()->addModules( 'ext.translate.special.importtranslations' );
		$this->getOutput()->addHelpLink( 'Help:Extension:Translate/Off-line_translation' );
		/**
		 * Ugly but necessary form building ahead, ohoy
		 */
		$this->getOutput()->addHTML(
			Xml::openElement( 'form', [
				'action' => $this->getPageTitle()->getLocalURL(),
				'method' => 'post',
				'enctype' => 'multipart/form-data',
				'id' => 'mw-translate-import',
			] ) .
				Html::hidden( 'token', $this->getUser()->getEditToken() ) .
				Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() ) .
				Xml::inputLabel(
					$this->msg( 'translate-import-from-local' )->text(),
					'upload-local', // name
					'mw-translate-up-local-input', // id
					50, // size
					$this->getRequest()->getText( 'upload-local' ),
					[ 'type' => 'file' ]
				) .
				Xml::submitButton( $this->msg( 'translate-import-load' )->text() ) .
				Xml::closeElement( 'form' )
		);
	}

	/**
	 * Try to get the file data from any of the supported methods.
	 * @param string &$filedata
	 * @return array
	 */
	protected function loadFile( &$filedata ) {
		$filename = $this->getRequest()->getFileTempname( 'upload-local' );

		if ( !is_uploaded_file( $filename ) ) {
			return [ 'ul-failed' ];
		}

		$filedata = file_get_contents( $filename );

		return [ 'ok' ];
	}

	/**
	 * Try parsing file.
	 * @param string $data
	 * @return array
	 */
	protected function parseFile( $data ) {
		/** Construct a dummy group for us...
		 * @todo Time to rethink the interface again?
		 * @var FileBasedMessageGroup $group
		 */
		$group = MessageGroupBase::factory( [
			'FILES' => [
				'class' => 'GettextFFS',
				'CtxtAsKey' => true,
			],
			'BASIC' => [
				'class' => 'FileBasedMessageGroup',
				'namespace' => -1,
			]
		] );

		$ffs = new GettextFFS( $group );
		$data = $ffs->readFromVariable( $data );

		/**
		 * Special data added by GettextFFS
		 */
		$metadata = $data['METADATA'];

		/**
		 * This should catch everything that is not a gettext file exported from us
		 */
		if ( !isset( $metadata['code'] ) || !isset( $metadata['group'] ) ) {
			return [ 'no-headers' ];
		}

		/**
		 * And check for stupid editors that drop msgctxt which
		 * unfortunately breaks submission.
		 */
		if ( isset( $metadata['warnings'] ) ) {
			return [ 'warnings', $this->getLanguage()->commaList( $metadata['warnings'] ) ];
		}

		return [ 'ok', $data ];
	}

	protected function setCachedData( $data ) {
		$key = wfMemcKey( 'translate', 'webimport', $this->getUser()->getId() );
		wfGetCache( CACHE_DB )->set( $key, $data, 60 * 30 );
	}

	protected function getCachedData() {
		$key = wfMemcKey( 'translate', 'webimport', $this->getUser()->getId() );

		return wfGetCache( CACHE_DB )->get( $key );
	}

	protected function deleteCachedData() {
		$key = wfMemcKey( 'translate', 'webimport', $this->getUser()->getId() );

		return wfGetCache( CACHE_DB )->delete( $key );
	}
}