dumpTextPass.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987
  1. <?php
  2. /**
  3. * BackupDumper that postprocesses XML dumps from dumpBackup.php to add page text
  4. *
  5. * Copyright (C) 2005 Brion Vibber <brion@pobox.com>
  6. * https://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 Maintenance
  25. */
  26. require_once __DIR__ . '/backup.inc';
  27. require_once __DIR__ . '/../includes/export/WikiExporter.php';
  28. /**
  29. * @ingroup Maintenance
  30. */
  31. class TextPassDumper extends BackupDumper {
  32. public $prefetch = null;
  33. // when we spend more than maxTimeAllowed seconds on this run, we continue
  34. // processing until we write out the next complete page, then save output file(s),
  35. // rename it/them and open new one(s)
  36. public $maxTimeAllowed = 0; // 0 = no limit
  37. protected $input = "php://stdin";
  38. protected $history = WikiExporter::FULL;
  39. protected $fetchCount = 0;
  40. protected $prefetchCount = 0;
  41. protected $prefetchCountLast = 0;
  42. protected $fetchCountLast = 0;
  43. protected $maxFailures = 5;
  44. protected $maxConsecutiveFailedTextRetrievals = 200;
  45. protected $failureTimeout = 5; // Seconds to sleep after db failure
  46. protected $bufferSize = 524288; // In bytes. Maximum size to read from the stub in on go.
  47. protected $php = "php";
  48. protected $spawn = false;
  49. /**
  50. * @var bool|resource
  51. */
  52. protected $spawnProc = false;
  53. /**
  54. * @var bool|resource
  55. */
  56. protected $spawnWrite = false;
  57. /**
  58. * @var bool|resource
  59. */
  60. protected $spawnRead = false;
  61. /**
  62. * @var bool|resource
  63. */
  64. protected $spawnErr = false;
  65. protected $xmlwriterobj = false;
  66. protected $timeExceeded = false;
  67. protected $firstPageWritten = false;
  68. protected $lastPageWritten = false;
  69. protected $checkpointJustWritten = false;
  70. protected $checkpointFiles = [];
  71. /**
  72. * @var DatabaseBase
  73. */
  74. protected $db;
  75. /**
  76. * @param array $args For backward compatibility
  77. */
  78. function __construct( $args = null ) {
  79. parent::__construct();
  80. $this->addDescription( <<<TEXT
  81. This script postprocesses XML dumps from dumpBackup.php to add
  82. page text which was stubbed out (using --stub).
  83. XML input is accepted on stdin.
  84. XML output is sent to stdout; progress reports are sent to stderr.
  85. TEXT
  86. );
  87. $this->stderr = fopen( "php://stderr", "wt" );
  88. $this->addOption( 'stub', 'To load a compressed stub dump instead of stdin. ' .
  89. 'Specify as --stub=<type>:<file>.', false, true );
  90. $this->addOption( 'prefetch', 'Use a prior dump file as a text source, to savepressure on the ' .
  91. 'database. (Requires the XMLReader extension). Specify as --prefetch=<type>:<file>',
  92. false, true );
  93. $this->addOption( 'maxtime', 'Write out checkpoint file after this many minutes (writing' .
  94. 'out complete page, closing xml file properly, and opening new one' .
  95. 'with header). This option requires the checkpointfile option.', false, true );
  96. $this->addOption( 'checkpointfile', 'Use this string for checkpoint filenames,substituting ' .
  97. 'first pageid written for the first %s (required) and the last pageid written for the ' .
  98. 'second %s if it exists.', false, true, false, true ); // This can be specified multiple times
  99. $this->addOption( 'quiet', 'Don\'t dump status reports to stderr.' );
  100. $this->addOption( 'current', 'Base ETA on number of pages in database instead of all revisions' );
  101. $this->addOption( 'spawn', 'Spawn a subprocess for loading text records' );
  102. $this->addOption( 'buffersize', 'Buffer size in bytes to use for reading the stub. ' .
  103. '(Default: 512KB, Minimum: 4KB)', false, true );
  104. if ( $args ) {
  105. $this->loadWithArgv( $args );
  106. $this->processOptions();
  107. }
  108. }
  109. function execute() {
  110. $this->processOptions();
  111. $this->dump( true );
  112. }
  113. function processOptions() {
  114. global $IP;
  115. parent::processOptions();
  116. if ( $this->hasOption( 'buffersize' ) ) {
  117. $this->bufferSize = max( intval( $this->getOption( 'buffersize' ) ), 4 * 1024 );
  118. }
  119. if ( $this->hasOption( 'prefetch' ) ) {
  120. require_once "$IP/maintenance/backupPrefetch.inc";
  121. $url = $this->processFileOpt( $this->getOption( 'prefetch' ) );
  122. $this->prefetch = new BaseDump( $url );
  123. }
  124. if ( $this->hasOption( 'stub' ) ) {
  125. $this->input = $this->processFileOpt( $this->getOption( 'stub' ) );
  126. }
  127. if ( $this->hasOption( 'maxtime' ) ) {
  128. $this->maxTimeAllowed = intval( $this->getOption( 'maxtime' ) ) * 60;
  129. }
  130. if ( $this->hasOption( 'checkpointfile' ) ) {
  131. $this->checkpointFiles = $this->getOption( 'checkpointfile' );
  132. }
  133. if ( $this->hasOption( 'current' ) ) {
  134. $this->history = WikiExporter::CURRENT;
  135. }
  136. if ( $this->hasOption( 'full' ) ) {
  137. $this->history = WikiExporter::FULL;
  138. }
  139. if ( $this->hasOption( 'spawn' ) ) {
  140. $this->spawn = true;
  141. $val = $this->getOption( 'spawn' );
  142. if ( $val !== 1 ) {
  143. $this->php = $val;
  144. }
  145. }
  146. }
  147. /**
  148. * Drop the database connection $this->db and try to get a new one.
  149. *
  150. * This function tries to get a /different/ connection if this is
  151. * possible. Hence, (if this is possible) it switches to a different
  152. * failover upon each call.
  153. *
  154. * This function resets $this->lb and closes all connections on it.
  155. *
  156. * @throws MWException
  157. */
  158. function rotateDb() {
  159. // Cleaning up old connections
  160. if ( isset( $this->lb ) ) {
  161. $this->lb->closeAll();
  162. unset( $this->lb );
  163. }
  164. if ( $this->forcedDb !== null ) {
  165. $this->db = $this->forcedDb;
  166. return;
  167. }
  168. if ( isset( $this->db ) && $this->db->isOpen() ) {
  169. throw new MWException( 'DB is set and has not been closed by the Load Balancer' );
  170. }
  171. unset( $this->db );
  172. // Trying to set up new connection.
  173. // We do /not/ retry upon failure, but delegate to encapsulating logic, to avoid
  174. // individually retrying at different layers of code.
  175. // 1. The LoadBalancer.
  176. try {
  177. $this->lb = wfGetLBFactory()->newMainLB();
  178. } catch ( Exception $e ) {
  179. throw new MWException( __METHOD__
  180. . " rotating DB failed to obtain new load balancer (" . $e->getMessage() . ")" );
  181. }
  182. // 2. The Connection, through the load balancer.
  183. try {
  184. $this->db = $this->lb->getConnection( DB_SLAVE, 'dump' );
  185. } catch ( Exception $e ) {
  186. throw new MWException( __METHOD__
  187. . " rotating DB failed to obtain new database (" . $e->getMessage() . ")" );
  188. }
  189. }
  190. function initProgress( $history = WikiExporter::FULL ) {
  191. parent::initProgress();
  192. $this->timeOfCheckpoint = $this->startTime;
  193. }
  194. function dump( $history, $text = WikiExporter::TEXT ) {
  195. // Notice messages will foul up your XML output even if they're
  196. // relatively harmless.
  197. if ( ini_get( 'display_errors' ) ) {
  198. ini_set( 'display_errors', 'stderr' );
  199. }
  200. $this->initProgress( $this->history );
  201. // We are trying to get an initial database connection to avoid that the
  202. // first try of this request's first call to getText fails. However, if
  203. // obtaining a good DB connection fails it's not a serious issue, as
  204. // getText does retry upon failure and can start without having a working
  205. // DB connection.
  206. try {
  207. $this->rotateDb();
  208. } catch ( Exception $e ) {
  209. // We do not even count this as failure. Just let eventual
  210. // watchdogs know.
  211. $this->progress( "Getting initial DB connection failed (" .
  212. $e->getMessage() . ")" );
  213. }
  214. $this->egress = new ExportProgressFilter( $this->sink, $this );
  215. // it would be nice to do it in the constructor, oh well. need egress set
  216. $this->finalOptionCheck();
  217. // we only want this so we know how to close a stream :-P
  218. $this->xmlwriterobj = new XmlDumpWriter();
  219. $input = fopen( $this->input, "rt" );
  220. $this->readDump( $input );
  221. if ( $this->spawnProc ) {
  222. $this->closeSpawn();
  223. }
  224. $this->report( true );
  225. }
  226. function processFileOpt( $opt ) {
  227. $split = explode( ':', $opt, 2 );
  228. $val = $split[0];
  229. $param = '';
  230. if ( count( $split ) === 2 ) {
  231. $param = $split[1];
  232. }
  233. $fileURIs = explode( ';', $param );
  234. foreach ( $fileURIs as $URI ) {
  235. switch ( $val ) {
  236. case "file":
  237. $newURI = $URI;
  238. break;
  239. case "gzip":
  240. $newURI = "compress.zlib://$URI";
  241. break;
  242. case "bzip2":
  243. $newURI = "compress.bzip2://$URI";
  244. break;
  245. case "7zip":
  246. $newURI = "mediawiki.compress.7z://$URI";
  247. break;
  248. default:
  249. $newURI = $URI;
  250. }
  251. $newFileURIs[] = $newURI;
  252. }
  253. $val = implode( ';', $newFileURIs );
  254. return $val;
  255. }
  256. /**
  257. * Overridden to include prefetch ratio if enabled.
  258. */
  259. function showReport() {
  260. if ( !$this->prefetch ) {
  261. parent::showReport();
  262. return;
  263. }
  264. if ( $this->reporting ) {
  265. $now = wfTimestamp( TS_DB );
  266. $nowts = microtime( true );
  267. $deltaAll = $nowts - $this->startTime;
  268. $deltaPart = $nowts - $this->lastTime;
  269. $this->pageCountPart = $this->pageCount - $this->pageCountLast;
  270. $this->revCountPart = $this->revCount - $this->revCountLast;
  271. if ( $deltaAll ) {
  272. $portion = $this->revCount / $this->maxCount;
  273. $eta = $this->startTime + $deltaAll / $portion;
  274. $etats = wfTimestamp( TS_DB, intval( $eta ) );
  275. if ( $this->fetchCount ) {
  276. $fetchRate = 100.0 * $this->prefetchCount / $this->fetchCount;
  277. } else {
  278. $fetchRate = '-';
  279. }
  280. $pageRate = $this->pageCount / $deltaAll;
  281. $revRate = $this->revCount / $deltaAll;
  282. } else {
  283. $pageRate = '-';
  284. $revRate = '-';
  285. $etats = '-';
  286. $fetchRate = '-';
  287. }
  288. if ( $deltaPart ) {
  289. if ( $this->fetchCountLast ) {
  290. $fetchRatePart = 100.0 * $this->prefetchCountLast / $this->fetchCountLast;
  291. } else {
  292. $fetchRatePart = '-';
  293. }
  294. $pageRatePart = $this->pageCountPart / $deltaPart;
  295. $revRatePart = $this->revCountPart / $deltaPart;
  296. } else {
  297. $fetchRatePart = '-';
  298. $pageRatePart = '-';
  299. $revRatePart = '-';
  300. }
  301. $this->progress( sprintf(
  302. "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
  303. . "%d revs (%0.1f|%0.1f/sec all|curr), %0.1f%%|%0.1f%% "
  304. . "prefetched (all|curr), ETA %s [max %d]",
  305. $now, wfWikiID(), $this->ID, $this->pageCount, $pageRate,
  306. $pageRatePart, $this->revCount, $revRate, $revRatePart,
  307. $fetchRate, $fetchRatePart, $etats, $this->maxCount
  308. ) );
  309. $this->lastTime = $nowts;
  310. $this->revCountLast = $this->revCount;
  311. $this->prefetchCountLast = $this->prefetchCount;
  312. $this->fetchCountLast = $this->fetchCount;
  313. }
  314. }
  315. function setTimeExceeded() {
  316. $this->timeExceeded = true;
  317. }
  318. function checkIfTimeExceeded() {
  319. if ( $this->maxTimeAllowed
  320. && ( $this->lastTime - $this->timeOfCheckpoint > $this->maxTimeAllowed )
  321. ) {
  322. return true;
  323. }
  324. return false;
  325. }
  326. function finalOptionCheck() {
  327. if ( ( $this->checkpointFiles && !$this->maxTimeAllowed )
  328. || ( $this->maxTimeAllowed && !$this->checkpointFiles )
  329. ) {
  330. throw new MWException( "Options checkpointfile and maxtime must be specified together.\n" );
  331. }
  332. foreach ( $this->checkpointFiles as $checkpointFile ) {
  333. $count = substr_count( $checkpointFile, "%s" );
  334. if ( $count != 2 ) {
  335. throw new MWException( "Option checkpointfile must contain two '%s' "
  336. . "for substitution of first and last pageids, count is $count instead, "
  337. . "file is $checkpointFile.\n" );
  338. }
  339. }
  340. if ( $this->checkpointFiles ) {
  341. $filenameList = (array)$this->egress->getFilenames();
  342. if ( count( $filenameList ) != count( $this->checkpointFiles ) ) {
  343. throw new MWException( "One checkpointfile must be specified "
  344. . "for each output option, if maxtime is used.\n" );
  345. }
  346. }
  347. }
  348. /**
  349. * @throws MWException Failure to parse XML input
  350. * @param string $input
  351. * @return bool
  352. */
  353. function readDump( $input ) {
  354. $this->buffer = "";
  355. $this->openElement = false;
  356. $this->atStart = true;
  357. $this->state = "";
  358. $this->lastName = "";
  359. $this->thisPage = 0;
  360. $this->thisRev = 0;
  361. $this->thisRevModel = null;
  362. $this->thisRevFormat = null;
  363. $parser = xml_parser_create( "UTF-8" );
  364. xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
  365. xml_set_element_handler(
  366. $parser,
  367. [ $this, 'startElement' ],
  368. [ $this, 'endElement' ]
  369. );
  370. xml_set_character_data_handler( $parser, [ $this, 'characterData' ] );
  371. $offset = 0; // for context extraction on error reporting
  372. do {
  373. if ( $this->checkIfTimeExceeded() ) {
  374. $this->setTimeExceeded();
  375. }
  376. $chunk = fread( $input, $this->bufferSize );
  377. if ( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
  378. wfDebug( "TextDumpPass::readDump encountered XML parsing error\n" );
  379. $byte = xml_get_current_byte_index( $parser );
  380. $msg = wfMessage( 'xml-error-string',
  381. 'XML import parse failure',
  382. xml_get_current_line_number( $parser ),
  383. xml_get_current_column_number( $parser ),
  384. $byte . ( is_null( $chunk ) ? null : ( '; "' . substr( $chunk, $byte - $offset, 16 ) . '"' ) ),
  385. xml_error_string( xml_get_error_code( $parser ) ) )->escaped();
  386. xml_parser_free( $parser );
  387. throw new MWException( $msg );
  388. }
  389. $offset += strlen( $chunk );
  390. } while ( $chunk !== false && !feof( $input ) );
  391. if ( $this->maxTimeAllowed ) {
  392. $filenameList = (array)$this->egress->getFilenames();
  393. // we wrote some stuff after last checkpoint that needs renamed
  394. if ( file_exists( $filenameList[0] ) ) {
  395. $newFilenames = [];
  396. # we might have just written the header and footer and had no
  397. # pages or revisions written... perhaps they were all deleted
  398. # there's no pageID 0 so we use that. the caller is responsible
  399. # for deciding what to do with a file containing only the
  400. # siteinfo information and the mw tags.
  401. if ( !$this->firstPageWritten ) {
  402. $firstPageID = str_pad( 0, 9, "0", STR_PAD_LEFT );
  403. $lastPageID = str_pad( 0, 9, "0", STR_PAD_LEFT );
  404. } else {
  405. $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
  406. $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
  407. }
  408. $filenameCount = count( $filenameList );
  409. for ( $i = 0; $i < $filenameCount; $i++ ) {
  410. $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
  411. $fileinfo = pathinfo( $filenameList[$i] );
  412. $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
  413. }
  414. $this->egress->closeAndRename( $newFilenames );
  415. }
  416. }
  417. xml_parser_free( $parser );
  418. return true;
  419. }
  420. /**
  421. * Applies applicable export transformations to $text.
  422. *
  423. * @param string $text
  424. * @param string $model
  425. * @param string|null $format
  426. *
  427. * @return string
  428. */
  429. private function exportTransform( $text, $model, $format = null ) {
  430. try {
  431. $handler = ContentHandler::getForModelID( $model );
  432. $text = $handler->exportTransform( $text, $format );
  433. }
  434. catch ( MWException $ex ) {
  435. $this->progress(
  436. "Unable to apply export transformation for content model '$model': " .
  437. $ex->getMessage()
  438. );
  439. }
  440. return $text;
  441. }
  442. /**
  443. * Tries to get the revision text for a revision id.
  444. * Export transformations are applied if the content model can is given or can be
  445. * determined from the database.
  446. *
  447. * Upon errors, retries (Up to $this->maxFailures tries each call).
  448. * If still no good revision get could be found even after this retrying, "" is returned.
  449. * If no good revision text could be returned for
  450. * $this->maxConsecutiveFailedTextRetrievals consecutive calls to getText, MWException
  451. * is thrown.
  452. *
  453. * @param string $id The revision id to get the text for
  454. * @param string|bool|null $model The content model used to determine
  455. * applicable export transformations.
  456. * If $model is null, it will be determined from the database.
  457. * @param string|null $format The content format used when applying export transformations.
  458. *
  459. * @throws MWException
  460. * @return string The revision text for $id, or ""
  461. */
  462. function getText( $id, $model = null, $format = null ) {
  463. global $wgContentHandlerUseDB;
  464. $prefetchNotTried = true; // Whether or not we already tried to get the text via prefetch.
  465. $text = false; // The candidate for a good text. false if no proper value.
  466. $failures = 0; // The number of times, this invocation of getText already failed.
  467. // The number of times getText failed without yielding a good text in between.
  468. static $consecutiveFailedTextRetrievals = 0;
  469. $this->fetchCount++;
  470. // To allow to simply return on success and do not have to worry about book keeping,
  471. // we assume, this fetch works (possible after some retries). Nevertheless, we koop
  472. // the old value, so we can restore it, if problems occur (See after the while loop).
  473. $oldConsecutiveFailedTextRetrievals = $consecutiveFailedTextRetrievals;
  474. $consecutiveFailedTextRetrievals = 0;
  475. if ( $model === null && $wgContentHandlerUseDB ) {
  476. $row = $this->db->selectRow(
  477. 'revision',
  478. [ 'rev_content_model', 'rev_content_format' ],
  479. [ 'rev_id' => $this->thisRev ],
  480. __METHOD__
  481. );
  482. if ( $row ) {
  483. $model = $row->rev_content_model;
  484. $format = $row->rev_content_format;
  485. }
  486. }
  487. if ( $model === null || $model === '' ) {
  488. $model = false;
  489. }
  490. while ( $failures < $this->maxFailures ) {
  491. // As soon as we found a good text for the $id, we will return immediately.
  492. // Hence, if we make it past the try catch block, we know that we did not
  493. // find a good text.
  494. try {
  495. // Step 1: Get some text (or reuse from previous iteratuon if checking
  496. // for plausibility failed)
  497. // Trying to get prefetch, if it has not been tried before
  498. if ( $text === false && isset( $this->prefetch ) && $prefetchNotTried ) {
  499. $prefetchNotTried = false;
  500. $tryIsPrefetch = true;
  501. $text = $this->prefetch->prefetch( intval( $this->thisPage ),
  502. intval( $this->thisRev ) );
  503. if ( $text === null ) {
  504. $text = false;
  505. }
  506. if ( is_string( $text ) && $model !== false ) {
  507. // Apply export transformation to text coming from an old dump.
  508. // The purpose of this transformation is to convert up from legacy
  509. // formats, which may still be used in the older dump that is used
  510. // for pre-fetching. Applying the transformation again should not
  511. // interfere with content that is already in the correct form.
  512. $text = $this->exportTransform( $text, $model, $format );
  513. }
  514. }
  515. if ( $text === false ) {
  516. // Fallback to asking the database
  517. $tryIsPrefetch = false;
  518. if ( $this->spawn ) {
  519. $text = $this->getTextSpawned( $id );
  520. } else {
  521. $text = $this->getTextDb( $id );
  522. }
  523. if ( $text !== false && $model !== false ) {
  524. // Apply export transformation to text coming from the database.
  525. // Prefetched text should already have transformations applied.
  526. $text = $this->exportTransform( $text, $model, $format );
  527. }
  528. // No more checks for texts from DB for now.
  529. // If we received something that is not false,
  530. // We treat it as good text, regardless of whether it actually is or is not
  531. if ( $text !== false ) {
  532. return $text;
  533. }
  534. }
  535. if ( $text === false ) {
  536. throw new MWException( "Generic error while obtaining text for id " . $id );
  537. }
  538. // We received a good candidate for the text of $id via some method
  539. // Step 2: Checking for plausibility and return the text if it is
  540. // plausible
  541. $revID = intval( $this->thisRev );
  542. if ( !isset( $this->db ) ) {
  543. throw new MWException( "No database available" );
  544. }
  545. if ( $model !== CONTENT_MODEL_WIKITEXT ) {
  546. $revLength = strlen( $text );
  547. } else {
  548. $revLength = $this->db->selectField( 'revision', 'rev_len', [ 'rev_id' => $revID ] );
  549. }
  550. if ( strlen( $text ) == $revLength ) {
  551. if ( $tryIsPrefetch ) {
  552. $this->prefetchCount++;
  553. }
  554. return $text;
  555. }
  556. $text = false;
  557. throw new MWException( "Received text is unplausible for id " . $id );
  558. } catch ( Exception $e ) {
  559. $msg = "getting/checking text " . $id . " failed (" . $e->getMessage() . ")";
  560. if ( $failures + 1 < $this->maxFailures ) {
  561. $msg .= " (Will retry " . ( $this->maxFailures - $failures - 1 ) . " more times)";
  562. }
  563. $this->progress( $msg );
  564. }
  565. // Something went wrong; we did not a text that was plausible :(
  566. $failures++;
  567. // A failure in a prefetch hit does not warrant resetting db connection etc.
  568. if ( !$tryIsPrefetch ) {
  569. // After backing off for some time, we try to reboot the whole process as
  570. // much as possible to not carry over failures from one part to the other
  571. // parts
  572. sleep( $this->failureTimeout );
  573. try {
  574. $this->rotateDb();
  575. if ( $this->spawn ) {
  576. $this->closeSpawn();
  577. $this->openSpawn();
  578. }
  579. } catch ( Exception $e ) {
  580. $this->progress( "Rebooting getText infrastructure failed (" . $e->getMessage() . ")" .
  581. " Trying to continue anyways" );
  582. }
  583. }
  584. }
  585. // Retirieving a good text for $id failed (at least) maxFailures times.
  586. // We abort for this $id.
  587. // Restoring the consecutive failures, and maybe aborting, if the dump
  588. // is too broken.
  589. $consecutiveFailedTextRetrievals = $oldConsecutiveFailedTextRetrievals + 1;
  590. if ( $consecutiveFailedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals ) {
  591. throw new MWException( "Graceful storage failure" );
  592. }
  593. return "";
  594. }
  595. /**
  596. * May throw a database error if, say, the server dies during query.
  597. * @param int $id
  598. * @return bool|string
  599. * @throws MWException
  600. */
  601. private function getTextDb( $id ) {
  602. global $wgContLang;
  603. if ( !isset( $this->db ) ) {
  604. throw new MWException( __METHOD__ . "No database available" );
  605. }
  606. $row = $this->db->selectRow( 'text',
  607. [ 'old_text', 'old_flags' ],
  608. [ 'old_id' => $id ],
  609. __METHOD__ );
  610. $text = Revision::getRevisionText( $row );
  611. if ( $text === false ) {
  612. return false;
  613. }
  614. $stripped = str_replace( "\r", "", $text );
  615. $normalized = $wgContLang->normalize( $stripped );
  616. return $normalized;
  617. }
  618. private function getTextSpawned( $id ) {
  619. MediaWiki\suppressWarnings();
  620. if ( !$this->spawnProc ) {
  621. // First time?
  622. $this->openSpawn();
  623. }
  624. $text = $this->getTextSpawnedOnce( $id );
  625. MediaWiki\restoreWarnings();
  626. return $text;
  627. }
  628. function openSpawn() {
  629. global $IP;
  630. if ( file_exists( "$IP/../multiversion/MWScript.php" ) ) {
  631. $cmd = implode( " ",
  632. array_map( 'wfEscapeShellArg',
  633. [
  634. $this->php,
  635. "$IP/../multiversion/MWScript.php",
  636. "fetchText.php",
  637. '--wiki', wfWikiID() ] ) );
  638. } else {
  639. $cmd = implode( " ",
  640. array_map( 'wfEscapeShellArg',
  641. [
  642. $this->php,
  643. "$IP/maintenance/fetchText.php",
  644. '--wiki', wfWikiID() ] ) );
  645. }
  646. $spec = [
  647. 0 => [ "pipe", "r" ],
  648. 1 => [ "pipe", "w" ],
  649. 2 => [ "file", "/dev/null", "a" ] ];
  650. $pipes = [];
  651. $this->progress( "Spawning database subprocess: $cmd" );
  652. $this->spawnProc = proc_open( $cmd, $spec, $pipes );
  653. if ( !$this->spawnProc ) {
  654. $this->progress( "Subprocess spawn failed." );
  655. return false;
  656. }
  657. list(
  658. $this->spawnWrite, // -> stdin
  659. $this->spawnRead, // <- stdout
  660. ) = $pipes;
  661. return true;
  662. }
  663. private function closeSpawn() {
  664. MediaWiki\suppressWarnings();
  665. if ( $this->spawnRead ) {
  666. fclose( $this->spawnRead );
  667. }
  668. $this->spawnRead = false;
  669. if ( $this->spawnWrite ) {
  670. fclose( $this->spawnWrite );
  671. }
  672. $this->spawnWrite = false;
  673. if ( $this->spawnErr ) {
  674. fclose( $this->spawnErr );
  675. }
  676. $this->spawnErr = false;
  677. if ( $this->spawnProc ) {
  678. pclose( $this->spawnProc );
  679. }
  680. $this->spawnProc = false;
  681. MediaWiki\restoreWarnings();
  682. }
  683. private function getTextSpawnedOnce( $id ) {
  684. global $wgContLang;
  685. $ok = fwrite( $this->spawnWrite, "$id\n" );
  686. // $this->progress( ">> $id" );
  687. if ( !$ok ) {
  688. return false;
  689. }
  690. $ok = fflush( $this->spawnWrite );
  691. // $this->progress( ">> [flush]" );
  692. if ( !$ok ) {
  693. return false;
  694. }
  695. // check that the text id they are sending is the one we asked for
  696. // this avoids out of sync revision text errors we have encountered in the past
  697. $newId = fgets( $this->spawnRead );
  698. if ( $newId === false ) {
  699. return false;
  700. }
  701. if ( $id != intval( $newId ) ) {
  702. return false;
  703. }
  704. $len = fgets( $this->spawnRead );
  705. // $this->progress( "<< " . trim( $len ) );
  706. if ( $len === false ) {
  707. return false;
  708. }
  709. $nbytes = intval( $len );
  710. // actual error, not zero-length text
  711. if ( $nbytes < 0 ) {
  712. return false;
  713. }
  714. $text = "";
  715. // Subprocess may not send everything at once, we have to loop.
  716. while ( $nbytes > strlen( $text ) ) {
  717. $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
  718. if ( $buffer === false ) {
  719. break;
  720. }
  721. $text .= $buffer;
  722. }
  723. $gotbytes = strlen( $text );
  724. if ( $gotbytes != $nbytes ) {
  725. $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
  726. return false;
  727. }
  728. // Do normalization in the dump thread...
  729. $stripped = str_replace( "\r", "", $text );
  730. $normalized = $wgContLang->normalize( $stripped );
  731. return $normalized;
  732. }
  733. function startElement( $parser, $name, $attribs ) {
  734. $this->checkpointJustWritten = false;
  735. $this->clearOpenElement( null );
  736. $this->lastName = $name;
  737. if ( $name == 'revision' ) {
  738. $this->state = $name;
  739. $this->egress->writeOpenPage( null, $this->buffer );
  740. $this->buffer = "";
  741. } elseif ( $name == 'page' ) {
  742. $this->state = $name;
  743. if ( $this->atStart ) {
  744. $this->egress->writeOpenStream( $this->buffer );
  745. $this->buffer = "";
  746. $this->atStart = false;
  747. }
  748. }
  749. if ( $name == "text" && isset( $attribs['id'] ) ) {
  750. $id = $attribs['id'];
  751. $model = trim( $this->thisRevModel );
  752. $format = trim( $this->thisRevFormat );
  753. $model = $model === '' ? null : $model;
  754. $format = $format === '' ? null : $format;
  755. $text = $this->getText( $id, $model, $format );
  756. $this->openElement = [ $name, [ 'xml:space' => 'preserve' ] ];
  757. if ( strlen( $text ) > 0 ) {
  758. $this->characterData( $parser, $text );
  759. }
  760. } else {
  761. $this->openElement = [ $name, $attribs ];
  762. }
  763. }
  764. function endElement( $parser, $name ) {
  765. $this->checkpointJustWritten = false;
  766. if ( $this->openElement ) {
  767. $this->clearOpenElement( "" );
  768. } else {
  769. $this->buffer .= "</$name>";
  770. }
  771. if ( $name == 'revision' ) {
  772. $this->egress->writeRevision( null, $this->buffer );
  773. $this->buffer = "";
  774. $this->thisRev = "";
  775. $this->thisRevModel = null;
  776. $this->thisRevFormat = null;
  777. } elseif ( $name == 'page' ) {
  778. if ( !$this->firstPageWritten ) {
  779. $this->firstPageWritten = trim( $this->thisPage );
  780. }
  781. $this->lastPageWritten = trim( $this->thisPage );
  782. if ( $this->timeExceeded ) {
  783. $this->egress->writeClosePage( $this->buffer );
  784. // nasty hack, we can't just write the chardata after the
  785. // page tag, it will include leading blanks from the next line
  786. $this->egress->sink->write( "\n" );
  787. $this->buffer = $this->xmlwriterobj->closeStream();
  788. $this->egress->writeCloseStream( $this->buffer );
  789. $this->buffer = "";
  790. $this->thisPage = "";
  791. // this could be more than one file if we had more than one output arg
  792. $filenameList = (array)$this->egress->getFilenames();
  793. $newFilenames = [];
  794. $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
  795. $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
  796. $filenamesCount = count( $filenameList );
  797. for ( $i = 0; $i < $filenamesCount; $i++ ) {
  798. $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
  799. $fileinfo = pathinfo( $filenameList[$i] );
  800. $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
  801. }
  802. $this->egress->closeRenameAndReopen( $newFilenames );
  803. $this->buffer = $this->xmlwriterobj->openStream();
  804. $this->timeExceeded = false;
  805. $this->timeOfCheckpoint = $this->lastTime;
  806. $this->firstPageWritten = false;
  807. $this->checkpointJustWritten = true;
  808. } else {
  809. $this->egress->writeClosePage( $this->buffer );
  810. $this->buffer = "";
  811. $this->thisPage = "";
  812. }
  813. } elseif ( $name == 'mediawiki' ) {
  814. $this->egress->writeCloseStream( $this->buffer );
  815. $this->buffer = "";
  816. }
  817. }
  818. function characterData( $parser, $data ) {
  819. $this->clearOpenElement( null );
  820. if ( $this->lastName == "id" ) {
  821. if ( $this->state == "revision" ) {
  822. $this->thisRev .= $data;
  823. } elseif ( $this->state == "page" ) {
  824. $this->thisPage .= $data;
  825. }
  826. } elseif ( $this->lastName == "model" ) {
  827. $this->thisRevModel .= $data;
  828. } elseif ( $this->lastName == "format" ) {
  829. $this->thisRevFormat .= $data;
  830. }
  831. // have to skip the newline left over from closepagetag line of
  832. // end of checkpoint files. nasty hack!!
  833. if ( $this->checkpointJustWritten ) {
  834. if ( $data[0] == "\n" ) {
  835. $data = substr( $data, 1 );
  836. }
  837. $this->checkpointJustWritten = false;
  838. }
  839. $this->buffer .= htmlspecialchars( $data );
  840. }
  841. function clearOpenElement( $style ) {
  842. if ( $this->openElement ) {
  843. $this->buffer .= Xml::element( $this->openElement[0], $this->openElement[1], $style );
  844. $this->openElement = false;
  845. }
  846. }
  847. }
  848. $maintClass = 'TextPassDumper';
  849. require_once RUN_MAINTENANCE_IF_MAIN;