Go to the documentation of this file.
27 require_once __DIR__ .
'/Maintenance.php';
44 parent::__construct();
45 $gz = in_array(
'compress.zlib', stream_get_wrappers() ) ?
'ok' :
'(disabled; requires PHP zlib module)';
46 $bz2 = in_array(
'compress.bzip2', stream_get_wrappers() ) ?
'ok' :
'(disabled; requires PHP bzip2 module)';
48 $this->mDescription = <<<TEXT
50 dumpBackup.php, and saves them into the current
wiki.
52 Compressed XML files may be read
directly:
55 .7z (
if 7za executable
is in PATH)
58 alternate methods which can be much faster
for full site restoration:
61 $this->stderr = fopen(
"php://stderr",
"wt" );
63 'Report position and speed after every n pages processed',
false,
true );
65 'Import only the pages from namespaces belonging to the list of ' .
66 'pipe-separated namespace names or namespace indexes',
false,
true );
67 $this->
addOption(
'dry-run',
'Parse dump without actually importing pages' );
68 $this->
addOption(
'debug',
'Output extra verbose debug information' );
69 $this->
addOption(
'uploads',
'Process file upload data if included (experimental)' );
70 $this->
addOption(
'no-updates',
'Disable link table updates. Is faster but leaves the wiki in an inconsistent state' );
71 $this->
addOption(
'image-base-path',
'Import files from a specified path',
false,
true );
72 $this->
addArg(
'file',
'Dump file to import [else use stdin]',
false );
77 $this->
error(
"Wiki is in read-only mode; you'll need to disable it for import to work.",
true );
80 $this->reportingInterval = intval( $this->
getOption(
'report', 100 ) );
81 if ( !$this->reportingInterval ) {
82 $this->reportingInterval = 100;
85 $this->dryRun = $this->
hasOption(
'dry-run' );
86 $this->uploads = $this->
hasOption(
'uploads' );
87 if ( $this->
hasOption(
'image-base-path' ) ) {
88 $this->imageBasePath = $this->
getOption(
'image-base-path' );
100 $this->
output(
"Done!\n" );
101 $this->
output(
"You might want to run rebuildrecentchanges.php to regenerate RecentChanges\n" );
106 $this->nsFilter =
false;
109 $this->nsFilter = array_unique( array_map(
array( $this,
'getNsIndex' ),
$namespaces ) );
117 $ns = intval( $namespace );
118 if ( strval( $ns ) === $namespace &&
$wgContLang->getNsText( $ns ) !==
false ) {
121 $this->
error(
"Unknown namespace text / index specified: $namespace",
true );
129 if ( $obj instanceof
Title ) {
130 $ns = $obj->getNamespace();
131 } elseif ( $obj instanceof
Revision ) {
132 $ns = $obj->getTitle()->getNamespace();
134 $ns = $obj->title->getNamespace();
137 $this->
error(
"Cannot get namespace of object in " . __METHOD__,
true );
139 return is_array( $this->nsFilter ) && !in_array( $ns, $this->nsFilter );
153 $this->
progress(
"Got bogus revision with null title!" );
164 if ( !$this->dryRun ) {
165 call_user_func( $this->importCallback,
$rev );
174 if ( $this->uploads ) {
178 $this->uploadCount++;
180 $this->
progress(
"upload: " . $revision->getFilename() );
182 if ( !$this->dryRun ) {
186 return $dbw->deadlockLoop(
array( $revision,
'importUpload' ) );
198 if ( !$this->dryRun ) {
199 call_user_func( $this->logItemCallback,
$rev );
204 if ( $final xor ( $this->pageCount % $this->reportingInterval == 0 ) ) {
210 if ( !$this->mQuiet ) {
211 $delta = microtime(
true ) - $this->startTime;
213 $rate = sprintf(
"%.2f", $this->pageCount / $delta );
214 $revrate = sprintf(
"%.2f", $this->revCount / $delta );
219 # Logs dumps don't have page tallies
220 if ( $this->pageCount ) {
221 $this->
progress(
"$this->pageCount ($rate pages/sec $revrate revs/sec)" );
223 $this->
progress(
"$this->revCount ($revrate revs/sec)" );
232 fwrite( $this->stderr, $string .
"\n" );
236 if ( preg_match(
'/\.gz$/', $filename ) ) {
237 $filename =
'compress.zlib://' . $filename;
238 } elseif ( preg_match(
'/\.bz2$/', $filename ) ) {
239 $filename =
'compress.bzip2://' . $filename;
240 } elseif ( preg_match(
'/\.7z$/', $filename ) ) {
241 $filename =
'mediawiki.compress.7z://' . $filename;
244 $file = fopen( $filename,
'rt' );
249 $file = fopen(
'php://stdin',
'rt' );
250 if ( self::posix_isatty(
$file ) ) {
257 $this->startTime = microtime(
true );
263 $importer->setDebug(
true );
265 if ( $this->
hasOption(
'no-updates' ) ) {
266 $importer->setNoUpdates(
true );
268 $importer->setPageCallback(
array( &$this,
'reportPage' ) );
269 $this->importCallback = $importer->setRevisionCallback(
270 array( &$this,
'handleRevision' ) );
271 $this->uploadCallback = $importer->setUploadCallback(
272 array( &$this,
'handleUpload' ) );
273 $this->logItemCallback = $importer->setLogItemCallback(
274 array( &$this,
'handleLogItem' ) );
275 if ( $this->uploads ) {
276 $importer->setImportUploads(
true );
278 if ( $this->imageBasePath ) {
279 $importer->setImageBasePath( $this->imageBasePath );
282 if ( $this->dryRun ) {
283 $importer->setPageOutCallback(
null );
286 return $importer->doImport();
XML file reader for the page data importer.
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. $reader:XMLReader object $logInfo:Array of information Return false to stop further processing of the tag 'ImportHandlePageXMLTag':When parsing a XML tag in a page. $reader:XMLReader object $pageInfo:Array of information Return false to stop further processing of the tag 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information Return false to stop further processing of the tag 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. $reader:XMLReader object Return false to stop further processing of the tag 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. $reader:XMLReader object $revisionInfo:Array of information Return false to stop further processing of the tag 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. $title:Title object for the current page $request:WebRequest $ignoreRedirect:boolean to skip redirect check $target:Title/string of redirect target $article:Article object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) $article:article(object) being checked 'IsTrustedProxy':Override the result of wfIsTrustedProxy() $ip:IP being check $result:Change this value to override the result of wfIsTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of User::isValidEmailAddr(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetMagic':DEPRECATED, use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetSpecialPageAliases':DEPRECATED, use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Associative array mapping language codes to prefixed links of the form "language:title". & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LinkBegin':Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
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
__construct()
Default constructor.
skin txt MediaWiki includes four core it has been set as the default in MediaWiki since the replacing Monobook it had been been the default skin since before being replaced by Vector largely rewritten in while keeping its appearance Several legacy skins were removed in the as the burden of supporting them became too heavy to bear Those in etc for skin dependent CSS etc for skin dependent JavaScript These can also be customised on a per user by etc This feature has led to a wide variety of user styles becoming that gallery is a good place to ending in php
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
maybeHelp( $force=false)
Maybe show the help.
& wfGetDB( $db, $groups=array(), $wiki=false)
Get a Database object.
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
addOption( $name, $description, $required=false, $withArg=false, $shortName=false)
Add a parameter to the script.
importFromFile( $filename)
require_once RUN_MAINTENANCE_IF_MAIN
wfReadOnly()
Check whether the wiki is in read-only mode.
setNsfilter(array $namespaces)
hasArg( $argId=0)
Does a given argument exist?
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the content language as $wgContLang
static doUpdates( $commit='')
Do any deferred updates and clear the list.
The ContentHandler facility adds support for arbitrary content types on wiki pages
wfBacktrace()
Get a debug backtrace as a string.
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
has been added to your &Future changes to this page and its associated Talk page will be listed there
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 database etc For and for historical it also represents a few features of articles that don t involve their such as access rights See also title txt Article Encapsulates access to the page table of the database The object represents a an and maintains state such as etc Revision Encapsulates individual page revision data and access to the revision text blobs storage system Higher level code should never touch text storage directly
Maintenance script that imports XML dump files into the current wiki.
the array() calling protocol came about after MediaWiki 1.4rc1.
List of Api Query prop modules.
when a variable name is used in a it is silently declared as a new masking the global
Use of locking define a new flag for $wgAntiLockFlags which allows them to be turned because we ll almost certainly need to do so on the Wikimedia cluster Instead of locking reads
wfWaitForSlaves( $maxLag=false, $wiki=false, $cluster=false)
Modern version of wfWaitForSlaves().
processing should stop and the error should be shown to the user * false
presenting them properly to the user as errors is done by the caller $title
importFromHandle( $handle)
if(PHP_SAPI !='cli') $file
presenting them properly to the user as errors is done by the caller return true use this to change the list i e etc $rev
Represents a title within MediaWiki.
namespace and then decline to actually register it & $namespaces
getOption( $name, $default=null)
Get an option, or return the default.
Prior to maintenance scripts were a hodgepodge of code that had no cohesion or formal method of action Beginning in
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
execute()
Do the actual work.
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 https
addArg( $arg, $description, $required=true)
Add some args that are needed.
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
if(PHP_SAPI !='cli') $source
error( $err, $die=0)
Throw an error to the user.
output( $out, $channel=null)
Throw some output to the user.
Please log in again after you receive it</td >< td > s a saved copy from
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 then executing the whole list after the page is displayed We don t do anything smart like collating updates to the same table or such because the list is almost always going to have just one item on if that
hasOption( $name)
Checks to see if a particular param exists.
getArg( $argId=0, $default=null)
Get an argument.