Apply patch from Karsten Düsterloh in Bug #28103.
[lhc/web/wiklou.git] / maintenance / importUseModWikipedia.php
1 <?php
2
3 /**
4 * A script to read a dump of the English Wikipedia from the UseModWiki period, and to
5 * generate an XML dump in MediaWiki format.
6 *
7 * Some relevant code was ported from UseModWiki 0.92.
8 *
9 */
10
11 require_once( dirname( __FILE__ ) . '/Maintenance.php' );
12 require_once( dirname( __FILE__ ) .'/../includes/normal/UtfNormalUtil.php' );
13
14
15 class ImportUseModWikipedia extends Maintenance {
16 var $encodeMap, $decodeMap;
17
18 var $deepRenames = array(
19 'JimboWales' => 983862286,
20 'TexaS' => 983918410,
21 'HistoryOfUnitedStatesTalk' => 984795423,
22 'MetallicA' => 985128533,
23 'PythagoreanTheorem' => 985225545,
24 'TheCanonofScripture' => 985368223,
25 'TaoTehChing' => 985368222,
26 //'TheMostRemarkableFormulaInTheWorld' => 985368221,
27 'TheRecorder' => 985368220,
28 'GladstoneOregon' => 985368219,
29 'PacificBeach' => '?',
30 'AaRiver' => '?',
31 );
32
33 var $replacements = array();
34
35 var $renameTextLinksOps = array(
36 983846265 => array(
37 'TestIgnore' => 'IgnoreTest',
38 ),
39 983848080 => array(
40 'UnitedLocomotiveWorks' => 'Atlas Shrugged/United Locomotive Works'
41 ),
42 983856376 => array(
43 'WikiPedia' => 'Wikipedia',
44 ),
45 983896152 => array(
46 'John_F_Kennedy' => 'John_F._Kennedy',
47 ),
48 983905871 => array(
49 'LarrySanger' => 'Larry_Sanger'
50 ),
51 984697068 => array(
52 'UnitedStates' => 'United States',
53 ),
54 984792748 => array(
55 'LibertarianisM' => 'Libertarianism'
56 ),
57 985327832 => array(
58 'AnarchisM' => 'Anarchism',
59 ),
60 985290063 => array(
61 'HistoryOfUnitedStatesDiscussion' => 'History_Of_United_States_Discussion'
62 ),
63 985290091 => array(
64 'BritishEmpire' => 'British Empire'
65 ),
66 /*
67 985468958 => array(
68 'ScienceFiction' => 'Science fiction',
69 ),*/
70 );
71
72 /**
73 * Hack for observed substitution issues
74 */
75 var $skipSelfSubstitution = array(
76 'Pythagorean_Theorem',
77 'The_Most_Remarkable_Formula_In_The_World',
78 'Wine',
79 );
80
81 var $unixLineEndingsOps = array(
82 987743732 => 'Wikipedia_FAQ'
83 );
84
85 var $replacementsDone = array();
86
87 var $moveLog = array();
88 var $moveDests = array();
89 var $revId;
90
91 var $rc = array();
92 var $textCache = array();
93 var $blacklist = array();
94
95 var $FS, $FS1, $FS2, $FS3;
96 var $FreeLinkPattern, $UrlPattern, $LinkPattern, $InterLinkPattern;
97
98 var $cp1252Table = array(
99 0x80 => 0x20ac,
100 0x81 => 0x0081,
101 0x82 => 0x201a,
102 0x83 => 0x0192,
103 0x84 => 0x201e,
104 0x85 => 0x2026,
105 0x86 => 0x2020,
106 0x87 => 0x2021,
107 0x88 => 0x02c6,
108 0x89 => 0x2030,
109 0x8a => 0x0160,
110 0x8b => 0x2039,
111 0x8c => 0x0152,
112 0x8d => 0x008d,
113 0x8e => 0x017d,
114 0x8f => 0x008f,
115 0x90 => 0x0090,
116 0x91 => 0x2018,
117 0x92 => 0x2019,
118 0x93 => 0x201c,
119 0x94 => 0x201d,
120 0x95 => 0x2022,
121 0x96 => 0x2013,
122 0x97 => 0x2014,
123 0x98 => 0x02dc,
124 0x99 => 0x2122,
125 0x9a => 0x0161,
126 0x9b => 0x203a,
127 0x9c => 0x0153,
128 0x9d => 0x009d,
129 0x9e => 0x017e,
130 0x9f => 0x0178);
131
132 public function __construct() {
133 parent::__construct();
134 $this->addOption( 'datadir', 'the value of $DataDir from wiki.cgi', true, true );
135 $this->addOption( 'outfile', 'the name of the output XML file', true, true );
136 $this->initLinkPatterns();
137
138 $this->encodeMap = $this->decodeMap = array();
139
140 for ($source = 0; $source <= 0xff; $source++) {
141 if ( isset( $this->cp1252Table[$source] ) ) {
142 $dest = $this->cp1252Table[$source];
143 } else {
144 $dest = $source;
145 }
146 $sourceChar = chr( $source );
147 $destChar = codepointToUtf8( $dest );
148 $this->encodeMap[$sourceChar] = $destChar;
149 $this->decodeMap[$destChar] = $sourceChar;
150 }
151 }
152
153 function initLinkPatterns() {
154 # Field separators are used in the URL-style patterns below.
155 $this->FS = "\xb3"; # The FS character is a superscript "3"
156 $this->FS1 = $this->FS . "1"; # The FS values are used to separate fields
157 $this->FS2 = $this->FS . "2"; # in stored hashtables and other data structures.
158 $this->FS3 = $this->FS . "3"; # The FS character is not allowed in user data.
159
160 $UpperLetter = "[A-Z";
161 $LowerLetter = "[a-z";
162 $AnyLetter = "[A-Za-z";
163 $AnyLetter .= "_0-9";
164 $UpperLetter .= "]"; $LowerLetter .= "]"; $AnyLetter .= "]";
165
166 # Main link pattern: lowercase between uppercase, then anything
167 $LpA = $UpperLetter . "+" . $LowerLetter . "+" . $UpperLetter
168 . $AnyLetter . "*";
169 # Optional subpage link pattern: uppercase, lowercase, then anything
170 $LpB = $UpperLetter . "+" . $LowerLetter . "+" . $AnyLetter . "*";
171
172 # Loose pattern: If subpage is used, subpage may be simple name
173 $this->LinkPattern = "((?:(?:$LpA)?\\/$LpB)|$LpA)";
174 $QDelim = '(?:"")?'; # Optional quote delimiter (not in output)
175 $this->LinkPattern .= $QDelim;
176
177 # Inter-site convention: sites must start with uppercase letter
178 # (Uppercase letter avoids confusion with URLs)
179 $InterSitePattern = $UpperLetter . $AnyLetter . "+";
180 $this->InterLinkPattern = "((?:$InterSitePattern:[^\\]\\s\"<>{$this->FS}]+)$QDelim)";
181
182 $AnyLetter = "[-,. _0-9A-Za-z]";
183 $this->FreeLinkPattern = "($AnyLetter+)";
184 $this->FreeLinkPattern = "((?:(?:$AnyLetter+)?\\/)?$AnyLetter+)";
185 $this->FreeLinkPattern .= $QDelim;
186
187 # Url-style links are delimited by one of:
188 # 1. Whitespace (kept in output)
189 # 2. Left or right angle-bracket (< or >) (kept in output)
190 # 3. Right square-bracket (]) (kept in output)
191 # 4. A single double-quote (") (kept in output)
192 # 5. A $FS (field separator) character (kept in output)
193 # 6. A double double-quote ("") (removed from output)
194
195 $UrlProtocols = "http|https|ftp|afs|news|nntp|mid|cid|mailto|wais|"
196 . "prospero|telnet|gopher";
197 $UrlProtocols .= '|file';
198 $this->UrlPattern = "((?:(?:$UrlProtocols):[^\\]\\s\"<>{$this->FS}]+)$QDelim)";
199 $ImageExtensions = "(gif|jpg|png|bmp|jpeg)";
200 $RFCPattern = "RFC\\s?(\\d+)";
201 $ISBNPattern = "ISBN:?([0-9- xX]{10,})";
202 }
203
204 function execute() {
205 $this->articleFileName = '/tmp/importUseMod.' . mt_rand( 0, 0x7ffffff ) . '.tmp';
206 $this->patchFileName = '/tmp/importUseMod.' . mt_rand( 0, 0x7ffffff ) . '.tmp';
207 $this->dataDir = $this->getOption( 'datadir' );
208 $this->outFile = fopen( $this->getOption( 'outfile' ), 'w' );
209 if ( !$this->outFile ) {
210 echo "Unable to open output file\n";
211 return 1;
212 }
213 $this->writeXmlHeader();
214 $this->readRclog();
215 $this->writeMoveLog();
216 $this->writeRevisions();
217 $this->reconcileCurrentRevs();
218 $this->writeXmlFooter();
219 unlink( $this->articleFileName );
220 unlink( $this->patchFileName );
221 return 0;
222 }
223
224 function writeXmlHeader() {
225 fwrite( $this->outFile, <<<EOT
226 <mediawiki xmlns="http://www.mediawiki.org/xml/export-0.3/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mediawiki.org/xml/export-0.3/ http://www.mediawiki.org/xml/export-0.3.xsd" version="0.3" xml:lang="en">
227 <siteinfo>
228 <sitename>Wikipedia</sitename>
229 <base>http://www.wikipedia.com/</base>
230 <generator>MediaWiki 1.18alpha importUseModWikipedia.php</generator>
231 <case>case-sensitive</case>
232 <namespaces>
233 <namespace key="0" />
234 </namespaces>
235 </siteinfo>
236
237 EOT
238 );
239 }
240
241 function writeXmlFooter() {
242 fwrite( $this->outFile, "</mediawiki>\n" );
243 }
244
245 function readRclog() {
246 $rcFile = fopen( "{$this->dataDir}/rclog", 'r' );
247 while ( $line = fgets( $rcFile ) ) {
248 $bits = explode( $this->FS3, $line );
249 if ( count( $bits ) !== 7 ) {
250 echo "Error reading rclog\n";
251 return;
252 }
253 $params = array(
254 'timestamp' => $bits[0],
255 'rctitle' => $bits[1],
256 'summary' => $bits[2],
257 'minor' => $bits[3],
258 'host' => $bits[4],
259 'kind' => $bits[5],
260 'extra' => array()
261 );
262 $extraList = explode( $this->FS2, $bits[6] );
263
264 for ( $i = 0; $i < count( $extraList ); $i += 2 ) {
265 $params['extra'][$extraList[$i]] = $extraList[$i + 1];
266 }
267 $this->rc[$params['timestamp']][] = $params;
268 }
269 }
270
271 function writeMoveLog() {
272 $this->moveLog = array();
273 $deepRenames = $this->deepRenames;
274 echo "Calculating move log...\n";
275 $this->processDiffFile( array( $this, 'moveLogCallback' ) );
276
277 // We have the timestamp intervals, now make a guess at the actual timestamp
278 foreach ( $this->moveLog as $newTitle => $params ) {
279 // Is there a time specified?
280 $drTime = false;
281 if ( isset( $deepRenames[$params['old']] ) ) {
282 $drTime = $deepRenames[$params['old']];
283 if ( $drTime !== '?' ) {
284 if ( ( !isset( $params['endTime'] ) || $drTime < $params['endTime'] )
285 && $drTime > $params['startTime'] )
286 {
287 $this->moveLog[$newTitle]['timestamp'] = $drTime;
288 $this->moveLog[$newTitle]['deep'] = true;
289
290 echo "{$params['old']} -> $newTitle at $drTime\n";
291 unset( $deepRenames[$params['old']] );
292 continue;
293 } else {
294 echo "WARNING: deep rename time invalid: {$params['old']}\n";
295 unset( $deepRenames[$params['old']] );
296 }
297 }
298 }
299
300 // Guess that it is one second after the last edit to the page before it was moved
301 $this->moveLog[$newTitle]['timestamp'] = $params['startTime'] + 1;
302 if ( $drTime === '?' ) {
303 $this->moveLog[$newTitle]['deep'] = true;
304 unset( $deepRenames[$params['old']] );
305 }
306 if ( isset( $params['endTime'] ) ) {
307 $this->printLatin1( "{$params['old']} -> $newTitle between " .
308 "{$params['startTime']} and {$params['endTime']}\n" );
309 } else {
310 $this->printLatin1( "{$params['old']} -> $newTitle after " .
311 "{$params['startTime']}\n" );
312 }
313 }
314
315 // Write the move log to the XML file
316 $id = 1;
317 foreach ( $this->moveLog as $newTitle => $params ) {
318 $out = "<logitem>\n" .
319 $this->element( 'id', $id++ ) .
320 $this->element( 'timestamp', wfTimestamp( TS_ISO_8601, $params['timestamp'] ) ) .
321 "<contributor>\n" .
322 $this->element( 'username', 'UseModWiki admin' ) .
323 "</contributor>" .
324 $this->element( 'type', 'move' ) .
325 $this->element( 'action', 'move' ) .
326 $this->element( 'logtitle', $params['old'] ) .
327 "<params xml:space=\"preserve\">" .
328 htmlspecialchars( $this->encode( "{$newTitle}\n1" ) ) .
329 "</params>\n" .
330 "</logitem>\n";
331 fwrite( $this->outFile, $out );
332 }
333
334 // Check for remaining deep rename entries
335 if ( $deepRenames ) {
336 echo "WARNING: the following entries in \$this->deepRenames are " .
337 "invalid, since no such move exists:\n" .
338 implode( "\n", array_keys( $deepRenames ) ) .
339 "\n\n";
340 }
341
342 }
343
344 function element( $name, $value ) {
345 return "<$name>" . htmlspecialchars( $this->encode( $value ) ) . "</$name>\n";
346 }
347
348 function moveLogCallback( $entry ) {
349 $rctitle = $entry['rctitle'];
350 $title = $entry['title'];
351 $this->moveDests[$rctitle] = $title;
352
353 if ( $rctitle === $title ) {
354 if ( isset( $this->moveLog[$rctitle] )
355 && !isset( $this->moveLog[$rctitle]['endTime'] ) )
356 {
357 // This is the latest time that the page could have been moved
358 $this->moveLog[$rctitle]['endTime'] = $entry['timestamp'];
359 }
360 } else {
361 if ( !isset( $this->moveLog[$rctitle] ) ) {
362 // Initialise the move log entry
363 $this->moveLog[$rctitle] = array(
364 'old' => $title
365 );
366 }
367 // Update the earliest time the page could have been moved
368 $this->moveLog[$rctitle]['startTime'] = $entry['timestamp'];
369 }
370 }
371
372 function writeRevisions() {
373 $this->numGoodRevs = 0;
374 $this->revId = 1;
375 $this->processDiffFile( array( $this, 'revisionCallback' ) );
376 echo "\n\nImported {$this->numGoodRevs} out of {$this->numRevs}\n";
377 }
378
379 function revisionCallback( $params ) {
380 $title = $params['rctitle'];
381 $editTime = $params['timestamp'];
382
383 if ( isset( $this->blacklist[$title] ) ) {
384 return;
385 }
386 $this->doPendingOps( $editTime );
387
388 $origText = $this->getText( $title );
389 $text = $this->patch( $origText, $params['diff'] );
390 if ( $text === false ) {
391 echo "$editTime $title attempting resolution...\n";
392 $linkSubstitutes = $this->resolveFailedDiff( $origText, $params['diff'] );
393 if ( !$linkSubstitutes ) {
394 $this->printLatin1( "$editTime $title DIFF FAILED\n" );
395 $this->blacklist[$title] = true;
396 return;
397 }
398 $this->printLatin1( "$editTime $title requires substitutions:\n" );
399 $time = $editTime - 1;
400 foreach ( $linkSubstitutes as $old => $new ) {
401 $this->printLatin1( "SUBSTITUTE $old -> $new\n" );
402 $this->renameTextLinks( $old, $new, $time-- );
403 }
404 $origText = $this->getText( $title );
405 $text = $this->patch( $origText, $params['diff'] );
406 if ( $text === false ) {
407 $this->printLatin1( "$editTime $title STILL FAILS!\n" );
408 $this->blacklist[$title] = true;
409 return;
410 }
411
412 echo "\n";
413 }
414
415 $params['text'] = $text;
416 $this->saveRevision( $params );
417 $this->numGoodRevs++;
418 #$this->printLatin1( "$editTime $title\n" );
419 }
420
421 function doPendingOps( $editTime ) {
422 foreach ( $this->moveLog as $newTitle => $entry ) {
423 if ( $entry['timestamp'] <= $editTime ) {
424 unset( $this->moveLog[$newTitle] );
425 if ( isset( $entry['deep'] ) ) {
426 $this->renameTextLinks( $entry['old'], $newTitle, $entry['timestamp'] );
427 }
428 }
429 }
430
431 foreach ( $this->renameTextLinksOps as $renameTime => $replacements ) {
432 if ( $editTime >= $renameTime ) {
433 foreach ( $replacements as $old => $new ) {
434 $this->printLatin1( "SUBSTITUTE $old -> $new\n" );
435 $this->renameTextLinks( $old, $new, $renameTime );
436 }
437 unset( $this->renameTextLinksOps[$renameTime] );
438 }
439 }
440
441 foreach ( $this->unixLineEndingsOps as $fixTime => $title ) {
442 if ( $editTime >= $fixTime ) {
443 $this->printLatin1( "$fixTime $title FIXING LINE ENDINGS\n" );
444 $text = $this->getText( $title );
445 $text = str_replace( "\r", '', $text );
446 $this->saveRevision( array(
447 'rctitle' => $title,
448 'timestamp' => $fixTime,
449 'extra' => array( 'name' => 'UseModWiki admin' ),
450 'text' => $text,
451 'summary' => 'Fixing line endings',
452 ) );
453 unset( $this->unixLineEndingsOps[$fixTime] );
454 }
455 }
456 }
457
458 function patch( $source, $diff ) {
459 file_put_contents( $this->articleFileName, $source );
460 file_put_contents( $this->patchFileName, $diff );
461 $error = wfShellExec(
462 wfEscapeShellArg(
463 'patch',
464 '-n',
465 '-r', '-',
466 '--no-backup-if-mismatch',
467 '--binary',
468 $this->articleFileName,
469 $this->patchFileName
470 ) . ' 2>&1',
471 $status
472 );
473 $text = file_get_contents( $this->articleFileName );
474 if ( $status || $text === false ) {
475 return false;
476 } else {
477 return $text;
478 }
479 }
480
481 function resolveFailedDiff( $origText, $diff ) {
482 $context = array();
483 $rxRange = '\d+(?:,(\d+))?';
484 $diffLines = explode( "\n", $diff );
485 for ( $i = 0; $i < count( $diffLines ); $i++ ) {
486 $diffLine = $diffLines[$i];
487 if ( !preg_match( '/^(\d+)(?:,\d+)?[acd]\d+(?:,\d+)?$/', $diffLine, $m ) ) {
488 continue;
489 }
490
491 $sourceIndex = intval( $m[1] );
492 $i++;
493 while ( $i < count( $diffLines ) && substr( $diffLines[$i], 0, 1 ) === '<' ) {
494 $context[$sourceIndex - 1] = substr( $diffLines[$i], 2 );
495 $sourceIndex++;
496 $i++;
497 }
498 $i--;
499 }
500
501 $changedLinks = array();
502 $origLines = explode( "\n", $origText );
503 foreach ( $context as $i => $contextLine ) {
504 $origLine = isset( $origLines[$i] ) ? $origLines[$i] : '';
505 if ( $contextLine === $origLine ) {
506 continue;
507 }
508 $newChanges = $this->resolveTextChange( $origLine, $contextLine );
509 if ( is_array( $newChanges ) ) {
510 $changedLinks += $newChanges;
511 } else {
512 echo "Resolution failure on line " . ( $i + 1 ) . "\n";
513 $this->printLatin1( $newChanges );
514 }
515 }
516
517 return $changedLinks;
518 }
519
520 function resolveTextChange( $source, $dest ) {
521 $changedLinks = array();
522 $sourceLinks = $this->getLinkList( $source );
523 $destLinks = $this->getLinkList( $dest );
524 $newLinks = array_diff( $destLinks, $sourceLinks );
525 $removedLinks = array_diff( $sourceLinks, $destLinks );
526
527 // Match up the removed links with the new links
528 foreach ( $newLinks as $j => $newLink ) {
529 $minDistance = 100000000;
530 $bestRemovedLink = false;
531 foreach ( $removedLinks as $k => $removedLink ) {
532 $editDistance = levenshtein( $newLink, $removedLink );
533 if ( $editDistance < $minDistance ) {
534 $minDistance = $editDistance;
535 $bestRemovedLink = $removedLink;
536 }
537 }
538 if ( $bestRemovedLink !== false ) {
539 $changedLinks[$bestRemovedLink] = $newLink;
540 $newLinks = array_diff( $newLinks, array( $newLink ) );
541 $removedLinks = array_diff( $removedLinks, array( $bestRemovedLink ) );
542 }
543 }
544
545 $proposal = $source;
546 foreach ( $changedLinks as $removedLink => $newLink ) {
547 $proposal = $this->substituteTextLinks( $removedLink, $newLink, $proposal );
548 }
549 if ( $proposal !== $dest ) {
550 // Resolution failed
551 $msg = "Source line: $source\n" .
552 "Source links: " . implode( ', ', $sourceLinks ) . "\n" .
553 "Context line: $dest\n" .
554 "Context links: " . implode( ', ', $destLinks ) . "\n" .
555 "Proposal: $proposal\n";
556 return $msg;
557 }
558 return $changedLinks;
559 }
560
561 function processDiffFile( $callback ) {
562 $diffFile = fopen( "{$this->dataDir}/diff_log", 'r' );
563
564 $delimiter = "------\n";
565 file_put_contents( $this->articleFileName, "Describe the new page here.\n" );
566
567 $line = fgets( $diffFile );
568 $lineNum = 1;
569 if ( $line !== $delimiter ) {
570 echo "Invalid diff file\n";
571 return false;
572 }
573 $lastReportLine = 0;
574 $this->numRevs = 0;
575
576 while ( true ) {
577 $line = fgets( $diffFile );
578 $lineNum++;
579 if ( $line === false ) {
580 break;
581 }
582 if ( $lineNum > $lastReportLine + 1000 ) {
583 $lastReportLine = $lineNum;
584 fwrite( STDERR, "$lineNum \r" );
585 fflush( STDERR );
586 }
587 $line = trim( $line );
588 if ( !preg_match( '/^([^|]+)\|(\d+)$/', $line, $matches ) ) {
589 echo "Invalid header on line $lineNum\n";
590 return true;
591 }
592 list( , $title, $editTime ) = $matches;
593
594 $diff = '';
595 $diffStartLine = $lineNum;
596 while ( true ) {
597 $line = fgets( $diffFile );
598 $lineNum++;
599 if ( $line === $delimiter ) {
600 break;
601 }
602 if ( $line === false ) {
603 break 2;
604 }
605 $diff .= $line;
606 }
607
608 $this->numRevs++;
609
610 if ( !isset( $this->rc[$editTime] ) ) {
611 $this->printLatin1( "$editTime $title DELETED, skipping\n" );
612 continue;
613 }
614
615 if ( count( $this->rc[$editTime] ) == 1 ) {
616 $params = $this->rc[$editTime][0];
617 } else {
618 $params = false;
619 $candidates = '';
620 foreach ( $this->rc[$editTime] as $rc ) {
621 if ( $rc['rctitle'] === $title ) {
622 $params = $rc;
623 break;
624 }
625 if ( $candidates === '' ) {
626 $candidates = $rc['rctitle'];
627 } else {
628 $candidates .= ', ' . $rc['rctitle'];
629 }
630 }
631 if ( !$params ) {
632 $this->printLatin1( "$editTime $title ERROR cannot resolve rclog\n" );
633 $this->printLatin1( "$editTime $title CANDIDATES: $candidates\n" );
634 continue;
635 }
636 }
637 $params['diff'] = $diff;
638 $params['title'] = $title;
639 $params['diffStartLine'] = $diffStartLine;
640 call_user_func( $callback, $params );
641 }
642 echo "\n";
643
644 if ( !feof( $diffFile ) ) {
645 echo "Stopped at line $lineNum\n";
646 }
647 return true;
648 }
649
650 function reconcileCurrentRevs() {
651 foreach ( $this->textCache as $title => $text ) {
652 $fileName = "{$this->dataDir}/page/";
653 if ( preg_match( '/^[A-Z]/', $title, $m ) ) {
654 $fileName .= $m[0];
655 } else {
656 $fileName .= 'other';
657 }
658 $fileName .= "/$title.db";
659
660 if ( !file_exists( $fileName ) ) {
661 $this->printLatin1( "ERROR: Cannot find page file for {$title}\n" );
662 continue;
663 }
664
665 $fileContents = file_get_contents( $fileName );
666 $page = $this->unserializeUseMod( $fileContents, $this->FS1 );
667 $section = $this->unserializeUseMod( $page['text_default'], $this->FS2 );
668 $data = $this->unserializeUseMod( $section['data'], $this->FS3 );
669 $pageText = $data['text'];
670 if ( $text !== $pageText ) {
671 $substs = $this->resolveTextChange( $text, $pageText );
672 if ( is_array( $substs ) ) {
673 foreach ( $substs as $source => $dest ) {
674 if ( isset( $this->moveLog[$dest] ) ) {
675 $this->printLatin1( "ERROR: need deep rename: $source\n" );
676 } else {
677 $this->printLatin1( "ERROR: need substitute: $source -> $dest\n" );
678 }
679 }
680 } else {
681 $this->printLatin1( "ERROR: unresolved diff in $title:\n" );
682 wfSuppressWarnings();
683 $diff = xdiff_string_diff( $text, $pageText ) . '';
684 wfRestoreWarnings();
685 $this->printLatin1( "$diff\n" );
686 }
687 }
688 }
689 }
690
691 function makeTitle( $titleText ) {
692 return Title::newFromText( $this->encode( $titleText ) );
693 }
694
695 function getText( $titleText ) {
696 if ( !isset( $this->textCache[$titleText] ) ) {
697 return "Describe the new page here.\n";
698 } else {
699 return $this->textCache[$titleText];
700 }
701 }
702
703 function saveRevision( $params ) {
704 $this->textCache[$params['rctitle']] = $params['text'];
705
706 $out = "<page>\n" .
707 $this->element( 'title', $params['rctitle'] ) .
708 "<revision>\n" .
709 $this->element( 'id', $this->revId ++ ) .
710 $this->element( 'timestamp', wfTimestamp( TS_ISO_8601, $params['timestamp'] ) ) .
711 "<contributor>\n";
712 if ( isset( $params['extra']['name'] ) ) {
713 $out .= $this->element( 'username', $params['extra']['name'] );
714 }
715 if ( isset( $params['extra']['id'] ) ) {
716 $out .= $this->element( 'id', $params['extra']['id'] );
717 }
718 if ( isset( $params['host'] ) ) {
719 $out .= $this->element( 'ip', $params['host'] );
720 }
721 $out .=
722 "</contributor>\n" .
723 $this->element( 'comment', $params['summary'] ) .
724 "<text xml:space=\"preserve\">" .
725 htmlspecialchars( $this->encode( $params['text'] ) ) .
726 "</text>\n" .
727 "</revision>\n" .
728 "</page>\n";
729 fwrite( $this->outFile, $out );
730 }
731
732 function renameTextLinks( $old, $new, $timestamp ) {
733 $newWithUnderscores = $new;
734 $old = str_replace( '_', ' ', $old );
735 $new = str_replace( '_', ' ', $new );
736
737 foreach ( $this->textCache as $title => $oldText ) {
738 if ( $newWithUnderscores === $title
739 && in_array( $title, $this->skipSelfSubstitution ) )
740 {
741 // Hack to make Pythagorean_Theorem etc. work
742 continue;
743 }
744
745 $newText = $this->substituteTextLinks( $old, $new, $oldText );
746 if ( $oldText !== $newText ) {
747 $this->saveRevision( array(
748 'rctitle' => $title,
749 'timestamp' => $timestamp,
750 'text' => $newText,
751 'extra' => array( 'name' => 'Page move link fixup script' ),
752 'summary' => '',
753 'minor' => true
754 ) );
755 }
756 }
757 }
758
759 function substituteTextLinks( $old, $new, $text ) {
760 $this->saveUrl = array();
761 $this->old = $old;
762 $this->new = $new;
763
764 $text = str_replace( $this->FS, '', $text ); # Remove separators (paranoia)
765 $text = preg_replace_callback( '/(<pre>(.*?)<\/pre>)/is',
766 array( $this, 'storeRaw' ), $text );
767 $text = preg_replace_callback( '/(<code>(.*?)<\/code>)/is',
768 array( $this, 'storeRaw' ), $text );
769 $text = preg_replace_callback( '/(<nowiki>(.*?)<\/nowiki>)/s',
770 array( $this, 'storeRaw' ), $text );
771
772 $text = preg_replace_callback( "/\[\[{$this->FreeLinkPattern}\|([^\]]+)\]\]/",
773 array( $this, 'subFreeLink' ), $text );
774 $text = preg_replace_callback( "/\[\[{$this->FreeLinkPattern}\]\]/",
775 array( $this, 'subFreeLink' ), $text );
776 $text = preg_replace_callback( "/(\[{$this->UrlPattern}\s+([^\]]+?)\])/",
777 array( $this, 'storeRaw' ), $text );
778 $text = preg_replace_callback( "/(\[{$this->InterLinkPattern}\s+([^\]]+?)\])/",
779 array( $this, 'storeRaw' ), $text );
780 $text = preg_replace_callback( "/(\[?{$this->UrlPattern}\]?)/",
781 array( $this, 'storeRaw' ), $text );
782 $text = preg_replace_callback( "/(\[?{$this->InterLinkPattern}\]?)/",
783 array( $this, 'storeRaw' ), $text );
784 $text = preg_replace_callback( "/{$this->LinkPattern}/",
785 array( $this, 'subWikiLink' ), $text );
786
787 $text = preg_replace_callback( "/{$this->FS}(\d+){$this->FS}/",
788 array( $this, 'restoreRaw' ), $text ); # Restore saved text
789 return $text;
790 }
791
792 function getLinkList( $text ) {
793 $this->saveUrl = array();
794 $this->linkList = array();
795
796 $text = str_replace( $this->FS, '', $text ); # Remove separators (paranoia)
797 $text = preg_replace_callback( '/(<pre>(.*?)<\/pre>)/is',
798 array( $this, 'storeRaw' ), $text );
799 $text = preg_replace_callback( '/(<code>(.*?)<\/code>)/is',
800 array( $this, 'storeRaw' ), $text );
801 $text = preg_replace_callback( '/(<nowiki>(.*?)<\/nowiki>)/s',
802 array( $this, 'storeRaw' ), $text );
803
804 $text = preg_replace_callback( "/\[\[{$this->FreeLinkPattern}\|([^\]]+)\]\]/",
805 array( $this, 'storeLink' ), $text );
806 $text = preg_replace_callback( "/\[\[{$this->FreeLinkPattern}\]\]/",
807 array( $this, 'storeLink' ), $text );
808 $text = preg_replace_callback( "/(\[{$this->UrlPattern}\s+([^\]]+?)\])/",
809 array( $this, 'storeRaw' ), $text );
810 $text = preg_replace_callback( "/(\[{$this->InterLinkPattern}\s+([^\]]+?)\])/",
811 array( $this, 'storeRaw' ), $text );
812 $text = preg_replace_callback( "/(\[?{$this->UrlPattern}\]?)/",
813 array( $this, 'storeRaw' ), $text );
814 $text = preg_replace_callback( "/(\[?{$this->InterLinkPattern}\]?)/",
815 array( $this, 'storeRaw' ), $text );
816 $text = preg_replace_callback( "/{$this->LinkPattern}/",
817 array( $this, 'storeLink' ), $text );
818
819 return $this->linkList;
820 }
821
822 function storeRaw( $m ) {
823 $this->saveUrl[] = $m[1];
824 return $this->FS . (count( $this->saveUrl ) - 1) . $this->FS;
825 }
826
827 function subFreeLink( $m ) {
828 $link = $m[1];
829 if ( isset( $m[2] ) ) {
830 $name = $m[2];
831 } else {
832 $name = '';
833 }
834 $oldlink = $link;
835 $link = preg_replace( '/^\s+/', '', $link );
836 $link = preg_replace( '/\s+$/', '', $link );
837 if ( $link == $this->old ) {
838 $link = $this->new;
839 } else {
840 $link = $oldlink; # Preserve spaces if no match
841 }
842 $link = "[[$link";
843 if ( $name !== "" ) {
844 $link .= "|$name";
845 }
846 $link .= "]]";
847 return $this->storeRaw( array( 1 => $link ) );
848 }
849
850 function subWikiLink( $m ) {
851 $link = $m[1];
852 if ( $link == $this->old ) {
853 $link = $this->new;
854 if ( !preg_match( "/^{$this->LinkPattern}$/", $this->new ) ) {
855 $link = "[[$link]]";
856 }
857 }
858 return $this->storeRaw( array( 1 => $link ) );
859 }
860
861 function restoreRaw( $m ) {
862 return $this->saveUrl[$m[1]];
863 }
864
865 function storeLink( $m ) {
866 $this->linkList[] = $m[1];
867 return $this->storeRaw( $m );
868 }
869
870 function encode( $s ) {
871 return strtr( $s, $this->encodeMap );
872 }
873
874 function decode( $s ) {
875 return strtr( $s, $this->decodeMap );
876 }
877
878 function printLatin1( $s ) {
879 echo $this->encode( $s );
880 }
881
882 function unserializeUseMod( $s, $sep ) {
883 $parts = explode( $sep, $s );
884 $result = array();
885 for ( $i = 0; $i < count( $parts ); $i += 2 ) {
886 $result[$parts[$i]] = $parts[$i+1];
887 }
888 return $result;
889 }
890 }
891
892 $maintClass = 'ImportUseModWikipedia';
893 require_once( RUN_MAINTENANCE_IF_MAIN );