Merge "Allow partially blocked users to import images"
[lhc/web/wiklou.git] / maintenance / importImages.php
1 <?php
2 /**
3 * Import one or more images from the local file system into the wiki without
4 * using the web-based interface.
5 *
6 * "Smart import" additions:
7 * - aim: preserve the essential metadata (user, description) when importing media
8 * files from an existing wiki.
9 * - process:
10 * - interface with the source wiki, don't use bare files only (see --source-wiki-url).
11 * - fetch metadata from source wiki for each file to import.
12 * - commit the fetched metadata to the destination wiki while submitting.
13 *
14 * This program is free software; you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation; either version 2 of the License, or
17 * (at your option) any later version.
18 *
19 * This program is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
23 *
24 * You should have received a copy of the GNU General Public License along
25 * with this program; if not, write to the Free Software Foundation, Inc.,
26 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
27 * http://www.gnu.org/copyleft/gpl.html
28 *
29 * @file
30 * @ingroup Maintenance
31 * @author Rob Church <robchur@gmail.com>
32 * @author Mij <mij@bitchx.it>
33 */
34
35 require_once __DIR__ . '/Maintenance.php';
36
37 use MediaWiki\MediaWikiServices;
38
39 class ImportImages extends Maintenance {
40
41 public function __construct() {
42 parent::__construct();
43
44 $this->addDescription( 'Imports images and other media files into the wiki' );
45 $this->addArg( 'dir', 'Path to the directory containing images to be imported' );
46
47 $this->addOption( 'extensions',
48 'Comma-separated list of allowable extensions, defaults to $wgFileExtensions',
49 false,
50 true
51 );
52 $this->addOption( 'overwrite',
53 'Overwrite existing images with the same name (default is to skip them)' );
54 $this->addOption( 'limit',
55 'Limit the number of images to process. Ignored or skipped images are not counted',
56 false,
57 true
58 );
59 $this->addOption( 'from',
60 "Ignore all files until the one with the given name. Useful for resuming aborted "
61 . "imports. The name should be the file's canonical database form.",
62 false,
63 true
64 );
65 $this->addOption( 'skip-dupes',
66 'Skip images that were already uploaded under a different name (check SHA1)' );
67 $this->addOption( 'search-recursively', 'Search recursively for files in subdirectories' );
68 $this->addOption( 'sleep',
69 'Sleep between files. Useful mostly for debugging',
70 false,
71 true
72 );
73 $this->addOption( 'user',
74 "Set username of uploader, default 'Maintenance script'",
75 false,
76 true
77 );
78 // This parameter can optionally have an argument. If none specified, getOption()
79 // returns 1 which is precisely what we need.
80 $this->addOption( 'check-userblock', 'Check if the user got blocked during import' );
81 $this->addOption( 'comment',
82 "Set file description, default 'Importing file'",
83 false,
84 true
85 );
86 $this->addOption( 'comment-file',
87 'Set description to the content of this file',
88 false,
89 true
90 );
91 $this->addOption( 'comment-ext',
92 'Causes the description for each file to be loaded from a file with the same name, but '
93 . 'the extension provided. If a global description is also given, it is appended.',
94 false,
95 true
96 );
97 $this->addOption( 'summary',
98 'Upload summary, description will be used if not provided',
99 false,
100 true
101 );
102 $this->addOption( 'license',
103 'Use an optional license template',
104 false,
105 true
106 );
107 $this->addOption( 'timestamp',
108 'Override upload time/date, all MediaWiki timestamp formats are accepted',
109 false,
110 true
111 );
112 $this->addOption( 'protect',
113 'Specify the protect value (autoconfirmed,sysop)',
114 false,
115 true
116 );
117 $this->addOption( 'unprotect', 'Unprotects all uploaded images' );
118 $this->addOption( 'source-wiki-url',
119 'If specified, take User and Comment data for each imported file from this URL. '
120 . 'For example, --source-wiki-url="http://en.wikipedia.org/',
121 false,
122 true
123 );
124 $this->addOption( 'dry', "Dry run, don't import anything" );
125 }
126
127 public function execute() {
128 global $wgFileExtensions, $wgUser, $wgRestrictionLevels;
129
130 $permissionManager = MediaWikiServices::getInstance()->getPermissionManager();
131
132 $processed = $added = $ignored = $skipped = $overwritten = $failed = 0;
133
134 $this->output( "Importing Files\n\n" );
135
136 $dir = $this->getArg( 0 );
137
138 # Check Protection
139 if ( $this->hasOption( 'protect' ) && $this->hasOption( 'unprotect' ) ) {
140 $this->fatalError( "Cannot specify both protect and unprotect. Only 1 is allowed.\n" );
141 }
142
143 if ( $this->hasOption( 'protect' ) && trim( $this->getOption( 'protect' ) ) ) {
144 $this->fatalError( "You must specify a protection option.\n" );
145 }
146
147 # Prepare the list of allowed extensions
148 $extensions = $this->hasOption( 'extensions' )
149 ? explode( ',', strtolower( $this->getOption( 'extensions' ) ) )
150 : $wgFileExtensions;
151
152 # Search the path provided for candidates for import
153 $files = $this->findFiles( $dir, $extensions, $this->hasOption( 'search-recursively' ) );
154
155 # Initialise the user for this operation
156 $user = $this->hasOption( 'user' )
157 ? User::newFromName( $this->getOption( 'user' ) )
158 : User::newSystemUser( 'Maintenance script', [ 'steal' => true ] );
159 if ( !$user instanceof User ) {
160 $user = User::newSystemUser( 'Maintenance script', [ 'steal' => true ] );
161 }
162 $wgUser = $user;
163
164 # Get block check. If a value is given, this specified how often the check is performed
165 $checkUserBlock = (int)$this->getOption( 'check-userblock' );
166
167 $from = $this->getOption( 'from' );
168 $sleep = (int)$this->getOption( 'sleep' );
169 $limit = (int)$this->getOption( 'limit' );
170 $timestamp = $this->getOption( 'timestamp', false );
171
172 # Get the upload comment. Provide a default one in case there's no comment given.
173 $commentFile = $this->getOption( 'comment-file' );
174 if ( $commentFile !== null ) {
175 $comment = file_get_contents( $commentFile );
176 if ( $comment === false || $comment === null ) {
177 $this->fatalError( "failed to read comment file: {$commentFile}\n" );
178 }
179 } else {
180 $comment = $this->getOption( 'comment', 'Importing file' );
181 }
182 $commentExt = $this->getOption( 'comment-ext' );
183 $summary = $this->getOption( 'summary', '' );
184
185 $license = $this->getOption( 'license', '' );
186
187 $sourceWikiUrl = $this->getOption( 'source-wiki-url' );
188
189 # Batch "upload" operation
190 $count = count( $files );
191 if ( $count > 0 ) {
192 foreach ( $files as $file ) {
193 if ( $sleep && ( $processed > 0 ) ) {
194 sleep( $sleep );
195 }
196
197 $base = UtfNormal\Validator::cleanUp( wfBaseName( $file ) );
198
199 # Validate a title
200 $title = Title::makeTitleSafe( NS_FILE, $base );
201 if ( !is_object( $title ) ) {
202 $this->output(
203 "{$base} could not be imported; a valid title cannot be produced\n" );
204 continue;
205 }
206
207 if ( $from ) {
208 if ( $from == $title->getDBkey() ) {
209 $from = null;
210 } else {
211 $ignored++;
212 continue;
213 }
214 }
215
216 if ( $checkUserBlock && ( ( $processed % $checkUserBlock ) == 0 ) ) {
217 $user->clearInstanceCache( 'name' ); // reload from DB!
218 if ( $permissionManager->isBlockedFrom( $user, $title ) ) {
219 $this->output(
220 "{$user->getName()} is blocked from {$title->getPrefixedText()}! skipping.\n"
221 );
222 $skipped++;
223 continue;
224 }
225 }
226
227 # Check existence
228 $image = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo()
229 ->newFile( $title );
230 if ( $image->exists() ) {
231 if ( $this->hasOption( 'overwrite' ) ) {
232 $this->output( "{$base} exists, overwriting..." );
233 $svar = 'overwritten';
234 } else {
235 $this->output( "{$base} exists, skipping\n" );
236 $skipped++;
237 continue;
238 }
239 } else {
240 if ( $this->hasOption( 'skip-dupes' ) ) {
241 $repo = $image->getRepo();
242 # XXX: we end up calculating this again when actually uploading. that sucks.
243 $sha1 = FSFile::getSha1Base36FromPath( $file );
244
245 $dupes = $repo->findBySha1( $sha1 );
246
247 if ( $dupes ) {
248 $this->output(
249 "{$base} already exists as {$dupes[0]->getName()}, skipping\n" );
250 $skipped++;
251 continue;
252 }
253 }
254
255 $this->output( "Importing {$base}..." );
256 $svar = 'added';
257 }
258
259 if ( $sourceWikiUrl ) {
260 /* find comment text directly from source wiki, through MW's API */
261 $real_comment = $this->getFileCommentFromSourceWiki( $sourceWikiUrl, $base );
262 if ( $real_comment === false ) {
263 $commentText = $comment;
264 } else {
265 $commentText = $real_comment;
266 }
267
268 /* find user directly from source wiki, through MW's API */
269 $real_user = $this->getFileUserFromSourceWiki( $sourceWikiUrl, $base );
270 if ( $real_user === false ) {
271 $wgUser = $user;
272 } else {
273 $wgUser = User::newFromName( $real_user );
274 if ( $wgUser === false ) {
275 # user does not exist in target wiki
276 $this->output(
277 "failed: user '$real_user' does not exist in target wiki." );
278 continue;
279 }
280 }
281 } else {
282 # Find comment text
283 $commentText = false;
284
285 if ( $commentExt ) {
286 $f = $this->findAuxFile( $file, $commentExt );
287 if ( !$f ) {
288 $this->output( " No comment file with extension {$commentExt} found "
289 . "for {$file}, using default comment. " );
290 } else {
291 $commentText = file_get_contents( $f );
292 if ( !$commentText ) {
293 $this->output(
294 " Failed to load comment file {$f}, using default comment. " );
295 }
296 }
297 }
298
299 if ( !$commentText ) {
300 $commentText = $comment;
301 }
302 }
303
304 # Import the file
305 if ( $this->hasOption( 'dry' ) ) {
306 $this->output(
307 " publishing {$file} by '{$wgUser->getName()}', comment '$commentText'... "
308 );
309 } else {
310 $mwProps = new MWFileProps( MediaWiki\MediaWikiServices::getInstance()->getMimeAnalyzer() );
311 $props = $mwProps->getPropsFromPath( $file, true );
312 $flags = 0;
313 $publishOptions = [];
314 $handler = MediaHandler::getHandler( $props['mime'] );
315 if ( $handler ) {
316 $metadata = \Wikimedia\AtEase\AtEase::quietCall( 'unserialize', $props['metadata'] );
317
318 $publishOptions['headers'] = $handler->getContentHeaders( $metadata );
319 } else {
320 $publishOptions['headers'] = [];
321 }
322 $archive = $image->publish( $file, $flags, $publishOptions );
323 if ( !$archive->isGood() ) {
324 $this->output( "failed. (" .
325 $archive->getWikiText( false, false, 'en' ) .
326 ")\n" );
327 $failed++;
328 continue;
329 }
330 }
331
332 $commentText = SpecialUpload::getInitialPageText( $commentText, $license );
333 if ( !$this->hasOption( 'summary' ) ) {
334 $summary = $commentText;
335 }
336
337 if ( $this->hasOption( 'dry' ) ) {
338 $this->output( "done.\n" );
339 } elseif ( $image->recordUpload2(
340 $archive->value,
341 $summary,
342 $commentText,
343 $props,
344 $timestamp
345 )->isOK() ) {
346 $this->output( "done.\n" );
347
348 $doProtect = false;
349
350 $protectLevel = $this->getOption( 'protect' );
351
352 if ( $protectLevel && in_array( $protectLevel, $wgRestrictionLevels ) ) {
353 $doProtect = true;
354 }
355 if ( $this->hasOption( 'unprotect' ) ) {
356 $protectLevel = '';
357 $doProtect = true;
358 }
359
360 if ( $doProtect ) {
361 # Protect the file
362 $this->output( "\nWaiting for replica DBs...\n" );
363 // Wait for replica DBs.
364 sleep( 2 ); # Why this sleep?
365 wfWaitForSlaves();
366
367 $this->output( "\nSetting image restrictions ... " );
368
369 $cascade = false;
370 $restrictions = [];
371 foreach ( $title->getRestrictionTypes() as $type ) {
372 $restrictions[$type] = $protectLevel;
373 }
374
375 $page = WikiPage::factory( $title );
376 $status = $page->doUpdateRestrictions( $restrictions, [], $cascade, '', $user );
377 $this->output( ( $status->isOK() ? 'done' : 'failed' ) . "\n" );
378 }
379 } else {
380 $this->output( "failed. (at recordUpload stage)\n" );
381 $svar = 'failed';
382 }
383
384 $$svar++;
385 $processed++;
386
387 if ( $limit && $processed >= $limit ) {
388 break;
389 }
390 }
391
392 # Print out some statistics
393 $this->output( "\n" );
394 foreach (
395 [
396 'count' => 'Found',
397 'limit' => 'Limit',
398 'ignored' => 'Ignored',
399 'added' => 'Added',
400 'skipped' => 'Skipped',
401 'overwritten' => 'Overwritten',
402 'failed' => 'Failed'
403 ] as $var => $desc
404 ) {
405 if ( $$var > 0 ) {
406 $this->output( "{$desc}: {$$var}\n" );
407 }
408 }
409 } else {
410 $this->output( "No suitable files could be found for import.\n" );
411 }
412 }
413
414 /**
415 * Search a directory for files with one of a set of extensions
416 *
417 * @param string $dir Path to directory to search
418 * @param array $exts Array of extensions to search for
419 * @param bool $recurse Search subdirectories recursively
420 * @return array|bool Array of filenames on success, or false on failure
421 */
422 private function findFiles( $dir, $exts, $recurse = false ) {
423 if ( is_dir( $dir ) ) {
424 $dhl = opendir( $dir );
425 if ( $dhl ) {
426 $files = [];
427 while ( ( $file = readdir( $dhl ) ) !== false ) {
428 if ( is_file( $dir . '/' . $file ) ) {
429 $ext = pathinfo( $file, PATHINFO_EXTENSION );
430 if ( array_search( strtolower( $ext ), $exts ) !== false ) {
431 $files[] = $dir . '/' . $file;
432 }
433 } elseif ( $recurse && is_dir( $dir . '/' . $file ) && $file !== '..' && $file !== '.' ) {
434 $files = array_merge( $files, $this->findFiles( $dir . '/' . $file, $exts, true ) );
435 }
436 }
437
438 return $files;
439 } else {
440 return [];
441 }
442 } else {
443 return [];
444 }
445 }
446
447 /**
448 * Find an auxilliary file with the given extension, matching
449 * the give base file path. $maxStrip determines how many extensions
450 * may be stripped from the original file name before appending the
451 * new extension. For example, with $maxStrip = 1 (the default),
452 * file files acme.foo.bar.txt and acme.foo.txt would be auxilliary
453 * files for acme.foo.bar and the extension ".txt". With $maxStrip = 2,
454 * acme.txt would also be acceptable.
455 *
456 * @param string $file Base path
457 * @param string $auxExtension The extension to be appended to the base path
458 * @param int $maxStrip The maximum number of extensions to strip from the base path (default: 1)
459 * @return string|bool
460 */
461 private function findAuxFile( $file, $auxExtension, $maxStrip = 1 ) {
462 if ( strpos( $auxExtension, '.' ) !== 0 ) {
463 $auxExtension = '.' . $auxExtension;
464 }
465
466 $d = dirname( $file );
467 $n = basename( $file );
468
469 while ( $maxStrip >= 0 ) {
470 $f = $d . '/' . $n . $auxExtension;
471
472 if ( file_exists( $f ) ) {
473 return $f;
474 }
475
476 $idx = strrpos( $n, '.' );
477 if ( !$idx ) {
478 break;
479 }
480
481 $n = substr( $n, 0, $idx );
482 $maxStrip -= 1;
483 }
484
485 return false;
486 }
487
488 # @todo FIXME: Access the api in a saner way and performing just one query
489 # (preferably batching files too).
490 private function getFileCommentFromSourceWiki( $wiki_host, $file ) {
491 $url = $wiki_host . '/api.php?action=query&format=xml&titles=File:'
492 . rawurlencode( $file ) . '&prop=imageinfo&&iiprop=comment';
493 $body = Http::get( $url, [], __METHOD__ );
494 if ( preg_match( '#<ii comment="([^"]*)" />#', $body, $matches ) == 0 ) {
495 return false;
496 }
497
498 return html_entity_decode( $matches[1] );
499 }
500
501 private function getFileUserFromSourceWiki( $wiki_host, $file ) {
502 $url = $wiki_host . '/api.php?action=query&format=xml&titles=File:'
503 . rawurlencode( $file ) . '&prop=imageinfo&&iiprop=user';
504 $body = Http::get( $url, [], __METHOD__ );
505 if ( preg_match( '#<ii user="([^"]*)" />#', $body, $matches ) == 0 ) {
506 return false;
507 }
508
509 return html_entity_decode( $matches[1] );
510 }
511
512 }
513
514 $maintClass = ImportImages::class;
515 require_once RUN_MAINTENANCE_IF_MAIN;