MediaWiki  1.27.2
WikiExporter.php
Go to the documentation of this file.
1 <?php
33 class WikiExporter {
35  public $list_authors = false;
36 
38  public $dumpUploads = false;
39 
41  public $dumpUploadFileContents = false;
42 
44  public $author_list = "";
45 
46  const FULL = 1;
47  const CURRENT = 2;
48  const STABLE = 4; // extension defined
49  const LOGS = 8;
50  const RANGE = 16;
51 
52  const BUFFER = 0;
53  const STREAM = 1;
54 
55  const TEXT = 0;
56  const STUB = 1;
57 
59  public $buffer;
60 
62  public $text;
63 
65  public $sink;
66 
71  public static function schemaVersion() {
72  return "0.10";
73  }
74 
91  function __construct( $db, $history = WikiExporter::CURRENT,
93  $this->db = $db;
94  $this->history = $history;
95  $this->buffer = $buffer;
96  $this->writer = new XmlDumpWriter();
97  $this->sink = new DumpOutput();
98  $this->text = $text;
99  }
100 
108  public function setOutputSink( &$sink ) {
109  $this->sink =& $sink;
110  }
111 
112  public function openStream() {
113  $output = $this->writer->openStream();
114  $this->sink->writeOpenStream( $output );
115  }
116 
117  public function closeStream() {
118  $output = $this->writer->closeStream();
119  $this->sink->writeCloseStream( $output );
120  }
121 
127  public function allPages() {
128  $this->dumpFrom( '' );
129  }
130 
138  public function pagesByRange( $start, $end ) {
139  $condition = 'page_id >= ' . intval( $start );
140  if ( $end ) {
141  $condition .= ' AND page_id < ' . intval( $end );
142  }
143  $this->dumpFrom( $condition );
144  }
145 
153  public function revsByRange( $start, $end ) {
154  $condition = 'rev_id >= ' . intval( $start );
155  if ( $end ) {
156  $condition .= ' AND rev_id < ' . intval( $end );
157  }
158  $this->dumpFrom( $condition );
159  }
160 
164  public function pageByTitle( $title ) {
165  $this->dumpFrom(
166  'page_namespace=' . $title->getNamespace() .
167  ' AND page_title=' . $this->db->addQuotes( $title->getDBkey() ) );
168  }
169 
174  public function pageByName( $name ) {
176  if ( is_null( $title ) ) {
177  throw new MWException( "Can't export invalid title" );
178  } else {
179  $this->pageByTitle( $title );
180  }
181  }
182 
186  public function pagesByName( $names ) {
187  foreach ( $names as $name ) {
188  $this->pageByName( $name );
189  }
190  }
191 
192  public function allLogs() {
193  $this->dumpFrom( '' );
194  }
195 
200  public function logsByRange( $start, $end ) {
201  $condition = 'log_id >= ' . intval( $start );
202  if ( $end ) {
203  $condition .= ' AND log_id < ' . intval( $end );
204  }
205  $this->dumpFrom( $condition );
206  }
207 
215  protected function do_list_authors( $cond ) {
216  $this->author_list = "<contributors>";
217  // rev_deleted
218 
219  $res = $this->db->select(
220  [ 'page', 'revision' ],
221  [ 'DISTINCT rev_user_text', 'rev_user' ],
222  [
223  $this->db->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0',
224  $cond,
225  'page_id = rev_id',
226  ],
227  __METHOD__
228  );
229 
230  foreach ( $res as $row ) {
231  $this->author_list .= "<contributor>" .
232  "<username>" .
233  htmlentities( $row->rev_user_text ) .
234  "</username>" .
235  "<id>" .
236  $row->rev_user .
237  "</id>" .
238  "</contributor>";
239  }
240  $this->author_list .= "</contributors>";
241  }
242 
248  protected function dumpFrom( $cond = '' ) {
249  # For logging dumps...
250  if ( $this->history & self::LOGS ) {
251  $where = [ 'user_id = log_user' ];
252  # Hide private logs
253  $hideLogs = LogEventsList::getExcludeClause( $this->db );
254  if ( $hideLogs ) {
255  $where[] = $hideLogs;
256  }
257  # Add on any caller specified conditions
258  if ( $cond ) {
259  $where[] = $cond;
260  }
261  # Get logging table name for logging.* clause
262  $logging = $this->db->tableName( 'logging' );
263 
264  if ( $this->buffer == WikiExporter::STREAM ) {
265  $prev = $this->db->bufferResults( false );
266  }
267  $result = null; // Assuring $result is not undefined, if exception occurs early
268  try {
269  $result = $this->db->select( [ 'logging', 'user' ],
270  [ "{$logging}.*", 'user_name' ], // grab the user name
271  $where,
272  __METHOD__,
273  [ 'ORDER BY' => 'log_id', 'USE INDEX' => [ 'logging' => 'PRIMARY' ] ]
274  );
275  $this->outputLogStream( $result );
276  if ( $this->buffer == WikiExporter::STREAM ) {
277  $this->db->bufferResults( $prev );
278  }
279  } catch ( Exception $e ) {
280  // Throwing the exception does not reliably free the resultset, and
281  // would also leave the connection in unbuffered mode.
282 
283  // Freeing result
284  try {
285  if ( $result ) {
286  $result->free();
287  }
288  } catch ( Exception $e2 ) {
289  // Already in panic mode -> ignoring $e2 as $e has
290  // higher priority
291  }
292 
293  // Putting database back in previous buffer mode
294  try {
295  if ( $this->buffer == WikiExporter::STREAM ) {
296  $this->db->bufferResults( $prev );
297  }
298  } catch ( Exception $e2 ) {
299  // Already in panic mode -> ignoring $e2 as $e has
300  // higher priority
301  }
302 
303  // Inform caller about problem
304  throw $e;
305  }
306  # For page dumps...
307  } else {
308  $tables = [ 'page', 'revision' ];
309  $opts = [ 'ORDER BY' => 'page_id ASC' ];
310  $opts['USE INDEX'] = [];
311  $join = [];
312  if ( is_array( $this->history ) ) {
313  # Time offset/limit for all pages/history...
314  $revJoin = 'page_id=rev_page';
315  # Set time order
316  if ( $this->history['dir'] == 'asc' ) {
317  $op = '>';
318  $opts['ORDER BY'] = 'rev_timestamp ASC';
319  } else {
320  $op = '<';
321  $opts['ORDER BY'] = 'rev_timestamp DESC';
322  }
323  # Set offset
324  if ( !empty( $this->history['offset'] ) ) {
325  $revJoin .= " AND rev_timestamp $op " .
326  $this->db->addQuotes( $this->db->timestamp( $this->history['offset'] ) );
327  }
328  $join['revision'] = [ 'INNER JOIN', $revJoin ];
329  # Set query limit
330  if ( !empty( $this->history['limit'] ) ) {
331  $opts['LIMIT'] = intval( $this->history['limit'] );
332  }
333  } elseif ( $this->history & WikiExporter::FULL ) {
334  # Full history dumps...
335  $join['revision'] = [ 'INNER JOIN', 'page_id=rev_page' ];
336  } elseif ( $this->history & WikiExporter::CURRENT ) {
337  # Latest revision dumps...
338  if ( $this->list_authors && $cond != '' ) { // List authors, if so desired
339  $this->do_list_authors( $cond );
340  }
341  $join['revision'] = [ 'INNER JOIN', 'page_id=rev_page AND page_latest=rev_id' ];
342  } elseif ( $this->history & WikiExporter::STABLE ) {
343  # "Stable" revision dumps...
344  # Default JOIN, to be overridden...
345  $join['revision'] = [ 'INNER JOIN', 'page_id=rev_page AND page_latest=rev_id' ];
346  # One, and only one hook should set this, and return false
347  if ( Hooks::run( 'WikiExporter::dumpStableQuery', [ &$tables, &$opts, &$join ] ) ) {
348  throw new MWException( __METHOD__ . " given invalid history dump type." );
349  }
350  } elseif ( $this->history & WikiExporter::RANGE ) {
351  # Dump of revisions within a specified range
352  $join['revision'] = [ 'INNER JOIN', 'page_id=rev_page' ];
353  $opts['ORDER BY'] = [ 'rev_page ASC', 'rev_id ASC' ];
354  } else {
355  # Unknown history specification parameter?
356  throw new MWException( __METHOD__ . " given invalid history dump type." );
357  }
358  # Query optimization hacks
359  if ( $cond == '' ) {
360  $opts[] = 'STRAIGHT_JOIN';
361  $opts['USE INDEX']['page'] = 'PRIMARY';
362  }
363  # Build text join options
364  if ( $this->text != WikiExporter::STUB ) { // 1-pass
365  $tables[] = 'text';
366  $join['text'] = [ 'INNER JOIN', 'rev_text_id=old_id' ];
367  }
368 
369  if ( $this->buffer == WikiExporter::STREAM ) {
370  $prev = $this->db->bufferResults( false );
371  }
372 
373  $result = null; // Assuring $result is not undefined, if exception occurs early
374  try {
375  Hooks::run( 'ModifyExportQuery',
376  [ $this->db, &$tables, &$cond, &$opts, &$join ] );
377 
378  # Do the query!
379  $result = $this->db->select( $tables, '*', $cond, __METHOD__, $opts, $join );
380  # Output dump results
381  $this->outputPageStream( $result );
382 
383  if ( $this->buffer == WikiExporter::STREAM ) {
384  $this->db->bufferResults( $prev );
385  }
386  } catch ( Exception $e ) {
387  // Throwing the exception does not reliably free the resultset, and
388  // would also leave the connection in unbuffered mode.
389 
390  // Freeing result
391  try {
392  if ( $result ) {
393  $result->free();
394  }
395  } catch ( Exception $e2 ) {
396  // Already in panic mode -> ignoring $e2 as $e has
397  // higher priority
398  }
399 
400  // Putting database back in previous buffer mode
401  try {
402  if ( $this->buffer == WikiExporter::STREAM ) {
403  $this->db->bufferResults( $prev );
404  }
405  } catch ( Exception $e2 ) {
406  // Already in panic mode -> ignoring $e2 as $e has
407  // higher priority
408  }
409 
410  // Inform caller about problem
411  throw $e;
412  }
413  }
414  }
415 
428  protected function outputPageStream( $resultset ) {
429  $last = null;
430  foreach ( $resultset as $row ) {
431  if ( $last === null ||
432  $last->page_namespace != $row->page_namespace ||
433  $last->page_title != $row->page_title ) {
434  if ( $last !== null ) {
435  $output = '';
436  if ( $this->dumpUploads ) {
437  $output .= $this->writer->writeUploads( $last, $this->dumpUploadFileContents );
438  }
439  $output .= $this->writer->closePage();
440  $this->sink->writeClosePage( $output );
441  }
442  $output = $this->writer->openPage( $row );
443  $this->sink->writeOpenPage( $row, $output );
444  $last = $row;
445  }
446  $output = $this->writer->writeRevision( $row );
447  $this->sink->writeRevision( $row, $output );
448  }
449  if ( $last !== null ) {
450  $output = '';
451  if ( $this->dumpUploads ) {
452  $output .= $this->writer->writeUploads( $last, $this->dumpUploadFileContents );
453  }
455  $output .= $this->writer->closePage();
456  $this->sink->writeClosePage( $output );
457  }
458  }
459 
463  protected function outputLogStream( $resultset ) {
464  foreach ( $resultset as $row ) {
465  $output = $this->writer->writeLogItem( $row );
466  $this->sink->writeLogItem( $row, $output );
467  }
468  }
469 }
DumpOutput $sink
bool $list_authors
Return distinct author list (when not returning full history)
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
Definition: hooks.txt:1932
setOutputSink(&$sink)
Set the DumpOutput or DumpFilter object which will receive various row objects and XML output for fil...
outputPageStream($resultset)
Runs through a query result set dumping page and revision records.
static newFromText($text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:277
dumpFrom($cond= '')
allPages()
Dumps a series of page and revision records for all pages in the database, either including complete ...
string $author_list
pagesByRange($start, $end)
Dumps a series of page and revision records for those pages in the database falling within the page_i...
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist & $tables
Definition: hooks.txt:965
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.Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page.Return false to stop further processing of the tag $reader:XMLReader object &$pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision.Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag.Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload.Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports.&$fullInterwikiPrefix:Interwiki prefix, may contain colons.&$pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable.Can be used to lazy-load the import sources list.&$importSources:The value of $wgImportSources.Modify as necessary.See the comment in DefaultSettings.php for the detail of how to structure this array. '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 '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 '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 '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. '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 IP::isTrustedProxy() &$ip:IP being check &$result:Change this value to override the result of IP::isTrustedProxy() '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 Sanitizer::validateEmail(), 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. '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) '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 '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. 'LanguageSelector':Hook to change the language selector available on a page.$out:The output page.$cssClassName:CSS class name of the language selector. '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
Definition: hooks.txt:1796
$last
pageByName($name)
revsByRange($start, $end)
Dumps a series of page and revision records for those pages in the database with revisions falling wi...
pagesByName($names)
__construct($db, $history=WikiExporter::CURRENT, $buffer=WikiExporter::BUFFER, $text=WikiExporter::TEXT)
If using WikiExporter::STREAM to stream a large amount of data, provide a database connection which i...
$res
Definition: database.txt:21
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:912
static run($event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:131
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
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
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object & $output
Definition: hooks.txt:1004
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:1584
const DELETED_USER
Definition: Revision.php:78
bool $dumpUploadFileContents
An extension writer
Definition: hooks.txt:51
static schemaVersion()
Returns the export schema version.
do_list_authors($cond)
Generates the distinct list of authors of an article Not called by default (depends on $this->list_au...
logsByRange($start, $end)
pageByTitle($title)
static getExcludeClause($db, $audience= 'public', User $user=null)
SQL clause to skip forbidden log types for this user.
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:310
outputLogStream($resultset)