Go to the documentation of this file.
35 'extensions',
'comment',
'comment-file',
'comment-ext',
'summary',
'user',
36 'license',
'sleep',
'limit',
'from',
'source-wiki-url',
'timestamp',
38 require_once __DIR__ .
'/commandLine.inc';
39 require_once __DIR__ .
'/importImages.inc';
42 echo
"Import Images\n\n";
45 if ( count(
$args ) == 0 ) {
53 die(
"Cannot specify both protect and unprotect. Only 1 is allowed.\n" );
57 die(
"You must specify a protection option.\n" );
60 # Prepare the list of allowed extensions
63 ? explode(
',', strtolower(
$options[
'extensions'] ) )
66 # Search the path provided for candidates for import
69 # Initialise the user for this operation
72 :
User::newFromName(
'Maintenance script' );
78 # Get block check. If a value is given, this specified how often the check is performed
79 if ( isset(
$options[
'check-userblock'] ) ) {
80 if ( !
$options[
'check-userblock'] ) {
83 $checkUserBlock = (int)
$options[
'check-userblock'];
86 $checkUserBlock =
false;
106 # Get the upload comment. Provide a default one in case there's no comment given.
109 if ( isset(
$options[
'comment-file'] ) ) {
112 die(
"failed to read comment file: {$options['comment-file']}\n" );
114 } elseif ( isset(
$options[
'comment'] ) ) {
122 # Get the license specifier
125 # Batch "upload" operation
134 if ( !is_object(
$title ) ) {
135 echo
"{$base} could not be imported; a valid title cannot be produced\n";
148 if ( $checkUserBlock && ( (
$processed % $checkUserBlock ) == 0 ) ) {
149 $user->clearInstanceCache(
'name' );
150 if (
$user->isBlocked() ) {
151 echo
$user->getName() .
" was blocked! Aborting.\n";
158 if ( $image->exists() ) {
159 if ( isset(
$options[
'overwrite'] ) ) {
160 echo
"{$base} exists, overwriting...";
161 $svar =
'overwritten';
163 echo
"{$base} exists, skipping\n";
168 if ( isset(
$options[
'skip-dupes'] ) ) {
169 $repo = $image->getRepo();
172 $dupes = $repo->findBySha1( $sha1 );
175 echo
"{$base} already exists as " . $dupes[0]->getName() .
", skipping\n";
181 echo
"Importing {$base}...";
185 if ( isset(
$options[
'source-wiki-url'] ) ) {
188 if ( $real_comment ===
false ) {
191 $commentText = $real_comment;
196 if ( $real_user ===
false ) {
201 # user does not exist in target wiki
202 echo
"failed: user '$real_user' does not exist in target wiki.";
208 $commentText =
false;
213 echo
" No comment file with extension {$commentExt} found for {$file}, using default comment. ";
215 $commentText = file_get_contents(
$f );
216 if ( !$commentText ) {
217 echo
" Failed to load comment file {$f}, using default comment. ";
222 if ( !$commentText ) {
229 echo
" publishing {$file} by '" .
$wgUser->
getName() .
"', comment '$commentText'... ";
233 $publishOptions =
array();
236 $publishOptions[
'headers'] = $handler->getStreamHeaders( $props[
'metadata'] );
238 $publishOptions[
'headers'] =
array();
240 $archive = $image->publish(
$file,
$flags, $publishOptions );
241 if ( !$archive->isGood() ) {
243 $archive->getWikiText() .
251 if ( !isset(
$options[
'summary'] ) ) {
257 } elseif ( $image->recordUpload2( $archive->value,
$summary, $commentText, $props,
$timestamp ) ) {
263 global $wgRestrictionLevels;
267 if ( $protectLevel && in_array( $protectLevel, $wgRestrictionLevels ) ) {
270 if ( isset(
$options[
'unprotect'] ) ) {
277 echo
"\nWaiting for slaves...\n";
279 sleep( 2.0 ); # Why
this sleep?
282 echo
"\nSetting image restrictions ... ";
285 $restrictions =
array();
287 $restrictions[
$type] = $protectLevel;
291 $status = $page->doUpdateRestrictions( $restrictions,
array(), $cascade,
'',
$user );
292 echo ( $status->isOK() ?
'done' :
'failed' ) .
"\n";
296 echo
"failed. (at recordUpload stage)\n";
312 # Print out some statistics
314 foreach (
array(
'count' =>
'Found',
'limit' =>
'Limit',
'ignored' =>
'Ignored',
315 'added' =>
'Added',
'skipped' =>
'Skipped',
'overwritten' =>
'Overwritten',
316 'failed' =>
'Failed' )
as $var => $desc ) {
318 echo
"{$desc}: {$$var}\n";
323 echo
"No suitable files could be found for import.\n";
334 Imports images and other media files into the
wiki
337 <dir> : Path to the
directory containing images to be imported
340 --extensions=<exts> Comma-separated
list of allowable extensions, defaults to \$wgFileExtensions
341 --overwrite Overwrite existing images with the same
name (
default is to skip them)
342 --limit=<num> Limit the number
of images to process. Ignored or skipped images
are not counted.
343 --
from=<
name> Ignore all files until the one with the given
name. Useful
for resuming
344 aborted imports. <
name> should be the
file's canonical database form.
345 --skip-dupes Skip images that were already uploaded under a different name (check SHA1)
346 --search-recursively Search recursively for files in subdirectories
347 --sleep=<sec> Sleep between files. Useful mostly for debugging.
348 --user=<username> Set username of uploader, default 'Maintenance script
'
349 --check-userblock Check if the user got blocked during import.
350 --comment=<text> Set file description, default 'Importing
file'.
351 --comment-file=<file> Set description to the content of <file>.
352 --comment-ext=<ext> Causes the description for each file to be loaded from a file with the same name
353 but the extension <ext>. If a global description is also given, it is appended.
354 --license=<code> Use an optional license template
355 --dry Dry run, don't
import anything
356 --protect=<protect> Specify the protect value (autoconfirmed,
sysop)
357 --summary=<summary> Upload summary, description
will be
used if not provided
358 --timestamp=<timestamp> Override upload time/date, all
MediaWiki timestamp formats
are accepted
359 --unprotect Unprotects all uploaded images
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
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
The most up to date schema for the tables in the database will always be tables sql in the maintenance directory
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
static getPropsFromPath( $path, $ext=true)
Get an associative array containing information about a file in the local filesystem.
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
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
wfBaseName( $path, $suffix='')
Return the final portion of a pathname.
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
it s the revision text itself In either if gzip is the revision text is gzipped $flags
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
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
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
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
wfWaitForSlaves( $maxLag=false, $wiki=false, $cluster=false)
Modern version of wfWaitForSlaves().
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
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
showUsage( $reason=false)
</td >< td > &</td >< td > t want your writing to be edited mercilessly and redistributed at will
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 & $options
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
if(isset( $options['protect']) &&isset( $options['unprotect'])) if(isset( $options['protect']) && $options['protect']==1) global $wgFileExtensions
findFiles( $dir, $exts, $recurse=false)
Search a directory for files with one of a set of extensions.
presenting them properly to the user as errors is done by the caller $title
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
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title after the basic globals have been set up
static getInitialPageText( $comment='', $license='', $copyStatus='', $source='')
Get the initial image page text based on a comment and optional file status information.
could not be made into a sysop(Did you enter the name correctly?) <
getFileUserFromSourceWiki( $wiki_host, $file)
if(PHP_SAPI !='cli') $file
if(isset( $options['comment-file'])) elseif(isset( $options['comment'])) $commentExt
if(! $user instanceof User) $wgUser
if(count( $args)==0) $dir
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
you don t have to do a grep find to see where the $wgReverseTitle variable is used
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
static sha1Base36( $path)
Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case encoding,...
return true to allow those checks to and false if checking is done use this to change the tables headers temp or archived zone change it to an object instance and return false override the list derivative used the name of the old file when set the default code will be skipped add a value to it if you want to add a cookie that have to vary cache options can modify source
getFileCommentFromSourceWiki( $wiki_host, $file)
Please log in again after you receive it</td >< td > s a saved copy from
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
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
findAuxFile( $file, $auxExtension, $maxStrip=1)
Find an auxilliary file with the given extension, matching the give base file path.
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
wfLocalFile( $title)
Get an object referring to a locally registered file.
getName()
Get the user name, or the IP of an anonymous user.