36 'extensions',
'comment',
'comment-file',
'comment-ext',
'summary',
'user',
37 'license',
'sleep',
'limit',
'from',
'source-wiki-url',
'timestamp',
41 'protect',
'unprotect',
'search-recursively',
'check-userblock',
'overwrite',
45 require_once __DIR__ .
'/commandLine.inc';
46 require_once __DIR__ .
'/importImages.inc';
47 $processed = $added = $ignored = $skipped = $overwritten = $failed = 0;
49 echo
"Import Images\n\n";
52 if ( count(
$args ) == 0 ) {
60 die(
"Cannot specify both protect and unprotect. Only 1 is allowed.\n" );
64 die(
"You must specify a protection option.\n" );
67 # Prepare the list of allowed extensions
70 ? explode(
',', strtolower(
$options[
'extensions'] ) )
73 # Search the path provided for candidates for import
76 # Initialise the user for this operation
79 : User::newSystemUser(
'Maintenance script', [
'steal' =>
true ] );
80 if ( !
$user instanceof User ) {
85 # Get block check. If a value is given, this specified how often the check is performed
86 if ( isset(
$options[
'check-userblock'] ) ) {
87 if ( !
$options[
'check-userblock'] ) {
90 $checkUserBlock = (int)
$options[
'check-userblock'];
93 $checkUserBlock =
false;
97 MediaWiki\suppressWarnings();
99 MediaWiki\restoreWarnings();
102 MediaWiki\suppressWarnings();
104 MediaWiki\restoreWarnings();
111 MediaWiki\suppressWarnings();
113 MediaWiki\restoreWarnings();
121 # Get the upload comment. Provide a default one in case there's no comment given.
124 if ( isset(
$options[
'comment-file'] ) ) {
127 die(
"failed to read comment file: {$options['comment-file']}\n" );
129 } elseif ( isset(
$options[
'comment'] ) ) {
137 # Get the license specifier
140 # Batch "upload" operation
149 if ( !is_object(
$title ) ) {
150 echo
"{$base} could not be imported; a valid title cannot be produced\n";
163 if ( $checkUserBlock && ( (
$processed % $checkUserBlock ) == 0 ) ) {
164 $user->clearInstanceCache(
'name' );
165 if (
$user->isBlocked() ) {
166 echo
$user->getName() .
" was blocked! Aborting.\n";
174 if ( isset(
$options[
'overwrite'] ) ) {
175 echo
"{$base} exists, overwriting...";
176 $svar =
'overwritten';
178 echo
"{$base} exists, skipping\n";
183 if ( isset(
$options[
'skip-dupes'] ) ) {
184 $repo =
$image->getRepo();
185 # XXX: we end up calculating this again when actually uploading. that sucks.
188 $dupes = $repo->findBySha1( $sha1 );
191 echo
"{$base} already exists as " . $dupes[0]->getName() .
", skipping\n";
197 echo
"Importing {$base}...";
201 if ( isset(
$options[
'source-wiki-url'] ) ) {
204 if ( $real_comment ===
false ) {
207 $commentText = $real_comment;
212 if ( $real_user ===
false ) {
217 # user does not exist in target wiki
218 echo
"failed: user '$real_user' does not exist in target wiki.";
224 $commentText =
false;
229 echo
" No comment file with extension {$commentExt} found "
230 .
"for {$file}, using default comment. ";
232 $commentText = file_get_contents( $f );
233 if ( !$commentText ) {
234 echo
" Failed to load comment file {$f}, using default comment. ";
239 if ( !$commentText ) {
246 echo
" publishing {$file} by '" .
$wgUser->
getName() .
"', comment '$commentText'... ";
249 $props = $mwProps->getPropsFromPath( $file,
true );
251 $publishOptions = [];
254 $publishOptions[
'headers'] =
$handler->getStreamHeaders( $props[
'metadata'] );
256 $publishOptions[
'headers'] = [];
258 $archive =
$image->publish( $file,
$flags, $publishOptions );
259 if ( !$archive->isGood() ) {
261 $archive->getWikiText(
false,
false,
'en' ) .
269 if ( !isset(
$options[
'summary'] ) ) {
275 } elseif (
$image->recordUpload2(
287 global $wgRestrictionLevels;
291 if ( $protectLevel && in_array( $protectLevel, $wgRestrictionLevels ) ) {
294 if ( isset(
$options[
'unprotect'] ) ) {
301 echo
"\nWaiting for replica DBs...\n";
303 sleep( 2.0 ); # Why
this sleep?
306 echo
"\nSetting image restrictions ... ";
311 $restrictions[
$type] = $protectLevel;
316 echo (
$status->isOK() ?
'done' :
'failed' ) .
"\n";
319 echo
"failed. (at recordUpload stage)\n";
335 # Print out some statistics
341 'ignored' =>
'Ignored',
343 'skipped' =>
'Skipped',
344 'overwritten' =>
'Overwritten',
349 echo
"{$desc}: {$$var}\n";
353 echo
"No suitable files could be found for import.\n";
367 <dir> : Path to
the directory containing images to be imported
372 --overwrite Overwrite existing images with
the same
name (
default
374 --limit=<num> Limit
the number
of images to process. Ignored
or
377 Useful
for resuming aborted imports. <
name> should be
378 the file's canonical database form.
379 --skip-dupes Skip images that were already uploaded under a different
381 --search-recursively Search recursively for files in subdirectories.
382 --sleep=<sec> Sleep between files. Useful mostly for debugging.
383 --user=<username> Set username of uploader, default 'Maintenance script
'.
384 --check-userblock Check if the user got blocked during import.
385 --comment=<text> Set file description, default 'Importing
file'.
386 --comment-file=<file> Set description to the content of <file>.
387 --comment-ext=<ext> Causes the description for each file to be loaded from a
388 file with the same name, but the extension <ext>. If a
389 global description is also given, it is appended.
390 --license=<code> Use an optional license template.
391 --dry Dry run, don't
import anything.
392 --protect=<protect> Specify
the protect value (autoconfirmed,
sysop).
393 --summary=<summary> Upload summary, description
will be
used if not
395 --timestamp=<timestamp> Override upload time/date, all
MediaWiki timestamp
396 formats
are accepted.
397 --unprotect Unprotects all uploaded images.
static newFromName($name, $validate= 'valid')
Static factory method for creation from username.
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
#define the
table suitable for use with IDatabase::select()
you don t have to do a grep find to see where the $wgReverseTitle variable is used
and how to run hooks for an and one after Each event has a preferably in CamelCase For ArticleDelete hook A clump of code and data that should be run when an event happens This can be either a function and a chunk of data
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
wfWaitForSlaves($ifWritesSince=null, $wiki=false, $cluster=false, $timeout=null)
Waits for the replica DBs to catch up to the master position.
if(isset($options['protect'])&&isset($options['unprotect'])) if(isset($options['protect'])&&$options['protect']==1) global $wgFileExtensions
static singleton()
Get an instance of this class.
We use the convention $dbr for read and $dbw for write to help you keep track of whether the database object is a the world will explode Or to be a subsequent write query which succeeded on the master may fail when replicated to the slave due to a unique key collision Replication on the slave will stop and it may take hours to repair the database and get it back online Setting read_only in my cnf on the slave will avoid this but given the dire we prefer to have as many checks as possible We provide a but the wrapper functions like please read the documentation for except in special pages derived from QueryPage It s a common pitfall for new developers to submit code containing SQL queries which examine huge numbers of rows Remember that COUNT * is(N), counting rows in atable is like counting beans in a bucket.------------------------------------------------------------------------Replication------------------------------------------------------------------------The largest installation of MediaWiki, Wikimedia, uses a large set ofslave MySQL servers replicating writes made to a master MySQL server.Itis important to understand the issues associated with this setup if youwant to write code destined for Wikipedia.It's often the case that the best algorithm to use for a given taskdepends on whether or not replication is in use.Due to our unabashedWikipedia-centrism, we often just use the replication-friendly version, but if you like, you can use wfGetLB() ->getServerCount() > 1 tocheck to see if replication is in use.===Lag===Lag primarily occurs when large write queries are sent to the master.Writes on the master are executed in parallel, but they are executed inserial when they are replicated to the slaves.The master writes thequery to the binlog when the transaction is committed.The slaves pollthe binlog and start executing the query as soon as it appears.They canservice reads while they are performing a write query, but will not readanything more from the binlog and thus will perform no more writes.Thismeans that if the write query runs for a long time, the slaves will lagbehind the master for the time it takes for the write query to complete.Lag can be exacerbated by high read load.MediaWiki's load balancer willstop sending reads to a slave when it is lagged by more than 30 seconds.If the load ratios are set incorrectly, or if there is too much loadgenerally, this may lead to a slave permanently hovering around 30seconds lag.If all slaves are lagged by more than 30 seconds, MediaWiki will stopwriting to the database.All edits and other write operations will berefused, with an error returned to the user.This gives the slaves achance to catch up.Before we had this mechanism, the slaves wouldregularly lag by several minutes, making review of recent editsdifficult.In addition to this, MediaWiki attempts to ensure that the user seesevents occurring on the wiki in chronological order.A few seconds of lagcan be tolerated, as long as the user sees a consistent picture fromsubsequent requests.This is done by saving the master binlog positionin the session, and then at the start of each request, waiting for theslave to catch up to that position before doing any reads from it.Ifthis wait times out, reads are allowed anyway, but the request isconsidered to be in"lagged slave mode".Lagged slave mode can bechecked by calling wfGetLB() ->getLaggedSlaveMode().The onlypractical consequence at present is a warning displayed in the pagefooter.===Lag avoidance===To avoid excessive lag, queries which write large numbers of rows shouldbe split up, generally to write one row at a time.Multi-row INSERT...SELECT queries are the worst offenders should be avoided altogether.Instead do the select first and then the insert.===Working with lag===Despite our best efforts, it's not practical to guarantee a low-lagenvironment.Lag will usually be less than one second, but mayoccasionally be up to 30 seconds.For scalability, it's very importantto keep load on the master low, so simply sending all your queries tothe master is not the answer.So when you have a genuine need forup-to-date data, the following approach is advised:1) Do a quick query to the master for a sequence number or timestamp 2) Run the full query on the slave and check if it matches the data you gotfrom the master 3) If it doesn't, run the full query on the masterTo avoid swamping the master every time the slaves lag, use of thisapproach should be kept to a minimum.In most cases you should just readfrom the slave and let the user deal with the delay.------------------------------------------------------------------------Lock contention------------------------------------------------------------------------Due to the high write rate on Wikipedia(and some other wikis), MediaWiki developers need to be very careful to structure their writesto avoid long-lasting locks.By default, MediaWiki opens a transactionat the first query, and commits it before the output is sent.Locks willbe held from the time when the query is done until the commit.So youcan reduce lock time by doing as much processing as possible before youdo your write queries.Often this approach is not good enough, and it becomes necessary toenclose small groups of queries in their own transaction.Use thefollowing syntax:$dbw=wfGetDB(DB_MASTER
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for and distribution as defined by Sections through of this document Licensor shall mean the copyright owner or entity authorized by the copyright owner that is granting the License Legal Entity shall mean the union of the acting entity and all other entities that control are controlled by or are under common control with that entity For the purposes of this definition control direct or to cause the direction or management of such whether by contract or including but not limited to software source documentation and configuration files Object form shall mean any form resulting from mechanical transformation or translation of a Source including but not limited to compiled object generated and conversions to other media types Work shall mean the work of whether in Source or Object made available under the as indicated by a copyright notice that is included in or attached to the whether in Source or Object that is based or other modifications as a an original work of authorship For the purposes of this Derivative Works shall not include works that remain separable from
globals txt Globals are evil The original MediaWiki code relied on globals for processing context far too often MediaWiki development since then has been a story of slowly moving context out of global variables and into objects Storing processing context in object member variables allows those objects to be reused in a much more flexible way Consider the elegance of
database rows
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
if(!$user instanceof User) $wgUser
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 example
getFileCommentFromSourceWiki($wiki_host, $file)
The most up to date schema for the tables in the database will always be tables sql in the maintenance directory
it s the revision text itself In either if gzip is the revision text is gzipped $flags
getFileUserFromSourceWiki($wiki_host, $file)
when a variable name is used in a it is silently declared as a new local masking the global
We ve cleaned up the code here by removing clumps of infrequently used code and moving them off somewhere else It s much easier for someone working with this code to see what s _really_ going and make changes or fix bugs In we can take all the code that deals with the little used title reversing options(say) and put it in one place.Instead of having little title-reversing if-blocks spread all over the codebase in showAnArticle
wfLocalFile($title)
Get an object referring to a locally registered file.
getName()
Get the user name, or the IP of an anonymous user.
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such and we might be restricted by PHP settings such as safe mode or open_basedir We cannot assume that the software even has read access anywhere useful Many shared hosts run all users web applications under the same so they can t rely on Unix and must forbid reads to even standard directories like tmp lest users read each others files We cannot assume that the user has the ability to install or run any programs not written as web accessible PHP scripts Since anything that works on cheap shared hosting will work if you have shell or root access MediaWiki s design is based around catering to the lowest common denominator Although we support higher end setups as the way many things work by default is tailored toward shared hosting These defaults are unconventional from the point of view of and they certainly aren t ideal for someone who s installing MediaWiki as MediaWiki does not conform to normal Unix filesystem layout Hopefully we ll offer direct support for standard layouts in the but for now *any change to the location of files is unsupported *Moving things and leaving symlinks will *probably *not break anything
Prior to maintenance scripts were a hodgepodge of code that had no cohesion or formal method of action Beginning maintenance scripts have been cleaned up to use a unified class Directory structure How to run a script How to write your own DIRECTORY STRUCTURE The maintenance directory of a MediaWiki installation contains several all of which have unique purposes HOW TO RUN A SCRIPT Ridiculously just call php someScript php that s in the top level maintenance directory if not default wiki
The ContentHandler facility adds support for arbitrary content types on wiki instead of relying on wikitext for everything It was introduced in MediaWiki Each kind of and so on Built in content types are
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
could not be made into a sysop(Did you enter the name correctly?)<
The ContentHandler facility adds support for arbitrary content types on wiki instead of relying on wikitext for everything It was introduced in MediaWiki Each kind of and so on Built in content types as usual *javascript user provided javascript code *json simple implementation for use by extensions
We ve cleaned up the code here by removing clumps of infrequently used code and moving them off somewhere else It s much easier for someone working with this code to see what s _really_ going and make changes or fix bugs In we can take all the code that deals with the little used title reversing we can concentrate it all in an extension file
findFiles($dir, $exts, $recurse=false)
Search a directory for files with one of a set of extensions.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
static newSystemUser($name, $options=[])
Static factory method for creation of a "system" user from username.
static getInitialPageText($comment= '', $license= '', $copyStatus= '', $source= '', Config $config=null)
Get the initial image page text based on a comment and optional file status information.
and(b) You must cause any modified files to carry prominent notices stating that You changed the files
static makeTitleSafe($ns, $title, $fragment= '', $interwiki= '')
Create a new Title from a namespace index and a DB key.
namespace and then decline to actually register it file or subcat img or subcat $title
static getSha1Base36FromPath($path)
Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case encoding, zero padded to 31 digits.
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object to manipulate or replace but no entry for that model exists in $wgContentHandlers if desired 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 inclusive false for true for descending in case the handler function wants to provide a converted Content object Note that $result getContentModel() must return $toModel. 'CustomEditor'$rcid is used in generating this variable which contains information about the new such as the revision s whether the revision was marked as a minor edit or not
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
wfBaseName($path, $suffix= '')
Return the final portion of a pathname.
null for the local wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify prev or next refreshes the diff cache allow viewing deleted revs difference engine object to be used for diff source
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at name
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add in any and then calling but I prefer the flexibility This should also do the output encoding The system allocates a global one in $wgOut Title Represents the title of an and does all the work of translating among various forms such as plain URL
if(isset($options['comment-file'])) elseif(isset($options['comment'])) $commentExt
MimeMagic helper wrapper.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $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 $image
findAuxFile($file, $auxExtension, $maxStrip=1)
Find an auxilliary file with the given extension, matching the give base file path.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring which defines all default service and specifies how they depend on each other("wiring").When a new service is added to MediaWiki core
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be skipped
</td >< td > &</td >< td > t want your writing to be edited mercilessly and redistributed at will
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
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached one of or reset my talk my contributions etc etc otherwise the built in rate limiting checks are if enabled allows for interception of redirect as a string mapping parameter names to values & $type
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached $page