SpecialExport.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. <?php
  2. /**
  3. * Implements Special:Export
  4. *
  5. * Copyright © 2003-2008 Brion Vibber <brion@pobox.com>
  6. *
  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.
  11. *
  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.
  16. *
  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
  21. *
  22. * @file
  23. * @ingroup SpecialPage
  24. */
  25. use MediaWiki\Logger\LoggerFactory;
  26. use MediaWiki\MediaWikiServices;
  27. /**
  28. * A special page that allows users to export pages in a XML file
  29. *
  30. * @ingroup SpecialPage
  31. */
  32. class SpecialExport extends SpecialPage {
  33. private $curonly, $doExport, $pageLinkDepth, $templates;
  34. public function __construct() {
  35. parent::__construct( 'Export' );
  36. }
  37. public function execute( $par ) {
  38. $this->setHeaders();
  39. $this->outputHeader();
  40. $config = $this->getConfig();
  41. // Set some variables
  42. $this->curonly = true;
  43. $this->doExport = false;
  44. $request = $this->getRequest();
  45. $this->templates = $request->getCheck( 'templates' );
  46. $this->pageLinkDepth = $this->validateLinkDepth(
  47. $request->getIntOrNull( 'pagelink-depth' )
  48. );
  49. $nsindex = '';
  50. $exportall = false;
  51. if ( $request->getCheck( 'addcat' ) ) {
  52. $page = $request->getText( 'pages' );
  53. $catname = $request->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.
  61. */
  62. $catpages = $this->getPagesFromCategory( $t );
  63. if ( $catpages ) {
  64. if ( $page !== '' ) {
  65. $page .= "\n";
  66. }
  67. $page .= implode( "\n", $catpages );
  68. }
  69. }
  70. }
  71. } elseif ( $request->getCheck( 'addns' ) && $config->get( 'ExportFromNamespaces' ) ) {
  72. $page = $request->getText( 'pages' );
  73. $nsindex = $request->getText( 'nsindex', '' );
  74. if ( strval( $nsindex ) !== '' ) {
  75. /**
  76. * Same implementation as above, so same @todo
  77. */
  78. $nspages = $this->getPagesFromNamespace( $nsindex );
  79. if ( $nspages ) {
  80. $page .= "\n" . implode( "\n", $nspages );
  81. }
  82. }
  83. } elseif ( $request->getCheck( 'exportall' ) && $config->get( 'ExportAllowAll' ) ) {
  84. $this->doExport = true;
  85. $exportall = true;
  86. /* Although $page and $history are not used later on, we
  87. nevertheless set them to avoid that PHP notices about using
  88. undefined variables foul up our XML output (see call to
  89. doExport(...) further down) */
  90. $page = '';
  91. $history = '';
  92. } elseif ( $request->wasPosted() && $par == '' ) {
  93. // Log to see if certain parameters are actually used.
  94. // If not, we could deprecate them and do some cleanup, here and in WikiExporter.
  95. LoggerFactory::getInstance( 'export' )->debug(
  96. 'Special:Export POST, dir: [{dir}], offset: [{offset}], limit: [{limit}]', [
  97. 'dir' => $request->getRawVal( 'dir' ),
  98. 'offset' => $request->getRawVal( 'offset' ),
  99. 'limit' => $request->getRawVal( 'limit' ),
  100. ] );
  101. $page = $request->getText( 'pages' );
  102. $this->curonly = $request->getCheck( 'curonly' );
  103. $rawOffset = $request->getVal( 'offset' );
  104. if ( $rawOffset ) {
  105. $offset = wfTimestamp( TS_MW, $rawOffset );
  106. } else {
  107. $offset = null;
  108. }
  109. $maxHistory = $config->get( 'ExportMaxHistory' );
  110. $limit = $request->getInt( 'limit' );
  111. $dir = $request->getVal( 'dir' );
  112. $history = [
  113. 'dir' => 'asc',
  114. 'offset' => false,
  115. 'limit' => $maxHistory,
  116. ];
  117. $historyCheck = $request->getCheck( 'history' );
  118. if ( $this->curonly ) {
  119. $history = WikiExporter::CURRENT;
  120. } elseif ( !$historyCheck ) {
  121. if ( $limit > 0 && ( $maxHistory == 0 || $limit < $maxHistory ) ) {
  122. $history['limit'] = $limit;
  123. }
  124. if ( !is_null( $offset ) ) {
  125. $history['offset'] = $offset;
  126. }
  127. if ( strtolower( $dir ) == 'desc' ) {
  128. $history['dir'] = 'desc';
  129. }
  130. }
  131. if ( $page != '' ) {
  132. $this->doExport = true;
  133. }
  134. } else {
  135. // Default to current-only for GET requests.
  136. $page = $request->getText( 'pages', $par );
  137. $historyCheck = $request->getCheck( 'history' );
  138. if ( $historyCheck ) {
  139. $history = WikiExporter::FULL;
  140. } else {
  141. $history = WikiExporter::CURRENT;
  142. }
  143. if ( $page != '' ) {
  144. $this->doExport = true;
  145. }
  146. }
  147. if ( !$config->get( 'ExportAllowHistory' ) ) {
  148. // Override
  149. $history = WikiExporter::CURRENT;
  150. }
  151. $list_authors = $request->getCheck( 'listauthors' );
  152. if ( !$this->curonly || !$config->get( 'ExportAllowListContributors' ) ) {
  153. $list_authors = false;
  154. }
  155. if ( $this->doExport ) {
  156. $this->getOutput()->disable();
  157. // Cancel output buffering and gzipping if set
  158. // This should provide safer streaming for pages with history
  159. wfResetOutputBuffers();
  160. $request->response()->header( "Content-type: application/xml; charset=utf-8" );
  161. $request->response()->header( "X-Robots-Tag: noindex,nofollow" );
  162. if ( $request->getCheck( 'wpDownload' ) ) {
  163. // Provide a sane filename suggestion
  164. $filename = urlencode( $config->get( 'Sitename' ) . '-' . wfTimestampNow() . '.xml' );
  165. $request->response()->header( "Content-disposition: attachment;filename={$filename}" );
  166. }
  167. $this->doExport( $page, $history, $list_authors, $exportall );
  168. return;
  169. }
  170. $out = $this->getOutput();
  171. $out->addWikiMsg( 'exporttext' );
  172. if ( $page == '' ) {
  173. $categoryName = $request->getText( 'catname' );
  174. } else {
  175. $categoryName = '';
  176. }
  177. $formDescriptor = [
  178. 'catname' => [
  179. 'type' => 'textwithbutton',
  180. 'name' => 'catname',
  181. 'horizontal-label' => true,
  182. 'label-message' => 'export-addcattext',
  183. 'default' => $categoryName,
  184. 'size' => 40,
  185. 'buttontype' => 'submit',
  186. 'buttonname' => 'addcat',
  187. 'buttondefault' => $this->msg( 'export-addcat' )->text(),
  188. 'hide-if' => [ '===', 'exportall', '1' ],
  189. ],
  190. ];
  191. if ( $config->get( 'ExportFromNamespaces' ) ) {
  192. $formDescriptor += [
  193. 'nsindex' => [
  194. 'type' => 'namespaceselectwithbutton',
  195. 'default' => $nsindex,
  196. 'label-message' => 'export-addnstext',
  197. 'horizontal-label' => true,
  198. 'name' => 'nsindex',
  199. 'id' => 'namespace',
  200. 'cssclass' => 'namespaceselector',
  201. 'buttontype' => 'submit',
  202. 'buttonname' => 'addns',
  203. 'buttondefault' => $this->msg( 'export-addns' )->text(),
  204. 'hide-if' => [ '===', 'exportall', '1' ],
  205. ],
  206. ];
  207. }
  208. if ( $config->get( 'ExportAllowAll' ) ) {
  209. $formDescriptor += [
  210. 'exportall' => [
  211. 'type' => 'check',
  212. 'label-message' => 'exportall',
  213. 'name' => 'exportall',
  214. 'id' => 'exportall',
  215. 'default' => $request->wasPosted() ? $request->getCheck( 'exportall' ) : false,
  216. ],
  217. ];
  218. }
  219. $formDescriptor += [
  220. 'textarea' => [
  221. 'class' => HTMLTextAreaField::class,
  222. 'name' => 'pages',
  223. 'label-message' => 'export-manual',
  224. 'nodata' => true,
  225. 'rows' => 10,
  226. 'default' => $page,
  227. 'hide-if' => [ '===', 'exportall', '1' ],
  228. ],
  229. ];
  230. if ( $config->get( 'ExportAllowHistory' ) ) {
  231. $formDescriptor += [
  232. 'curonly' => [
  233. 'type' => 'check',
  234. 'label-message' => 'exportcuronly',
  235. 'name' => 'curonly',
  236. 'id' => 'curonly',
  237. 'default' => $request->wasPosted() ? $request->getCheck( 'curonly' ) : true,
  238. ],
  239. ];
  240. } else {
  241. $out->addWikiMsg( 'exportnohistory' );
  242. }
  243. $formDescriptor += [
  244. 'templates' => [
  245. 'type' => 'check',
  246. 'label-message' => 'export-templates',
  247. 'name' => 'templates',
  248. 'id' => 'wpExportTemplates',
  249. 'default' => $request->wasPosted() ? $request->getCheck( 'templates' ) : false,
  250. ],
  251. ];
  252. if ( $config->get( 'ExportMaxLinkDepth' ) || $this->userCanOverrideExportDepth() ) {
  253. $formDescriptor += [
  254. 'pagelink-depth' => [
  255. 'type' => 'text',
  256. 'name' => 'pagelink-depth',
  257. 'id' => 'pagelink-depth',
  258. 'label-message' => 'export-pagelinks',
  259. 'default' => '0',
  260. 'size' => 20,
  261. ],
  262. ];
  263. }
  264. $formDescriptor += [
  265. 'wpDownload' => [
  266. 'type' => 'check',
  267. 'name' => 'wpDownload',
  268. 'id' => 'wpDownload',
  269. 'default' => $request->wasPosted() ? $request->getCheck( 'wpDownload' ) : true,
  270. 'label-message' => 'export-download',
  271. ],
  272. ];
  273. if ( $config->get( 'ExportAllowListContributors' ) ) {
  274. $formDescriptor += [
  275. 'listauthors' => [
  276. 'type' => 'check',
  277. 'label-message' => 'exportlistauthors',
  278. 'default' => $request->wasPosted() ? $request->getCheck( 'listauthors' ) : false,
  279. 'name' => 'listauthors',
  280. 'id' => 'listauthors',
  281. ],
  282. ];
  283. }
  284. $htmlForm = HTMLForm::factory( 'ooui', $formDescriptor, $this->getContext() );
  285. $htmlForm->setSubmitTextMsg( 'export-submit' );
  286. $htmlForm->prepareForm()->displayForm( false );
  287. $this->addHelpLink( 'Help:Export' );
  288. }
  289. /**
  290. * @return bool
  291. */
  292. private function userCanOverrideExportDepth() {
  293. return MediaWikiServices::getInstance()
  294. ->getPermissionManager()
  295. ->userHasRight( $this->getUser(), 'override-export-depth' );
  296. }
  297. /**
  298. * Do the actual page exporting
  299. *
  300. * @param string $page User input on what page(s) to export
  301. * @param int $history One of the WikiExporter history export constants
  302. * @param bool $list_authors Whether to add distinct author list (when
  303. * not returning full history)
  304. * @param bool $exportall Whether to export everything
  305. */
  306. private function doExport( $page, $history, $list_authors, $exportall ) {
  307. // If we are grabbing everything, enable full history and ignore the rest
  308. if ( $exportall ) {
  309. $history = WikiExporter::FULL;
  310. } else {
  311. $pageSet = []; // Inverted index of all pages to look up
  312. // Split up and normalize input
  313. foreach ( explode( "\n", $page ) as $pageName ) {
  314. $pageName = trim( $pageName );
  315. $title = Title::newFromText( $pageName );
  316. if ( $title && !$title->isExternal() && $title->getText() !== '' ) {
  317. // Only record each page once!
  318. $pageSet[$title->getPrefixedText()] = true;
  319. }
  320. }
  321. // Set of original pages to pass on to further manipulation...
  322. $inputPages = array_keys( $pageSet );
  323. // Look up any linked pages if asked...
  324. if ( $this->templates ) {
  325. $pageSet = $this->getTemplates( $inputPages, $pageSet );
  326. }
  327. $linkDepth = $this->pageLinkDepth;
  328. if ( $linkDepth ) {
  329. $pageSet = $this->getPageLinks( $inputPages, $pageSet, $linkDepth );
  330. }
  331. $pages = array_keys( $pageSet );
  332. // Normalize titles to the same format and remove dupes, see T19374
  333. foreach ( $pages as $k => $v ) {
  334. $pages[$k] = str_replace( " ", "_", $v );
  335. }
  336. $pages = array_unique( $pages );
  337. }
  338. /* Ok, let's get to it... */
  339. $db = wfGetDB( DB_REPLICA );
  340. $exporter = new WikiExporter( $db, $history );
  341. $exporter->list_authors = $list_authors;
  342. $exporter->openStream();
  343. if ( $exportall ) {
  344. $exporter->allPages();
  345. } else {
  346. $permissionManager = MediaWikiServices::getInstance()->getPermissionManager();
  347. foreach ( $pages as $page ) {
  348. # T10824: Only export pages the user can read
  349. $title = Title::newFromText( $page );
  350. if ( is_null( $title ) ) {
  351. // @todo Perhaps output an <error> tag or something.
  352. continue;
  353. }
  354. if ( !$permissionManager->userCan( 'read', $this->getUser(), $title ) ) {
  355. // @todo Perhaps output an <error> tag or something.
  356. continue;
  357. }
  358. $exporter->pageByTitle( $title );
  359. }
  360. }
  361. $exporter->closeStream();
  362. }
  363. /**
  364. * @param Title $title
  365. * @return string[]
  366. */
  367. private function getPagesFromCategory( $title ) {
  368. $maxPages = $this->getConfig()->get( 'ExportPagelistLimit' );
  369. $name = $title->getDBkey();
  370. $dbr = wfGetDB( DB_REPLICA );
  371. $res = $dbr->select(
  372. [ 'page', 'categorylinks' ],
  373. [ 'page_namespace', 'page_title' ],
  374. [ 'cl_from=page_id', 'cl_to' => $name ],
  375. __METHOD__,
  376. [ 'LIMIT' => $maxPages ]
  377. );
  378. $pages = [];
  379. foreach ( $res as $row ) {
  380. $pages[] = Title::makeName( $row->page_namespace, $row->page_title );
  381. }
  382. return $pages;
  383. }
  384. /**
  385. * @param int $nsindex
  386. * @return string[]
  387. */
  388. private function getPagesFromNamespace( $nsindex ) {
  389. $maxPages = $this->getConfig()->get( 'ExportPagelistLimit' );
  390. $dbr = wfGetDB( DB_REPLICA );
  391. $res = $dbr->select(
  392. 'page',
  393. [ 'page_namespace', 'page_title' ],
  394. [ 'page_namespace' => $nsindex ],
  395. __METHOD__,
  396. [ 'LIMIT' => $maxPages ]
  397. );
  398. $pages = [];
  399. foreach ( $res as $row ) {
  400. $pages[] = Title::makeName( $row->page_namespace, $row->page_title );
  401. }
  402. return $pages;
  403. }
  404. /**
  405. * Expand a list of pages to include templates used in those pages.
  406. * @param array $inputPages List of titles to look up
  407. * @param array $pageSet Associative array indexed by titles for output
  408. * @return array Associative array index by titles
  409. */
  410. private function getTemplates( $inputPages, $pageSet ) {
  411. return $this->getLinks( $inputPages, $pageSet,
  412. 'templatelinks',
  413. [ 'namespace' => 'tl_namespace', 'title' => 'tl_title' ],
  414. [ 'page_id=tl_from' ]
  415. );
  416. }
  417. /**
  418. * Validate link depth setting, if available.
  419. * @param int $depth
  420. * @return int
  421. */
  422. private function validateLinkDepth( $depth ) {
  423. if ( $depth < 0 ) {
  424. return 0;
  425. }
  426. if ( !$this->userCanOverrideExportDepth() ) {
  427. $maxLinkDepth = $this->getConfig()->get( 'ExportMaxLinkDepth' );
  428. if ( $depth > $maxLinkDepth ) {
  429. return $maxLinkDepth;
  430. }
  431. }
  432. /*
  433. * There's a HARD CODED limit of 5 levels of recursion here to prevent a
  434. * crazy-big export from being done by someone setting the depth
  435. * number too high. In other words, last resort safety net.
  436. */
  437. return intval( min( $depth, 5 ) );
  438. }
  439. /**
  440. * Expand a list of pages to include pages linked to from that page.
  441. * @param array $inputPages
  442. * @param array $pageSet
  443. * @param int $depth
  444. * @return array
  445. */
  446. private function getPageLinks( $inputPages, $pageSet, $depth ) {
  447. for ( ; $depth > 0; --$depth ) {
  448. $pageSet = $this->getLinks(
  449. $inputPages, $pageSet, 'pagelinks',
  450. [ 'namespace' => 'pl_namespace', 'title' => 'pl_title' ],
  451. [ 'page_id=pl_from' ]
  452. );
  453. $inputPages = array_keys( $pageSet );
  454. }
  455. return $pageSet;
  456. }
  457. /**
  458. * Expand a list of pages to include items used in those pages.
  459. * @param array $inputPages Array of page titles
  460. * @param array $pageSet
  461. * @param string $table
  462. * @param array $fields Array of field names
  463. * @param array $join
  464. * @return array
  465. */
  466. private function getLinks( $inputPages, $pageSet, $table, $fields, $join ) {
  467. $dbr = wfGetDB( DB_REPLICA );
  468. foreach ( $inputPages as $page ) {
  469. $title = Title::newFromText( $page );
  470. if ( $title ) {
  471. $pageSet[$title->getPrefixedText()] = true;
  472. /// @todo FIXME: May or may not be more efficient to batch these
  473. /// by namespace when given multiple input pages.
  474. $result = $dbr->select(
  475. [ 'page', $table ],
  476. $fields,
  477. array_merge(
  478. $join,
  479. [
  480. 'page_namespace' => $title->getNamespace(),
  481. 'page_title' => $title->getDBkey()
  482. ]
  483. ),
  484. __METHOD__
  485. );
  486. foreach ( $result as $row ) {
  487. $template = Title::makeTitle( $row->namespace, $row->title );
  488. $pageSet[$template->getPrefixedText()] = true;
  489. }
  490. }
  491. }
  492. return $pageSet;
  493. }
  494. protected function getGroupName() {
  495. return 'pagetools';
  496. }
  497. }