PageRenderTime 56ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/host-tools/offline-renderer/mediawiki-offline/maintenance/dumpTextPass.php

https://github.com/sunnysujan/wikireader
PHP | 525 lines | 399 code | 68 blank | 58 comment | 62 complexity | 2bc46ae4441b724bd7ab12451dde849d MD5 | raw file
  1. <?php
  2. /**
  3. * Copyright (C) 2005 Brion Vibber <brion@pobox.com>
  4. * http://www.mediawiki.org/
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 2 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License along
  17. * with this program; if not, write to the Free Software Foundation, Inc.,
  18. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  19. * http://www.gnu.org/copyleft/gpl.html
  20. *
  21. * @file
  22. * @ingroup Maintenance
  23. */
  24. $originalDir = getcwd();
  25. require_once( 'commandLine.inc' );
  26. require_once( 'backup.inc' );
  27. /**
  28. * Stream wrapper around 7za filter program.
  29. * Required since we can't pass an open file resource to XMLReader->open()
  30. * which is used for the text prefetch.
  31. *
  32. * @ingroup Maintenance
  33. */
  34. class SevenZipStream {
  35. var $stream;
  36. private function stripPath( $path ) {
  37. $prefix = 'mediawiki.compress.7z://';
  38. return substr( $path, strlen( $prefix ) );
  39. }
  40. function stream_open( $path, $mode, $options, &$opened_path ) {
  41. if( $mode{0} == 'r' ) {
  42. $options = 'e -bd -so';
  43. } elseif( $mode{0} == 'w' ) {
  44. $options = 'a -bd -si';
  45. } else {
  46. return false;
  47. }
  48. $arg = wfEscapeShellArg( $this->stripPath( $path ) );
  49. $command = "7za $options $arg";
  50. if( !wfIsWindows() ) {
  51. // Suppress the stupid messages on stderr
  52. $command .= ' 2>/dev/null';
  53. }
  54. $this->stream = popen( $command, $mode );
  55. return ($this->stream !== false);
  56. }
  57. function url_stat( $path, $flags ) {
  58. return stat( $this->stripPath( $path ) );
  59. }
  60. // This is all so lame; there should be a default class we can extend
  61. function stream_close() {
  62. return fclose( $this->stream );
  63. }
  64. function stream_flush() {
  65. return fflush( $this->stream );
  66. }
  67. function stream_read( $count ) {
  68. return fread( $this->stream, $count );
  69. }
  70. function stream_write( $data ) {
  71. return fwrite( $this->stream, $data );
  72. }
  73. function stream_tell() {
  74. return ftell( $this->stream );
  75. }
  76. function stream_eof() {
  77. return feof( $this->stream );
  78. }
  79. function stream_seek( $offset, $whence ) {
  80. return fseek( $this->stream, $offset, $whence );
  81. }
  82. }
  83. stream_wrapper_register( 'mediawiki.compress.7z', 'SevenZipStream' );
  84. /**
  85. * @ingroup Maintenance
  86. */
  87. class TextPassDumper extends BackupDumper {
  88. var $prefetch = null;
  89. var $input = "php://stdin";
  90. var $history = WikiExporter::FULL;
  91. var $fetchCount = 0;
  92. var $prefetchCount = 0;
  93. var $failures = 0;
  94. var $maxFailures = 200;
  95. var $failureTimeout = 5; // Seconds to sleep after db failure
  96. var $php = "php";
  97. var $spawn = false;
  98. var $spawnProc = false;
  99. var $spawnWrite = false;
  100. var $spawnRead = false;
  101. var $spawnErr = false;
  102. function dump() {
  103. # This shouldn't happen if on console... ;)
  104. header( 'Content-type: text/html; charset=UTF-8' );
  105. # Notice messages will foul up your XML output even if they're
  106. # relatively harmless.
  107. if( ini_get( 'display_errors' ) )
  108. ini_set( 'display_errors', 'stderr' );
  109. $this->initProgress( $this->history );
  110. $this->db = $this->backupDb();
  111. $this->egress = new ExportProgressFilter( $this->sink, $this );
  112. $input = fopen( $this->input, "rt" );
  113. $result = $this->readDump( $input );
  114. if( WikiError::isError( $result ) ) {
  115. wfDie( $result->getMessage() );
  116. }
  117. if( $this->spawnProc ) {
  118. $this->closeSpawn();
  119. }
  120. $this->report( true );
  121. }
  122. function processOption( $opt, $val, $param ) {
  123. $url = $this->processFileOpt( $val, $param );
  124. switch( $opt ) {
  125. case 'prefetch':
  126. global $IP;
  127. require_once "$IP/maintenance/backupPrefetch.inc";
  128. $this->prefetch = new BaseDump( $url );
  129. break;
  130. case 'stub':
  131. $this->input = $url;
  132. break;
  133. case 'current':
  134. $this->history = WikiExporter::CURRENT;
  135. break;
  136. case 'full':
  137. $this->history = WikiExporter::FULL;
  138. break;
  139. case 'spawn':
  140. $this->spawn = true;
  141. if( $val ) {
  142. $this->php = $val;
  143. }
  144. break;
  145. }
  146. }
  147. function processFileOpt( $val, $param ) {
  148. switch( $val ) {
  149. case "file":
  150. return $param;
  151. case "gzip":
  152. return "compress.zlib://$param";
  153. case "bzip2":
  154. return "compress.bzip2://$param";
  155. case "7zip":
  156. return "mediawiki.compress.7z://$param";
  157. default:
  158. return $val;
  159. }
  160. }
  161. /**
  162. * Overridden to include prefetch ratio if enabled.
  163. */
  164. function showReport() {
  165. if( !$this->prefetch ) {
  166. return parent::showReport();
  167. }
  168. if( $this->reporting ) {
  169. $delta = wfTime() - $this->startTime;
  170. $now = wfTimestamp( TS_DB );
  171. if( $delta ) {
  172. $rate = $this->pageCount / $delta;
  173. $revrate = $this->revCount / $delta;
  174. $portion = $this->revCount / $this->maxCount;
  175. $eta = $this->startTime + $delta / $portion;
  176. $etats = wfTimestamp( TS_DB, intval( $eta ) );
  177. $fetchrate = 100.0 * $this->prefetchCount / $this->fetchCount;
  178. } else {
  179. $rate = '-';
  180. $revrate = '-';
  181. $etats = '-';
  182. $fetchrate = '-';
  183. }
  184. $this->progress( sprintf( "%s: %s %d pages (%0.3f/sec), %d revs (%0.3f/sec), %0.1f%% prefetched, ETA %s [max %d]",
  185. $now, wfWikiID(), $this->pageCount, $rate, $this->revCount, $revrate, $fetchrate, $etats, $this->maxCount ) );
  186. }
  187. }
  188. function readDump( $input ) {
  189. $this->buffer = "";
  190. $this->openElement = false;
  191. $this->atStart = true;
  192. $this->state = "";
  193. $this->lastName = "";
  194. $this->thisPage = 0;
  195. $this->thisRev = 0;
  196. $parser = xml_parser_create( "UTF-8" );
  197. xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
  198. xml_set_element_handler( $parser, array( &$this, 'startElement' ), array( &$this, 'endElement' ) );
  199. xml_set_character_data_handler( $parser, array( &$this, 'characterData' ) );
  200. $offset = 0; // for context extraction on error reporting
  201. $bufferSize = 512 * 1024;
  202. do {
  203. $chunk = fread( $input, $bufferSize );
  204. if( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
  205. wfDebug( "TextDumpPass::readDump encountered XML parsing error\n" );
  206. return new WikiXmlError( $parser, 'XML import parse failure', $chunk, $offset );
  207. }
  208. $offset += strlen( $chunk );
  209. } while( $chunk !== false && !feof( $input ) );
  210. xml_parser_free( $parser );
  211. return true;
  212. }
  213. function getText( $id ) {
  214. $this->fetchCount++;
  215. if( isset( $this->prefetch ) ) {
  216. $text = $this->prefetch->prefetch( $this->thisPage, $this->thisRev );
  217. if( $text === null ) {
  218. // Entry missing from prefetch dump
  219. } elseif( $text === "" ) {
  220. // Blank entries may indicate that the prior dump was broken.
  221. // To be safe, reload it.
  222. } else {
  223. $this->prefetchCount++;
  224. return $text;
  225. }
  226. }
  227. return $this->doGetText( $id );
  228. }
  229. private function doGetText( $id ) {
  230. if( $this->spawn ) {
  231. return $this->getTextSpawned( $id );
  232. } else {
  233. return $this->getTextDbSafe( $id );
  234. }
  235. }
  236. /**
  237. * Fetch a text revision from the database, retrying in case of failure.
  238. * This may survive some transitory errors by reconnecting, but
  239. * may not survive a long-term server outage.
  240. */
  241. private function getTextDbSafe( $id ) {
  242. while( true ) {
  243. try {
  244. $text = $this->getTextDb( $id );
  245. $ex = new MWException("Graceful storage failure");
  246. } catch (DBQueryError $ex) {
  247. $text = false;
  248. }
  249. if( $text === false ) {
  250. $this->failures++;
  251. if( $this->failures > $this->maxFailures ) {
  252. throw $ex;
  253. } else {
  254. $this->progress( "Database failure $this->failures " .
  255. "of allowed $this->maxFailures for revision $id! " .
  256. "Pausing $this->failureTimeout seconds..." );
  257. sleep( $this->failureTimeout );
  258. }
  259. } else {
  260. return $text;
  261. }
  262. }
  263. }
  264. /**
  265. * May throw a database error if, say, the server dies during query.
  266. */
  267. private function getTextDb( $id ) {
  268. $id = intval( $id );
  269. $row = $this->db->selectRow( 'text',
  270. array( 'old_text', 'old_flags' ),
  271. array( 'old_id' => $id ),
  272. 'TextPassDumper::getText' );
  273. $text = Revision::getRevisionText( $row );
  274. if( $text === false ) {
  275. return false;
  276. }
  277. $stripped = str_replace( "\r", "", $text );
  278. $normalized = UtfNormal::cleanUp( $stripped );
  279. return $normalized;
  280. }
  281. private function getTextSpawned( $id ) {
  282. wfSuppressWarnings();
  283. if( !$this->spawnProc ) {
  284. // First time?
  285. $this->openSpawn();
  286. }
  287. while( true ) {
  288. $text = $this->getTextSpawnedOnce( $id );
  289. if( !is_string( $text ) ) {
  290. $this->progress("Database subprocess failed. Respawning...");
  291. $this->closeSpawn();
  292. sleep( $this->failureTimeout );
  293. $this->openSpawn();
  294. continue;
  295. }
  296. wfRestoreWarnings();
  297. return $text;
  298. }
  299. }
  300. function openSpawn() {
  301. global $IP, $wgDBname;
  302. $cmd = implode( " ",
  303. array_map( 'wfEscapeShellArg',
  304. array(
  305. $this->php,
  306. "$IP/maintenance/fetchText.php",
  307. $wgDBname ) ) );
  308. $spec = array(
  309. 0 => array( "pipe", "r" ),
  310. 1 => array( "pipe", "w" ),
  311. 2 => array( "file", "/dev/null", "a" ) );
  312. $pipes = array();
  313. $this->progress( "Spawning database subprocess: $cmd" );
  314. $this->spawnProc = proc_open( $cmd, $spec, $pipes );
  315. if( !$this->spawnProc ) {
  316. // shit
  317. $this->progress( "Subprocess spawn failed." );
  318. return false;
  319. }
  320. list(
  321. $this->spawnWrite, // -> stdin
  322. $this->spawnRead, // <- stdout
  323. ) = $pipes;
  324. return true;
  325. }
  326. private function closeSpawn() {
  327. wfSuppressWarnings();
  328. if( $this->spawnRead )
  329. fclose( $this->spawnRead );
  330. $this->spawnRead = false;
  331. if( $this->spawnWrite )
  332. fclose( $this->spawnWrite );
  333. $this->spawnWrite = false;
  334. if( $this->spawnErr )
  335. fclose( $this->spawnErr );
  336. $this->spawnErr = false;
  337. if( $this->spawnProc )
  338. pclose( $this->spawnProc );
  339. $this->spawnProc = false;
  340. wfRestoreWarnings();
  341. }
  342. private function getTextSpawnedOnce( $id ) {
  343. $ok = fwrite( $this->spawnWrite, "$id\n" );
  344. //$this->progress( ">> $id" );
  345. if( !$ok ) return false;
  346. $ok = fflush( $this->spawnWrite );
  347. //$this->progress( ">> [flush]" );
  348. if( !$ok ) return false;
  349. $len = fgets( $this->spawnRead );
  350. //$this->progress( "<< " . trim( $len ) );
  351. if( $len === false ) return false;
  352. $nbytes = intval( $len );
  353. $text = "";
  354. // Subprocess may not send everything at once, we have to loop.
  355. while( $nbytes > strlen( $text ) ) {
  356. $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
  357. if( $text === false ) break;
  358. $text .= $buffer;
  359. }
  360. $gotbytes = strlen( $text );
  361. if( $gotbytes != $nbytes ) {
  362. $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes ");
  363. return false;
  364. }
  365. // Do normalization in the dump thread...
  366. $stripped = str_replace( "\r", "", $text );
  367. $normalized = UtfNormal::cleanUp( $stripped );
  368. return $normalized;
  369. }
  370. function startElement( $parser, $name, $attribs ) {
  371. $this->clearOpenElement( null );
  372. $this->lastName = $name;
  373. if( $name == 'revision' ) {
  374. $this->state = $name;
  375. $this->egress->writeOpenPage( null, $this->buffer );
  376. $this->buffer = "";
  377. } elseif( $name == 'page' ) {
  378. $this->state = $name;
  379. if( $this->atStart ) {
  380. $this->egress->writeOpenStream( $this->buffer );
  381. $this->buffer = "";
  382. $this->atStart = false;
  383. }
  384. }
  385. if( $name == "text" && isset( $attribs['id'] ) ) {
  386. $text = $this->getText( $attribs['id'] );
  387. $this->openElement = array( $name, array( 'xml:space' => 'preserve' ) );
  388. if( strlen( $text ) > 0 ) {
  389. $this->characterData( $parser, $text );
  390. }
  391. } else {
  392. $this->openElement = array( $name, $attribs );
  393. }
  394. }
  395. function endElement( $parser, $name ) {
  396. if( $this->openElement ) {
  397. $this->clearOpenElement( "" );
  398. } else {
  399. $this->buffer .= "</$name>";
  400. }
  401. if( $name == 'revision' ) {
  402. $this->egress->writeRevision( null, $this->buffer );
  403. $this->buffer = "";
  404. $this->thisRev = "";
  405. } elseif( $name == 'page' ) {
  406. $this->egress->writeClosePage( $this->buffer );
  407. $this->buffer = "";
  408. $this->thisPage = "";
  409. } elseif( $name == 'mediawiki' ) {
  410. $this->egress->writeCloseStream( $this->buffer );
  411. $this->buffer = "";
  412. }
  413. }
  414. function characterData( $parser, $data ) {
  415. $this->clearOpenElement( null );
  416. if( $this->lastName == "id" ) {
  417. if( $this->state == "revision" ) {
  418. $this->thisRev .= $data;
  419. } elseif( $this->state == "page" ) {
  420. $this->thisPage .= $data;
  421. }
  422. }
  423. $this->buffer .= htmlspecialchars( $data );
  424. }
  425. function clearOpenElement( $style ) {
  426. if( $this->openElement ) {
  427. $this->buffer .= Xml::element( $this->openElement[0], $this->openElement[1], $style );
  428. $this->openElement = false;
  429. }
  430. }
  431. }
  432. $dumper = new TextPassDumper( $argv );
  433. if( true ) {
  434. $dumper->dump();
  435. } else {
  436. $dumper->progress( <<<ENDS
  437. This script postprocesses XML dumps from dumpBackup.php to add
  438. page text which was stubbed out (using --stub).
  439. XML input is accepted on stdin.
  440. XML output is sent to stdout; progress reports are sent to stderr.
  441. Usage: php dumpTextPass.php [<options>]
  442. Options:
  443. --stub=<type>:<file> To load a compressed stub dump instead of stdin
  444. --prefetch=<type>:<file> Use a prior dump file as a text source, to save
  445. pressure on the database.
  446. (Requires PHP 5.0+ and the XMLReader PECL extension)
  447. --quiet Don't dump status reports to stderr.
  448. --report=n Report position and speed after every n pages processed.
  449. (Default: 100)
  450. --server=h Force reading from MySQL server h
  451. --current Base ETA on number of pages in database instead of all revisions
  452. --spawn Spawn a subprocess for loading text records
  453. ENDS
  454. );
  455. }