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  $services = MediaWikiServices::getInstance();
131  $permissionManager = $services->getPermissionManager();
132 
133  $processed = $added = $ignored = $skipped = $overwritten = $failed = 0;
134 
135  $this->output( "Importing Files\n\n" );
136 
137  $dir = $this->getArg( 0 );
138 
139  # Check Protection
140  if ( $this->hasOption( 'protect' ) && $this->hasOption( 'unprotect' ) ) {
141  $this->fatalError( "Cannot specify both protect and unprotect. Only 1 is allowed.\n" );
142  }
143 
144  if ( $this->hasOption( 'protect' ) && trim( $this->getOption( 'protect' ) ) ) {
145  $this->fatalError( "You must specify a protection option.\n" );
146  }
147 
148  # Prepare the list of allowed extensions
149  $extensions = $this->hasOption( 'extensions' )
150  ? explode( ',', strtolower( $this->getOption( 'extensions' ) ) )
152 
153  # Search the path provided for candidates for import
154  $files = $this->findFiles( $dir, $extensions, $this->hasOption( 'search-recursively' ) );
155 
156  # Initialise the user for this operation
157  $user = $this->hasOption( 'user' )
158  ? User::newFromName( $this->getOption( 'user' ) )
159  : User::newSystemUser( 'Maintenance script', [ 'steal' => true ] );
160  if ( !$user instanceof User ) {
161  $user = User::newSystemUser( 'Maintenance script', [ 'steal' => true ] );
162  }
163  $wgUser = $user;
164 
165  # Get block check. If a value is given, this specified how often the check is performed
166  $checkUserBlock = (int)$this->getOption( 'check-userblock' );
167 
168  $from = $this->getOption( 'from' );
169  $sleep = (int)$this->getOption( 'sleep' );
170  $limit = (int)$this->getOption( 'limit' );
171  $timestamp = $this->getOption( 'timestamp', false );
172 
173  # Get the upload comment. Provide a default one in case there's no comment given.
174  $commentFile = $this->getOption( 'comment-file' );
175  if ( $commentFile !== null ) {
176  $comment = file_get_contents( $commentFile );
177  if ( $comment === false || $comment === null ) {
178  $this->fatalError( "failed to read comment file: {$commentFile}\n" );
179  }
180  } else {
181  $comment = $this->getOption( 'comment', 'Importing file' );
182  }
183  $commentExt = $this->getOption( 'comment-ext' );
184  $summary = $this->getOption( 'summary', '' );
185 
186  $license = $this->getOption( 'license', '' );
187 
188  $sourceWikiUrl = $this->getOption( 'source-wiki-url' );
189 
190  # Batch "upload" operation
191  $count = count( $files );
192  if ( $count > 0 ) {
193  $lbFactory = $services->getDBLoadBalancerFactory();
194  foreach ( $files as $file ) {
195  if ( $sleep && ( $processed > 0 ) ) {
196  sleep( $sleep );
197  }
198 
199  $base = UtfNormal\Validator::cleanUp( wfBaseName( $file ) );
200 
201  # Validate a title
203  if ( !is_object( $title ) ) {
204  $this->output(
205  "{$base} could not be imported; a valid title cannot be produced\n"
206  );
207  continue;
208  }
209 
210  if ( $from ) {
211  if ( $from == $title->getDBkey() ) {
212  $from = null;
213  } else {
214  $ignored++;
215  continue;
216  }
217  }
218 
219  if ( $checkUserBlock && ( ( $processed % $checkUserBlock ) == 0 ) ) {
220  $user->clearInstanceCache( 'name' ); // reload from DB!
221  if ( $permissionManager->isBlockedFrom( $user, $title ) ) {
222  $this->output(
223  "{$user->getName()} is blocked from {$title->getPrefixedText()}! skipping.\n"
224  );
225  $skipped++;
226  continue;
227  }
228  }
229 
230  # Check existence
231  $image = $services->getRepoGroup()->getLocalRepo()
232  ->newFile( $title );
233  if ( $image->exists() ) {
234  if ( $this->hasOption( 'overwrite' ) ) {
235  $this->output( "{$base} exists, overwriting..." );
236  $svar = 'overwritten';
237  } else {
238  $this->output( "{$base} exists, skipping\n" );
239  $skipped++;
240  continue;
241  }
242  } else {
243  if ( $this->hasOption( 'skip-dupes' ) ) {
244  $repo = $image->getRepo();
245  # XXX: we end up calculating this again when actually uploading. that sucks.
247 
248  $dupes = $repo->findBySha1( $sha1 );
249 
250  if ( $dupes ) {
251  $this->output(
252  "{$base} already exists as {$dupes[0]->getName()}, skipping\n"
253  );
254  $skipped++;
255  continue;
256  }
257  }
258 
259  $this->output( "Importing {$base}..." );
260  $svar = 'added';
261  }
262 
263  if ( $sourceWikiUrl ) {
264  /* find comment text directly from source wiki, through MW's API */
265  $real_comment = $this->getFileCommentFromSourceWiki( $sourceWikiUrl, $base );
266  if ( $real_comment === false ) {
267  $commentText = $comment;
268  } else {
269  $commentText = $real_comment;
270  }
271 
272  /* find user directly from source wiki, through MW's API */
273  $real_user = $this->getFileUserFromSourceWiki( $sourceWikiUrl, $base );
274  if ( $real_user === false ) {
275  // don't change $wgUser
276  } else {
277  $realUser = User::newFromName( $real_user );
278  if ( $realUser === false ) {
279  # user does not exist in target wiki
280  $this->output(
281  "failed: user '$real_user' does not exist in target wiki."
282  );
283  continue;
284  }
285  $wgUser = $realUser;
286  $user = $realUser;
287  }
288  } else {
289  # Find comment text
290  $commentText = false;
291 
292  if ( $commentExt ) {
293  $f = $this->findAuxFile( $file, $commentExt );
294  if ( !$f ) {
295  $this->output( " No comment file with extension {$commentExt} found "
296  . "for {$file}, using default comment. " );
297  } else {
298  $commentText = file_get_contents( $f );
299  if ( !$commentText ) {
300  $this->output(
301  " Failed to load comment file {$f}, using default comment. "
302  );
303  }
304  }
305  }
306 
307  if ( !$commentText ) {
308  $commentText = $comment;
309  }
310  }
311 
312  # Import the file
313  if ( $this->hasOption( 'dry' ) ) {
314  $this->output(
315  " publishing {$file} by '{$user->getName()}', comment '$commentText'... "
316  );
317  } else {
318  $mwProps = new MWFileProps( $services->getMimeAnalyzer() );
319  $props = $mwProps->getPropsFromPath( $file, true );
320  $flags = 0;
321  $publishOptions = [];
322  $handler = MediaHandler::getHandler( $props['mime'] );
323  if ( $handler ) {
324  $metadata = \Wikimedia\AtEase\AtEase::quietCall( 'unserialize', $props['metadata'] );
325 
326  $publishOptions['headers'] = $handler->getContentHeaders( $metadata );
327  } else {
328  $publishOptions['headers'] = [];
329  }
330  $archive = $image->publish( $file, $flags, $publishOptions );
331  if ( !$archive->isGood() ) {
332  $this->output( "failed. (" .
333  $archive->getMessage( false, false, 'en' )->text() .
334  ")\n" );
335  $failed++;
336  continue;
337  }
338  }
339 
340  $commentText = SpecialUpload::getInitialPageText( $commentText, $license );
341  if ( !$this->hasOption( 'summary' ) ) {
342  $summary = $commentText;
343  }
344 
345  if ( $this->hasOption( 'dry' ) ) {
346  $this->output( "done.\n" );
347  } elseif ( $image->recordUpload3(
348  $archive->value,
349  $summary,
350  $commentText,
351  $user,
352  $props,
353  $timestamp
354  )->isOK() ) {
355  $this->output( "done.\n" );
356 
357  $doProtect = false;
358 
359  $protectLevel = $this->getOption( 'protect' );
360 
361  if ( $protectLevel && in_array( $protectLevel, $wgRestrictionLevels ) ) {
362  $doProtect = true;
363  }
364  if ( $this->hasOption( 'unprotect' ) ) {
365  $protectLevel = '';
366  $doProtect = true;
367  }
368 
369  if ( $doProtect ) {
370  # Protect the file
371  $this->output( "\nWaiting for replica DBs...\n" );
372  // Wait for replica DBs.
373  sleep( 2 ); # Why this sleep?
374  $lbFactory->waitForReplication();
375 
376  $this->output( "\nSetting image restrictions ... " );
377 
378  $cascade = false;
379  $restrictions = [];
380  foreach ( $title->getRestrictionTypes() as $type ) {
381  $restrictions[$type] = $protectLevel;
382  }
383 
384  $page = $services->getWikiPageFactory()->newFromTitle( $title );
385  $status = $page->doUpdateRestrictions( $restrictions, [], $cascade, '', $user );
386  $this->output( ( $status->isOK() ? 'done' : 'failed' ) . "\n" );
387  }
388  } else {
389  $this->output( "failed. (at recordUpload stage)\n" );
390  $svar = 'failed';
391  }
392 
393  $$svar++;
394  $processed++;
395 
396  if ( $limit && $processed >= $limit ) {
397  break;
398  }
399  }
400 
401  # Print out some statistics
402  $this->output( "\n" );
403  foreach (
404  [
405  'count' => 'Found',
406  'limit' => 'Limit',
407  'ignored' => 'Ignored',
408  'added' => 'Added',
409  'skipped' => 'Skipped',
410  'overwritten' => 'Overwritten',
411  'failed' => 'Failed'
412  ] as $var => $desc
413  ) {
414  if ( $$var > 0 ) {
415  $this->output( "{$desc}: {$$var}\n" );
416  }
417  }
418  } else {
419  $this->output( "No suitable files could be found for import.\n" );
420  }
421  }
422 
431  private function findFiles( $dir, $exts, $recurse = false ) {
432  if ( is_dir( $dir ) ) {
433  $dhl = opendir( $dir );
434  if ( $dhl ) {
435  $files = [];
436  while ( ( $file = readdir( $dhl ) ) !== false ) {
437  if ( is_file( $dir . '/' . $file ) ) {
438  $ext = pathinfo( $file, PATHINFO_EXTENSION );
439  if ( array_search( strtolower( $ext ), $exts ) !== false ) {
440  $files[] = $dir . '/' . $file;
441  }
442  } elseif ( $recurse && is_dir( $dir . '/' . $file ) && $file !== '..' && $file !== '.' ) {
443  $files = array_merge( $files, $this->findFiles( $dir . '/' . $file, $exts, true ) );
444  }
445  }
446 
447  return $files;
448  } else {
449  return [];
450  }
451  } else {
452  return [];
453  }
454  }
455 
470  private function findAuxFile( $file, $auxExtension, $maxStrip = 1 ) {
471  if ( strpos( $auxExtension, '.' ) !== 0 ) {
472  $auxExtension = '.' . $auxExtension;
473  }
474 
475  $d = dirname( $file );
476  $n = basename( $file );
477 
478  while ( $maxStrip >= 0 ) {
479  $f = $d . '/' . $n . $auxExtension;
480 
481  if ( file_exists( $f ) ) {
482  return $f;
483  }
484 
485  $idx = strrpos( $n, '.' );
486  if ( !$idx ) {
487  break;
488  }
489 
490  $n = substr( $n, 0, $idx );
491  $maxStrip -= 1;
492  }
493 
494  return false;
495  }
496 
506  private function getFileCommentFromSourceWiki( $wiki_host, $file ) {
507  $url = $wiki_host . '/api.php?action=query&format=xml&titles=File:'
508  . rawurlencode( $file ) . '&prop=imageinfo&&iiprop=comment';
509  $body = Http::get( $url, [], __METHOD__ );
510  if ( preg_match( '#<ii comment="([^"]*)" />#', $body, $matches ) == 0 ) {
511  return false;
512  }
513 
514  return html_entity_decode( $matches[1] );
515  }
516 
517  private function getFileUserFromSourceWiki( $wiki_host, $file ) {
518  $url = $wiki_host . '/api.php?action=query&format=xml&titles=File:'
519  . rawurlencode( $file ) . '&prop=imageinfo&&iiprop=user';
520  $body = Http::get( $url, [], __METHOD__ );
521  if ( preg_match( '#<ii user="([^"]*)" />#', $body, $matches ) == 0 ) {
522  return false;
523  }
524 
525  return html_entity_decode( $matches[1] );
526  }
527 
528 }
529 
530 $maintClass = ImportImages::class;
531 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:645
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:165
Maintenance\fatalError
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
Definition: Maintenance.php:486
Maintenance\addDescription
addDescription( $text)
Set the description text.
Definition: Maintenance.php:327
$wgFileExtensions
$wgFileExtensions
This is the list of preferred extensions for uploading files.
Definition: DefaultSettings.php:1026
wfBaseName
wfBaseName( $path, $suffix='')
Return the final portion of a pathname.
Definition: GlobalFunctions.php:2324
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')
Definition: User.php:545
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:55
$base
$base
Definition: generateLocalAutoload.php:11
ImportImages\getFileUserFromSourceWiki
getFileUserFromSourceWiki( $wiki_host, $file)
Definition: importImages.php:517
User\newSystemUser
static newSystemUser( $name, $options=[])
Static factory method for creation of a "system" user from username.
Definition: User.php:738
ImportImages\findFiles
findFiles( $dir, $exts, $recurse=false)
Search a directory for files with one of a set of extensions.
Definition: importImages.php:431
ImportImages\getFileCommentFromSourceWiki
getFileCommentFromSourceWiki( $wiki_host, $file)
Definition: importImages.php:506
$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:245
$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:617
ImportImages\findAuxFile
findAuxFile( $file, $auxExtension, $maxStrip=1)
Find an auxilliary file with the given extension, matching the give base file path.
Definition: importImages.php:470
Maintenance\getOption
getOption( $name, $default=null)
Get an option, or return the default.
Definition: Maintenance.php:281
Maintenance\addArg
addArg( $arg, $description, $required=true)
Add some args that are needed.
Definition: Maintenance.php:298
MediaHandler\getHandler
static getHandler( $type)
Get a MediaHandler for a given MIME type from the instance cache.
Definition: MediaHandler.php:53
$wgRestrictionLevels
$wgRestrictionLevels
Rights which can be required for each protection level (via action=protect)
Definition: DefaultSettings.php:5759
Maintenance\output
output( $out, $channel=null)
Throw some output to the user.
Definition: Maintenance.php:433
$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:266
Maintenance\getArg
getArg( $argId=0, $default=null)
Get an argument.
Definition: Maintenance.php:351
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:56
ImportImages\execute
execute()
Do the actual work.
Definition: importImages.php:127
ImportImages
Definition: importImages.php:39
$maintClass
$maintClass
Definition: importImages.php:530
$type
$type
Definition: testCompression.php:52