Tidy up the class
[mediawiki.git] / includes / specials / SpecialExport.php
blobb9a44d48374c98e52868677b9ff8411b20990332
1 <?php
2 # Copyright (C) 2003-2008 Brion Vibber <brion@pobox.com>
3 # http://www.mediawiki.org/
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 # http://www.gnu.org/copyleft/gpl.html
19 /**
20 * @file
21 * @ingroup SpecialPage
24 class SpecialExport extends SpecialPage {
26 private $curonly, $doExport, $pageLinkDepth, $templates;
27 private $images;
29 public function __construct() {
30 parent::__construct( 'Export' );
33 public function execute( $par ) {
34 global $wgOut, $wgRequest, $wgSitename, $wgExportAllowListContributors;
35 global $wgExportAllowHistory, $wgExportMaxHistory, $wgExportMaxLinkDepth;
36 global $wgExportFromNamespaces;
38 $this->setHeaders();
39 $this->outputHeader();
41 // Set some variables
42 $this->curonly = true;
43 $this->doExport = false;
44 $this->templates = $wgRequest->getCheck( 'templates' );
45 $this->images = $wgRequest->getCheck( 'images' ); // Doesn't do anything yet
46 $this->pageLinkDepth = $this->validateLinkDepth(
47 $wgRequest->getIntOrNull( 'pagelink-depth' ) );
48 $nsindex = '';
50 if ( $wgRequest->getCheck( 'addcat' ) ) {
51 $page = $wgRequest->getText( 'pages' );
52 $catname = $wgRequest->getText( 'catname' );
54 if ( $catname !== '' && $catname !== null && $catname !== false ) {
55 $t = Title::makeTitleSafe( NS_MAIN, $catname );
56 if ( $t ) {
57 /**
58 * @todo Fixme: this can lead to hitting memory limit for very large
59 * categories. Ideally we would do the lookup synchronously
60 * during the export in a single query.
62 $catpages = $this->getPagesFromCategory( $t );
63 if ( $catpages ) $page .= "\n" . implode( "\n", $catpages );
67 else if( $wgRequest->getCheck( 'addns' ) && $wgExportFromNamespaces ) {
68 $page = $wgRequest->getText( 'pages' );
69 $nsindex = $wgRequest->getText( 'nsindex', '' );
71 if ( strval( $nsindex ) !== '' ) {
72 /**
73 * Same implementation as above, so same @todo
75 $nspages = $this->getPagesFromNamespace( $nsindex );
76 if ( $nspages ) $page .= "\n" . implode( "\n", $nspages );
79 else if( $wgRequest->wasPosted() && $par == '' ) {
80 $page = $wgRequest->getText( 'pages' );
81 $this->curonly = $wgRequest->getCheck( 'curonly' );
82 $rawOffset = $wgRequest->getVal( 'offset' );
83 if( $rawOffset ) {
84 $offset = wfTimestamp( TS_MW, $rawOffset );
85 } else {
86 $offset = null;
88 $limit = $wgRequest->getInt( 'limit' );
89 $dir = $wgRequest->getVal( 'dir' );
90 $history = array(
91 'dir' => 'asc',
92 'offset' => false,
93 'limit' => $wgExportMaxHistory,
95 $historyCheck = $wgRequest->getCheck( 'history' );
96 if ( $this->curonly ) {
97 $history = WikiExporter::CURRENT;
98 } elseif ( !$historyCheck ) {
99 if ( $limit > 0 && ($wgExportMaxHistory == 0 || $limit < $wgExportMaxHistory ) ) {
100 $history['limit'] = $limit;
102 if ( !is_null( $offset ) ) {
103 $history['offset'] = $offset;
105 if ( strtolower( $dir ) == 'desc' ) {
106 $history['dir'] = 'desc';
110 if( $page != '' ) $this->doExport = true;
111 } else {
112 // Default to current-only for GET requests
113 $page = $wgRequest->getText( 'pages', $par );
114 $historyCheck = $wgRequest->getCheck( 'history' );
115 if( $historyCheck ) {
116 $history = WikiExporter::FULL;
117 } else {
118 $history = WikiExporter::CURRENT;
121 if( $page != '' ) $this->doExport = true;
124 if( !$wgExportAllowHistory ) {
125 // Override
126 $history = WikiExporter::CURRENT;
129 $list_authors = $wgRequest->getCheck( 'listauthors' );
130 if ( !$this->curonly || !$wgExportAllowListContributors ) $list_authors = false ;
132 if ( $this->doExport ) {
133 $wgOut->disable();
134 // Cancel output buffering and gzipping if set
135 // This should provide safer streaming for pages with history
136 wfResetOutputBuffers();
137 header( "Content-type: application/xml; charset=utf-8" );
138 if( $wgRequest->getCheck( 'wpDownload' ) ) {
139 // Provide a sane filename suggestion
140 $filename = urlencode( $wgSitename . '-' . wfTimestampNow() . '.xml' );
141 $wgRequest->response()->header( "Content-disposition: attachment;filename={$filename}" );
143 $this->doExport( $page, $history, $list_authors );
144 return;
147 $wgOut->addWikiMsg( 'exporttext' );
149 $form = Xml::openElement( 'form', array( 'method' => 'post',
150 'action' => $this->getTitle()->getLocalUrl( 'action=submit' ) ) );
151 $form .= Xml::inputLabel( wfMsg( 'export-addcattext' ) , 'catname', 'catname', 40 ) . '&nbsp;';
152 $form .= Xml::submitButton( wfMsg( 'export-addcat' ), array( 'name' => 'addcat' ) ) . '<br />';
154 if ( $wgExportFromNamespaces ) {
155 $form .= Xml::namespaceSelector( $nsindex, null, 'nsindex', wfMsg( 'export-addnstext' ) ) . '&nbsp;';
156 $form .= Xml::submitButton( wfMsg( 'export-addns' ), array( 'name' => 'addns' ) ) . '<br />';
159 $form .= Xml::element( 'textarea', array( 'name' => 'pages', 'cols' => 40, 'rows' => 10 ), $page, false );
160 $form .= '<br />';
162 if( $wgExportAllowHistory ) {
163 $form .= Xml::checkLabel( wfMsg( 'exportcuronly' ), 'curonly', 'curonly', true ) . '<br />';
164 } else {
165 $wgOut->addHTML( wfMsgExt( 'exportnohistory', 'parse' ) );
167 $form .= Xml::checkLabel( wfMsg( 'export-templates' ), 'templates', 'wpExportTemplates', false ) . '<br />';
168 if( $wgExportMaxLinkDepth || $this->userCanOverrideExportDepth() ) {
169 $form .= Xml::inputLabel( wfMsg( 'export-pagelinks' ), 'pagelink-depth', 'pagelink-depth', 20, 0 ) . '<br />';
171 // Enable this when we can do something useful exporting/importing image information. :)
172 //$form .= Xml::checkLabel( wfMsg( 'export-images' ), 'images', 'wpExportImages', false ) . '<br />';
173 $form .= Xml::checkLabel( wfMsg( 'export-download' ), 'wpDownload', 'wpDownload', true ) . '<br />';
175 $form .= Xml::submitButton( wfMsg( 'export-submit' ), array( 'accesskey' => 's' ) );
176 $form .= Xml::closeElement( 'form' );
177 $wgOut->addHTML( $form );
180 private function userCanOverrideExportDepth() {
181 global $wgUser;
183 return $wgUser->isAllowed( 'override-export-depth' );
187 * Do the actual page exporting
188 * @param string $page User input on what page(s) to export
189 * @param mixed $history one of the WikiExporter history export constants
191 private function doExport( $page, $history, $list_authors ) {
192 global $wgExportMaxHistory;
194 $pageSet = array(); // Inverted index of all pages to look up
196 // Split up and normalize input
197 foreach( explode( "\n", $page ) as $pageName ) {
198 $pageName = trim( $pageName );
199 $title = Title::newFromText( $pageName );
200 if( $title && $title->getInterwiki() == '' && $title->getText() !== '' ) {
201 // Only record each page once!
202 $pageSet[$title->getPrefixedText()] = true;
206 // Set of original pages to pass on to further manipulation...
207 $inputPages = array_keys( $pageSet );
209 // Look up any linked pages if asked...
210 if( $this->templates ) {
211 $pageSet = $this->getTemplates( $inputPages, $pageSet );
214 if( $linkDepth = $this->pageLinkDepth ) {
215 $pageSet = $this->getPageLinks( $inputPages, $pageSet, $linkDepth );
219 // Enable this when we can do something useful exporting/importing image information. :)
220 if( $this->images ) ) {
221 $pageSet = $this->getImages( $inputPages, $pageSet );
225 $pages = array_keys( $pageSet );
227 // Normalize titles to the same format and remove dupes, see bug 17374
228 foreach( $pages as $k => $v ) {
229 $pages[$k] = str_replace( " ", "_", $v );
231 $pages = array_unique( $pages );
233 /* Ok, let's get to it... */
234 if( $history == WikiExporter::CURRENT ) {
235 $lb = false;
236 $db = wfGetDB( DB_SLAVE );
237 $buffer = WikiExporter::BUFFER;
238 } else {
239 // Use an unbuffered query; histories may be very long!
240 $lb = wfGetLBFactory()->newMainLB();
241 $db = $lb->getConnection( DB_SLAVE );
242 $buffer = WikiExporter::STREAM;
244 // This might take a while... :D
245 wfSuppressWarnings();
246 set_time_limit(0);
247 wfRestoreWarnings();
249 $exporter = new WikiExporter( $db, $history, $buffer );
250 $exporter->list_authors = $list_authors;
251 $exporter->openStream();
252 foreach( $pages as $page ) {
254 if( $wgExportMaxHistory && !$this->curonly ) {
255 $title = Title::newFromText( $page );
256 if( $title ) {
257 $count = Revision::countByTitle( $db, $title );
258 if( $count > $wgExportMaxHistory ) {
259 wfDebug( __FUNCTION__ .
260 ": Skipped $page, $count revisions too big\n" );
261 continue;
265 #Bug 8824: Only export pages the user can read
266 $title = Title::newFromText( $page );
267 if( is_null( $title ) ) continue; #TODO: perhaps output an <error> tag or something.
268 if( !$title->userCanRead() ) continue; #TODO: perhaps output an <error> tag or something.
270 $exporter->pageByTitle( $title );
273 $exporter->closeStream();
274 if( $lb ) {
275 $lb->closeAll();
279 private function getPagesFromCategory( $title ) {
280 global $wgContLang;
282 $name = $title->getDBkey();
284 $dbr = wfGetDB( DB_SLAVE );
285 $res = $dbr->select( array('page', 'categorylinks' ),
286 array( 'page_namespace', 'page_title' ),
287 array('cl_from=page_id', 'cl_to' => $name ),
288 __METHOD__, array('LIMIT' => '5000'));
290 $pages = array();
291 while ( $row = $dbr->fetchObject( $res ) ) {
292 $n = $row->page_title;
293 if ($row->page_namespace) {
294 $ns = $wgContLang->getNsText( $row->page_namespace );
295 $n = $ns . ':' . $n;
298 $pages[] = $n;
300 $dbr->freeResult($res);
302 return $pages;
305 private function getPagesFromNamespace( $nsindex ) {
306 global $wgContLang;
308 $dbr = wfGetDB( DB_SLAVE );
309 $res = $dbr->select( 'page', array('page_namespace', 'page_title'),
310 array('page_namespace' => $nsindex),
311 __METHOD__, array('LIMIT' => '5000') );
313 $pages = array();
314 while ( $row = $dbr->fetchObject( $res ) ) {
315 $n = $row->page_title;
316 if ($row->page_namespace) {
317 $ns = $wgContLang->getNsText( $row->page_namespace );
318 $n = $ns . ':' . $n;
321 $pages[] = $n;
323 $dbr->freeResult($res);
325 return $pages;
328 * Expand a list of pages to include templates used in those pages.
329 * @param $inputPages array, list of titles to look up
330 * @param $pageSet array, associative array indexed by titles for output
331 * @return array associative array index by titles
333 private function getTemplates( $inputPages, $pageSet ) {
334 return $this->getLinks( $inputPages, $pageSet,
335 'templatelinks',
336 array( 'tl_namespace AS namespace', 'tl_title AS title' ),
337 array( 'page_id=tl_from' ) );
341 * Validate link depth setting, if available.
343 private function validateLinkDepth( $depth ) {
344 global $wgExportMaxLinkDepth, $wgExportMaxLinkDepthLimit;
345 if( $depth < 0 ) {
346 return 0;
348 if ( !$this->userCanOverrideExportDepth() ) {
349 if( $depth > $wgExportMaxLinkDepth ) {
350 return $wgExportMaxLinkDepth;
354 * There's a HARD CODED limit of 5 levels of recursion here to prevent a
355 * crazy-big export from being done by someone setting the depth
356 * number too high. In other words, last resort safety net.
358 return intval( min( $depth, 5 ) );
361 /** Expand a list of pages to include pages linked to from that page. */
362 private function getPageLinks( $inputPages, $pageSet, $depth ) {
363 for( $depth=$depth; $depth>0; --$depth ) {
364 $pageSet = $this->getLinks( $inputPages, $pageSet, 'pagelinks',
365 array( 'pl_namespace AS namespace', 'pl_title AS title' ),
366 array( 'page_id=pl_from' ) );
367 $inputPages = array_keys( $pageSet );
369 return $pageSet;
373 * Expand a list of pages to include images used in those pages.
374 * @param $inputPages array, list of titles to look up
375 * @param $pageSet array, associative array indexed by titles for output
376 * @return array associative array index by titles
378 private function getImages( $inputPages, $pageSet ) {
379 return $this->getLinks( $inputPages, $pageSet,
380 'imagelinks',
381 array( NS_FILE . ' AS namespace', 'il_to AS title' ),
382 array( 'page_id=il_from' ) );
386 * Expand a list of pages to include items used in those pages.
387 * @private
389 private function getLinks( $inputPages, $pageSet, $table, $fields, $join ) {
390 $dbr = wfGetDB( DB_SLAVE );
391 foreach( $inputPages as $page ) {
392 $title = Title::newFromText( $page );
393 if( $title ) {
394 $pageSet[$title->getPrefixedText()] = true;
395 /// @todo Fixme: May or may not be more efficient to batch these
396 /// by namespace when given multiple input pages.
397 $result = $dbr->select(
398 array( 'page', $table ),
399 $fields,
400 array_merge( $join,
401 array(
402 'page_namespace' => $title->getNamespace(),
403 'page_title' => $title->getDBkey() ) ),
404 __METHOD__ );
405 foreach( $result as $row ) {
406 $template = Title::makeTitle( $row->namespace, $row->title );
407 $pageSet[$template->getPrefixedText()] = true;
411 return $pageSet;