summaryrefslogtreecommitdiff
blob: dbb38d00c23d9b51ad28cc6fc762dc7c80a7f5fa (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
<?php
/**
 * API module for managing message group changes
 * @file
 * @author Abijeet Patro
 * @license GPL-2.0-or-later
 */

use MediaWiki\Extension\Translate\MessageSync\MessageSourceChange;
use MediaWiki\Extension\Translate\Utilities\StringComparators\SimpleStringComparator;

/**
 * API module for managing message group changes.
 * Marks message as a rename of another message or as a new message.
 * Updates the cdb file.
 * @since 2019.10
 * @license GPL-2.0-or-later
 * @ingroup API TranslateAPI
 */
class ApiManageMessageGroups extends ApiBase {
	private const RIGHT = 'translate-manage';

	public function execute() {
		$this->checkUserRightsAny( self::RIGHT );
		$params = $this->extractRequestParams();

		$groupId = $params['groupId'];
		$op = $params['operation'];
		$msgKey = $params['messageKey'];
		$name = $params['changesetName'] ?? MessageChangeStorage::DEFAULT_NAME;
		$changesetModifiedTime = $params['changesetModified'];
		$renameKey = null;

		if ( !MessageChangeStorage::isValidCdbName( $name ) ) {
			$this->dieWithError(
				[ 'apierror-translate-invalid-changeset-name', wfEscapeWikiText( $name ) ],
				'invalidchangeset'
			);
		}
		$cdbPath = MessageChangeStorage::getCdbPath( $name );

		if ( !MessageChangeStorage::isModifiedSince( $cdbPath, $changesetModifiedTime ) ) {
			// Changeset file has been modified since the time the page was generated.
			$this->dieWithError( [ 'apierror-translate-changeset-modified' ] );
		}

		if ( $op === 'rename' ) {
			if ( !isset( $params['renameMessageKey'] ) ) {
				$this->dieWithError( [ 'apierror-missingparam', 'renameMessageKey' ] );
			}
			$renameKey = $params['renameMessageKey'];
		}

		$sourceChanges = MessageChangeStorage::getGroupChanges( $cdbPath, $groupId );
		if ( $sourceChanges->getAllModifications() === [] ) {
			$this->dieWithError( [ 'apierror-translate-smg-nochanges' ] );
		}

		$group = MessageGroups::getGroup( $groupId );
		if ( $group === null ) {
			$this->dieWithError( 'apierror-translate-invalidgroup', 'invalidgroup' );
		}

		try {
			if ( $op === 'rename' ) {
				$this->handleRename(
					$group, $sourceChanges, $msgKey, $renameKey, $group->getSourceLanguage()
				);
			} elseif ( $op === 'new' ) {
				$this->handleNew( $sourceChanges, $msgKey, $group->getSourceLanguage() );
			} else {
				$this->dieWithError(
					[ 'apierror-translate-invalid-operation', wfEscapeWikiText( $op ),
						wfEscapeWikiText( implode( '/', [ 'new' , 'rename' ] ) ) ],
					'invalidoperation'
				);
			}
		} catch ( Exception $ex ) {
			// Log necessary parameters and rethrow.
			$data = [
				'op' => $op,
				'msgKey' => $msgKey,
				'renameKey' => $renameKey,
				'groupId' => $group->getId(),
				'group' => $group->getLabel(),
				'groupSourceLang' => $group->getSourceLanguage(),
				'exception' => $ex
			];

			error_log(
				"Error while running: ApiManageMessageGroups::execute. Inputs: \n" .
				FormatJson::encode( $data, true )
			);

			throw $ex;
		}

		// Write the source changes back to file.
		MessageChangeStorage::writeGroupChanges( $sourceChanges, $groupId, $cdbPath );

		$this->getResult()->addValue( null, $this->getModuleName(), [
			'success' => 1
		] );
	}

	/**
	 * Handles rename requests
	 * @param MessageGroup $group
	 * @param MessageSourceChange $sourceChanges
	 * @param string $msgKey New rename key
	 * @param string $renameKey Target key being renamed
	 * @param string $sourceLanguage
	 */
	protected function handleRename( MessageGroup $group, MessageSourceChange $sourceChanges,
		$msgKey, $renameKey, $sourceLanguage
	) {
		$languages = $sourceChanges->getLanguages();

		foreach ( $languages as $code ) {
			$msgState = $renameMsgState = null;

			$isSourceLang = $sourceLanguage === $code;
			if ( $isSourceLang ) {
				$this->handleSourceRename( $sourceChanges, $code, $msgKey, $renameKey );
				continue;
			}

			// Check for changes with the new key, then with the old key.
			// If there are no changes, we won't find anything at all, and
			// can skip this languageCode.
			$msg = $sourceChanges->findMessage( $code, $msgKey, [
				MessageSourceChange::ADDITION,
				MessageSourceChange::RENAME
			], $msgState );

			// This case will arise if the message key has been changed in the source
			// language, but has not been modified in this language code.
			// NOTE: We are also searching under deletions. This means that if the source
			// language key is renamed, but one of the non source language keys is removed,
			// renaming it will not remove the translation, but only rename it. This
			// scenario is highly unlikely though.
			$msg = $msg ?? $sourceChanges->findMessage( $code, $renameKey, [
				MessageSourceChange::DELETION,
				MessageSourceChange::CHANGE,
				MessageSourceChange::RENAME
			], $msgState );

			if ( $msg === null ) {
				continue;
			}

			// Check for the renamed message in the rename list, and deleted list.
			$renameMsg = $sourceChanges->findMessage(
				$code, $renameKey, [ MessageSourceChange::RENAME, MessageSourceChange::DELETION ],
				$renameMsgState
			);

			// content / msg will not be present if the message was deleted from the wiki or
			// was for some reason unavailable during processing incoming changes. We're going
			// to try and load it here again from the database. Very rare chance of this happening.
			if ( $renameMsg === null || !isset( $renameMsg['content'] ) ) {
				$title = Title::newFromText(
					TranslateUtils::title( $renameKey, $code, $group->getNamespace() ),
					$group->getNamespace()
				);

				$renameContent = TranslateUtils::getContentForTitle( $title, true ) ?? '';

				$renameMsg = [
					'key' => $renameKey,
					'content' => $renameContent
				];

				// If the message was found in changes, this will be set, otherwise set it
				// to none
				if ( $renameMsgState === null ) {
					$renameMsgState = MessageSourceChange::NONE;
				}
			}

			// Remove previous states
			if ( $msgState === MessageSourceChange::RENAME ) {
				$msgState = $sourceChanges->breakRename( $code, $msg['key'] );
			} else {
				$sourceChanges->removeBasedOnType( $code, [ $msg['key'] ], $msgState );
			}

			if ( $renameMsgState === MessageSourceChange::RENAME ) {
				$renameMsgState = $sourceChanges->breakRename( $code, $renameMsg['key'] );
			} elseif ( $renameMsgState !== MessageSourceChange::NONE ) {
				$sourceChanges->removeBasedOnType( $code, [ $renameKey ], $renameMsgState );
			}

			// This is done in case the key has not been renamed in the non-source language.
			$msg['key'] = $msgKey;

			// Add as rename
			$stringComparator = new SimpleStringComparator();
			$similarity = $stringComparator->getSimilarity(
				$msg['content'],
				$renameMsg['content']
			);
			$sourceChanges->addRename( $code, $msg, $renameMsg, $similarity );
			$sourceChanges->setRenameState( $code, $msgKey, $msgState );
			$sourceChanges->setRenameState( $code, $renameKey, $renameMsgState );
		}
	}

	protected function handleSourceRename( MessageSourceChange $sourceChanges, $code,
		$msgKey, $renameKey
	) {
		$msgState = $renameMsgState = null;

		$msg = $sourceChanges->findMessage(
			$code, $msgKey, [ MessageSourceChange::ADDITION, MessageSourceChange::RENAME ], $msgState
		);

		$renameMsg = $sourceChanges->findMessage(
			$code,
			$renameKey,
			[ MessageSourceChange::DELETION, MessageSourceChange::RENAME ],
			$renameMsgState
		);

		if ( $msg === null || $renameMsg === null ) {
			$this->dieWithError( 'apierror-translate-rename-key-invalid' );
		}

		if ( $msgState === MessageSourceChange::RENAME ) {
			// @phan-suppress-next-line PhanTypeArraySuspiciousNullable T240141
			$msgState = $sourceChanges->breakRename( $code, $msg['key'] );
		}

		if ( $renameMsgState === MessageSourceChange::RENAME ) {
			// @phan-suppress-next-line PhanTypeArraySuspiciousNullable T240141
			$renameMsgState = $sourceChanges->breakRename( $code, $renameMsg['key'] );
		}

		// Ensure that one of them is an ADDITION, and one is DELETION
		if ( $msgState !== MessageSourceChange::ADDITION ||
			$renameMsgState !== MessageSourceChange::DELETION ) {
			$this->dieWithError( [
				'apierror-translate-rename-state-invalid',
				wfEscapeWikiText( $msgState ), wfEscapeWikiText( $renameMsgState )
			] );
		}

		// Remove previous states
		$sourceChanges->removeAdditions( $code, [ $msgKey ] );
		$sourceChanges->removeDeletions( $code, [ $renameKey ] );

		// Add as rename
		$stringComparator = new SimpleStringComparator();
		$similarity = $stringComparator->getSimilarity(
			// @phan-suppress-next-line PhanTypeArraySuspiciousNullable T240141
			$msg['content'],
			// @phan-suppress-next-line PhanTypeArraySuspiciousNullable T240141
			$renameMsg['content']
		);
		$sourceChanges->addRename( $code, $msg, $renameMsg, $similarity );
	}

	/**
	 * Handles add message as new request
	 * @param MessageSourceChange $sourceChanges
	 * @param string $msgKey
	 * @param string $sourceLang
	 */
	protected function handleNew( MessageSourceChange $sourceChanges, $msgKey, $sourceLang ) {
		$msgState = null;
		$languages = $sourceChanges->getLanguages();

		foreach ( $languages as $code ) {
			$msg = $sourceChanges->findMessage(
				$code, $msgKey, [ MessageSourceChange::RENAME ], $msgState
			);

			if ( $code === $sourceLang && $msg === null ) {
				$this->dieWithError( 'apierror-translate-addition-key-invalid' );
			}

			if ( $code === $sourceLang && $msgState !== MessageSourceChange::RENAME ) {
				$this->dieWithError( 'apierror-translate-rename-msg-new' );
			}

			// For any other language, its possible for the message to be not found.
			if ( $msg === null ) {
				continue;
			}

			// breakRename will add the message back to its previous state, nothing more to do
			$sourceChanges->breakRename( $code, $msg['key'] );
		}
	}

	protected function getAllowedParams() {
		return [
			'groupId' => [
				ApiBase::PARAM_TYPE => 'string',
				ApiBase::PARAM_REQUIRED => true,
			],
			'renameMessageKey' => [
				ApiBase::PARAM_TYPE => 'string',
				ApiBase::PARAM_REQUIRED => false,
			],
			'messageKey' => [
				ApiBase::PARAM_TYPE => 'string',
				ApiBase::PARAM_REQUIRED => true,
			],
			'operation' => [
				ApiBase::PARAM_TYPE => [ 'rename', 'new' ],
				ApiBase::PARAM_ISMULTI => false,
				ApiBase::PARAM_REQUIRED => true,
			],
			'changesetName' => [
				ApiBase::PARAM_TYPE => 'string',
				ApiBase::PARAM_DFLT => MessageChangeStorage::DEFAULT_NAME
			],
			'changesetModified' => [
				ApiBase::PARAM_TYPE => 'integer',
				ApiBase::PARAM_REQUIRED => true,
			]
		];
	}

	public function isInternal() {
		return true;
	}

	public function needsToken() {
		return 'csrf';
	}
}