Whitelist the <wbr> element.
[mediawiki.git] / maintenance / backup.inc
blobdb045cf2d6f70c1de299c42d983dce5fcfa10331
1 <?php
2 /**
3  * Base classes for database dumpers
4  *
5  * Copyright © 2005 Brion Vibber <brion@pobox.com>
6  * http://www.mediawiki.org/
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License along
19  * with this program; if not, write to the Free Software Foundation, Inc.,
20  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21  * http://www.gnu.org/copyleft/gpl.html
22  *
23  * @file
24  * @ingroup Dump Maintenance
25  */
27 /**
28  * @ingroup Dump Maintenance
29  */
30 class DumpDBZip2Output extends DumpPipeOutput {
31         function __construct( $file ) {
32                 parent::__construct( "dbzip2", $file );
33         }
36 /**
37  * @ingroup Dump Maintenance
38  */
39 class BackupDumper {
40         var $reportingInterval = 100;
41         var $reporting = true;
42         var $pageCount = 0;
43         var $revCount = 0;
44         var $server = null; // use default
45         var $pages = null; // all pages
46         var $skipHeader = false; // don't output <mediawiki> and <siteinfo>
47         var $skipFooter = false; // don't output </mediawiki>
48         var $startId = 0;
49         var $endId = 0;
50         var $revStartId = 0;
51         var $revEndId = 0;
52         var $sink = null; // Output filters
53         var $stubText = false; // include rev_text_id instead of text; for 2-pass dump
54         var $dumpUploads = false;
55         var $dumpUploadFileContents = false;
56         var $lastTime = 0;
57         var $pageCountLast = 0;
58         var $revCountLast = 0;
59         var $ID = 0;
61         var $outputTypes = array(), $filterTypes = array();
63         /**
64          * The dependency-injected database to use.
65          *
66          * @var DatabaseBase|null
67          *
68          * @see self::setDb
69          */
70         protected $forcedDb = null;
72         /**
73          * @var LoadBalancer
74          */
75         protected $lb;
77         function __construct( $args ) {
78                 $this->stderr = fopen( "php://stderr", "wt" );
80                 // Built-in output and filter plugins
81                 $this->registerOutput( 'file', 'DumpFileOutput' );
82                 $this->registerOutput( 'gzip', 'DumpGZipOutput' );
83                 $this->registerOutput( 'bzip2', 'DumpBZip2Output' );
84                 $this->registerOutput( 'dbzip2', 'DumpDBZip2Output' );
85                 $this->registerOutput( '7zip', 'Dump7ZipOutput' );
87                 $this->registerFilter( 'latest', 'DumpLatestFilter' );
88                 $this->registerFilter( 'notalk', 'DumpNotalkFilter' );
89                 $this->registerFilter( 'namespace', 'DumpNamespaceFilter' );
91                 $this->sink = $this->processArgs( $args );
92         }
94         /**
95          * @param $name String
96          * @param $class String: name of output filter plugin class
97          */
98         function registerOutput( $name, $class ) {
99                 $this->outputTypes[$name] = $class;
100         }
102         /**
103          * @param $name String
104          * @param $class String: name of filter plugin class
105          */
106         function registerFilter( $name, $class ) {
107                 $this->filterTypes[$name] = $class;
108         }
110         /**
111          * Load a plugin and register it
112          *
113          * @param $class String: name of plugin class; must have a static 'register'
114          *               method that takes a BackupDumper as a parameter.
115          * @param $file String: full or relative path to the PHP file to load, or empty
116          */
117         function loadPlugin( $class, $file ) {
118                 if ( $file != '' ) {
119                         require_once $file;
120                 }
121                 $register = array( $class, 'register' );
122                 call_user_func_array( $register, array( &$this ) );
123         }
125         /**
126          * @param $args Array
127          * @return Array
128          */
129         function processArgs( $args ) {
130                 $sink = null;
131                 $sinks = array();
132                 foreach ( $args as $arg ) {
133                         $matches = array();
134                         if ( preg_match( '/^--(.+?)(?:=(.+?)(?::(.+?))?)?$/', $arg, $matches ) ) {
135                                 @list( /* $full */ , $opt, $val, $param ) = $matches;
136                                 switch ( $opt ) {
137                                 case "plugin":
138                                         $this->loadPlugin( $val, $param );
139                                         break;
140                                 case "output":
141                                         if ( !is_null( $sink ) ) {
142                                                 $sinks[] = $sink;
143                                         }
144                                         if ( !isset( $this->outputTypes[$val] ) ) {
145                                                 $this->fatalError( "Unrecognized output sink type '$val'" );
146                                         }
147                                         $type = $this->outputTypes[$val];
148                                         $sink = new $type( $param );
149                                         break;
150                                 case "filter":
151                                         if ( is_null( $sink ) ) {
152                                                 $sink = new DumpOutput();
153                                         }
154                                         if ( !isset( $this->filterTypes[$val] ) ) {
155                                                 $this->fatalError( "Unrecognized filter type '$val'" );
156                                         }
157                                         $type = $this->filterTypes[$val];
158                                         $filter = new $type( $sink, $param );
160                                         // references are lame in php...
161                                         unset( $sink );
162                                         $sink = $filter;
164                                         break;
165                                 case "report":
166                                         $this->reportingInterval = intval( $val );
167                                         break;
168                                 case "server":
169                                         $this->server = $val;
170                                         break;
171                                 case "force-normal":
172                                         if ( !function_exists( 'utf8_normalize' ) ) {
173                                                 wfDl( "php_utfnormal.so" );
174                                                 if ( !function_exists( 'utf8_normalize' ) ) {
175                                                         $this->fatalError( "Failed to load UTF-8 normalization extension. " .
176                                                                 "Install or remove --force-normal parameter to use slower code." );
177                                                 }
178                                         }
179                                         break;
180                                 default:
181                                         $this->processOption( $opt, $val, $param );
182                                 }
183                         }
184                 }
186                 if ( is_null( $sink ) ) {
187                         $sink = new DumpOutput();
188                 }
189                 $sinks[] = $sink;
191                 if ( count( $sinks ) > 1 ) {
192                         return new DumpMultiWriter( $sinks );
193                 } else {
194                         return $sink;
195                 }
196         }
198         function processOption( $opt, $val, $param ) {
199                 // extension point for subclasses to add options
200         }
202         function dump( $history, $text = WikiExporter::TEXT ) {
203                 # Notice messages will foul up your XML output even if they're
204                 # relatively harmless.
205                 if ( ini_get( 'display_errors' ) ) {
206                         ini_set( 'display_errors', 'stderr' );
207                 }
209                 $this->initProgress( $history );
211                 $db = $this->backupDb();
212                 $exporter = new WikiExporter( $db, $history, WikiExporter::STREAM, $text );
213                 $exporter->dumpUploads = $this->dumpUploads;
214                 $exporter->dumpUploadFileContents = $this->dumpUploadFileContents;
216                 $wrapper = new ExportProgressFilter( $this->sink, $this );
217                 $exporter->setOutputSink( $wrapper );
219                 if ( !$this->skipHeader ) {
220                         $exporter->openStream();
221                 }
222                 # Log item dumps: all or by range
223                 if ( $history & WikiExporter::LOGS ) {
224                         if ( $this->startId || $this->endId ) {
225                                 $exporter->logsByRange( $this->startId, $this->endId );
226                         } else {
227                                 $exporter->allLogs();
228                         }
229                 # Page dumps: all or by page ID range
230                 } elseif ( is_null( $this->pages ) ) {
231                         if ( $this->startId || $this->endId ) {
232                                 $exporter->pagesByRange( $this->startId, $this->endId );
233                         } elseif ( $this->revStartId || $this->revEndId ) {
234                                 $exporter->revsByRange( $this->revStartId, $this->revEndId );
235                         } else {
236                                 $exporter->allPages();
237                         }
238                 # Dump of specific pages
239                 } else {
240                         $exporter->pagesByName( $this->pages );
241                 }
243                 if ( !$this->skipFooter ) {
244                         $exporter->closeStream();
245                 }
247                 $this->report( true );
248         }
250         /**
251          * Initialise starting time and maximum revision count.
252          * We'll make ETA calculations based an progress, assuming relatively
253          * constant per-revision rate.
254          * @param $history Integer: WikiExporter::CURRENT or WikiExporter::FULL
255          */
256         function initProgress( $history = WikiExporter::FULL ) {
257                 $table = ( $history == WikiExporter::CURRENT ) ? 'page' : 'revision';
258                 $field = ( $history == WikiExporter::CURRENT ) ? 'page_id' : 'rev_id';
260                 $dbr = $this->forcedDb;
261                 if ( $this->forcedDb === null ) {
262                         $dbr = wfGetDB( DB_SLAVE );
263                 }
264                 $this->maxCount = $dbr->selectField( $table, "MAX($field)", '', __METHOD__ );
265                 $this->startTime = microtime( true );
266                 $this->lastTime = $this->startTime;
267                 $this->ID = getmypid();
268         }
270         /**
271          * @todo Fixme: the --server parameter is currently not respected, as it
272          * doesn't seem terribly easy to ask the load balancer for a particular
273          * connection by name.
274          * @return DatabaseBase
275          */
276         function backupDb() {
277                 if ( $this->forcedDb !== null ) {
278                         return $this->forcedDb;
279                 }
281                 $this->lb = wfGetLBFactory()->newMainLB();
282                 $db = $this->lb->getConnection( DB_SLAVE, 'backup' );
284                 // Discourage the server from disconnecting us if it takes a long time
285                 // to read out the big ol' batch query.
286                 $db->setSessionOptions( array( 'connTimeout' => 3600 * 24 ) );
288                 return $db;
289         }
291         /**
292          * Force the dump to use the provided database connection for database
293          * operations, wherever possible.
294          *
295          * @param $db DatabaseBase|null: (Optional) the database connection to
296          *            use. If null, resort to use the globally provided ways to
297          *            get database connections.
298          */
299         function setDb( DatabaseBase $db = null ) {
300                 $this->forcedDb = $db;
301         }
303         function __destruct() {
304                 if ( isset( $this->lb ) ) {
305                         $this->lb->closeAll();
306                 }
307         }
309         function backupServer() {
310                 global $wgDBserver;
311                 return $this->server
312                         ? $this->server
313                         : $wgDBserver;
314         }
316         function reportPage() {
317                 $this->pageCount++;
318         }
320         function revCount() {
321                 $this->revCount++;
322                 $this->report();
323         }
325         function report( $final = false ) {
326                 if ( $final xor ( $this->revCount % $this->reportingInterval == 0 ) ) {
327                         $this->showReport();
328                 }
329         }
331         function showReport() {
332                 if ( $this->reporting ) {
333                         $now = wfTimestamp( TS_DB );
334                         $nowts = microtime( true );
335                         $deltaAll = $nowts - $this->startTime;
336                         $deltaPart = $nowts - $this->lastTime;
337                         $this->pageCountPart = $this->pageCount - $this->pageCountLast;
338                         $this->revCountPart = $this->revCount - $this->revCountLast;
340                         if ( $deltaAll ) {
341                                 $portion = $this->revCount / $this->maxCount;
342                                 $eta = $this->startTime + $deltaAll / $portion;
343                                 $etats = wfTimestamp( TS_DB, intval( $eta ) );
344                                 $pageRate = $this->pageCount / $deltaAll;
345                                 $revRate = $this->revCount / $deltaAll;
346                         } else {
347                                 $pageRate = '-';
348                                 $revRate = '-';
349                                 $etats = '-';
350                         }
351                         if ( $deltaPart ) {
352                                 $pageRatePart = $this->pageCountPart / $deltaPart;
353                                 $revRatePart = $this->revCountPart / $deltaPart;
354                         } else {
355                                 $pageRatePart = '-';
356                                 $revRatePart = '-';
357                         }
358                         $this->progress( sprintf( "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), %d revs (%0.1f|%0.1f/sec all|curr), ETA %s [max %d]",
359                                         $now, wfWikiID(), $this->ID, $this->pageCount, $pageRate, $pageRatePart, $this->revCount, $revRate, $revRatePart, $etats, $this->maxCount ) );
360                         $this->lastTime = $nowts;
361                         $this->revCountLast = $this->revCount;
362                 }
363         }
365         function progress( $string ) {
366                 fwrite( $this->stderr, $string . "\n" );
367         }
369         function fatalError( $msg ) {
370                 $this->progress( "$msg\n" );
371                 die( 1 );
372         }
375 class ExportProgressFilter extends DumpFilter {
376         function __construct( &$sink, &$progress ) {
377                 parent::__construct( $sink );
378                 $this->progress = $progress;
379         }
381         function writeClosePage( $string ) {
382                 parent::writeClosePage( $string );
383                 $this->progress->reportPage();
384         }
386         function writeRevision( $rev, $string ) {
387                 parent::writeRevision( $rev, $string );
388                 $this->progress->revCount();
389         }