mediawiki.userSuggest: Use formatversion=2 for API request
[mediawiki.git] / includes / specials / SpecialExport.php
blob3ce9c76a8ec34cd2f70ebeb36f060d48fe7dcff2
1 <?php
2 /**
3 * Implements Special:Export
5 * Copyright © 2003-2008 Brion Vibber <brion@pobox.com>
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
22 * @file
23 * @ingroup SpecialPage
26 /**
27 * A special page that allows users to export pages in a XML file
29 * @ingroup SpecialPage
31 class SpecialExport extends SpecialPage {
32 private $curonly, $doExport, $pageLinkDepth, $templates;
34 public function __construct() {
35 parent::__construct( 'Export' );
38 public function execute( $par ) {
39 $this->setHeaders();
40 $this->outputHeader();
41 $config = $this->getConfig();
43 // Set some variables
44 $this->curonly = true;
45 $this->doExport = false;
46 $request = $this->getRequest();
47 $this->templates = $request->getCheck( 'templates' );
48 $this->pageLinkDepth = $this->validateLinkDepth(
49 $request->getIntOrNull( 'pagelink-depth' )
51 $nsindex = '';
52 $exportall = false;
54 if ( $request->getCheck( 'addcat' ) ) {
55 $page = $request->getText( 'pages' );
56 $catname = $request->getText( 'catname' );
58 if ( $catname !== '' && $catname !== null && $catname !== false ) {
59 $t = Title::makeTitleSafe( NS_MAIN, $catname );
60 if ( $t ) {
61 /**
62 * @todo FIXME: This can lead to hitting memory limit for very large
63 * categories. Ideally we would do the lookup synchronously
64 * during the export in a single query.
66 $catpages = $this->getPagesFromCategory( $t );
67 if ( $catpages ) {
68 if ( $page !== '' ) {
69 $page .= "\n";
71 $page .= implode( "\n", $catpages );
75 } elseif ( $request->getCheck( 'addns' ) && $config->get( 'ExportFromNamespaces' ) ) {
76 $page = $request->getText( 'pages' );
77 $nsindex = $request->getText( 'nsindex', '' );
79 if ( strval( $nsindex ) !== '' ) {
80 /**
81 * Same implementation as above, so same @todo
83 $nspages = $this->getPagesFromNamespace( $nsindex );
84 if ( $nspages ) {
85 $page .= "\n" . implode( "\n", $nspages );
88 } elseif ( $request->getCheck( 'exportall' ) && $config->get( 'ExportAllowAll' ) ) {
89 $this->doExport = true;
90 $exportall = true;
92 /* Although $page and $history are not used later on, we
93 nevertheless set them to avoid that PHP notices about using
94 undefined variables foul up our XML output (see call to
95 doExport(...) further down) */
96 $page = '';
97 $history = '';
98 } elseif ( $request->wasPosted() && $par == '' ) {
99 $page = $request->getText( 'pages' );
100 $this->curonly = $request->getCheck( 'curonly' );
101 $rawOffset = $request->getVal( 'offset' );
103 if ( $rawOffset ) {
104 $offset = wfTimestamp( TS_MW, $rawOffset );
105 } else {
106 $offset = null;
109 $maxHistory = $config->get( 'ExportMaxHistory' );
110 $limit = $request->getInt( 'limit' );
111 $dir = $request->getVal( 'dir' );
112 $history = array(
113 'dir' => 'asc',
114 'offset' => false,
115 'limit' => $maxHistory,
117 $historyCheck = $request->getCheck( 'history' );
119 if ( $this->curonly ) {
120 $history = WikiExporter::CURRENT;
121 } elseif ( !$historyCheck ) {
122 if ( $limit > 0 && ( $maxHistory == 0 || $limit < $maxHistory ) ) {
123 $history['limit'] = $limit;
126 if ( !is_null( $offset ) ) {
127 $history['offset'] = $offset;
130 if ( strtolower( $dir ) == 'desc' ) {
131 $history['dir'] = 'desc';
135 if ( $page != '' ) {
136 $this->doExport = true;
138 } else {
139 // Default to current-only for GET requests.
140 $page = $request->getText( 'pages', $par );
141 $historyCheck = $request->getCheck( 'history' );
143 if ( $historyCheck ) {
144 $history = WikiExporter::FULL;
145 } else {
146 $history = WikiExporter::CURRENT;
149 if ( $page != '' ) {
150 $this->doExport = true;
154 if ( !$config->get( 'ExportAllowHistory' ) ) {
155 // Override
156 $history = WikiExporter::CURRENT;
159 $list_authors = $request->getCheck( 'listauthors' );
160 if ( !$this->curonly || !$config->get( 'ExportAllowListContributors' ) ) {
161 $list_authors = false;
164 if ( $this->doExport ) {
165 $this->getOutput()->disable();
167 // Cancel output buffering and gzipping if set
168 // This should provide safer streaming for pages with history
169 wfResetOutputBuffers();
170 $request->response()->header( "Content-type: application/xml; charset=utf-8" );
172 if ( $request->getCheck( 'wpDownload' ) ) {
173 // Provide a sane filename suggestion
174 $filename = urlencode( $config->get( 'Sitename' ) . '-' . wfTimestampNow() . '.xml' );
175 $request->response()->header( "Content-disposition: attachment;filename={$filename}" );
178 $this->doExport( $page, $history, $list_authors, $exportall );
180 return;
183 $out = $this->getOutput();
184 $out->addWikiMsg( 'exporttext' );
186 if ( $page == '' ) {
187 $categoryName = $request->getText( 'catname' );
188 } else {
189 $categoryName = '';
192 $formDescriptor = array(
193 'catname' => array(
194 'type' => 'textwithbutton',
195 'name' => 'catname',
196 'horizontal-label' => true,
197 'label-message' => 'export-addcattext',
198 'default' => $categoryName,
199 'size' => 40,
200 'buttontype' => 'submit',
201 'buttonname' => 'addcat',
202 'buttondefault' => $this->msg( 'export-addcat' )->text(),
205 if ( $config->get( 'ExportFromNamespaces' ) ) {
206 $formDescriptor += array(
207 'nsindex' => array(
208 'type' => 'namespaceselectwithbutton',
209 'default' => $nsindex,
210 'label-message' => 'export-addnstext',
211 'horizontal-label' => true,
212 'name' => 'nsindex',
213 'id' => 'namespace',
214 'cssclass' => 'namespaceselector',
215 'buttontype' => 'submit',
216 'buttonname' => 'addns',
217 'buttondefault' => $this->msg( 'export-addns' )->text(),
222 if ( $config->get( 'ExportAllowAll' ) ) {
223 $formDescriptor += array(
224 'exportall' => array(
225 'type' => 'check',
226 'label-message' => 'exportall',
227 'name' => 'exportall',
228 'id' => 'exportall',
229 'default' => $request->wasPosted() ? $request->getCheck( 'exportall' ) : false,
234 $formDescriptor += array(
235 'textarea' => array(
236 'class' => 'HTMLTextAreaField',
237 'name' => 'pages',
238 'label-message' => 'export-manual',
239 'nodata' => true,
240 'rows' => 10,
241 'default' => $page,
245 if ( $config->get( 'ExportAllowHistory' ) ) {
246 $formDescriptor += array(
247 'curonly' => array(
248 'type' => 'check',
249 'label-message' => 'exportcuronly',
250 'name' => 'curonly',
251 'id' => 'curonly',
252 'default' => $request->wasPosted() ? $request->getCheck( 'curonly' ) : true,
255 } else {
256 $out->addWikiMsg( 'exportnohistory' );
259 $formDescriptor += array(
260 'templates' => array(
261 'type' => 'check',
262 'label-message' => 'export-templates',
263 'name' => 'templates',
264 'id' => 'wpExportTemplates',
265 'default' => $request->wasPosted() ? $request->getCheck( 'templates' ) : false,
269 if ( $config->get( 'ExportMaxLinkDepth' ) || $this->userCanOverrideExportDepth() ) {
270 $formDescriptor += array(
271 'pagelink-depth' => array(
272 'type' => 'text',
273 'name' => 'pagelink-depth',
274 'id' => 'pagelink-depth',
275 'label-message' => 'export-pagelinks',
276 'default' => '0',
277 'size' => 20,
282 $formDescriptor += array(
283 'wpDownload' => array(
284 'type' => 'check',
285 'name' =>'wpDownload',
286 'id' => 'wpDownload',
287 'default' => $request->wasPosted() ? $request->getCheck( 'wpDownload' ) : true,
288 'label-message' => 'export-download',
292 if ( $config->get( 'ExportAllowListContributors' ) ) {
293 $formDescriptor += array(
294 'listauthors' => array(
295 'type' => 'check',
296 'label-message' => 'exportlistauthors',
297 'default' => $request->wasPosted() ? $request->getCheck( 'listauthors' ) : false,
298 'name' => 'listauthors',
299 'id' => 'listauthors',
304 $htmlForm = HTMLForm::factory( 'ooui', $formDescriptor, $this->getContext() );
305 $htmlForm->setSubmitTextMsg( 'export-submit' );
306 $htmlForm->prepareForm()->displayForm( false );
307 $this->addHelpLink( 'Help:Export' );
311 * @return bool
313 private function userCanOverrideExportDepth() {
314 return $this->getUser()->isAllowed( 'override-export-depth' );
318 * Do the actual page exporting
320 * @param string $page User input on what page(s) to export
321 * @param int $history One of the WikiExporter history export constants
322 * @param bool $list_authors Whether to add distinct author list (when
323 * not returning full history)
324 * @param bool $exportall Whether to export everything
326 private function doExport( $page, $history, $list_authors, $exportall ) {
328 // If we are grabbing everything, enable full history and ignore the rest
329 if ( $exportall ) {
330 $history = WikiExporter::FULL;
331 } else {
332 $pageSet = array(); // Inverted index of all pages to look up
334 // Split up and normalize input
335 foreach ( explode( "\n", $page ) as $pageName ) {
336 $pageName = trim( $pageName );
337 $title = Title::newFromText( $pageName );
338 if ( $title && !$title->isExternal() && $title->getText() !== '' ) {
339 // Only record each page once!
340 $pageSet[$title->getPrefixedText()] = true;
344 // Set of original pages to pass on to further manipulation...
345 $inputPages = array_keys( $pageSet );
347 // Look up any linked pages if asked...
348 if ( $this->templates ) {
349 $pageSet = $this->getTemplates( $inputPages, $pageSet );
351 $linkDepth = $this->pageLinkDepth;
352 if ( $linkDepth ) {
353 $pageSet = $this->getPageLinks( $inputPages, $pageSet, $linkDepth );
356 $pages = array_keys( $pageSet );
358 // Normalize titles to the same format and remove dupes, see bug 17374
359 foreach ( $pages as $k => $v ) {
360 $pages[$k] = str_replace( " ", "_", $v );
363 $pages = array_unique( $pages );
366 /* Ok, let's get to it... */
367 if ( $history == WikiExporter::CURRENT ) {
368 $lb = false;
369 $db = wfGetDB( DB_SLAVE );
370 $buffer = WikiExporter::BUFFER;
371 } else {
372 // Use an unbuffered query; histories may be very long!
373 $lb = wfGetLBFactory()->newMainLB();
374 $db = $lb->getConnection( DB_SLAVE );
375 $buffer = WikiExporter::STREAM;
377 // This might take a while... :D
378 MediaWiki\suppressWarnings();
379 set_time_limit( 0 );
380 MediaWiki\restoreWarnings();
383 $exporter = new WikiExporter( $db, $history, $buffer );
384 $exporter->list_authors = $list_authors;
385 $exporter->openStream();
387 if ( $exportall ) {
388 $exporter->allPages();
389 } else {
390 foreach ( $pages as $page ) {
391 # Bug 8824: Only export pages the user can read
392 $title = Title::newFromText( $page );
393 if ( is_null( $title ) ) {
394 // @todo Perhaps output an <error> tag or something.
395 continue;
398 if ( !$title->userCan( 'read', $this->getUser() ) ) {
399 // @todo Perhaps output an <error> tag or something.
400 continue;
403 $exporter->pageByTitle( $title );
407 $exporter->closeStream();
409 if ( $lb ) {
410 $lb->closeAll();
415 * @param Title $title
416 * @return array
418 private function getPagesFromCategory( $title ) {
419 global $wgContLang;
421 $name = $title->getDBkey();
423 $dbr = wfGetDB( DB_SLAVE );
424 $res = $dbr->select(
425 array( 'page', 'categorylinks' ),
426 array( 'page_namespace', 'page_title' ),
427 array( 'cl_from=page_id', 'cl_to' => $name ),
428 __METHOD__,
429 array( 'LIMIT' => '5000' )
432 $pages = array();
434 foreach ( $res as $row ) {
435 $n = $row->page_title;
436 if ( $row->page_namespace ) {
437 $ns = $wgContLang->getNsText( $row->page_namespace );
438 $n = $ns . ':' . $n;
441 $pages[] = $n;
444 return $pages;
448 * @param int $nsindex
449 * @return array
451 private function getPagesFromNamespace( $nsindex ) {
452 global $wgContLang;
454 $dbr = wfGetDB( DB_SLAVE );
455 $res = $dbr->select(
456 'page',
457 array( 'page_namespace', 'page_title' ),
458 array( 'page_namespace' => $nsindex ),
459 __METHOD__,
460 array( 'LIMIT' => '5000' )
463 $pages = array();
465 foreach ( $res as $row ) {
466 $n = $row->page_title;
468 if ( $row->page_namespace ) {
469 $ns = $wgContLang->getNsText( $row->page_namespace );
470 $n = $ns . ':' . $n;
473 $pages[] = $n;
476 return $pages;
480 * Expand a list of pages to include templates used in those pages.
481 * @param array $inputPages List of titles to look up
482 * @param array $pageSet Associative array indexed by titles for output
483 * @return array Associative array index by titles
485 private function getTemplates( $inputPages, $pageSet ) {
486 return $this->getLinks( $inputPages, $pageSet,
487 'templatelinks',
488 array( 'namespace' => 'tl_namespace', 'title' => 'tl_title' ),
489 array( 'page_id=tl_from' )
494 * Validate link depth setting, if available.
495 * @param int $depth
496 * @return int
498 private function validateLinkDepth( $depth ) {
499 if ( $depth < 0 ) {
500 return 0;
503 if ( !$this->userCanOverrideExportDepth() ) {
504 $maxLinkDepth = $this->getConfig()->get( 'ExportMaxLinkDepth' );
505 if ( $depth > $maxLinkDepth ) {
506 return $maxLinkDepth;
511 * There's a HARD CODED limit of 5 levels of recursion here to prevent a
512 * crazy-big export from being done by someone setting the depth
513 * number too high. In other words, last resort safety net.
516 return intval( min( $depth, 5 ) );
520 * Expand a list of pages to include pages linked to from that page.
521 * @param array $inputPages
522 * @param array $pageSet
523 * @param int $depth
524 * @return array
526 private function getPageLinks( $inputPages, $pageSet, $depth ) {
527 // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect
528 for ( ; $depth > 0; --$depth ) {
529 // @codingStandardsIgnoreEnd
530 $pageSet = $this->getLinks(
531 $inputPages, $pageSet, 'pagelinks',
532 array( 'namespace' => 'pl_namespace', 'title' => 'pl_title' ),
533 array( 'page_id=pl_from' )
535 $inputPages = array_keys( $pageSet );
538 return $pageSet;
542 * Expand a list of pages to include items used in those pages.
543 * @param array $inputPages Array of page titles
544 * @param array $pageSet
545 * @param string $table
546 * @param array $fields Array of field names
547 * @param array $join
548 * @return array
550 private function getLinks( $inputPages, $pageSet, $table, $fields, $join ) {
551 $dbr = wfGetDB( DB_SLAVE );
553 foreach ( $inputPages as $page ) {
554 $title = Title::newFromText( $page );
556 if ( $title ) {
557 $pageSet[$title->getPrefixedText()] = true;
558 /// @todo FIXME: May or may not be more efficient to batch these
559 /// by namespace when given multiple input pages.
560 $result = $dbr->select(
561 array( 'page', $table ),
562 $fields,
563 array_merge(
564 $join,
565 array(
566 'page_namespace' => $title->getNamespace(),
567 'page_title' => $title->getDBkey()
570 __METHOD__
573 foreach ( $result as $row ) {
574 $template = Title::makeTitle( $row->namespace, $row->title );
575 $pageSet[$template->getPrefixedText()] = true;
580 return $pageSet;
583 protected function getGroupName() {
584 return 'pagetools';