35require_once __DIR__ .
'/Maintenance.php';
45 parent::__construct();
47 $this->
addDescription(
'Imports images and other media files into the wiki' );
48 $this->
addArg(
'dir',
'Path to the directory containing images to be imported' );
51 'Comma-separated list of allowable extensions, defaults to $wgFileExtensions',
56 'Overwrite existing images with the same name (default is to skip them)' );
58 'Limit the number of images to process. Ignored or skipped images are not counted',
63 "Ignore all files until the one with the given name. Useful for resuming aborted "
64 .
"imports. The name should be the file's canonical database form.",
69 'Skip images that were already uploaded under a different name (check SHA1)' );
70 $this->
addOption(
'search-recursively',
'Search recursively for files in subdirectories' );
72 'Sleep between files. Useful mostly for debugging',
77 "Set username of uploader, default 'Maintenance script'",
83 $this->
addOption(
'check-userblock',
'Check if the user got blocked during import' );
85 "Set file description, default 'Importing file'",
90 'Set description to the content of this file',
95 'Causes the description for each file to be loaded from a file with the same name, but '
96 .
'the extension provided. If a global description is also given, it is appended.',
101 'Upload summary, description will be used if not provided',
106 'Use an optional license template',
111 'Override upload time/date, all MediaWiki timestamp formats are accepted',
116 'Specify the protect value (autoconfirmed,sysop)',
120 $this->
addOption(
'unprotect',
'Unprotects all uploaded images' );
122 'If specified, take User and Comment data for each imported file from this URL. '
123 .
'For example, --source-wiki-url="https://en.wikipedia.org/w/',
127 $this->
addOption(
'dry',
"Dry run, don't import anything" );
131 $services = MediaWikiServices::getInstance();
132 $permissionManager = $services->getPermissionManager();
144 $this->
output(
"Importing Files\n\n" );
146 $dir = $this->
getArg( 0 );
150 $this->
fatalError(
"Cannot specify both protect and unprotect. Only 1 is allowed.\n" );
154 $this->
fatalError(
"You must specify a protection option.\n" );
157 # Prepare the list of allowed extensions
158 $extensions = $this->
hasOption(
'extensions' )
159 ? explode(
',', strtolower( $this->
getOption(
'extensions' ) ) )
160 : $this->
getConfig()->get( MainConfigNames::FileExtensions );
162 # Search the path provided for candidates for import
163 $files = $this->findFiles( $dir, $extensions, $this->
hasOption(
'search-recursively' ) );
164 if ( !$files->valid() ) {
165 $this->
output(
"No suitable files could be found for import.\n" );
169 # Initialise the user for this operation
173 if ( !$user instanceof
User ) {
176 '@phan-var User $user';
177 StubGlobalUser::setUser( $user );
179 # Get block check. If a value is given, this specified how often the check is performed
180 $checkUserBlock = (int)$this->
getOption(
'check-userblock' );
183 $sleep = (int)$this->
getOption(
'sleep' );
184 $limit = (int)$this->
getOption(
'limit' );
185 $timestamp = $this->
getOption(
'timestamp',
false );
187 # Get the upload comment. Provide a default one in case there's no comment given.
188 $commentFile = $this->
getOption(
'comment-file' );
189 if ( $commentFile !==
null ) {
190 $comment = file_get_contents( $commentFile );
191 if ( $comment ===
false || $comment ===
null ) {
192 $this->
fatalError(
"failed to read comment file: {$commentFile}\n" );
195 $comment = $this->
getOption(
'comment',
'Importing file' );
197 $commentExt = $this->
getOption(
'comment-ext' );
198 $summary = $this->
getOption(
'summary',
'' );
199 $license = $this->
getOption(
'license',
'' );
200 $sourceWikiUrl = $this->
getOption(
'source-wiki-url' );
206 # Batch "upload" operation
207 $restrictionStore = $services->getRestrictionStore();
208 foreach ( $files as
$file ) {
210 if ( $sleep && ( $processed > 0 ) ) {
220 "{$base} could not be imported; a valid title cannot be produced\n"
226 if ( $from !==
$title->getDBkey() ) {
227 $statistics[
'ignored']++;
234 if ( $checkUserBlock && ( ( $processed % $checkUserBlock ) == 0 ) ) {
235 $user->clearInstanceCache(
'name' );
236 if ( $permissionManager->isBlockedFrom( $user,
$title ) ) {
238 "{$user->getName()} is blocked from {$title->getPrefixedText()}! skipping.\n"
240 $statistics[
'skipped']++;
246 $image = $services->getRepoGroup()->getLocalRepo()
248 if ( $image->exists() ) {
250 $this->
output(
"{$base} exists, overwriting..." );
251 $svar =
'overwritten';
253 $this->
output(
"{$base} exists, skipping\n" );
254 $statistics[
'skipped']++;
258 if ( $this->
hasOption(
'skip-dupes' ) ) {
259 $repo = $image->getRepo();
260 # XXX: we end up calculating this again when actually uploading. that sucks.
262 $dupes = $repo->findBySha1( $sha1 );
265 "{$base} already exists as {$dupes[0]->getName()}, skipping\n"
267 $statistics[
'skipped']++;
272 $this->
output(
"Importing {$base}..." );
276 if ( $sourceWikiUrl ) {
278 $real_comment = $this->getFileCommentFromSourceWiki( $sourceWikiUrl,
$base );
279 $commentText = $real_comment !==
false ? $real_comment : $comment;
282 $real_user = $this->getFileUserFromSourceWiki( $sourceWikiUrl,
$base );
283 if ( $real_user !==
false ) {
285 if ( $realUser ===
false ) {
286 # user does not exist in target wiki
288 "failed: user '$real_user' does not exist in target wiki."
292 StubGlobalUser::setUser( $realUser );
297 $commentText =
false;
300 $f = $this->findAuxFile(
$file, $commentExt );
302 $this->
output(
" No comment file with extension {$commentExt} found "
303 .
"for {$file}, using default comment." );
305 $commentText = file_get_contents( $f );
306 if ( !$commentText ) {
308 " Failed to load comment file {$f}, using default comment."
314 if ( !$commentText ) {
315 $commentText = $comment;
322 " publishing {$file} by '{$user->getName()}', comment '$commentText'..."
325 $mwProps =
new MWFileProps( $services->getMimeAnalyzer() );
326 $props = $mwProps->getPropsFromPath(
$file,
true );
328 $publishOptions = [];
331 $publishOptions[
'headers'] = $handler->getContentHeaders( $props[
'metadata'] );
333 $publishOptions[
'headers'] = [];
335 $archive = $image->publish(
$file, $flags, $publishOptions );
336 if ( !$archive->isGood() ) {
337 $this->
output(
"failed. (" .
338 $archive->getMessage(
false,
false,
'en' )->text() .
340 $statistics[
'failed']++;
345 $commentText = SpecialUpload::getInitialPageText( $commentText, $license );
347 $summary = $commentText;
351 $this->
output(
"done.\n" );
352 } elseif ( $image->recordUpload3(
363 $this->
output(
"done.\n" );
367 $protectLevel = $this->
getOption(
'protect' );
368 $restrictionLevels = $this->
getConfig()->get( MainConfigNames::RestrictionLevels );
370 if ( $protectLevel && in_array( $protectLevel, $restrictionLevels ) ) {
380 $this->
output(
"\nWaiting for replica DBs...\n" );
382 sleep( 2 ); # Why
this sleep?
385 $this->
output(
"\nSetting image restrictions ..." );
389 foreach ( $restrictionStore->listApplicableRestrictionTypes(
$title ) as
$type ) {
390 $restrictions[
$type] = $protectLevel;
393 $page = $services->getWikiPageFactory()->newFromTitle(
$title );
394 $status = $page->doUpdateRestrictions( $restrictions, [], $cascade,
'', $user );
395 $this->
output( ( $status->isOK() ?
'done' :
'failed' ) .
"\n" );
398 $this->
output(
"failed. (at recordUpload stage)\n" );
402 $statistics[$svar]++;
405 if ( $limit && $processed >= $limit ) {
410 # Print out some statistics
412 foreach ( array_merge(
418 ) as $desc => $number ) {
420 $this->
output( ucfirst( $desc ) .
": $number\n" );
433 private function findFiles( $dir, $exts, $recurse =
false ) {
434 $dhl = is_dir( $dir ) ? opendir( $dir ) : false;
439 while ( (
$file = readdir( $dhl ) ) !==
false ) {
440 if ( is_file( $dir .
'/' .
$file ) ) {
441 $ext = pathinfo(
$file, PATHINFO_EXTENSION );
442 if ( in_array( strtolower(
$ext ), $exts ) ) {
443 yield $dir .
'/' .
$file;
445 } elseif ( $recurse && is_dir( $dir .
'/' .
$file ) &&
$file !==
'..' &&
$file !==
'.' ) {
446 yield from $this->findFiles( $dir .
'/' .
$file, $exts,
true );
465 private function findAuxFile(
$file, $auxExtension, $maxStrip = 1 ) {
466 if ( !str_starts_with( $auxExtension,
'.' ) ) {
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 );
501 private function getFileCommentFromSourceWiki( $wiki_host,
$file ) {
502 $url = $wiki_host .
'/api.php?action=query&format=xml&titles=File:'
503 . rawurlencode(
$file ) .
'&prop=imageinfo&&iiprop=comment';
504 $body = MediaWikiServices::getInstance()->getHttpRequestFactory()->get( $url, [], __METHOD__ );
505 if ( preg_match(
'#<ii comment="([^"]*)" />#', $body,
$matches ) == 0 ) {
509 return html_entity_decode(
$matches[1] );
512 private function getFileUserFromSourceWiki( $wiki_host,
$file ) {
513 $url = $wiki_host .
'/api.php?action=query&format=xml&titles=File:'
514 . rawurlencode(
$file ) .
'&prop=imageinfo&&iiprop=user';
515 $body = MediaWikiServices::getInstance()->getHttpRequestFactory()->get( $url, [], __METHOD__ );
516 if ( preg_match(
'#<ii user="([^"]*)" />#', $body,
$matches ) == 0 ) {
520 return html_entity_decode(
$matches[1] );
526require_once RUN_MAINTENANCE_IF_MAIN;
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.
__construct()
Default constructor.
MimeMagic helper wrapper.
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
addArg( $arg, $description, $required=true, $multi=false)
Add some args that are needed.
output( $out, $channel=null)
Throw some output to the user.
waitForReplication()
Wait for replica DBs to catch up.
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.
A class containing constants representing the names of configuration variables.
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