MediaWiki  1.28.0
upgradeLogging.php
Go to the documentation of this file.
1 <?php
24 require __DIR__ . '/../commandLine.inc';
25 
33 
37  public $dbw;
38  public $batchSize = 1000;
39  public $minTs = false;
40 
41  function execute() {
42  $this->dbw = $this->getDB( DB_MASTER );
43  $logging = $this->dbw->tableName( 'logging' );
44  $logging_1_10 = $this->dbw->tableName( 'logging_1_10' );
45  $logging_pre_1_10 = $this->dbw->tableName( 'logging_pre_1_10' );
46 
47  if ( $this->dbw->tableExists( 'logging_pre_1_10' ) && !$this->dbw->tableExists( 'logging' ) ) {
48  # Fix previous aborted run
49  echo "Cleaning up from previous aborted run\n";
50  $this->dbw->query( "RENAME TABLE $logging_pre_1_10 TO $logging", __METHOD__ );
51  }
52 
53  if ( $this->dbw->tableExists( 'logging_pre_1_10' ) ) {
54  echo "This script has already been run to completion\n";
55 
56  return;
57  }
58 
59  # Create the target table
60  if ( !$this->dbw->tableExists( 'logging_1_10' ) ) {
62 
63  $sql = <<<EOT
64 CREATE TABLE $logging_1_10 (
65  -- Log ID, for referring to this specific log entry, probably for deletion and such.
66  log_id int unsigned NOT NULL auto_increment,
67 
68  -- Symbolic keys for the general log type and the action type
69  -- within the log. The output format will be controlled by the
70  -- action field, but only the type controls categorization.
71  log_type varbinary(10) NOT NULL default '',
72  log_action varbinary(10) NOT NULL default '',
73 
74  -- Timestamp. Duh.
75  log_timestamp binary(14) NOT NULL default '19700101000000',
76 
77  -- The user who performed this action; key to user_id
78  log_user int unsigned NOT NULL default 0,
79 
80  -- Key to the page affected. Where a user is the target,
81  -- this will point to the user page.
82  log_namespace int NOT NULL default 0,
83  log_title varchar(255) binary NOT NULL default '',
84 
85  -- Freeform text. Interpreted as edit history comments.
86  log_comment varchar(255) NOT NULL default '',
87 
88  -- LF separated list of miscellaneous parameters
89  log_params blob NOT NULL,
90 
91  -- rev_deleted for logs
92  log_deleted tinyint unsigned NOT NULL default '0',
93 
94  PRIMARY KEY log_id (log_id),
95  KEY type_time (log_type, log_timestamp),
96  KEY user_time (log_user, log_timestamp),
97  KEY page_time (log_namespace, log_title, log_timestamp),
98  KEY times (log_timestamp)
99 
100 ) $wgDBTableOptions
101 EOT;
102  echo "Creating table logging_1_10\n";
103  $this->dbw->query( $sql, __METHOD__ );
104  }
105 
106  # Synchronise the tables
107  echo "Doing initial sync...\n";
108  $this->sync( 'logging', 'logging_1_10' );
109  echo "Sync done\n\n";
110 
111  # Rename the old table away
112  echo "Renaming the old table to $logging_pre_1_10\n";
113  $this->dbw->query( "RENAME TABLE $logging TO $logging_pre_1_10", __METHOD__ );
114 
115  # Copy remaining old rows
116  # Done before the new table is active so that $copyPos is accurate
117  echo "Doing final sync...\n";
118  $this->sync( 'logging_pre_1_10', 'logging_1_10' );
119 
120  # Move the new table in
121  echo "Moving the new table in...\n";
122  $this->dbw->query( "RENAME TABLE $logging_1_10 TO $logging", __METHOD__ );
123  echo "Finished.\n";
124  }
125 
131  function sync( $srcTable, $dstTable ) {
132  $batchSize = 1000;
133  $minTs = $this->dbw->selectField( $srcTable, 'MIN(log_timestamp)', false, __METHOD__ );
134  $minTsUnix = wfTimestamp( TS_UNIX, $minTs );
135  $numRowsCopied = 0;
136 
137  while ( true ) {
138  $maxTs = $this->dbw->selectField( $srcTable, 'MAX(log_timestamp)', false, __METHOD__ );
139  $copyPos = $this->dbw->selectField( $dstTable, 'MAX(log_timestamp)', false, __METHOD__ );
140  $maxTsUnix = wfTimestamp( TS_UNIX, $maxTs );
141  $copyPosUnix = wfTimestamp( TS_UNIX, $copyPos );
142 
143  if ( $copyPos === null ) {
144  $percent = 0;
145  } else {
146  $percent = ( $copyPosUnix - $minTsUnix ) / ( $maxTsUnix - $minTsUnix ) * 100;
147  }
148  printf( "%s %.2f%%\n", $copyPos, $percent );
149 
150  # Handle all entries with timestamp equal to $copyPos
151  if ( $copyPos !== null ) {
152  $numRowsCopied += $this->copyExactMatch( $srcTable, $dstTable, $copyPos );
153  }
154 
155  # Now copy a batch of rows
156  if ( $copyPos === null ) {
157  $conds = false;
158  } else {
159  $conds = [ 'log_timestamp > ' . $this->dbw->addQuotes( $copyPos ) ];
160  }
161  $srcRes = $this->dbw->select( $srcTable, '*', $conds, __METHOD__,
162  [ 'LIMIT' => $batchSize, 'ORDER BY' => 'log_timestamp' ] );
163 
164  if ( !$srcRes->numRows() ) {
165  # All done
166  break;
167  }
168 
169  $batch = [];
170  foreach ( $srcRes as $srcRow ) {
171  $batch[] = (array)$srcRow;
172  }
173  $this->dbw->insert( $dstTable, $batch, __METHOD__ );
174  $numRowsCopied += count( $batch );
175 
176  wfWaitForSlaves();
177  }
178  echo "Copied $numRowsCopied rows\n";
179  }
180 
181  function copyExactMatch( $srcTable, $dstTable, $copyPos ) {
182  $numRowsCopied = 0;
183  $srcRes = $this->dbw->select( $srcTable, '*', [ 'log_timestamp' => $copyPos ], __METHOD__ );
184  $dstRes = $this->dbw->select( $dstTable, '*', [ 'log_timestamp' => $copyPos ], __METHOD__ );
185 
186  if ( $srcRes->numRows() ) {
187  $srcRow = $srcRes->fetchObject();
188  $srcFields = array_keys( (array)$srcRow );
189  $srcRes->seek( 0 );
190  $dstRowsSeen = [];
191 
192  # Make a hashtable of rows that already exist in the destination
193  foreach ( $dstRes as $dstRow ) {
194  $reducedDstRow = [];
195  foreach ( $srcFields as $field ) {
196  $reducedDstRow[$field] = $dstRow->$field;
197  }
198  $hash = md5( serialize( $reducedDstRow ) );
199  $dstRowsSeen[$hash] = true;
200  }
201 
202  # Copy all the source rows that aren't already in the destination
203  foreach ( $srcRes as $srcRow ) {
204  $hash = md5( serialize( (array)$srcRow ) );
205  if ( !isset( $dstRowsSeen[$hash] ) ) {
206  $this->dbw->insert( $dstTable, (array)$srcRow, __METHOD__ );
207  $numRowsCopied++;
208  }
209  }
210  }
211 
212  return $numRowsCopied;
213  }
214 }
215 
216 $ul = new UpdateLogging;
217 $ul->execute();
#define the
table suitable for use with IDatabase::select()
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
Definition: deferred.txt:11
the array() calling protocol came about after MediaWiki 1.4rc1.
wfWaitForSlaves($ifWritesSince=null, $wiki=false, $cluster=false, $timeout=null)
Waits for the replica DBs to catch up to the master position.
copyExactMatch($srcTable, $dstTable, $copyPos)
sync($srcTable, $dstTable)
Copy all rows from $srcTable to $dstTable.
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
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
Definition: globals.txt:10
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
const DB_MASTER
Definition: defines.php:23
const TS_UNIX
Unix time - the number of seconds since 1970-01-01 00:00:00 UTC.
Definition: defines.php:6
it sets a lot of them automatically from query and such
Definition: design.txt:93
$batch
Definition: linkcache.txt:23
wfTimestamp($outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
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 key
Definition: design.txt:25
as see the revision history and logs
Definition: LICENSE.txt:5
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 user
Wikitext formatted, in the key only.
Definition: distributors.txt:9
and(b) You must cause any modified files to carry prominent notices stating that You changed the files
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 text
Definition: design.txt:12
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 or merely the Work and Derivative Works thereof Contribution shall mean any work of including the original version of the Work and any modifications or additions to that Work or Derivative Works that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner For the purposes of this submitted means any form of or written communication sent to the Licensor or its including but not limited to communication on electronic mailing source code control and issue tracking systems that are managed by
$wgDBTableOptions
MySQL table options to use during installation or update.
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
Definition: distributors.txt:9
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
Definition: injection.txt:35
presenting them properly to the user as errors is done by the caller return true use this to change the list i e etc next in line in page history
Definition: hooks.txt:1721
This document describes the state of Postgres support in and is fairly well maintained The main code is very well while extensions are very hit and miss it is probably the most supported database after MySQL Much of the work in making MediaWiki database agnostic came about through the work of creating Postgres as and are nearing end of but without copying over all the usage comments General notes on the but these can almost always be programmed around *Although Postgres has a true BOOLEAN type
Definition: postgres.txt:22
Maintenance script that upgrade for log_id/log_deleted fields in a replication-safe way...
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 output() to send it all.It could be easily changed to send incrementally if that becomes useful
serialize()
Definition: ApiMessage.php:94
</td >< td > &</td >< td > t want your writing to be edited mercilessly and redistributed at will
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 page
Definition: hooks.txt:2491
if the prop value should be in the metadata multi language array format
Definition: hooks.txt:1610
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 performed
Definition: hooks.txt:802