MediaWiki  master
importImages.php
Go to the documentation of this file.
1 <?php
35 require_once __DIR__ . '/Maintenance.php';
36 
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' ) ) )
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  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
193  foreach ( $files as $file ) {
194  if ( $sleep && ( $processed > 0 ) ) {
195  sleep( $sleep );
196  }
197 
198  $base = UtfNormal\Validator::cleanUp( wfBaseName( $file ) );
199 
200  # Validate a title
202  if ( !is_object( $title ) ) {
203  $this->output(
204  "{$base} could not be imported; a valid title cannot be produced\n"
205  );
206  continue;
207  }
208 
209  if ( $from ) {
210  if ( $from == $title->getDBkey() ) {
211  $from = null;
212  } else {
213  $ignored++;
214  continue;
215  }
216  }
217 
218  if ( $checkUserBlock && ( ( $processed % $checkUserBlock ) == 0 ) ) {
219  $user->clearInstanceCache( 'name' ); // reload from DB!
220  if ( $permissionManager->isBlockedFrom( $user, $title ) ) {
221  $this->output(
222  "{$user->getName()} is blocked from {$title->getPrefixedText()}! skipping.\n"
223  );
224  $skipped++;
225  continue;
226  }
227  }
228 
229  # Check existence
230  $image = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo()
231  ->newFile( $title );
232  if ( $image->exists() ) {
233  if ( $this->hasOption( 'overwrite' ) ) {
234  $this->output( "{$base} exists, overwriting..." );
235  $svar = 'overwritten';
236  } else {
237  $this->output( "{$base} exists, skipping\n" );
238  $skipped++;
239  continue;
240  }
241  } else {
242  if ( $this->hasOption( 'skip-dupes' ) ) {
243  $repo = $image->getRepo();
244  # XXX: we end up calculating this again when actually uploading. that sucks.
246 
247  $dupes = $repo->findBySha1( $sha1 );
248 
249  if ( $dupes ) {
250  $this->output(
251  "{$base} already exists as {$dupes[0]->getName()}, skipping\n"
252  );
253  $skipped++;
254  continue;
255  }
256  }
257 
258  $this->output( "Importing {$base}..." );
259  $svar = 'added';
260  }
261 
262  if ( $sourceWikiUrl ) {
263  /* find comment text directly from source wiki, through MW's API */
264  $real_comment = $this->getFileCommentFromSourceWiki( $sourceWikiUrl, $base );
265  if ( $real_comment === false ) {
266  $commentText = $comment;
267  } else {
268  $commentText = $real_comment;
269  }
270 
271  /* find user directly from source wiki, through MW's API */
272  $real_user = $this->getFileUserFromSourceWiki( $sourceWikiUrl, $base );
273  if ( $real_user === false ) {
274  $wgUser = $user;
275  } else {
276  $wgUser = User::newFromName( $real_user );
277  if ( $wgUser === false ) {
278  # user does not exist in target wiki
279  $this->output(
280  "failed: user '$real_user' does not exist in target wiki."
281  );
282  continue;
283  }
284  }
285  } else {
286  # Find comment text
287  $commentText = false;
288 
289  if ( $commentExt ) {
290  $f = $this->findAuxFile( $file, $commentExt );
291  if ( !$f ) {
292  $this->output( " No comment file with extension {$commentExt} found "
293  . "for {$file}, using default comment. " );
294  } else {
295  $commentText = file_get_contents( $f );
296  if ( !$commentText ) {
297  $this->output(
298  " Failed to load comment file {$f}, using default comment. "
299  );
300  }
301  }
302  }
303 
304  if ( !$commentText ) {
305  $commentText = $comment;
306  }
307  }
308 
309  # Import the file
310  if ( $this->hasOption( 'dry' ) ) {
311  $this->output(
312  " publishing {$file} by '{$wgUser->getName()}', comment '$commentText'... "
313  );
314  } else {
315  $mwProps = new MWFileProps( MediaWiki\MediaWikiServices::getInstance()->getMimeAnalyzer() );
316  $props = $mwProps->getPropsFromPath( $file, true );
317  $flags = 0;
318  $publishOptions = [];
319  $handler = MediaHandler::getHandler( $props['mime'] );
320  if ( $handler ) {
321  $metadata = \Wikimedia\AtEase\AtEase::quietCall( 'unserialize', $props['metadata'] );
322 
323  $publishOptions['headers'] = $handler->getContentHeaders( $metadata );
324  } else {
325  $publishOptions['headers'] = [];
326  }
327  $archive = $image->publish( $file, $flags, $publishOptions );
328  if ( !$archive->isGood() ) {
329  $this->output( "failed. (" .
330  $archive->getMessage( false, false, 'en' )->text() .
331  ")\n" );
332  $failed++;
333  continue;
334  }
335  }
336 
337  $commentText = SpecialUpload::getInitialPageText( $commentText, $license );
338  if ( !$this->hasOption( 'summary' ) ) {
339  $summary = $commentText;
340  }
341 
342  if ( $this->hasOption( 'dry' ) ) {
343  $this->output( "done.\n" );
344  } elseif ( $image->recordUpload2(
345  $archive->value,
346  $summary,
347  $commentText,
348  $props,
349  $timestamp
350  )->isOK() ) {
351  $this->output( "done.\n" );
352 
353  $doProtect = false;
354 
355  $protectLevel = $this->getOption( 'protect' );
356 
357  if ( $protectLevel && in_array( $protectLevel, $wgRestrictionLevels ) ) {
358  $doProtect = true;
359  }
360  if ( $this->hasOption( 'unprotect' ) ) {
361  $protectLevel = '';
362  $doProtect = true;
363  }
364 
365  if ( $doProtect ) {
366  # Protect the file
367  $this->output( "\nWaiting for replica DBs...\n" );
368  // Wait for replica DBs.
369  sleep( 2 ); # Why this sleep?
370  $lbFactory->waitForReplication();
371 
372  $this->output( "\nSetting image restrictions ... " );
373 
374  $cascade = false;
375  $restrictions = [];
376  foreach ( $title->getRestrictionTypes() as $type ) {
377  $restrictions[$type] = $protectLevel;
378  }
379 
380  $page = WikiPage::factory( $title );
381  $status = $page->doUpdateRestrictions( $restrictions, [], $cascade, '', $user );
382  $this->output( ( $status->isOK() ? 'done' : 'failed' ) . "\n" );
383  }
384  } else {
385  $this->output( "failed. (at recordUpload stage)\n" );
386  $svar = 'failed';
387  }
388 
389  $$svar++;
390  $processed++;
391 
392  if ( $limit && $processed >= $limit ) {
393  break;
394  }
395  }
396 
397  # Print out some statistics
398  $this->output( "\n" );
399  foreach (
400  [
401  'count' => 'Found',
402  'limit' => 'Limit',
403  'ignored' => 'Ignored',
404  'added' => 'Added',
405  'skipped' => 'Skipped',
406  'overwritten' => 'Overwritten',
407  'failed' => 'Failed'
408  ] as $var => $desc
409  ) {
410  if ( $$var > 0 ) {
411  $this->output( "{$desc}: {$$var}\n" );
412  }
413  }
414  } else {
415  $this->output( "No suitable files could be found for import.\n" );
416  }
417  }
418 
427  private function findFiles( $dir, $exts, $recurse = false ) {
428  if ( is_dir( $dir ) ) {
429  $dhl = opendir( $dir );
430  if ( $dhl ) {
431  $files = [];
432  while ( ( $file = readdir( $dhl ) ) !== false ) {
433  if ( is_file( $dir . '/' . $file ) ) {
434  $ext = pathinfo( $file, PATHINFO_EXTENSION );
435  if ( array_search( strtolower( $ext ), $exts ) !== false ) {
436  $files[] = $dir . '/' . $file;
437  }
438  } elseif ( $recurse && is_dir( $dir . '/' . $file ) && $file !== '..' && $file !== '.' ) {
439  $files = array_merge( $files, $this->findFiles( $dir . '/' . $file, $exts, true ) );
440  }
441  }
442 
443  return $files;
444  } else {
445  return [];
446  }
447  } else {
448  return [];
449  }
450  }
451 
466  private function findAuxFile( $file, $auxExtension, $maxStrip = 1 ) {
467  if ( strpos( $auxExtension, '.' ) !== 0 ) {
468  $auxExtension = '.' . $auxExtension;
469  }
470 
471  $d = dirname( $file );
472  $n = basename( $file );
473 
474  while ( $maxStrip >= 0 ) {
475  $f = $d . '/' . $n . $auxExtension;
476 
477  if ( file_exists( $f ) ) {
478  return $f;
479  }
480 
481  $idx = strrpos( $n, '.' );
482  if ( !$idx ) {
483  break;
484  }
485 
486  $n = substr( $n, 0, $idx );
487  $maxStrip -= 1;
488  }
489 
490  return false;
491  }
492 
502  private function getFileCommentFromSourceWiki( $wiki_host, $file ) {
503  $url = $wiki_host . '/api.php?action=query&format=xml&titles=File:'
504  . rawurlencode( $file ) . '&prop=imageinfo&&iiprop=comment';
505  $body = Http::get( $url, [], __METHOD__ );
506  if ( preg_match( '#<ii comment="([^"]*)" />#', $body, $matches ) == 0 ) {
507  return false;
508  }
509 
510  return html_entity_decode( $matches[1] );
511  }
512 
513  private function getFileUserFromSourceWiki( $wiki_host, $file ) {
514  $url = $wiki_host . '/api.php?action=query&format=xml&titles=File:'
515  . rawurlencode( $file ) . '&prop=imageinfo&&iiprop=user';
516  $body = Http::get( $url, [], __METHOD__ );
517  if ( preg_match( '#<ii user="([^"]*)" />#', $body, $matches ) == 0 ) {
518  return false;
519  }
520 
521  return html_entity_decode( $matches[1] );
522  }
523 
524 }
525 
526 $maintClass = ImportImages::class;
527 require_once RUN_MAINTENANCE_IF_MAIN;
RUN_MAINTENANCE_IF_MAIN
const RUN_MAINTENANCE_IF_MAIN
Definition: Maintenance.php:38
SpecialUpload\getInitialPageText
static getInitialPageText( $comment='', $license='', $copyStatus='', $source='', Config $config=null)
Get the initial image page text based on a comment and optional file status information.
Definition: SpecialUpload.php:611
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:146
Maintenance\fatalError
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
Definition: Maintenance.php:480
Maintenance\addDescription
addDescription( $text)
Set the description text.
Definition: Maintenance.php:323
$wgFileExtensions
$wgFileExtensions
This is the list of preferred extensions for uploading files.
Definition: DefaultSettings.php:1001
wfBaseName
wfBaseName( $path, $suffix='')
Return the final portion of a pathname.
Definition: GlobalFunctions.php:2315
NS_FILE
const NS_FILE
Definition: Defines.php:75
$file
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition: router.php:42
User\newFromName
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition: User.php:535
ImportImages\__construct
__construct()
Default constructor.
Definition: importImages.php:41
Maintenance
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: Maintenance.php:53
$base
$base
Definition: generateLocalAutoload.php:11
ImportImages\getFileUserFromSourceWiki
getFileUserFromSourceWiki( $wiki_host, $file)
Definition: importImages.php:513
User\newSystemUser
static newSystemUser( $name, $options=[])
Static factory method for creation of a "system" user from username.
Definition: User.php:757
ImportImages\findFiles
findFiles( $dir, $exts, $recurse=false)
Search a directory for files with one of a set of extensions.
Definition: importImages.php:427
WikiPage\factory
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:146
ImportImages\getFileCommentFromSourceWiki
getFileCommentFromSourceWiki( $wiki_host, $file)
Definition: importImages.php:502
$matches
$matches
Definition: NoLocalSettings.php:24
Http\get
static get( $url, array $options=[], $caller=__METHOD__)
Simple wrapper for Http::request( 'GET' )
Definition: Http.php:63
FSFile\getSha1Base36FromPath
static getSha1Base36FromPath( $path)
Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case encoding,...
Definition: FSFile.php:225
Maintenance\addOption
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
Definition: Maintenance.php:241
MediaWiki
A helper class for throttling authentication attempts.
$title
$title
Definition: testCompression.php:38
MWFileProps
MimeMagic helper wrapper.
Definition: MWFileProps.php:28
Title\makeTitleSafe
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:621
ImportImages\findAuxFile
findAuxFile( $file, $auxExtension, $maxStrip=1)
Find an auxilliary file with the given extension, matching the give base file path.
Definition: importImages.php:466
Maintenance\getOption
getOption( $name, $default=null)
Get an option, or return the default.
Definition: Maintenance.php:277
Maintenance\addArg
addArg( $arg, $description, $required=true)
Add some args that are needed.
Definition: Maintenance.php:294
MediaHandler\getHandler
static getHandler( $type)
Get a MediaHandler for a given MIME type from the instance cache.
Definition: MediaHandler.php:51
$wgRestrictionLevels
$wgRestrictionLevels
Rights which can be required for each protection level (via action=protect)
Definition: DefaultSettings.php:5683
Maintenance\output
output( $out, $channel=null)
Throw some output to the user.
Definition: Maintenance.php:429
$ext
if(!is_readable( $file)) $ext
Definition: router.php:48
Maintenance\hasOption
hasOption( $name)
Checks to see if a particular option exists.
Definition: Maintenance.php:262
Maintenance\getArg
getArg( $argId=0, $default=null)
Get an argument.
Definition: Maintenance.php:347
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:55
ImportImages\execute
execute()
Do the actual work.
Definition: importImages.php:127
ImportImages
Definition: importImages.php:39
$maintClass
$maintClass
Definition: importImages.php:526
$type
$type
Definition: testCompression.php:52