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 $services = MediaWikiServices::getInstance();
131 $permissionManager = $services->getPermissionManager();
133 $processed = $added = $ignored = $skipped = $overwritten = $failed = 0;
135 $this->
output(
"Importing Files\n\n" );
137 $dir = $this->
getArg( 0 );
141 $this->
fatalError(
"Cannot specify both protect and unprotect. Only 1 is allowed.\n" );
145 $this->
fatalError(
"You must specify a protection option.\n" );
148 # Prepare the list of allowed extensions
149 $extensions = $this->
hasOption(
'extensions' )
150 ? explode(
',', strtolower( $this->
getOption(
'extensions' ) ) )
153 # Search the path provided for candidates for import
154 $files = $this->
findFiles( $dir, $extensions, $this->
hasOption(
'search-recursively' ) );
156 # Initialise the user for this operation
160 if ( !$user instanceof
User ) {
165 # Get block check. If a value is given, this specified how often the check is performed
166 $checkUserBlock = (int)$this->
getOption(
'check-userblock' );
169 $sleep = (int)$this->
getOption(
'sleep' );
170 $limit = (int)$this->
getOption(
'limit' );
171 $timestamp = $this->
getOption(
'timestamp',
false );
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" );
181 $comment = $this->
getOption(
'comment',
'Importing file' );
183 $commentExt = $this->
getOption(
'comment-ext' );
184 $summary = $this->
getOption(
'summary',
'' );
186 $license = $this->
getOption(
'license',
'' );
188 $sourceWikiUrl = $this->
getOption(
'source-wiki-url' );
194 # Batch "upload" operation
195 $count = count( $files );
197 $lbFactory = $services->getDBLoadBalancerFactory();
198 foreach ( $files as
$file ) {
199 if ( $sleep && ( $processed > 0 ) ) {
207 if ( !is_object(
$title ) ) {
209 "{$base} could not be imported; a valid title cannot be produced\n"
215 if ( $from ==
$title->getDBkey() ) {
223 if ( $checkUserBlock && ( ( $processed % $checkUserBlock ) == 0 ) ) {
224 $user->clearInstanceCache(
'name' );
225 if ( $permissionManager->isBlockedFrom( $user,
$title ) ) {
227 "{$user->getName()} is blocked from {$title->getPrefixedText()}! skipping.\n"
235 $image = $services->getRepoGroup()->getLocalRepo()
237 if ( $image->exists() ) {
239 $this->
output(
"{$base} exists, overwriting..." );
240 $svar =
'overwritten';
242 $this->
output(
"{$base} exists, skipping\n" );
247 if ( $this->
hasOption(
'skip-dupes' ) ) {
248 $repo = $image->getRepo();
249 # XXX: we end up calculating this again when actually uploading. that sucks.
252 $dupes = $repo->findBySha1( $sha1 );
256 "{$base} already exists as {$dupes[0]->getName()}, skipping\n"
263 $this->
output(
"Importing {$base}..." );
267 if ( $sourceWikiUrl ) {
270 if ( $real_comment ===
false ) {
271 $commentText = $comment;
273 $commentText = $real_comment;
278 if ( $real_user ===
false ) {
282 if ( $realUser ===
false ) {
283 # user does not exist in target wiki
285 "failed: user '$real_user' does not exist in target wiki."
294 $commentText =
false;
299 $this->
output(
" No comment file with extension {$commentExt} found "
300 .
"for {$file}, using default comment." );
302 $commentText = file_get_contents( $f );
303 if ( !$commentText ) {
305 " Failed to load comment file {$f}, using default comment."
311 if ( !$commentText ) {
312 $commentText = $comment;
319 " publishing {$file} by '{$user->getName()}', comment '$commentText'..."
322 $mwProps =
new MWFileProps( $services->getMimeAnalyzer() );
323 $props = $mwProps->getPropsFromPath(
$file,
true );
325 $publishOptions = [];
328 $publishOptions[
'headers'] = $handler->getContentHeaders( $props[
'metadata'] );
330 $publishOptions[
'headers'] = [];
332 $archive = $image->publish(
$file, $flags, $publishOptions );
333 if ( !$archive->isGood() ) {
334 $this->
output(
"failed. (" .
335 $archive->getMessage(
false,
false,
'en' )->text() .
342 $commentText = SpecialUpload::getInitialPageText( $commentText, $license );
344 $summary = $commentText;
348 $this->
output(
"done.\n" );
349 } elseif ( $image->recordUpload3(
358 $this->
output(
"done.\n" );
362 $protectLevel = $this->
getOption(
'protect' );
374 $this->
output(
"\nWaiting for replica DBs...\n" );
376 sleep( 2 ); # Why
this sleep?
377 $lbFactory->waitForReplication();
379 $this->
output(
"\nSetting image restrictions ..." );
383 foreach (
$title->getRestrictionTypes() as
$type ) {
384 $restrictions[
$type] = $protectLevel;
387 $page = $services->getWikiPageFactory()->newFromTitle(
$title );
388 $status = $page->doUpdateRestrictions( $restrictions, [], $cascade,
'', $user );
389 $this->
output( ( $status->isOK() ?
'done' :
'failed' ) .
"\n" );
392 $this->
output(
"failed. (at recordUpload stage)\n" );
399 if ( $limit && $processed >= $limit ) {
404 # Print out some statistics
410 'ignored' =>
'Ignored',
412 'skipped' =>
'Skipped',
413 'overwritten' =>
'Overwritten',
418 $this->
output(
"{$desc}: {$$var}\n" );
422 $this->
output(
"No suitable files could be found for import.\n" );
434 private function findFiles( $dir, $exts, $recurse =
false ) {
435 if ( is_dir( $dir ) ) {
436 $dhl = opendir( $dir );
439 while ( (
$file = readdir( $dhl ) ) !==
false ) {
440 if ( is_file( $dir .
'/' .
$file ) ) {
441 $ext = pathinfo(
$file, PATHINFO_EXTENSION );
442 if ( array_search( strtolower(
$ext ), $exts ) !==
false ) {
443 $files[] = $dir .
'/' .
$file;
445 } elseif ( $recurse && is_dir( $dir .
'/' .
$file ) &&
$file !==
'..' &&
$file !==
'.' ) {
446 $files = array_merge( $files, $this->
findFiles( $dir .
'/' .
$file, $exts,
true ) );
474 if ( strpos( $auxExtension,
'.' ) !== 0 ) {
475 $auxExtension =
'.' . $auxExtension;
478 $d = dirname(
$file );
479 $n = basename(
$file );
481 while ( $maxStrip >= 0 ) {
482 $f = $d .
'/' . $n . $auxExtension;
484 if ( file_exists( $f ) ) {
488 $idx = strrpos( $n,
'.' );
493 $n = substr( $n, 0, $idx );
510 $url = $wiki_host .
'/api.php?action=query&format=xml&titles=File:'
511 . rawurlencode(
$file ) .
'&prop=imageinfo&&iiprop=comment';
512 $body = MediaWikiServices::getInstance()->getHttpRequestFactory()->get( $url, [], __METHOD__ );
513 if ( preg_match(
'#<ii comment="([^"]*)" />#', $body,
$matches ) == 0 ) {
517 return html_entity_decode(
$matches[1] );
521 $url = $wiki_host .
'/api.php?action=query&format=xml&titles=File:'
522 . rawurlencode(
$file ) .
'&prop=imageinfo&&iiprop=user';
523 $body = MediaWikiServices::getInstance()->getHttpRequestFactory()->get( $url, [], __METHOD__ );
524 if ( preg_match(
'#<ii user="([^"]*)" />#', $body,
$matches ) == 0 ) {
528 return html_entity_decode(
$matches[1] );
534require_once RUN_MAINTENANCE_IF_MAIN;
$wgRestrictionLevels
Rights which can be required for each protection level (via action=protect)
$wgFileExtensions
This is the list of preferred extensions for uploading files.
wfBaseName( $path, $suffix='')
Return the final portion of a pathname.
static getSha1Base36FromPath( $path)
Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case encoding,...
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 was set.
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 setUser( $user)
Reset the stub global user to a different "real" user object, while ensuring that any method calls on...
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
static newFromName( $name, $validate='valid')
static newSystemUser( $name, $options=[])
Static factory method for creation of a "system" user from username.
const MAINTENANCE_SCRIPT_USER
Username used for various maintenance scripts.
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
if(!is_readable( $file)) $ext