35require_once __DIR__ .
'/Maintenance.php';
40 parent::__construct();
42 $this->
addDescription(
'Imports images and other media files into the wiki' );
43 $this->
addArg(
'dir',
'Path to the directory containing images to be imported' );
46 'Comma-separated list of allowable extensions, defaults to $wgFileExtensions',
51 'Overwrite existing images with the same name (default is to skip them)' );
53 'Limit the number of images to process. Ignored or skipped images are not counted',
58 "Ignore all files until the one with the given name. Useful for resuming aborted "
59 .
"imports. The name should be the file's canonical database form.",
64 'Skip images that were already uploaded under a different name (check SHA1)' );
65 $this->
addOption(
'search-recursively',
'Search recursively for files in subdirectories' );
67 'Sleep between files. Useful mostly for debugging',
72 "Set username of uploader, default 'Maintenance script'",
78 $this->
addOption(
'check-userblock',
'Check if the user got blocked during import' );
80 "Set file description, default 'Importing file'",
85 'Set description to the content of this file',
90 'Causes the description for each file to be loaded from a file with the same name, but '
91 .
'the extension provided. If a global description is also given, it is appended.',
96 'Upload summary, description will be used if not provided',
101 'Use an optional license template',
106 'Override upload time/date, all MediaWiki timestamp formats are accepted',
111 'Specify the protect value (autoconfirmed,sysop)',
115 $this->
addOption(
'unprotect',
'Unprotects all uploaded images' );
117 'If specified, take User and Comment data for each imported file from this URL. '
118 .
'For example, --source-wiki-url="http://en.wikipedia.org/',
122 $this->
addOption(
'dry',
"Dry run, don't import anything" );
128 $processed = $added = $ignored = $skipped = $overwritten = $failed = 0;
130 $this->
output(
"Import Images\n\n" );
132 $dir = $this->
getArg( 0 );
136 $this->
fatalError(
"Cannot specify both protect and unprotect. Only 1 is allowed.\n" );
140 $this->
fatalError(
"You must specify a protection option.\n" );
143 # Prepare the list of allowed extensions
144 $extensions = $this->
hasOption(
'extensions' )
145 ? explode(
',', strtolower( $this->
getOption(
'extensions' ) ) )
148 # Search the path provided for candidates for import
149 $files = $this->
findFiles( $dir, $extensions, $this->
hasOption(
'search-recursively' ) );
151 # Initialise the user for this operation
155 if ( !$user instanceof
User ) {
160 # Get block check. If a value is given, this specified how often the check is performed
161 $checkUserBlock = (int)$this->
getOption(
'check-userblock' );
164 $sleep = (int)$this->
getOption(
'sleep' );
165 $limit = (int)$this->
getOption(
'limit' );
166 $timestamp = $this->
getOption(
'timestamp',
false );
168 # Get the upload comment. Provide a default one in case there's no comment given.
169 $commentFile = $this->
getOption(
'comment-file' );
170 if ( $commentFile !==
null ) {
171 $comment = file_get_contents( $commentFile );
172 if ( $comment ===
false || $comment ===
null ) {
173 $this->
fatalError(
"failed to read comment file: {$commentFile}\n" );
176 $comment = $this->
getOption(
'comment',
'Importing file' );
178 $commentExt = $this->
getOption(
'comment-ext' );
179 $summary = $this->
getOption(
'summary',
'' );
181 $license = $this->
getOption(
'license',
'' );
183 $sourceWikiUrl = $this->
getOption(
'source-wiki-url' );
185 # Batch "upload" operation
186 $count = count( $files );
188 foreach ( $files as $file ) {
189 if ( $sleep && ( $processed > 0 ) ) {
197 if ( !is_object( $title ) ) {
199 "{$base} could not be imported; a valid title cannot be produced\n" );
204 if ( $from == $title->getDBkey() ) {
212 if ( $checkUserBlock && ( ( $processed % $checkUserBlock ) == 0 ) ) {
213 $user->clearInstanceCache(
'name' );
214 if ( $user->isBlocked() ) {
215 $this->
output( $user->getName() .
" was blocked! Aborting.\n" );
224 $this->
output(
"{$base} exists, overwriting..." );
225 $svar =
'overwritten';
227 $this->
output(
"{$base} exists, skipping\n" );
232 if ( $this->
hasOption(
'skip-dupes' ) ) {
233 $repo =
$image->getRepo();
234 # XXX: we end up calculating this again when actually uploading. that sucks.
237 $dupes = $repo->findBySha1( $sha1 );
241 "{$base} already exists as {$dupes[0]->getName()}, skipping\n" );
247 $this->
output(
"Importing {$base}..." );
251 if ( $sourceWikiUrl ) {
254 if ( $real_comment ===
false ) {
255 $commentText = $comment;
257 $commentText = $real_comment;
262 if ( $real_user ===
false ) {
266 if ( $wgUser ===
false ) {
267 # user does not exist in target wiki
269 "failed: user '$real_user' does not exist in target wiki." );
275 $commentText =
false;
280 $this->
output(
" No comment file with extension {$commentExt} found "
281 .
"for {$file}, using default comment. " );
283 $commentText = file_get_contents( $f );
284 if ( !$commentText ) {
286 " Failed to load comment file {$f}, using default comment. " );
291 if ( !$commentText ) {
292 $commentText = $comment;
299 " publishing {$file} by '{$wgUser->getName()}', comment '$commentText'... "
303 $props = $mwProps->getPropsFromPath( $file,
true );
305 $publishOptions = [];
308 $metadata = Wikimedia\quietCall(
'unserialize', $props[
'metadata'] );
310 $publishOptions[
'headers'] =
$handler->getContentHeaders( $metadata );
312 $publishOptions[
'headers'] = [];
314 $archive =
$image->publish( $file, $flags, $publishOptions );
315 if ( !$archive->isGood() ) {
316 $this->
output(
"failed. (" .
317 $archive->getWikiText(
false,
false,
'en' ) .
326 $summary = $commentText;
330 $this->
output(
"done.\n" );
331 } elseif (
$image->recordUpload2(
339 $this->
output(
"done.\n" );
343 $protectLevel = $this->
getOption(
'protect' );
355 $this->
output(
"\nWaiting for replica DBs...\n" );
357 sleep( 2.0 ); # Why
this sleep?
360 $this->
output(
"\nSetting image restrictions ... " );
364 foreach ( $title->getRestrictionTypes() as
$type ) {
365 $restrictions[
$type] = $protectLevel;
368 $page = WikiPage::factory( $title );
369 $status = $page->doUpdateRestrictions( $restrictions, [], $cascade,
'', $user );
370 $this->
output( (
$status->isOK() ?
'done' :
'failed' ) .
"\n" );
373 $this->
output(
"failed. (at recordUpload stage)\n" );
380 if ( $limit && $processed >= $limit ) {
385 # Print out some statistics
391 'ignored' =>
'Ignored',
393 'skipped' =>
'Skipped',
394 'overwritten' =>
'Overwritten',
399 $this->
output(
"{$desc}: {$$var}\n" );
403 $this->
output(
"No suitable files could be found for import.\n" );
415 private function findFiles( $dir, $exts, $recurse =
false ) {
416 if ( is_dir( $dir ) ) {
417 $dhl = opendir( $dir );
420 while ( ( $file = readdir( $dhl ) ) !==
false ) {
421 if ( is_file( $dir .
'/' . $file ) ) {
423 if ( array_search( strtolower(
$ext ), $exts ) !==
false ) {
424 $files[] = $dir .
'/' . $file;
426 } elseif ( $recurse && is_dir( $dir .
'/' . $file ) && $file !==
'..' && $file !==
'.' ) {
427 $files = array_merge( $files, $this->
findFiles( $dir .
'/' . $file, $exts,
true ) );
447 $parts = explode(
'.', $filename );
448 $ext = $parts[count( $parts ) - 1];
449 unset( $parts[count( $parts ) - 1] );
450 $fname = implode(
'.', $parts );
469 private function findAuxFile( $file, $auxExtension, $maxStrip = 1 ) {
470 if ( strpos( $auxExtension,
'.' ) !== 0 ) {
471 $auxExtension =
'.' . $auxExtension;
474 $d = dirname( $file );
475 $n = basename( $file );
477 while ( $maxStrip >= 0 ) {
478 $f = $d .
'/' . $n . $auxExtension;
480 if ( file_exists( $f ) ) {
484 $idx = strrpos( $n,
'.' );
489 $n = substr( $n, 0, $idx );
496 # @todo FIXME: Access the api in a saner way and performing just one query
497 # (preferably batching files too).
499 $url = $wiki_host .
'/api.php?action=query&format=xml&titles=File:'
500 . rawurlencode( $file ) .
'&prop=imageinfo&&iiprop=comment';
501 $body =
Http::get( $url, [], __METHOD__ );
502 if ( preg_match(
'#<ii comment="([^"]*)" />#', $body,
$matches ) == 0 ) {
506 return html_entity_decode(
$matches[1] );
510 $url = $wiki_host .
'/api.php?action=query&format=xml&titles=File:'
511 . rawurlencode( $file ) .
'&prop=imageinfo&&iiprop=user';
512 $body =
Http::get( $url, [], __METHOD__ );
513 if ( preg_match(
'#<ii user="([^"]*)" />#', $body,
$matches ) == 0 ) {
517 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.
wfLocalFile( $title)
Get an object referring to a locally registered file.
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings,...
static getSha1Base36FromPath( $path)
Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case encoding,...
static get( $url, $options=[], $caller=__METHOD__)
Simple wrapper for Http::request( 'GET' )
execute()
Do the actual work.
getFileCommentFromSourceWiki( $wiki_host, $file)
splitFilename( $filename)
Split a filename into filename and extension.
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.
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check $image
Status::newGood()` to allow deletion, and then `return false` from the hook function. Ensure you consume the 'ChangeTagAfterDelete' hook to carry out custom deletion actions. $tag:name of the tag $user:user initiating the action & $status:Status object. See above. 'ChangeTagsListActive':Allows you to nominate which of the tags your extension uses are in active use. & $tags:list of all active tags. Append to this array. 'ChangeTagsAfterUpdateTags':Called after tags have been updated with the ChangeTags::updateTags function. Params:$addedTags:tags effectively added in the update $removedTags:tags effectively removed in the update $prevTags:tags that were present prior to the update $rc_id:recentchanges table id $rev_id:revision table id $log_id:logging table id $params:tag params $rc:RecentChange being tagged when the tagging accompanies the action, or null $user:User who performed the tagging when the tagging is subsequent to the action, or null 'ChangeTagsAllowedAdd':Called when checking if a user can add tags to a change. & $allowedTags:List of all the tags the user is allowed to add. Any tags the user wants to add( $addTags) that are not in this array will cause it to fail. You may add or remove tags to this array as required. $addTags:List of tags user intends to add. $user:User who is adding the tags. 'ChangeUserGroups':Called before user groups are changed. $performer:The User who will perform the change $user:The User whose groups will be changed & $add:The groups that will be added & $remove:The groups that will be removed 'Collation::factory':Called if $wgCategoryCollation is an unknown collation. $collationName:Name of the collation in question & $collationObject:Null. Replace with a subclass of the Collation class that implements the collation given in $collationName. 'ConfirmEmailComplete':Called after a user 's email has been confirmed successfully. $user:user(object) whose email is being confirmed 'ContentAlterParserOutput':Modify parser output for a given content object. Called by Content::getParserOutput after parsing has finished. Can be used for changes that depend on the result of the parsing but have to be done before LinksUpdate is called(such as adding tracking categories based on the rendered HTML). $content:The Content to render $title:Title of the page, as context $parserOutput:ParserOutput to manipulate 'ContentGetParserOutput':Customize parser output for a given content object, called by AbstractContent::getParserOutput. May be used to override the normal model-specific rendering of page content. $content:The Content to render $title:Title of the page, as context $revId:The revision ID, as context $options:ParserOptions for rendering. To avoid confusing the parser cache, the output can only depend on parameters provided to this hook function, not on global state. $generateHtml:boolean, indicating whether full HTML should be generated. If false, generation of HTML may be skipped, but other information should still be present in the ParserOutput object. & $output:ParserOutput, to manipulate or replace 'ContentHandlerDefaultModelFor':Called when the default content model is determined for a given title. May be used to assign a different model for that title. $title:the Title in question & $model:the model name. Use with CONTENT_MODEL_XXX constants. 'ContentHandlerForModelID':Called when a ContentHandler is requested for a given content model name, but no entry for that model exists in $wgContentHandlers. Note:if your extension implements additional models via this hook, please use GetContentModels hook to make them known to core. $modeName:the requested content model name & $handler:set this to a ContentHandler object, if desired. 'ContentModelCanBeUsedOn':Called to determine whether that content model can be used on a given page. This is especially useful to prevent some content models to be used in some special location. $contentModel:ID of the content model in question $title:the Title in question. & $ok:Output parameter, whether it is OK to use $contentModel on $title. Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok. 'ContribsPager::getQueryInfo':Before the contributions query is about to run & $pager:Pager object for contributions & $queryInfo:The query for the contribs Pager 'ContribsPager::reallyDoQuery':Called before really executing the query for My Contributions & $data:an array of results of all contribs queries $pager:The ContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'ContributionsLineEnding':Called before a contributions HTML line is finished $page:SpecialPage object for contributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'ContributionsToolLinks':Change tool links above Special:Contributions $id:User identifier $title:User page title & $tools:Array of tool links $specialPage:SpecialPage instance for context and services. Can be either SpecialContributions or DeletedContributionsPage. Extensions should type hint against a generic SpecialPage though. 'ConvertContent':Called by AbstractContent::convert when a conversion to another content model is requested. Handler functions that modify $result should generally return false to disable further attempts at conversion. $content:The Content object to be converted. $toModel:The ID of the content model to convert to. $lossy: boolean indicating whether lossy conversion is allowed. & $result:Output parameter, in case the handler function wants to provide a converted Content object. Note that $result->getContentModel() must return $toModel. 'ContentSecurityPolicyDefaultSource':Modify the allowed CSP load sources. This affects all directives except for the script directive. If you want to add a script source, see ContentSecurityPolicyScriptSource hook. & $defaultSrc:Array of Content-Security-Policy allowed sources $policyConfig:Current configuration for the Content-Security-Policy header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyDirectives':Modify the content security policy directives. Use this only if ContentSecurityPolicyDefaultSource and ContentSecurityPolicyScriptSource do not meet your needs. & $directives:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyScriptSource':Modify the allowed CSP script sources. Note that you also have to use ContentSecurityPolicyDefaultSource if you want non-script sources to be loaded from whatever you add. & $scriptSrc:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'CustomEditor':When invoking the page editor Return true to allow the normal editor to be used, or false if implementing a custom editor, e.g. for a special namespace, etc. $article:Article being edited $user:User performing the edit 'DatabaseOraclePostInit':Called after initialising an Oracle database $db:the DatabaseOracle object 'DeletedContribsPager::reallyDoQuery':Called before really executing the query for Special:DeletedContributions Similar to ContribsPager::reallyDoQuery & $data:an array of results of all contribs queries $pager:The DeletedContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'DeletedContributionsLineEnding':Called before a DeletedContributions HTML line is finished. Similar to ContributionsLineEnding $page:SpecialPage object for DeletedContributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'DeleteUnknownPreferences':Called by the cleanupPreferences.php maintenance script to build a WHERE clause with which to delete preferences that are not known about. This hook is used by extensions that have dynamically-named preferences that should not be deleted in the usual cleanup process. For example, the Gadgets extension creates preferences prefixed with 'gadget-', and so anything with that prefix is excluded from the deletion. &where:An array that will be passed as the $cond parameter to IDatabase::select() to determine what will be deleted from the user_properties table. $db:The IDatabase object, useful for accessing $db->buildLike() etc. 'DifferenceEngineAfterLoadNewText':called in DifferenceEngine::loadNewText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before returning true from this function. $differenceEngine:DifferenceEngine object 'DifferenceEngineLoadTextAfterNewContentIsLoaded':called in DifferenceEngine::loadText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before checking if the variable 's value is null. This hook can be used to inject content into said class member variable. $differenceEngine:DifferenceEngine object 'DifferenceEngineMarkPatrolledLink':Allows extensions to change the "mark as
patrolled" link which is shown both on the diff header as well as on the bottom of a page, usually wrapped in a span element which has class="patrollink". $differenceEngine:DifferenceEngine object & $markAsPatrolledLink:The "mark as patrolled" link HTML(string) $rcid:Recent change ID(rc_id) for this change(int) 'DifferenceEngineMarkPatrolledRCID':Allows extensions to possibly change the rcid parameter. For example the rcid might be set to zero due to the user being the same as the performer of the change but an extension might still want to show it under certain conditions. & $rcid:rc_id(int) of the change or 0 $differenceEngine:DifferenceEngine object $change:RecentChange object $user:User object representing the current user 'DifferenceEngineNewHeader':Allows extensions to change the $newHeader variable, which contains information about the new revision, such as the revision 's author, whether the revision was marked as a minor edit or not, etc. $differenceEngine:DifferenceEngine object & $newHeader:The string containing the various #mw-diff-otitle[1-5] divs, which include things like revision author info, revision comment, RevisionDelete link and more $formattedRevisionTools:Array containing revision tools, some of which may have been injected with the DiffRevisionTools hook $nextlink:String containing the link to the next revision(if any) $status
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check set to true or false to override the $wgMaxImageArea check result gives extension the possibility to transform it themselves $handler
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
require_once RUN_MAINTENANCE_IF_MAIN
if(!is_readable( $file)) $ext