summaryrefslogtreecommitdiff
blob: 977011c3e9bb9bcd2e33c7d9c27d8bbbf44895c5 (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
<?php
/**
 * Command line script to mark translations fuzzy (similar to gettext fuzzy).
 *
 * @file
 * @author Niklas Laxström
 * @author Siebrand Mazeland
 * @copyright Copyright © 2007-2013, Niklas Laxström, Siebrand Mazeland
 * @license GPL-2.0-or-later
 */

// Standard boilerplate to define $IP
if ( getenv( 'MW_INSTALL_PATH' ) !== false ) {
	$IP = getenv( 'MW_INSTALL_PATH' );
} else {
	$dir = __DIR__;
	$IP = "$dir/../../..";
}
require_once "$IP/maintenance/Maintenance.php";

# Override the memory limit for wfShellExec, 100 MB appears to be too little
$wgMaxShellMemory = 1024 * 200;

class Fuzzy extends Maintenance {
	public function __construct() {
		parent::__construct();
		$this->mDescription = 'Fuzzy bot command line script.';
		$this->addArg(
			'arg',
			'Title pattern or username if user option is provided.'
		);
		$this->addOption(
			'really',
			'(optional) Really fuzzy, no dry-run'
		);
		$this->addOption(
			'skiplanguages',
			'(optional) Skip some languages (comma separated)',
			false, /*required*/
			true /*has arg*/
		);
		$this->addOption(
			'comment',
			'(optional) Comment for updating',
			false, /*required*/
			true /*has arg*/
		);
		$this->addOption(
			'user',
			'(optional) Fuzzy the translations made by user given as an argument.',
			false, /*required*/
			false /*has arg*/
		);
	}

	public function execute() {
		$skipLanguages = [];
		if ( $this->hasOption( 'skiplanguages' ) ) {
			$skipLanguages = array_map(
				'trim',
				explode( ',', $this->getOption( 'skiplanguages' ) )
			);
		}

		if ( $this->hasOption( 'user' ) ) {
			$user = User::newFromName( $this->getArg( 0 ) );
			$pages = FuzzyScript::getPagesForUser( $user, $skipLanguages );
		} else {
			$pages = FuzzyScript::getPagesForPattern( $this->getArg( 0 ), $skipLanguages );
		}

		$bot = new FuzzyScript( $pages );
		$bot->comment = $this->getOption( 'comment' );
		$bot->dryrun = !$this->hasOption( 'really' );
		$bot->setProgressCallback( [ $this, 'myOutput' ] );
		$bot->execute();
	}

	/**
	 * Public alternative for protected Maintenance::output() as we need to get
	 * messages from the ChangeSyncer class to the commandline.
	 * @param string $text The text to show to the user
	 * @param string|null $channel Unique identifier for the channel.
	 * @param bool $error Whether this is an error message
	 */
	public function myOutput( $text, $channel = null, $error = false ) {
		if ( $error ) {
			$this->error( $text, $channel );
		} else {
			$this->output( $text, $channel );
		}
	}
}

/**
 * Class for marking translation fuzzy.
 */
class FuzzyScript {
	/**
	 * @var bool Check for configuration problems.
	 */
	private $allclear = false;

	/** @var callable Function to report progress updates */
	protected $progressCallback;

	/**
	 * @var bool Dont do anything unless confirmation is given
	 */
	public $dryrun = true;

	/**
	 * @var string Edit summary.
	 */
	public $comment;

	/**
	 * @param array $pages
	 */
	public function __construct( $pages ) {
		$this->pages = $pages;
		$this->allclear = true;
	}

	public function setProgressCallback( $callback ) {
		$this->progressCallback = $callback;
	}

	/// @see Maintenance::output for param docs
	protected function reportProgress( $text, $channel, $severity = 'status' ) {
		if ( is_callable( $this->progressCallback ) ) {
			$useErrorOutput = $severity === 'error';
			call_user_func( $this->progressCallback, $text, $channel, $useErrorOutput );
		}
	}

	public function execute() {
		if ( !$this->allclear ) {
			return;
		}

		$msgs = $this->pages;
		$count = count( $msgs );
		$this->reportProgress( "Found $count pages to update.", 'pagecount' );

		foreach ( $msgs as $phpIsStupid ) {
			list( $title, $text ) = $phpIsStupid;
			$this->updateMessage( $title, TRANSLATE_FUZZY . $text, $this->dryrun, $this->comment );
			unset( $phpIsStupid );
		}
	}

	/// Searches pages that match given patterns
	public static function getPagesForPattern( $pattern, $skipLanguages = [] ) {
		global $wgTranslateMessageNamespaces;
		$dbr = wfGetDB( DB_REPLICA );

		$search = [];
		foreach ( (array)$pattern as $title ) {
			$title = Title::newFromText( $title );
			$ns = $title->getNamespace();
			if ( !isset( $search[$ns] ) ) {
				$search[$ns] = [];
			}
			$search[$ns][] = 'page_title' . $dbr->buildLike( $title->getDBkey(), $dbr->anyString() );
		}

		$title_conds = [];
		foreach ( $search as $ns => $names ) {
			if ( $ns === NS_MAIN ) {
				$ns = $wgTranslateMessageNamespaces;
			}
			$titles = $dbr->makeList( $names, LIST_OR );
			$title_conds[] = $dbr->makeList( [ 'page_namespace' => $ns, $titles ], LIST_AND );
		}

		$conds = [
			'page_latest=rev_id',
			'rev_text_id=old_id',
			$dbr->makeList( $title_conds, LIST_OR ),
		];

		if ( count( $skipLanguages ) ) {
			$skiplist = $dbr->makeList( $skipLanguages );
			$conds[] = "substring_index(page_title, '/', -1) NOT IN ($skiplist)";
		}

		$rows = $dbr->select(
			[ 'page', 'revision', 'text' ],
			[ 'page_title', 'page_namespace', 'old_text', 'old_flags' ],
			$conds,
			__METHOD__
		);

		$messagesContents = [];
		foreach ( $rows as $row ) {
			$title = Title::makeTitle( $row->page_namespace, $row->page_title );
			$messagesContents[] = [ $title, Revision::getRevisionText( $row ) ];
		}

		$rows->free();

		return $messagesContents;
	}

	public static function getPagesForUser( User $user, $skipLanguages = [] ) {
		global $wgTranslateMessageNamespaces;
		$dbr = wfGetDB( DB_REPLICA );

		if ( class_exists( ActorMigration::class ) ) {
			$revWhere = ActorMigration::newMigration()->getWhere( $dbr, 'rev_user', $user );
		} else {
			$revWhere = [
				'tables' => [],
				'conds' => 'rev_user = ' . (int)$user->getId(),
				'joins' => [],
			];
		}

		$conds = [
			$revWhere['conds'],
			'page_namespace' => $wgTranslateMessageNamespaces,
			'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() ),
		];

		if ( count( $skipLanguages ) ) {
			$skiplist = $dbr->makeList( $skipLanguages );
			$conds[] = "substring_index(page_title, '/', -1) NOT IN ($skiplist)";
		}

		$rows = $dbr->select(
			[ 'page', 'revision', 'text' ] + $revWhere['tables'],
			[ 'page_title', 'page_namespace', 'old_text', 'old_flags' ],
			$conds,
			__METHOD__,
			[],
			[
				'revision' => [ 'JOIN', 'page_latest=rev_id' ],
				'text' => [ 'JOIN', 'rev_text_id=old_id' ],
			] + $revWhere['joins']
		);

		$messagesContents = [];
		foreach ( $rows as $row ) {
			$title = Title::makeTitle( $row->page_namespace, $row->page_title );
			$messagesContents[] = [ $title, Revision::getRevisionText( $row ) ];
		}

		$rows->free();

		return $messagesContents;
	}

	/**
	 * Does the actual edit if possible.
	 * @param Title $title
	 * @param string $text
	 * @param bool $dryrun Whether to really do it or just show what would be done.
	 * @param string $comment Edit summary.
	 */
	private function updateMessage( $title, $text, $dryrun, $comment = null ) {
		global $wgTranslateDocumentationLanguageCode;

		$this->reportProgress( "Updating {$title->getPrefixedText()}... ", $title );
		if ( !$title instanceof Title ) {
			$this->reportProgress( 'INVALID TITLE!', $title );

			return;
		}

		$items = explode( '/', $title->getText(), 2 );
		if ( isset( $items[1] ) && $items[1] === $wgTranslateDocumentationLanguageCode ) {
			$this->reportProgress( 'IGNORED!', $title );

			return;
		}

		if ( $dryrun ) {
			$this->reportProgress( 'DRY RUN!', $title );

			return;
		}

		$wikipage = new WikiPage( $title );
		$content = ContentHandler::makeContent( $text, $title );
		$status = $wikipage->doEditContent(
			$content,
			$comment ? $comment : 'Marking as fuzzy',
			EDIT_FORCE_BOT | EDIT_UPDATE,
			false, /*base revision id*/
			FuzzyBot::getUser()
		);

		$success = $status === true || ( is_object( $status ) && $status->isOK() );
		$this->reportProgress( $success ? 'OK' : 'FAILED', $title );
	}
}

$maintClass = 'Fuzzy';
require_once RUN_MAINTENANCE_IF_MAIN;