35f8542d56e5addc2b640afa2be188abbf76f26a
[lhc/web/wiklou.git] / includes / diff / DifferenceInterface.php
1 <?php
2 /**
3 * @defgroup DifferenceEngine DifferenceEngine
4 */
5
6 /**
7 * Constant to indicate diff cache compatibility.
8 * Bump this when changing the diff formatting in a way that
9 * fixes important bugs or such to force cached diff views to
10 * clear.
11 */
12 define( 'MW_DIFF_VERSION', '1.11a' );
13
14 /**
15 * @todo document
16 * @ingroup DifferenceEngine
17 */
18 class DifferenceEngine {
19 /**#@+
20 * @private
21 */
22 var $mOldid, $mNewid, $mTitle;
23 var $mOldtitle, $mNewtitle, $mPagetitle;
24 var $mOldtext, $mNewtext;
25 var $mOldPage, $mNewPage;
26 var $mRcidMarkPatrolled;
27 var $mOldRev, $mNewRev;
28 var $mRevisionsLoaded = false; // Have the revisions been loaded
29 var $mTextLoaded = 0; // How many text blobs have been loaded, 0, 1 or 2?
30 var $mCacheHit = false; // Was the diff fetched from cache?
31 var $htmldiff;
32
33 /**
34 * Set this to true to add debug info to the HTML output.
35 * Warning: this may cause RSS readers to spuriously mark articles as "new"
36 * (bug 20601)
37 */
38 var $enableDebugComment = false;
39
40 // If true, line X is not displayed when X is 1, for example to increase
41 // readability and conserve space with many small diffs.
42 protected $mReducedLineNumbers = false;
43
44 protected $unhide = false;
45 /**#@-*/
46
47 /**
48 * Constructor
49 * @param $titleObj Title object that the diff is associated with
50 * @param $old Integer: old ID we want to show and diff with.
51 * @param $new String: either 'prev' or 'next'.
52 * @param $rcid Integer: ??? FIXME (default 0)
53 * @param $refreshCache boolean If set, refreshes the diff cache
54 * @param $htmldiff boolean If set, output using HTMLDiff instead of raw wikicode diff
55 * @param $unhide boolean If set, allow viewing deleted revs
56 */
57 function __construct( $titleObj = null, $old = 0, $new = 0, $rcid = 0,
58 $refreshCache = false, $htmldiff = false, $unhide = false )
59 {
60 if ( $titleObj ) {
61 $this->mTitle = $titleObj;
62 } else {
63 global $wgTitle;
64 $this->mTitle = $wgTitle;
65 }
66 wfDebug("DifferenceEngine old '$old' new '$new' rcid '$rcid'\n");
67
68 if ( 'prev' === $new ) {
69 # Show diff between revision $old and the previous one.
70 # Get previous one from DB.
71 $this->mNewid = intval($old);
72 $this->mOldid = $this->mTitle->getPreviousRevisionID( $this->mNewid );
73 } elseif ( 'next' === $new ) {
74 # Show diff between revision $old and the next one.
75 # Get next one from DB.
76 $this->mOldid = intval($old);
77 $this->mNewid = $this->mTitle->getNextRevisionID( $this->mOldid );
78 if ( false === $this->mNewid ) {
79 # if no result, NewId points to the newest old revision. The only newer
80 # revision is cur, which is "0".
81 $this->mNewid = 0;
82 }
83 } else {
84 $this->mOldid = intval($old);
85 $this->mNewid = intval($new);
86 wfRunHooks( 'NewDifferenceEngine', array(&$titleObj, &$this->mOldid, &$this->mNewid, $old, $new) );
87 }
88 $this->mRcidMarkPatrolled = intval($rcid); # force it to be an integer
89 $this->mRefreshCache = $refreshCache;
90 $this->htmldiff = $htmldiff;
91 $this->unhide = $unhide;
92 }
93
94 function setReducedLineNumbers( $value = true ) {
95 $this->mReducedLineNumbers = $value;
96 }
97
98 function getTitle() {
99 return $this->mTitle;
100 }
101
102 function wasCacheHit() {
103 return $this->mCacheHit;
104 }
105
106 function getOldid() {
107 return $this->mOldid;
108 }
109
110 function getNewid() {
111 return $this->mNewid;
112 }
113
114 function showDiffPage( $diffOnly = false ) {
115 global $wgUser, $wgOut, $wgUseExternalEditor, $wgUseRCPatrol, $wgEnableHtmlDiff;
116 wfProfileIn( __METHOD__ );
117
118
119 # If external diffs are enabled both globally and for the user,
120 # we'll use the application/x-external-editor interface to call
121 # an external diff tool like kompare, kdiff3, etc.
122 if($wgUseExternalEditor && $wgUser->getOption('externaldiff')) {
123 global $wgInputEncoding,$wgServer,$wgScript,$wgLang;
124 $wgOut->disable();
125 header ( "Content-type: application/x-external-editor; charset=".$wgInputEncoding );
126 $url1=$this->mTitle->getFullURL( array(
127 'action' => 'raw',
128 'oldid' => $this->mOldid
129 ) );
130 $url2=$this->mTitle->getFullURL( array(
131 'action' => 'raw',
132 'oldid' => $this->mNewid
133 ) );
134 $special=$wgLang->getNsText(NS_SPECIAL);
135 $control=<<<CONTROL
136 [Process]
137 Type=Diff text
138 Engine=MediaWiki
139 Script={$wgServer}{$wgScript}
140 Special namespace={$special}
141
142 [File]
143 Extension=wiki
144 URL=$url1
145
146 [File 2]
147 Extension=wiki
148 URL=$url2
149 CONTROL;
150 echo($control);
151 return;
152 }
153
154 $wgOut->setArticleFlag( false );
155 if ( !$this->loadRevisionData() ) {
156 $t = $this->mTitle->getPrefixedText();
157 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid, $this->mNewid );
158 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
159 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", $d );
160 wfProfileOut( __METHOD__ );
161 return;
162 }
163
164 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev, $this->mNewRev ) );
165
166 if ( $this->mNewRev->isCurrent() ) {
167 $wgOut->setArticleFlag( true );
168 }
169
170 # mOldid is false if the difference engine is called with a "vague" query for
171 # a diff between a version V and its previous version V' AND the version V
172 # is the first version of that article. In that case, V' does not exist.
173 if ( $this->mOldid === false ) {
174 $this->showFirstRevision();
175 $this->renderNewRevision(); // should we respect $diffOnly here or not?
176 wfProfileOut( __METHOD__ );
177 return;
178 }
179
180 $wgOut->suppressQuickbar();
181
182 $oldTitle = $this->mOldPage->getPrefixedText();
183 $newTitle = $this->mNewPage->getPrefixedText();
184 if( $oldTitle == $newTitle ) {
185 $wgOut->setPageTitle( $newTitle );
186 } else {
187 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
188 }
189 $wgOut->setSubtitle( wfMsgExt( 'difference', array( 'parseinline' ) ) );
190 $wgOut->setRobotPolicy( 'noindex,nofollow' );
191
192 if ( !$this->mOldPage->userCanRead() || !$this->mNewPage->userCanRead() ) {
193 $wgOut->loginToUse();
194 $wgOut->output();
195 $wgOut->disable();
196 wfProfileOut( __METHOD__ );
197 return;
198 }
199
200 $sk = $wgUser->getSkin();
201
202 // Check if page is editable
203 $editable = $this->mNewRev->getTitle()->userCan( 'edit' );
204 if ( $editable && $this->mNewRev->isCurrent() && $wgUser->isAllowed( 'rollback' ) ) {
205 $rollback = '&nbsp;&nbsp;&nbsp;' . $sk->generateRollback( $this->mNewRev );
206 } else {
207 $rollback = '';
208 }
209
210 // Prepare a change patrol link, if applicable
211 if( $wgUseRCPatrol && $this->mTitle->userCan('patrol') ) {
212 // If we've been given an explicit change identifier, use it; saves time
213 if( $this->mRcidMarkPatrolled ) {
214 $rcid = $this->mRcidMarkPatrolled;
215 $rc = RecentChange::newFromId( $rcid );
216 // Already patrolled?
217 $rcid = is_object($rc) && !$rc->getAttribute('rc_patrolled') ? $rcid : 0;
218 } else {
219 // Look for an unpatrolled change corresponding to this diff
220 $db = wfGetDB( DB_SLAVE );
221 $change = RecentChange::newFromConds(
222 array(
223 // Redundant user,timestamp condition so we can use the existing index
224 'rc_user_text' => $this->mNewRev->getRawUserText(),
225 'rc_timestamp' => $db->timestamp( $this->mNewRev->getTimestamp() ),
226 'rc_this_oldid' => $this->mNewid,
227 'rc_last_oldid' => $this->mOldid,
228 'rc_patrolled' => 0
229 ),
230 __METHOD__
231 );
232 if( $change instanceof RecentChange ) {
233 $rcid = $change->mAttribs['rc_id'];
234 $this->mRcidMarkPatrolled = $rcid;
235 } else {
236 // None found
237 $rcid = 0;
238 }
239 }
240 // Build the link
241 if( $rcid ) {
242 $patrol = ' <span class="patrollink">[' . $sk->link(
243 $this->mTitle,
244 wfMsgHtml( 'markaspatrolleddiff' ),
245 array(),
246 array(
247 'action' => 'markpatrolled',
248 'rcid' => $rcid
249 ),
250 array(
251 'known',
252 'noclasses'
253 )
254 ) . ']</span>';
255 } else {
256 $patrol = '';
257 }
258 } else {
259 $patrol = '';
260 }
261
262 # Carry over 'diffonly' param via navigation links
263 if( $diffOnly != $wgUser->getBoolOption('diffonly') ) {
264 $query['diffonly'] = $diffOnly;
265 }
266
267 $htmldiffarg = $this->htmlDiffArgument();
268
269 if( $htmldiffarg ) {
270 $query['htmldiff'] = $htmldiffarg['htmldiff'];
271 }
272
273 # Make "previous revision link"
274 $query['diff'] = 'prev';
275 $query['oldid'] = $this->mOldid;
276 # Cascade unhide param in links for easy deletion browsing
277 if( $this->unhide ) {
278 $query['unhide'] = 1;
279 }
280 $prevlink = $sk->link(
281 $this->mTitle,
282 wfMsgHtml( 'previousdiff' ),
283 array(
284 'id' => 'differences-prevlink'
285 ),
286 $query,
287 array(
288 'known',
289 'noclasses'
290 )
291 );
292
293 # Make "next revision link"
294 $query['diff'] = 'next';
295 $query['oldid'] = $this->mNewid;
296 # Skip next link on the top revision
297 if( $this->mNewRev->isCurrent() ) {
298 $nextlink = '&nbsp;';
299 } else {
300 $nextlink = $sk->link(
301 $this->mTitle,
302 wfMsgHtml( 'nextdiff' ),
303 array(
304 'id' => 'differences-nextlink'
305 ),
306 $query,
307 array(
308 'known',
309 'noclasses'
310 )
311 );
312 }
313
314 $oldminor = '';
315 $newminor = '';
316
317 if( $this->mOldRev->isMinor() ) {
318 $oldminor = ChangesList::flag( 'minor' );
319 }
320 if( $this->mNewRev->isMinor() ) {
321 $newminor = ChangesList::flag( 'minor' );
322 }
323
324 $rdel = ''; $ldel = '';
325 # Handle RevisionDelete links...
326 if( $wgUser->isAllowed( 'deletedhistory' ) ) {
327 // Don't show useless link to people who cannot hide revisions
328 if( $this->mOldRev->getVisibility() || $wgUser->isAllowed( 'deleterevision' ) ) {
329 if( !$this->mOldRev->userCan( Revision::DELETED_RESTRICTED ) ) {
330 // If revision was hidden from sysops
331 $ldel = Xml::tags( 'span', array( 'class' => 'mw-revdelundel-link' ),
332 '(' . wfMsgHtml( 'rev-delundel' ) . ')' );
333 } else {
334 $query = array(
335 'type' => 'revision',
336 'target' => $this->mOldRev->mTitle->getPrefixedDbkey(),
337 'ids' => $this->mOldRev->getId()
338 );
339 $ldel = $sk->revDeleteLink( $query, $this->mOldRev->isDeleted( Revision::DELETED_RESTRICTED ) );
340 }
341 $ldel = "&nbsp;&nbsp;&nbsp;$ldel ";
342 }
343 // Don't show useless link to people who cannot hide revisions
344 if( $this->mNewRev->getVisibility() || $wgUser->isAllowed( 'deleterevision' ) ) {
345 if( !$this->mNewRev->userCan( Revision::DELETED_RESTRICTED ) ) {
346 // If revision was hidden from sysops
347 $rdel = Xml::tags( 'span', array( 'class'=>'mw-revdelundel-link' ), '('.wfMsgHtml( 'rev-delundel' ).')' );
348 } else {
349 $query = array(
350 'type' => 'revision',
351 'target' => $this->mNewRev->mTitle->getPrefixedDbkey(),
352 'ids' => $this->mNewRev->getId()
353 );
354 $rdel = $sk->revDeleteLink( $query, $this->mNewRev->isDeleted( Revision::DELETED_RESTRICTED ) );
355 }
356 $rdel = "&nbsp;&nbsp;&nbsp;$rdel ";
357 }
358 }
359
360 $oldHeader = '<div id="mw-diff-otitle1"><strong>'.$this->mOldtitle.'</strong></div>' .
361 '<div id="mw-diff-otitle2">' . $sk->revUserTools( $this->mOldRev, !$this->unhide ) . "</div>" .
362 '<div id="mw-diff-otitle3">' . $oldminor . $sk->revComment( $this->mOldRev, !$diffOnly, !$this->unhide ).$ldel."</div>" .
363 '<div id="mw-diff-otitle4">' . $prevlink .'</div>';
364 $newHeader = '<div id="mw-diff-ntitle1"><strong>'.$this->mNewtitle.'</strong></div>' .
365 '<div id="mw-diff-ntitle2">' . $sk->revUserTools( $this->mNewRev, !$this->unhide ) . " $rollback</div>" .
366 '<div id="mw-diff-ntitle3">' . $newminor . $sk->revComment( $this->mNewRev, !$diffOnly, !$this->unhide ).$rdel."</div>" .
367 '<div id="mw-diff-ntitle4">' . $nextlink . $patrol . '</div>';
368
369 # Check if this user can see the revisions
370 $allowed = $this->mOldRev->userCan(Revision::DELETED_TEXT)
371 && $this->mNewRev->userCan(Revision::DELETED_TEXT);
372 # Check if one of the revisions is deleted/suppressed
373 $deleted = $suppressed = false;
374 if( $this->mOldRev->isDeleted(Revision::DELETED_TEXT) ) {
375 $deleted = true; // old revisions text is hidden
376 if( $this->mOldRev->isDeleted(Revision::DELETED_RESTRICTED) )
377 $suppressed = true; // also suppressed
378 }
379 if( $this->mNewRev->isDeleted(Revision::DELETED_TEXT) ) {
380 $deleted = true; // new revisions text is hidden
381 if( $this->mNewRev->isDeleted(Revision::DELETED_RESTRICTED) )
382 $suppressed = true; // also suppressed
383 }
384 # If the diff cannot be shown due to a deleted revision, then output
385 # the diff header and links to unhide (if available)...
386 if( $deleted && (!$this->unhide || !$allowed) ) {
387 $this->showDiffStyle();
388 $multi = $this->getMultiNotice();
389 $wgOut->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
390 if( !$allowed ) {
391 # Give explanation for why revision is not visible
392 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
393 array( 'rev-deleted-no-diff' ) );
394 } else {
395 # Give explanation and add a link to view the diff...
396 $link = $this->mTitle->getFullUrl( array(
397 'diff' => $this->mNewid,
398 'oldid' => $this->mOldid,
399 'unhide' => 1
400 ) );
401 $msg = $suppressed ? 'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
402 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", array( $msg, $link ) );
403 }
404 # Otherwise, output the HTML diff if requested...
405 } else if( $wgEnableHtmlDiff && $this->htmldiff ) {
406 $multi = $this->getMultiNotice();
407 $wgOut->addHTML( '<div class="diff-switchtype">' . $sk->link(
408 $this->mTitle,
409 wfMsgHtml( 'wikicodecomparison' ),
410 array(
411 'id' => 'differences-switchtype'
412 ),
413 array(
414 'diff' => $this->mNewid,
415 'oldid' => $this->mOldid,
416 'htmldiff' => 0
417 ),
418 array(
419 'known',
420 'noclasses'
421 )
422 ) . '</div>');
423 $wgOut->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
424 # Add deletion notice if the user is viewing deleted content
425 if( $deleted ) {
426 $msg = $suppressed ? 'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
427 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", $msg );
428 }
429 $this->renderHtmlDiff();
430 # Otherwise, output a regular diff...
431 } else {
432 if( $wgEnableHtmlDiff ) {
433 $wgOut->addHTML( '<div class="diff-switchtype">' . $sk->link(
434 $this->mTitle,
435 wfMsgHtml( 'visualcomparison' ),
436 array( 'id' => 'differences-switchtype' ),
437 array(
438 'diff' => $this->mNewid,
439 'oldid' => $this->mOldid,
440 'htmldiff' => 1
441 ),
442 array( 'known', 'noclasses' )
443 ) . '</div>');
444 }
445 # Add deletion notice if the user is viewing deleted content
446 $notice = '';
447 if( $deleted ) {
448 $msg = $suppressed ? 'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
449 $notice = "<div class='mw-warning plainlinks'>\n".wfMsgExt($msg,'parseinline')."</div>\n";
450 }
451 $this->showDiff( $oldHeader, $newHeader, $notice );
452 if( !$diffOnly ) {
453 $this->renderNewRevision();
454 }
455 }
456 wfProfileOut( __METHOD__ );
457 }
458
459 /**
460 * Show the new revision of the page.
461 */
462 function renderNewRevision() {
463 global $wgOut, $wgUser;
464 wfProfileIn( __METHOD__ );
465
466 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
467 # Add deleted rev tag if needed
468 if( !$this->mNewRev->userCan(Revision::DELETED_TEXT) ) {
469 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-permission' );
470 } else if( $this->mNewRev->isDeleted(Revision::DELETED_TEXT) ) {
471 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-view' );
472 }
473
474 if( !$this->mNewRev->isCurrent() ) {
475 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
476 }
477
478 $this->loadNewText();
479 if( is_object( $this->mNewRev ) ) {
480 $wgOut->setRevisionId( $this->mNewRev->getId() );
481 }
482
483 if( $this->mTitle->isCssJsSubpage() || $this->mTitle->isCssOrJsPage() ) {
484 // Stolen from Article::view --AG 2007-10-11
485 // Give hooks a chance to customise the output
486 if( wfRunHooks( 'ShowRawCssJs', array( $this->mNewtext, $this->mTitle, $wgOut ) ) ) {
487 // Wrap the whole lot in a <pre> and don't parse
488 $m = array();
489 preg_match( '!\.(css|js)$!u', $this->mTitle->getText(), $m );
490 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
491 $wgOut->addHTML( htmlspecialchars( $this->mNewtext ) );
492 $wgOut->addHTML( "\n</pre>\n" );
493 }
494 } else {
495 $wgOut->addWikiTextTidy( $this->mNewtext );
496 }
497
498 if( is_object( $this->mNewRev ) && !$this->mNewRev->isCurrent() ) {
499 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
500 }
501 # Add redundant patrol link on bottom...
502 if( $this->mRcidMarkPatrolled && $this->mTitle->quickUserCan('patrol') ) {
503 $sk = $wgUser->getSkin();
504 $wgOut->addHTML(
505 "<div class='patrollink'>[" . $sk->link(
506 $this->mTitle,
507 wfMsgHtml( 'markaspatrolleddiff' ),
508 array(),
509 array(
510 'action' => 'markpatrolled',
511 'rcid' => $this->mRcidMarkPatrolled
512 )
513 ) . ']</div>'
514 );
515 }
516
517 wfProfileOut( __METHOD__ );
518 }
519
520
521 function renderHtmlDiff() {
522 global $wgOut, $wgParser, $wgDebugComments;
523 wfProfileIn( __METHOD__ );
524
525 $this->showDiffStyle();
526
527 $wgOut->addHTML( '<h2>'.wfMsgHtml( 'visual-comparison' )."</h2>\n" );
528 #add deleted rev tag if needed
529 if( !$this->mNewRev->userCan(Revision::DELETED_TEXT) ) {
530 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-permission' );
531 } else if( $this->mNewRev->isDeleted(Revision::DELETED_TEXT) ) {
532 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-view' );
533 }
534
535 if( !$this->mNewRev->isCurrent() ) {
536 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
537 }
538
539 $this->loadText();
540
541 // Old revision
542 if( is_object( $this->mOldRev ) ) {
543 $wgOut->setRevisionId( $this->mOldRev->getId() );
544 }
545
546 $popts = $wgOut->parserOptions();
547 $oldTidy = $popts->setTidy( true );
548 $popts->setEditSection( false );
549
550 $parserOutput = $wgParser->parse( $this->mOldtext, $this->getTitle(), $popts, true, true, $wgOut->getRevisionId() );
551 $popts->setTidy( $oldTidy );
552
553 //only for new?
554 //$wgOut->addParserOutputNoText( $parserOutput );
555 $oldHtml = $parserOutput->getText();
556 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$oldHtml ) );
557
558 // New revision
559 if( is_object( $this->mNewRev ) ) {
560 $wgOut->setRevisionId( $this->mNewRev->getId() );
561 }
562
563 $popts = $wgOut->parserOptions();
564 $oldTidy = $popts->setTidy( true );
565
566 $parserOutput = $wgParser->parse( $this->mNewtext, $this->getTitle(), $popts, true, true, $wgOut->getRevisionId() );
567 $popts->setTidy( $oldTidy );
568
569 $wgOut->addParserOutputNoText( $parserOutput );
570 $newHtml = $parserOutput->getText();
571 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$newHtml ) );
572
573 unset($parserOutput, $popts);
574
575 $differ = new HTMLDiffer(new DelegatingContentHandler($wgOut));
576 $differ->htmlDiff($oldHtml, $newHtml);
577 if ( $wgDebugComments ) {
578 $wgOut->addHTML( "\n<!-- HtmlDiff Debug Output:\n" . HTMLDiffer::getDebugOutput() . " End Debug -->" );
579 }
580
581 wfProfileOut( __METHOD__ );
582 }
583
584 /**
585 * Show the first revision of an article. Uses normal diff headers in
586 * contrast to normal "old revision" display style.
587 */
588 function showFirstRevision() {
589 global $wgOut, $wgUser;
590 wfProfileIn( __METHOD__ );
591
592 # Get article text from the DB
593 #
594 if ( ! $this->loadNewText() ) {
595 $t = $this->mTitle->getPrefixedText();
596 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ), $this->mOldid, $this->mNewid );
597 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
598 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", $d );
599 wfProfileOut( __METHOD__ );
600 return;
601 }
602 if ( $this->mNewRev->isCurrent() ) {
603 $wgOut->setArticleFlag( true );
604 }
605
606 # Check if user is allowed to look at this page. If not, bail out.
607 #
608 if ( !$this->mTitle->userCanRead() ) {
609 $wgOut->loginToUse();
610 $wgOut->output();
611 wfProfileOut( __METHOD__ );
612 throw new MWException("Permission Error: you do not have access to view this page");
613 }
614
615 # Prepare the header box
616 #
617 $sk = $wgUser->getSkin();
618
619 $next = $this->mTitle->getNextRevisionID( $this->mNewid );
620 if( !$next ) {
621 $nextlink = '';
622 } else {
623 $nextlink = '<br/>' . $sk->link(
624 $this->mTitle,
625 wfMsgHtml( 'nextdiff' ),
626 array(
627 'id' => 'differences-nextlink'
628 ),
629 array(
630 'diff' => 'next',
631 'oldid' => $this->mNewid,
632 $this->htmlDiffArgument()
633 ),
634 array(
635 'known',
636 'noclasses'
637 )
638 );
639 }
640 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\">" .
641 $sk->revUserTools( $this->mNewRev ) . "<br/>" . $sk->revComment( $this->mNewRev ) . $nextlink . "</div>\n";
642
643 $wgOut->addHTML( $header );
644
645 $wgOut->setSubtitle( wfMsgExt( 'difference', array( 'parseinline' ) ) );
646 $wgOut->setRobotPolicy( 'noindex,nofollow' );
647
648 wfProfileOut( __METHOD__ );
649 }
650
651 function htmlDiffArgument(){
652 global $wgEnableHtmlDiff;
653 if($wgEnableHtmlDiff){
654 if($this->htmldiff){
655 return array( 'htmldiff' => 1 );
656 }else{
657 return array( 'htmldiff' => 0 );
658 }
659 }else{
660 return array();
661 }
662 }
663
664 /**
665 * Get the diff text, send it to $wgOut
666 * Returns false if the diff could not be generated, otherwise returns true
667 */
668 function showDiff( $otitle, $ntitle, $notice = '' ) {
669 global $wgOut;
670 $diff = $this->getDiff( $otitle, $ntitle, $notice );
671 if ( $diff === false ) {
672 $wgOut->addWikiMsg( 'missing-article', "<nowiki>(fixme, bug)</nowiki>", '' );
673 return false;
674 } else {
675 $this->showDiffStyle();
676 $wgOut->addHTML( $diff );
677 return true;
678 }
679 }
680
681 /**
682 * Add style sheets and supporting JS for diff display.
683 */
684 function showDiffStyle() {
685 global $wgStylePath, $wgStyleVersion, $wgOut;
686 $wgOut->addStyle( 'common/diff.css' );
687
688 // JS is needed to detect old versions of Mozilla to work around an annoyance bug.
689 $wgOut->addScript( "<script type=\"text/javascript\" src=\"$wgStylePath/common/diff.js?$wgStyleVersion\"></script>" );
690 }
691
692 /**
693 * Get complete diff table, including header
694 *
695 * @param Title $otitle Old title
696 * @param Title $ntitle New title
697 * @param string $notice HTML between diff header and body
698 * @return mixed
699 */
700 function getDiff( $otitle, $ntitle, $notice = '' ) {
701 $body = $this->getDiffBody();
702 if ( $body === false ) {
703 return false;
704 } else {
705 $multi = $this->getMultiNotice();
706 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
707 }
708 }
709
710 /**
711 * Get the diff table body, without header
712 *
713 * @return mixed
714 */
715 function getDiffBody() {
716 global $wgMemc;
717 wfProfileIn( __METHOD__ );
718 $this->mCacheHit = true;
719 // Check if the diff should be hidden from this user
720 if ( !$this->loadRevisionData() )
721 return '';
722 if ( $this->mOldRev && !$this->mOldRev->userCan(Revision::DELETED_TEXT) ) {
723 return '';
724 } else if ( $this->mNewRev && !$this->mNewRev->userCan(Revision::DELETED_TEXT) ) {
725 return '';
726 } else if ( $this->mOldRev && $this->mNewRev && $this->mOldRev->getID() == $this->mNewRev->getID() ) {
727 return '';
728 }
729 // Cacheable?
730 $key = false;
731 if ( $this->mOldid && $this->mNewid ) {
732 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION, 'oldid', $this->mOldid, 'newid', $this->mNewid );
733 // Try cache
734 if ( !$this->mRefreshCache ) {
735 $difftext = $wgMemc->get( $key );
736 if ( $difftext ) {
737 wfIncrStats( 'diff_cache_hit' );
738 $difftext = $this->localiseLineNumbers( $difftext );
739 $difftext .= "\n<!-- diff cache key $key -->\n";
740 wfProfileOut( __METHOD__ );
741 return $difftext;
742 }
743 } // don't try to load but save the result
744 }
745 $this->mCacheHit = false;
746
747 // Loadtext is permission safe, this just clears out the diff
748 if ( !$this->loadText() ) {
749 wfProfileOut( __METHOD__ );
750 return false;
751 }
752
753 $difftext = $this->generateDiffBody( $this->mOldtext, $this->mNewtext );
754
755 // Save to cache for 7 days
756 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
757 wfIncrStats( 'diff_uncacheable' );
758 } else if ( $key !== false && $difftext !== false ) {
759 wfIncrStats( 'diff_cache_miss' );
760 $wgMemc->set( $key, $difftext, 7*86400 );
761 } else {
762 wfIncrStats( 'diff_uncacheable' );
763 }
764 // Replace line numbers with the text in the user's language
765 if ( $difftext !== false ) {
766 $difftext = $this->localiseLineNumbers( $difftext );
767 }
768 wfProfileOut( __METHOD__ );
769 return $difftext;
770 }
771
772 /**
773 * Make sure the proper modules are loaded before we try to
774 * make the diff
775 */
776 private function initDiffEngines() {
777 global $wgExternalDiffEngine;
778 if ( $wgExternalDiffEngine == 'wikidiff' && !function_exists( 'wikidiff_do_diff' ) ) {
779 wfProfileIn( __METHOD__ . '-php_wikidiff.so' );
780 wfSuppressWarnings();
781 dl( 'php_wikidiff.so' );
782 wfRestoreWarnings();
783 wfProfileOut( __METHOD__ . '-php_wikidiff.so' );
784 }
785 else if ( $wgExternalDiffEngine == 'wikidiff2' && !function_exists( 'wikidiff2_do_diff' ) ) {
786 wfProfileIn( __METHOD__ . '-php_wikidiff2.so' );
787 wfSuppressWarnings();
788 dl( 'php_wikidiff2.so' );
789 wfRestoreWarnings();
790 wfProfileOut( __METHOD__ . '-php_wikidiff2.so' );
791 }
792 }
793
794 /**
795 * Generate a diff, no caching
796 * $otext and $ntext must be already segmented
797 */
798 function generateDiffBody( $otext, $ntext ) {
799 global $wgExternalDiffEngine, $wgContLang;
800
801 $otext = str_replace( "\r\n", "\n", $otext );
802 $ntext = str_replace( "\r\n", "\n", $ntext );
803
804 $this->initDiffEngines();
805
806 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
807 # For historical reasons, external diff engine expects
808 # input text to be HTML-escaped already
809 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
810 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
811 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
812 $this->debug( 'wikidiff1' );
813 }
814
815 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
816 # Better external diff engine, the 2 may some day be dropped
817 # This one does the escaping and segmenting itself
818 wfProfileIn( 'wikidiff2_do_diff' );
819 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
820 $text .= $this->debug( 'wikidiff2' );
821 wfProfileOut( 'wikidiff2_do_diff' );
822 return $text;
823 }
824 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
825 # Diff via the shell
826 global $wgTmpDirectory;
827 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
828 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
829
830 $tempFile1 = fopen( $tempName1, "w" );
831 if ( !$tempFile1 ) {
832 wfProfileOut( __METHOD__ );
833 return false;
834 }
835 $tempFile2 = fopen( $tempName2, "w" );
836 if ( !$tempFile2 ) {
837 wfProfileOut( __METHOD__ );
838 return false;
839 }
840 fwrite( $tempFile1, $otext );
841 fwrite( $tempFile2, $ntext );
842 fclose( $tempFile1 );
843 fclose( $tempFile2 );
844 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
845 wfProfileIn( __METHOD__ . "-shellexec" );
846 $difftext = wfShellExec( $cmd );
847 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
848 wfProfileOut( __METHOD__ . "-shellexec" );
849 unlink( $tempName1 );
850 unlink( $tempName2 );
851 return $difftext;
852 }
853
854 # Native PHP diff
855 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
856 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
857 $diffs = new Diff( $ota, $nta );
858 $formatter = new TableDiffFormatter();
859 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
860 $this->debug();
861 }
862
863 /**
864 * Generate a debug comment indicating diff generating time,
865 * server node, and generator backend.
866 */
867 protected function debug( $generator="internal" ) {
868 global $wgShowHostnames;
869 if ( !$this->enableDebugComment ) {
870 return '';
871 }
872 $data = array( $generator );
873 if( $wgShowHostnames ) {
874 $data[] = wfHostname();
875 }
876 $data[] = wfTimestamp( TS_DB );
877 return "<!-- diff generator: " .
878 implode( " ",
879 array_map(
880 "htmlspecialchars",
881 $data ) ) .
882 " -->\n";
883 }
884
885 /**
886 * Replace line numbers with the text in the user's language
887 */
888 function localiseLineNumbers( $text ) {
889 return preg_replace_callback( '/<!--LINE (\d+)-->/',
890 array( &$this, 'localiseLineNumbersCb' ), $text );
891 }
892
893 function localiseLineNumbersCb( $matches ) {
894 global $wgLang;
895 if ( $matches[1] === '1' && $this->mReducedLineNumbers ) return '';
896 return wfMsgExt( 'lineno', 'escape', $wgLang->formatNum( $matches[1] ) );
897 }
898
899
900 /**
901 * If there are revisions between the ones being compared, return a note saying so.
902 */
903 function getMultiNotice() {
904 if ( !is_object($this->mOldRev) || !is_object($this->mNewRev) )
905 return '';
906
907 if( !$this->mOldPage->equals( $this->mNewPage ) ) {
908 // Comparing two different pages? Count would be meaningless.
909 return '';
910 }
911
912 $oldid = $this->mOldRev->getId();
913 $newid = $this->mNewRev->getId();
914 if ( $oldid > $newid ) {
915 $tmp = $oldid; $oldid = $newid; $newid = $tmp;
916 }
917
918 $n = $this->mTitle->countRevisionsBetween( $oldid, $newid );
919 if ( !$n )
920 return '';
921
922 return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n );
923 }
924
925
926 /**
927 * Add the header to a diff body
928 */
929 static function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
930 $header = "<table class='diff'>";
931 if( $diff ) { // Safari/Chrome show broken output if cols not used
932 $header .= "
933 <col class='diff-marker' />
934 <col class='diff-content' />
935 <col class='diff-marker' />
936 <col class='diff-content' />";
937 $colspan = 2;
938 $multiColspan = 4;
939 } else {
940 $colspan = 1;
941 $multiColspan = 2;
942 }
943 $header .= "
944 <tr valign='top'>
945 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
946 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
947 </tr>";
948
949 if ( $multi != '' ) {
950 $header .= "<tr><td colspan='{$multiColspan}' align='center' class='diff-multi'>{$multi}</td></tr>";
951 }
952 if ( $notice != '' ) {
953 $header .= "<tr><td colspan='{$multiColspan}' align='center'>{$notice}</td></tr>";
954 }
955
956 return $header . $diff . "</table>";
957 }
958
959 /**
960 * Use specified text instead of loading from the database
961 */
962 function setText( $oldText, $newText ) {
963 $this->mOldtext = $oldText;
964 $this->mNewtext = $newText;
965 $this->mTextLoaded = 2;
966 $this->mRevisionsLoaded = true;
967 }
968
969 /**
970 * Load revision metadata for the specified articles. If newid is 0, then compare
971 * the old article in oldid to the current article; if oldid is 0, then
972 * compare the current article to the immediately previous one (ignoring the
973 * value of newid).
974 *
975 * If oldid is false, leave the corresponding revision object set
976 * to false. This is impossible via ordinary user input, and is provided for
977 * API convenience.
978 */
979 function loadRevisionData() {
980 global $wgLang, $wgUser;
981 if ( $this->mRevisionsLoaded ) {
982 return true;
983 } else {
984 // Whether it succeeds or fails, we don't want to try again
985 $this->mRevisionsLoaded = true;
986 }
987
988 // Load the new revision object
989 $this->mNewRev = $this->mNewid
990 ? Revision::newFromId( $this->mNewid )
991 : Revision::newFromTitle( $this->mTitle );
992 if( !$this->mNewRev instanceof Revision )
993 return false;
994
995 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
996 $this->mNewid = $this->mNewRev->getId();
997
998 // Check if page is editable
999 $editable = $this->mNewRev->getTitle()->userCan( 'edit' );
1000
1001 // Set assorted variables
1002 $timestamp = $wgLang->timeanddate( $this->mNewRev->getTimestamp(), true );
1003 $dateofrev = $wgLang->date( $this->mNewRev->getTimestamp(), true );
1004 $timeofrev = $wgLang->time( $this->mNewRev->getTimestamp(), true );
1005 $this->mNewPage = $this->mNewRev->getTitle();
1006 if( $this->mNewRev->isCurrent() ) {
1007 $newLink = $this->mNewPage->escapeLocalUrl( array(
1008 'oldid' => $this->mNewid
1009 ) );
1010 $this->mPagetitle = htmlspecialchars( wfMsg(
1011 'currentrev-asof',
1012 $timestamp,
1013 $dateofrev,
1014 $timeofrev
1015 ) );
1016 $newEdit = $this->mNewPage->escapeLocalUrl( array(
1017 'action' => 'edit'
1018 ) );
1019
1020 $this->mNewtitle = "<a href='$newLink'>{$this->mPagetitle}</a>";
1021 $this->mNewtitle .= " (<a href='$newEdit'>" . wfMsgHtml( $editable ? 'editold' : 'viewsourceold' ) . "</a>)";
1022 } else {
1023 $newLink = $this->mNewPage->escapeLocalUrl( array(
1024 'oldid' => $this->mNewid
1025 ) );
1026 $newEdit = $this->mNewPage->escapeLocalUrl( array(
1027 'action' => 'edit',
1028 'oldid' => $this->mNewid
1029 ) );
1030 $this->mPagetitle = htmlspecialchars( wfMsg(
1031 'revisionasof',
1032 $timestamp,
1033 $dateofrev,
1034 $timeofrev
1035 ) );
1036
1037 $this->mNewtitle = "<a href='$newLink'>{$this->mPagetitle}</a>";
1038 $this->mNewtitle .= " (<a href='$newEdit'>" . wfMsgHtml( $editable ? 'editold' : 'viewsourceold' ) . "</a>)";
1039 }
1040 if( !$this->mNewRev->userCan(Revision::DELETED_TEXT) ) {
1041 $this->mNewtitle = "<span class='history-deleted'>{$this->mPagetitle}</span>";
1042 } else if ( $this->mNewRev->isDeleted(Revision::DELETED_TEXT) ) {
1043 $this->mNewtitle = "<span class='history-deleted'>{$this->mNewtitle}</span>";
1044 }
1045
1046 // Load the old revision object
1047 $this->mOldRev = false;
1048 if( $this->mOldid ) {
1049 $this->mOldRev = Revision::newFromId( $this->mOldid );
1050 } elseif ( $this->mOldid === 0 ) {
1051 $rev = $this->mNewRev->getPrevious();
1052 if( $rev ) {
1053 $this->mOldid = $rev->getId();
1054 $this->mOldRev = $rev;
1055 } else {
1056 // No previous revision; mark to show as first-version only.
1057 $this->mOldid = false;
1058 $this->mOldRev = false;
1059 }
1060 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
1061
1062 if( is_null( $this->mOldRev ) ) {
1063 return false;
1064 }
1065
1066 if ( $this->mOldRev ) {
1067 $this->mOldPage = $this->mOldRev->getTitle();
1068
1069 $t = $wgLang->timeanddate( $this->mOldRev->getTimestamp(), true );
1070 $dateofrev = $wgLang->date( $this->mOldRev->getTimestamp(), true );
1071 $timeofrev = $wgLang->time( $this->mOldRev->getTimestamp(), true );
1072 $oldLink = $this->mOldPage->escapeLocalUrl( array(
1073 'oldid' => $this->mOldid
1074 ) );
1075 $oldEdit = $this->mOldPage->escapeLocalUrl( array(
1076 'action' => 'edit',
1077 'oldid' => $this->mOldid
1078 ) );
1079 $this->mOldPagetitle = htmlspecialchars( wfMsg( 'revisionasof', $t, $dateofrev, $timeofrev ) );
1080
1081 $this->mOldtitle = "<a href='$oldLink'>{$this->mOldPagetitle}</a>"
1082 . " (<a href='$oldEdit'>" . wfMsgHtml( $editable ? 'editold' : 'viewsourceold' ) . "</a>)";
1083 // Add an "undo" link
1084 $newUndo = $this->mNewPage->escapeLocalUrl( array(
1085 'action' => 'edit',
1086 'undoafter' => $this->mOldid,
1087 'undo' => $this->mNewid
1088 ) );
1089 $htmlLink = htmlspecialchars( wfMsg( 'editundo' ) );
1090 $htmlTitle = $wgUser->getSkin()->tooltip( 'undo' );
1091 if( $editable && !$this->mOldRev->isDeleted( Revision::DELETED_TEXT ) && !$this->mNewRev->isDeleted( Revision::DELETED_TEXT ) ) {
1092 $this->mNewtitle .= " (<a href='$newUndo' $htmlTitle>" . $htmlLink . "</a>)";
1093 }
1094
1095 if( !$this->mOldRev->userCan( Revision::DELETED_TEXT ) ) {
1096 $this->mOldtitle = '<span class="history-deleted">' . $this->mOldPagetitle . '</span>';
1097 } else if( $this->mOldRev->isDeleted( Revision::DELETED_TEXT ) ) {
1098 $this->mOldtitle = '<span class="history-deleted">' . $this->mOldtitle . '</span>';
1099 }
1100 }
1101
1102 return true;
1103 }
1104
1105 /**
1106 * Load the text of the revisions, as well as revision data.
1107 */
1108 function loadText() {
1109 if ( $this->mTextLoaded == 2 ) {
1110 return true;
1111 } else {
1112 // Whether it succeeds or fails, we don't want to try again
1113 $this->mTextLoaded = 2;
1114 }
1115
1116 if ( !$this->loadRevisionData() ) {
1117 return false;
1118 }
1119 if ( $this->mOldRev ) {
1120 $this->mOldtext = $this->mOldRev->getText( Revision::FOR_THIS_USER );
1121 if ( $this->mOldtext === false ) {
1122 return false;
1123 }
1124 }
1125 if ( $this->mNewRev ) {
1126 $this->mNewtext = $this->mNewRev->getText( Revision::FOR_THIS_USER );
1127 if ( $this->mNewtext === false ) {
1128 return false;
1129 }
1130 }
1131 return true;
1132 }
1133
1134 /**
1135 * Load the text of the new revision, not the old one
1136 */
1137 function loadNewText() {
1138 if ( $this->mTextLoaded >= 1 ) {
1139 return true;
1140 } else {
1141 $this->mTextLoaded = 1;
1142 }
1143 if ( !$this->loadRevisionData() ) {
1144 return false;
1145 }
1146 $this->mNewtext = $this->mNewRev->getText( Revision::FOR_THIS_USER );
1147 return true;
1148 }
1149 }