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