HTMLForm: throw a warning when no callback is set
[mediawiki.git] / maintenance / backup.inc
blob04c65ba159d4a829edfcc4269c542465b25e06a4
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' );
208                 $this->initProgress( $history );
210                 $db = $this->backupDb();
211                 $exporter = new WikiExporter( $db, $history, WikiExporter::STREAM, $text );
212                 $exporter->dumpUploads = $this->dumpUploads;
213                 $exporter->dumpUploadFileContents = $this->dumpUploadFileContents;
215                 $wrapper = new ExportProgressFilter( $this->sink, $this );
216                 $exporter->setOutputSink( $wrapper );
218                 if ( !$this->skipHeader )
219                         $exporter->openStream();
220                 # Log item dumps: all or by range
221                 if ( $history & WikiExporter::LOGS ) {
222                         if ( $this->startId || $this->endId ) {
223                                 $exporter->logsByRange( $this->startId, $this->endId );
224                         } else {
225                                 $exporter->allLogs();
226                         }
227                 # Page dumps: all or by page ID range
228                 } else if ( is_null( $this->pages ) ) {
229                         if ( $this->startId || $this->endId ) {
230                                 $exporter->pagesByRange( $this->startId, $this->endId );
231                         } elseif ( $this->revStartId || $this->revEndId ) {
232                                 $exporter->revsByRange( $this->revStartId, $this->revEndId );
233                         } else {
234                                 $exporter->allPages();
235                         }
236                 # Dump of specific pages
237                 } else {
238                         $exporter->pagesByName( $this->pages );
239                 }
241                 if ( !$this->skipFooter )
242                         $exporter->closeStream();
244                 $this->report( true );
245         }
247         /**
248          * Initialise starting time and maximum revision count.
249          * We'll make ETA calculations based an progress, assuming relatively
250          * constant per-revision rate.
251          * @param $history Integer: WikiExporter::CURRENT or WikiExporter::FULL
252          */
253         function initProgress( $history = WikiExporter::FULL ) {
254                 $table = ( $history == WikiExporter::CURRENT ) ? 'page' : 'revision';
255                 $field = ( $history == WikiExporter::CURRENT ) ? 'page_id' : 'rev_id';
257                 $dbr = $this->forcedDb;
258                 if ( $this->forcedDb === null ) {
259                         $dbr = wfGetDB( DB_SLAVE );
260                 }
261                 $this->maxCount = $dbr->selectField( $table, "MAX($field)", '', __METHOD__ );
262                 $this->startTime = wfTime();
263                 $this->lastTime = $this->startTime;
264                 $this->ID = getmypid();
265         }
267         /**
268          * @todo Fixme: the --server parameter is currently not respected, as it
269          * doesn't seem terribly easy to ask the load balancer for a particular
270          * connection by name.
271          * @return DatabaseBase
272          */
273         function backupDb() {
274                 if ( $this->forcedDb !== null ) {
275                         return $this->forcedDb;
276                 }
278                 $this->lb = wfGetLBFactory()->newMainLB();
279                 $db = $this->lb->getConnection( DB_SLAVE, 'backup' );
281                 // Discourage the server from disconnecting us if it takes a long time
282                 // to read out the big ol' batch query.
283                 $db->setSessionOptions( array( 'connTimeout' => 3600 * 24 ) );
285                 return $db;
286         }
288         /**
289          * Force the dump to use the provided database connection for database
290          * operations, wherever possible.
291          *
292          * @param $db DatabaseBase|null: (Optional) the database connection to
293          *            use. If null, resort to use the globally provided ways to
294          *            get database connections.
295          */
296         function setDb( DatabaseBase $db = null ) {
297                 $this->forcedDb = $db;
298         }
300         function __destruct() {
301                 if ( isset( $this->lb ) ) {
302                         $this->lb->closeAll();
303                 }
304         }
306         function backupServer() {
307                 global $wgDBserver;
308                 return $this->server
309                         ? $this->server
310                         : $wgDBserver;
311         }
313         function reportPage() {
314                 $this->pageCount++;
315         }
317         function revCount() {
318                 $this->revCount++;
319                 $this->report();
320         }
322         function report( $final = false ) {
323                 if ( $final xor ( $this->revCount % $this->reportingInterval == 0 ) ) {
324                         $this->showReport();
325                 }
326         }
328         function showReport() {
329                 if ( $this->reporting ) {
330                         $now = wfTimestamp( TS_DB );
331                         $nowts = wfTime();
332                         $deltaAll = wfTime() - $this->startTime;
333                         $deltaPart = wfTime() - $this->lastTime;
334                         $this->pageCountPart = $this->pageCount - $this->pageCountLast;
335                         $this->revCountPart = $this->revCount - $this->revCountLast;
337                         if ( $deltaAll ) {
338                                 $portion = $this->revCount / $this->maxCount;
339                                 $eta = $this->startTime + $deltaAll / $portion;
340                                 $etats = wfTimestamp( TS_DB, intval( $eta ) );
341                                 $pageRate = $this->pageCount / $deltaAll;
342                                 $revRate = $this->revCount / $deltaAll;
343                         } else {
344                                 $pageRate = '-';
345                                 $revRate = '-';
346                                 $etats = '-';
347                         }
348                         if ( $deltaPart ) {
349                                 $pageRatePart = $this->pageCountPart / $deltaPart;
350                                 $revRatePart = $this->revCountPart / $deltaPart;
351                         } else {
352                                 $pageRatePart = '-';
353                                 $revRatePart = '-';
354                         }
355                         $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]",
356                                         $now, wfWikiID(), $this->ID, $this->pageCount, $pageRate, $pageRatePart, $this->revCount, $revRate, $revRatePart, $etats, $this->maxCount ) );
357                         $this->lastTime = $nowts;
358                         $this->revCountLast = $this->revCount;
359                 }
360         }
362         function progress( $string ) {
363                 fwrite( $this->stderr, $string . "\n" );
364         }
366         function fatalError( $msg ) {
367                 $this->progress( "$msg\n" );
368                 die(1);
369         }
372 class ExportProgressFilter extends DumpFilter {
373         function __construct( &$sink, &$progress ) {
374                 parent::__construct( $sink );
375                 $this->progress = $progress;
376         }
378         function writeClosePage( $string ) {
379                 parent::writeClosePage( $string );
380                 $this->progress->reportPage();
381         }
383         function writeRevision( $rev, $string ) {
384                 parent::writeRevision( $rev, $string );
385                 $this->progress->revCount();
386         }