35require_once __DIR__ .
'/Maintenance.php';
42 parent::__construct();
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' );
48 'Comma-separated list of allowable extensions, defaults to $wgFileExtensions',
53 'Overwrite existing images with the same name (default is to skip them)' );
55 'Limit the number of images to process. Ignored or skipped images are not counted',
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.",
66 'Skip images that were already uploaded under a different name (check SHA1)' );
67 $this->
addOption(
'search-recursively',
'Search recursively for files in subdirectories' );
69 'Sleep between files. Useful mostly for debugging',
74 "Set username of uploader, default 'Maintenance script'",
80 $this->
addOption(
'check-userblock',
'Check if the user got blocked during import' );
82 "Set file description, default 'Importing file'",
87 'Set description to the content of this file',
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.',
98 'Upload summary, description will be used if not provided',
103 'Use an optional license template',
108 'Override upload time/date, all MediaWiki timestamp formats are accepted',
113 'Specify the protect value (autoconfirmed,sysop)',
117 $this->
addOption(
'unprotect',
'Unprotects all uploaded images' );
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/',
124 $this->
addOption(
'dry',
"Dry run, don't import anything" );
130 $permissionManager = MediaWikiServices::getInstance()->getPermissionManager();
132 $processed = $added = $ignored = $skipped = $overwritten = $failed = 0;
134 $this->
output(
"Importing Files\n\n" );
136 $dir = $this->
getArg( 0 );
140 $this->
fatalError(
"Cannot specify both protect and unprotect. Only 1 is allowed.\n" );
144 $this->
fatalError(
"You must specify a protection option.\n" );
147 # Prepare the list of allowed extensions
148 $extensions = $this->
hasOption(
'extensions' )
149 ? explode(
',', strtolower( $this->
getOption(
'extensions' ) ) )
152 # Search the path provided for candidates for import
153 $files = $this->
findFiles( $dir, $extensions, $this->
hasOption(
'search-recursively' ) );
155 # Initialise the user for this operation
159 if ( !$user instanceof
User ) {
164 # Get block check. If a value is given, this specified how often the check is performed
165 $checkUserBlock = (int)$this->
getOption(
'check-userblock' );
168 $sleep = (int)$this->
getOption(
'sleep' );
169 $limit = (int)$this->
getOption(
'limit' );
170 $timestamp = $this->
getOption(
'timestamp',
false );
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" );
180 $comment = $this->
getOption(
'comment',
'Importing file' );
182 $commentExt = $this->
getOption(
'comment-ext' );
183 $summary = $this->
getOption(
'summary',
'' );
185 $license = $this->
getOption(
'license',
'' );
187 $sourceWikiUrl = $this->
getOption(
'source-wiki-url' );
189 # Batch "upload" operation
190 $count = count( $files );
192 foreach ( $files as
$file ) {
193 if ( $sleep && ( $processed > 0 ) ) {
201 if ( !is_object(
$title ) ) {
203 "{$base} could not be imported; a valid title cannot be produced\n"
209 if ( $from ==
$title->getDBkey() ) {
217 if ( $checkUserBlock && ( ( $processed % $checkUserBlock ) == 0 ) ) {
218 $user->clearInstanceCache(
'name' );
219 if ( $permissionManager->isBlockedFrom( $user,
$title ) ) {
221 "{$user->getName()} is blocked from {$title->getPrefixedText()}! skipping.\n"
229 $image = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo()
231 if ( $image->exists() ) {
233 $this->
output(
"{$base} exists, overwriting..." );
234 $svar =
'overwritten';
236 $this->
output(
"{$base} exists, skipping\n" );
241 if ( $this->
hasOption(
'skip-dupes' ) ) {
242 $repo = $image->getRepo();
243 # XXX: we end up calculating this again when actually uploading. that sucks.
246 $dupes = $repo->findBySha1( $sha1 );
250 "{$base} already exists as {$dupes[0]->getName()}, skipping\n"
257 $this->
output(
"Importing {$base}..." );
261 if ( $sourceWikiUrl ) {
264 if ( $real_comment ===
false ) {
265 $commentText = $comment;
267 $commentText = $real_comment;
272 if ( $real_user ===
false ) {
276 if ( $wgUser ===
false ) {
277 # user does not exist in target wiki
279 "failed: user '$real_user' does not exist in target wiki."
286 $commentText =
false;
291 $this->
output(
" No comment file with extension {$commentExt} found "
292 .
"for {$file}, using default comment. " );
294 $commentText = file_get_contents( $f );
295 if ( !$commentText ) {
297 " Failed to load comment file {$f}, using default comment. "
303 if ( !$commentText ) {
304 $commentText = $comment;
311 " publishing {$file} by '{$wgUser->getName()}', comment '$commentText'... "
315 $props = $mwProps->getPropsFromPath(
$file,
true );
317 $publishOptions = [];
320 $metadata = \Wikimedia\AtEase\AtEase::quietCall(
'unserialize', $props[
'metadata'] );
322 $publishOptions[
'headers'] = $handler->getContentHeaders( $metadata );
324 $publishOptions[
'headers'] = [];
326 $archive = $image->publish(
$file, $flags, $publishOptions );
327 if ( !$archive->isGood() ) {
328 $this->
output(
"failed. (" .
329 $archive->getMessage(
false,
false,
'en' )->text() .
338 $summary = $commentText;
342 $this->
output(
"done.\n" );
343 } elseif ( $image->recordUpload2(
350 $this->
output(
"done.\n" );
354 $protectLevel = $this->
getOption(
'protect' );
366 $this->
output(
"\nWaiting for replica DBs...\n" );
368 sleep( 2 ); # Why
this sleep?
371 $this->
output(
"\nSetting image restrictions ... " );
375 foreach (
$title->getRestrictionTypes() as
$type ) {
376 $restrictions[
$type] = $protectLevel;
379 $page = WikiPage::factory(
$title );
380 $status = $page->doUpdateRestrictions( $restrictions, [], $cascade,
'', $user );
381 $this->
output( ( $status->isOK() ?
'done' :
'failed' ) .
"\n" );
384 $this->
output(
"failed. (at recordUpload stage)\n" );
391 if ( $limit && $processed >= $limit ) {
396 # Print out some statistics
402 'ignored' =>
'Ignored',
404 'skipped' =>
'Skipped',
405 'overwritten' =>
'Overwritten',
410 $this->
output(
"{$desc}: {$$var}\n" );
414 $this->
output(
"No suitable files could be found for import.\n" );
426 private function findFiles( $dir, $exts, $recurse =
false ) {
427 if ( is_dir( $dir ) ) {
428 $dhl = opendir( $dir );
431 while ( (
$file = readdir( $dhl ) ) !==
false ) {
432 if ( is_file( $dir .
'/' .
$file ) ) {
433 $ext = pathinfo(
$file, PATHINFO_EXTENSION );
434 if ( array_search( strtolower(
$ext ), $exts ) !==
false ) {
435 $files[] = $dir .
'/' .
$file;
437 } elseif ( $recurse && is_dir( $dir .
'/' .
$file ) &&
$file !==
'..' &&
$file !==
'.' ) {
438 $files = array_merge( $files, $this->
findFiles( $dir .
'/' .
$file, $exts,
true ) );
466 if ( strpos( $auxExtension,
'.' ) !== 0 ) {
467 $auxExtension =
'.' . $auxExtension;
470 $d = dirname(
$file );
471 $n = basename(
$file );
473 while ( $maxStrip >= 0 ) {
474 $f = $d .
'/' . $n . $auxExtension;
476 if ( file_exists( $f ) ) {
480 $idx = strrpos( $n,
'.' );
485 $n = substr( $n, 0, $idx );
492 # @todo FIXME: Access the api in a saner way and performing just one query
493 # (preferably batching files too).
495 $url = $wiki_host .
'/api.php?action=query&format=xml&titles=File:'
496 . rawurlencode(
$file ) .
'&prop=imageinfo&&iiprop=comment';
497 $body =
Http::get( $url, [], __METHOD__ );
498 if ( preg_match(
'#<ii comment="([^"]*)" />#', $body,
$matches ) == 0 ) {
502 return html_entity_decode(
$matches[1] );
506 $url = $wiki_host .
'/api.php?action=query&format=xml&titles=File:'
507 . rawurlencode(
$file ) .
'&prop=imageinfo&&iiprop=user';
508 $body =
Http::get( $url, [], __METHOD__ );
509 if ( preg_match(
'#<ii user="([^"]*)" />#', $body,
$matches ) == 0 ) {
513 return html_entity_decode(
$matches[1] );
$wgRestrictionLevels
Rights which can be required for each protection level (via action=protect)
$wgFileExtensions
This is the list of preferred extensions for uploading files.
wfWaitForSlaves( $ifWritesSince=null, $wiki=false, $cluster=false, $timeout=null)
Waits for the replica DBs to catch up to the master position.
wfBaseName( $path, $suffix='')
Return the final portion of a pathname.
const RUN_MAINTENANCE_IF_MAIN
static getSha1Base36FromPath( $path)
Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case encoding,...
static get( $url, array $options=[], $caller=__METHOD__)
Simple wrapper for Http::request( 'GET' )
execute()
Do the actual work.
getFileCommentFromSourceWiki( $wiki_host, $file)
findFiles( $dir, $exts, $recurse=false)
Search a directory for files with one of a set of extensions.
__construct()
Default constructor.
findAuxFile( $file, $auxExtension, $maxStrip=1)
Find an auxilliary file with the given extension, matching the give base file path.
getFileUserFromSourceWiki( $wiki_host, $file)
MimeMagic helper wrapper.
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
addArg( $arg, $description, $required=true)
Add some args that are needed.
output( $out, $channel=null)
Throw some output to the user.
hasOption( $name)
Checks to see if a particular option exists.
getArg( $argId=0, $default=null)
Get an argument.
addDescription( $text)
Set the description text.
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
getOption( $name, $default=null)
Get an option, or return the default.
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
static getInitialPageText( $comment='', $license='', $copyStatus='', $source='', Config $config=null)
Get the initial image page text based on a comment and optional file status information.
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
static newSystemUser( $name, $options=[])
Static factory method for creation of a "system" user from username.
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
if(!is_readable( $file)) $ext