summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/Translate/specials/SpecialManageTranslatorSandbox.php
blob: 28311452cc223b2937c6c370e938a664c3c4759d (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
<?php
/**
 * Contains logic for Special:ManageTranslatorSandbox
 *
 * @file
 * @author Niklas Laxström
 * @author Amir E. Aharoni
 * @license GPL-2.0-or-later
 */

/**
 * Special page for managing sandboxed users.
 *
 * @ingroup SpecialPage TranslateSpecialPage
 */
class SpecialManageTranslatorSandbox extends SpecialPage {
	/** @var TranslationStashStorage */
	protected $stash;

	public function __construct() {
		global $wgTranslateUseSandbox;
		parent::__construct(
			'ManageTranslatorSandbox',
			'translate-sandboxmanage',
			$wgTranslateUseSandbox
		);
	}

	public function doesWrites() {
		return true;
	}

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

	public function execute( $params ) {
		$this->setHeaders();
		$this->checkPermissions();
		$out = $this->getOutput();
		$out->addModuleStyles( [
			'ext.translate.special.managetranslatorsandbox.styles',
			'mediawiki.ui.button',
			'jquery.uls.grid'
		] );
		$out->addModules( 'ext.translate.special.managetranslatorsandbox' );
		$this->stash = new TranslationStashStorage( wfGetDB( DB_MASTER ) );

		$this->prepareForTests();
		$this->showPage();
	}

	/**
	 * Deletes a user page if it exists.
	 * This is needed especially when deleting sandbox users
	 * that were created as part of the integration tests.
	 * @param User $user
	 */
	protected function deleteUserPage( $user ) {
		$userpage = WikiPage::factory( $user->getUserPage() );
		if ( $userpage->exists() ) {
			$dummyError = '';
			$userpage->doDeleteArticleReal(
				wfMessage( 'tsb-delete-userpage-summary' )->inContentLanguage()->text(),
				false,
				0,
				true,
				$dummyError,
				$this->getUser()
			);
		}
	}

	/**
	 * Add users to the sandbox or delete them to facilitate browsers tests.
	 * Use with caution!
	 */
	public function prepareForTests() {
		global $wgTranslateTestUsers;

		$user = $this->getUser();
		$request = $this->getRequest();

		if ( !in_array( $user->getName(), $wgTranslateTestUsers, true ) ) {
			return;
		}

		if ( $request->getVal( 'integrationtesting' ) === 'populate' ) {
			// Empty all the users, even if they were created manually
			// to ensure the number of users is what the tests expect
			$this->emptySandbox();

			$textUsernamePrefixes = [ 'Pupu', 'Orava' ];
			$testLanguages = [ 'fi', 'uk', 'nl', 'he', 'bn' ];
			$testLanguagesCount = count( $testLanguages );

			foreach ( $textUsernamePrefixes as $prefix ) {
				for ( $i = 0; $i < $testLanguagesCount; $i++ ) {
					$name = "$prefix$i";

					// Get rid of users, even if promoted during tests
					$userToDelete = User::newFromName( $name, false );
					$this->deleteUserPage( $userToDelete );
					TranslateSandbox::deleteUser( $userToDelete, 'force' );

					$user = TranslateSandbox::addUser( $name, "$name@blackhole.io", 'porkkana' );
					$user->setOption(
						'translate-sandbox',
						FormatJson::encode( [
							'languages' => [ $testLanguages[$i] ],
							'comment' => '',
						] )
					);

					$reminders = [];
					for ( $reminderIndex = 0; $reminderIndex < $i; $reminderIndex++ ) {
						$reminders[] = wfTimestamp() - $reminderIndex * $i * 10000;
					}

					$user->setOption(
						'translate-sandbox-reminders',
						implode( '|', $reminders )
					);
					$user->saveSettings();

					for ( $j = 0; $j < $i; $j++ ) {
						$title = Title::makeTitle(
							NS_MEDIAWIKI,
							wfRandomString( 24 ) . '/' . $testLanguages[$i]
						);
						$translation = 'plop';
						$stashedTranslation = new StashedTranslation( $user, $title, $translation );
						$this->stash->addTranslation( $stashedTranslation );
					}
				}
			}

			// Another account for testing a translator to multiple languages
			$oldPolyglotUser = User::newFromName( 'Kissa', false );
			$this->deleteUserPage( $oldPolyglotUser );
			TranslateSandbox::deleteUser( $oldPolyglotUser, 'force' );

			$polyglotUser = TranslateSandbox::addUser( 'Kissa', 'kissa@blackhole.io', 'porkkana' );
			$polyglotUser->setOption(
				'translate-sandbox',
				FormatJson::encode( [
					'languages' => $testLanguages,
					'comment' => "I know some languages, and I'm a developer.",
				] )
			);
			$polyglotUser->saveSettings();
			for ( $polyglotLang = 0; $polyglotLang < $testLanguagesCount; $polyglotLang++ ) {
				$title = Title::makeTitle(
					NS_MEDIAWIKI,
					wfRandomString( 24 ) . '/' . $testLanguages[$polyglotLang]
				);
				$translation = "plop in $testLanguages[$polyglotLang]";
				$stashedTranslation = new StashedTranslation( $polyglotUser, $title, $translation );
				$this->stash->addTranslation( $stashedTranslation );
			}
		} elseif ( $request->getVal( 'integrationtesting' ) === 'empty' ) {
			$this->emptySandbox();
		}
	}

	/**
	 * Delete all the users in the sandbox.
	 * Use with caution!
	 * To facilitate browsers tests.
	 */
	protected function emptySandbox() {
		$users = TranslateSandbox::getUsers();
		foreach ( $users as $user ) {
			TranslateSandbox::deleteUser( $user );
		}
	}

	/**
	 * Generates the whole page html and appends it to output
	 */
	protected function showPage() {
		$out = $this->getOutput();

		$nojs = Html::element(
			'div',
			[ 'class' => 'tux-nojs errorbox' ],
			$this->msg( 'tux-nojs' )->plain()
		);
		$out->addHTML( $nojs );

		$out->addHTML( <<<HTML
<div class="grid">
	<div class="row">
		<div class="nine columns pane filter">{$this->makeFilter()}</div>
		<div class="three columns pane search">{$this->makeSearchBox()}</div>
	</div>
	<div class="row tsb-body">
		<div class="four columns pane requests">
			{$this->makeList()}
			<div class="request-footer">
				<span class="selected-counter">
					{$this->msg( 'tsb-selected-count' )->numParams( 0 )->escaped()}
				</span>
				&nbsp;
				<a href="#" class="older-requests-indicator"></a>
			</div>
		</div>
		<div class="eight columns pane details"></div>
	</div>
</div>
HTML
		);
	}

	protected function makeFilter() {
		return $this->msg( 'tsb-filter-pending' )->escaped();
	}

	protected function makeSearchBox() {
		return <<<HTML
<input class="request-filter-box right"
	placeholder="{$this->msg( 'tsb-search-requests' )->escaped()}" type="search">
</input>
HTML;
	}

	protected function makeList() {
		$items = [];
		$requests = [];
		$users = TranslateSandbox::getUsers();

		/** @var User $user */
		foreach ( $users as $user ) {
			$reminders = $user->getOption( 'translate-sandbox-reminders' );
			$reminders = $reminders ? explode( '|', $reminders ) : [];
			$remindersCount = count( $reminders );
			if ( $remindersCount ) {
				$lastReminderTimestamp = new MWTimestamp( end( $reminders ) );
				$lastReminderAgo = htmlspecialchars(
					$lastReminderTimestamp->getHumanTimestamp()
				);
			} else {
				$lastReminderAgo = '';
			}

			$requests[] = [
				'username' => $user->getName(),
				'email' => $user->getEmail(),
				'gender' => $user->getOption( 'gender' ),
				'registrationdate' => $user->getRegistration(),
				'translations' => count( $this->stash->getTranslations( $user ) ),
				'languagepreferences' => FormatJson::decode( $user->getOption( 'translate-sandbox' ) ),
				'userid' => $user->getId(),
				'reminderscount' => $remindersCount,
				'lastreminder' => $lastReminderAgo,
			];
		}

		// Sort the requests based on translations and registration date
		usort( $requests, [ __CLASS__, 'translatorRequestSort' ] );

		foreach ( $requests as $request ) {
			$items[] = $this->makeRequestItem( $request );
		}

		$requestsList = implode( "\n", $items );

		return <<<HTML
<div class="row request-header">
	<div class="four columns">
		<button class="language-selector unselected">
			{$this->msg( 'tsb-all-languages-button-label' )->escaped()}
		</button>
	</div>
	<div class="five columns request-count"></div>
	<div class="three columns center">
		<input class="request-selector-all" name="request" type="checkbox" />
	</div>
</div>
<div class="requests-list">
	{$requestsList}
</div>
HTML;
	}

	protected function makeRequestItem( $request ) {
		$requestdataEnc = htmlspecialchars( FormatJson::encode( $request ) );
		$nameEnc = htmlspecialchars( $request['username'] );
		$nameEncForId = htmlspecialchars( Sanitizer::escapeId( $request['username'], 'noninitial' ) );
		$emailEnc = htmlspecialchars( $request['email'] );
		$countEnc = htmlspecialchars( $request['translations'] );
		$timestamp = new MWTimestamp( $request['registrationdate'] );
		$agoEnc = htmlspecialchars( $timestamp->getHumanTimestamp() );

		return <<<HTML
<div class="row request" data-data="$requestdataEnc" id="tsb-request-$nameEncForId">
	<div class="two columns amount">
		<div class="translation-count">$countEnc</div>
	</div>
	<div class="seven columns request-info">
		<div class="row username">$nameEnc</div>
		<div class="row email">$emailEnc</div>
	</div>
	<div class="three columns approval center">
		<input class="row request-selector" name="request" type="checkbox" />
		<div class="row signup-age">$agoEnc</div>
	</div>
</div>
HTML;
	}

	/**
	 * Sorts groups by descending order of number of translations,
	 * registration date and username
	 *
	 * @since 2013.12
	 * @param array $a Translation request
	 * @param array $b Translation request
	 * @return int comparison result
	 */
	public static function translatorRequestSort( $a, $b ) {
		$translationCountDiff = $b['translations'] - $a['translations'];
		if ( $translationCountDiff !== 0 ) {
			return $translationCountDiff;
		}

		$registrationDateDiff = $b['registrationdate'] - $a['registrationdate'];
		if ( $registrationDateDiff !== 0 ) {
			return $registrationDateDiff;
		}

		return strcmp( $a['username'], $b['username'] );
	}
}