3 * User interface for the difference engine
6 * @ingroup DifferenceEngine
10 * Constant to indicate diff cache compatibility.
11 * Bump this when changing the diff formatting in a way that
12 * fixes important bugs or such to force cached diff views to
15 define( 'MW_DIFF_VERSION', '1.11a' );
19 * @ingroup DifferenceEngine
21 class DifferenceEngine
{
26 var $mOldtitle, $mNewtitle, $mPagetitle;
27 var $mOldtext, $mNewtext;
32 var $mOldPage, $mNewPage, $mTitle;
33 var $mRcidMarkPatrolled;
38 var $mOldRev, $mNewRev;
39 var $mRevisionsLoaded = false; // Have the revisions been loaded
40 var $mTextLoaded = 0; // How many text blobs have been loaded, 0, 1 or 2?
41 var $mCacheHit = false; // Was the diff fetched from cache?
44 * Set this to true to add debug info to the HTML output.
45 * Warning: this may cause RSS readers to spuriously mark articles as "new"
48 var $enableDebugComment = false;
50 // If true, line X is not displayed when X is 1, for example to increase
51 // readability and conserve space with many small diffs.
52 protected $mReducedLineNumbers = false;
54 protected $unhide = false; # show rev_deleted content if allowed
59 * @param $titleObj Title object that the diff is associated with
60 * @param $old Integer old ID we want to show and diff with.
61 * @param $new String either 'prev' or 'next'.
62 * @param $rcid Integer ??? FIXME (default 0)
63 * @param $refreshCache boolean If set, refreshes the diff cache
64 * @param $unhide boolean If set, allow viewing deleted revs
66 function __construct( $titleObj = null, $old = 0, $new = 0, $rcid = 0,
67 $refreshCache = false, $unhide = false )
70 $this->mTitle
= $titleObj;
73 $this->mTitle
= $wgTitle; // @TODO: get rid of this
75 wfDebug( "DifferenceEngine old '$old' new '$new' rcid '$rcid'\n" );
77 if ( 'prev' === $new ) {
78 # Show diff between revision $old and the previous one.
79 # Get previous one from DB.
80 $this->mNewid
= intval( $old );
81 $this->mOldid
= $this->mTitle
->getPreviousRevisionID( $this->mNewid
);
82 } elseif ( 'next' === $new ) {
83 # Show diff between revision $old and the next one.
84 # Get next one from DB.
85 $this->mOldid
= intval( $old );
86 $this->mNewid
= $this->mTitle
->getNextRevisionID( $this->mOldid
);
87 if ( false === $this->mNewid
) {
88 # if no result, NewId points to the newest old revision. The only newer
89 # revision is cur, which is "0".
93 $this->mOldid
= intval( $old );
94 $this->mNewid
= intval( $new );
95 wfRunHooks( 'NewDifferenceEngine', array( &$titleObj, &$this->mOldid
, &$this->mNewid
, $old, $new ) );
97 $this->mRcidMarkPatrolled
= intval( $rcid ); # force it to be an integer
98 $this->mRefreshCache
= $refreshCache;
99 $this->unhide
= $unhide;
105 function setReducedLineNumbers( $value = true ) {
106 $this->mReducedLineNumbers
= $value;
112 function getTitle() {
113 return $this->mTitle
;
119 function wasCacheHit() {
120 return $this->mCacheHit
;
126 function getOldid() {
127 return $this->mOldid
;
133 function getNewid() {
134 return $this->mNewid
;
138 * Look up a special:Undelete link to the given deleted revision id,
139 * as a workaround for being unable to load deleted diffs in currently.
141 * @param int $id revision ID
142 * @return mixed URL or false
144 function deletedLink( $id ) {
146 if ( $wgUser->isAllowed( 'deletedhistory' ) ) {
147 $dbr = wfGetDB( DB_SLAVE
);
148 $row = $dbr->selectRow('archive', '*',
149 array( 'ar_rev_id' => $id ),
152 $rev = Revision
::newFromArchiveRow( $row );
153 $title = Title
::makeTitleSafe( $row->ar_namespace
, $row->ar_title
);
154 return SpecialPage
::getTitleFor( 'Undelete' )->getFullURL( array(
155 'target' => $title->getPrefixedText(),
156 'timestamp' => $rev->getTimestamp()
164 * Build a wikitext link toward a deleted revision, if viewable.
166 * @param int $id revision ID
167 * @return string wikitext fragment
169 function deletedIdMarker( $id ) {
170 $link = $this->deletedLink( $id );
172 return "[$link $id]";
178 function showDiffPage( $diffOnly = false ) {
179 global $wgUser, $wgOut, $wgUseExternalEditor, $wgUseRCPatrol;
180 wfProfileIn( __METHOD__
);
182 # Allow frames except in certain special cases
183 $wgOut->allowClickjacking();
185 # If external diffs are enabled both globally and for the user,
186 # we'll use the application/x-external-editor interface to call
187 # an external diff tool like kompare, kdiff3, etc.
188 if ( $wgUseExternalEditor && $wgUser->getOption( 'externaldiff' ) ) {
189 global $wgServer, $wgScript, $wgLang;
191 header ( "Content-type: application/x-external-editor; charset=UTF-8" );
192 $url1 = $this->mTitle
->getFullURL( array(
194 'oldid' => $this->mOldid
196 $url2 = $this->mTitle
->getFullURL( array(
198 'oldid' => $this->mNewid
200 $special = $wgLang->getNsText( NS_SPECIAL
);
201 $control = <<<CONTROL
205 Script={$wgServer}{$wgScript}
206 Special namespace={$special}
218 wfProfileOut( __METHOD__
);
222 $wgOut->setArticleFlag( false );
223 if ( !$this->loadRevisionData() ) {
224 // Sounds like a deleted revision... Let's see what we can do.
225 $deletedLink = $this->deletedLink( $this->mNewid
);
227 $t = $this->mTitle
->getPrefixedText();
228 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ),
229 $this->deletedIdMarker( $this->mOldid
),
230 $this->deletedIdMarker( $this->mNewid
) );
231 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
232 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", "<span class='plainlinks'>$d</span>" );
233 wfProfileOut( __METHOD__
);
237 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
239 if ( $this->mNewRev
->isCurrent() ) {
240 $wgOut->setArticleFlag( true );
243 # mOldid is false if the difference engine is called with a "vague" query for
244 # a diff between a version V and its previous version V' AND the version V
245 # is the first version of that article. In that case, V' does not exist.
246 if ( $this->mOldid
=== false ) {
247 $this->showFirstRevision();
248 $this->renderNewRevision(); // should we respect $diffOnly here or not?
249 wfProfileOut( __METHOD__
);
253 $oldTitle = $this->mOldPage
->getPrefixedText();
254 $newTitle = $this->mNewPage
->getPrefixedText();
255 if ( $oldTitle == $newTitle ) {
256 $wgOut->setPageTitle( $newTitle );
258 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
260 if ( $this->mNewPage
->equals( $this->mOldPage
) ) {
261 $wgOut->setSubtitle( wfMsgExt( 'difference', array( 'parseinline' ) ) );
263 $wgOut->setSubtitle( wfMsgExt( 'difference-multipage', array( 'parseinline' ) ) );
265 $wgOut->setRobotPolicy( 'noindex,nofollow' );
267 if ( !$this->mOldPage
->userCanRead() ||
!$this->mNewPage
->userCanRead() ) {
268 $wgOut->loginToUse();
271 wfProfileOut( __METHOD__
);
275 $sk = $wgUser->getSkin();
276 if ( method_exists( $sk, 'suppressQuickbar' ) ) {
277 $sk->suppressQuickbar();
280 // Check if page is editable
281 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
282 if ( $editable && $this->mNewRev
->isCurrent() && $wgUser->isAllowed( 'rollback' ) ) {
283 $wgOut->preventClickjacking();
284 $rollback = '   ' . $sk->generateRollback( $this->mNewRev
);
289 // Prepare a change patrol link, if applicable
290 if ( $wgUseRCPatrol && $this->mTitle
->userCan( 'patrol' ) ) {
291 // If we've been given an explicit change identifier, use it; saves time
292 if ( $this->mRcidMarkPatrolled
) {
293 $rcid = $this->mRcidMarkPatrolled
;
294 $rc = RecentChange
::newFromId( $rcid );
295 // Already patrolled?
296 $rcid = is_object( $rc ) && !$rc->getAttribute( 'rc_patrolled' ) ?
$rcid : 0;
298 // Look for an unpatrolled change corresponding to this diff
299 $db = wfGetDB( DB_SLAVE
);
300 $change = RecentChange
::newFromConds(
302 // Redundant user,timestamp condition so we can use the existing index
303 'rc_user_text' => $this->mNewRev
->getRawUserText(),
304 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
305 'rc_this_oldid' => $this->mNewid
,
306 'rc_last_oldid' => $this->mOldid
,
311 if ( $change instanceof RecentChange
) {
312 $rcid = $change->mAttribs
['rc_id'];
313 $this->mRcidMarkPatrolled
= $rcid;
321 $wgOut->preventClickjacking();
322 $token = $wgUser->editToken( $rcid );
323 $patrol = ' <span class="patrollink">[' . $sk->link(
325 wfMsgHtml( 'markaspatrolleddiff' ),
328 'action' => 'markpatrolled',
344 # Carry over 'diffonly' param via navigation links
345 if ( $diffOnly != $wgUser->getBoolOption( 'diffonly' ) ) {
346 $query['diffonly'] = $diffOnly;
349 # Make "previous revision link"
350 $query['diff'] = 'prev';
351 $query['oldid'] = $this->mOldid
;
352 # Cascade unhide param in links for easy deletion browsing
353 if ( $this->unhide
) {
354 $query['unhide'] = 1;
356 if ( !$this->mOldRev
->getPrevious() ) {
357 $prevlink = ' ';
359 $prevlink = $sk->link(
361 wfMsgHtml( 'previousdiff' ),
363 'id' => 'differences-prevlink'
373 # Make "next revision link"
374 $query['diff'] = 'next';
375 $query['oldid'] = $this->mNewid
;
376 # Skip next link on the top revision
377 if ( $this->mNewRev
->isCurrent() ) {
378 $nextlink = ' ';
380 $nextlink = $sk->link(
382 wfMsgHtml( 'nextdiff' ),
384 'id' => 'differences-nextlink'
397 if ( $this->mOldRev
->isMinor() ) {
398 $oldminor = ChangesList
::flag( 'minor' );
400 if ( $this->mNewRev
->isMinor() ) {
401 $newminor = ChangesList
::flag( 'minor' );
404 # Handle RevisionDelete links...
405 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
406 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
408 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $this->mOldtitle
. '</strong></div>' .
409 '<div id="mw-diff-otitle2">' .
410 $sk->revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
411 '<div id="mw-diff-otitle3">' . $oldminor .
412 $sk->revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
413 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
414 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $this->mNewtitle
. '</strong></div>' .
415 '<div id="mw-diff-ntitle2">' . $sk->revUserTools( $this->mNewRev
, !$this->unhide
) .
417 '<div id="mw-diff-ntitle3">' . $newminor .
418 $sk->revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
419 '<div id="mw-diff-ntitle4">' . $nextlink . $patrol . '</div>';
421 # Check if this user can see the revisions
422 $allowed = $this->mOldRev
->userCan( Revision
::DELETED_TEXT
)
423 && $this->mNewRev
->userCan( Revision
::DELETED_TEXT
);
424 # Check if one of the revisions is deleted/suppressed
425 $deleted = $suppressed = false;
426 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
427 $deleted = true; // old revisions text is hidden
428 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
429 $suppressed = true; // also suppressed
431 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
432 $deleted = true; // new revisions text is hidden
433 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
434 $suppressed = true; // also suppressed
436 # If the diff cannot be shown due to a deleted revision, then output
437 # the diff header and links to unhide (if available)...
438 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
439 $this->showDiffStyle();
440 $multi = $this->getMultiNotice();
441 $wgOut->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
443 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
444 # Give explanation for why revision is not visible
445 $wgOut->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
448 # Give explanation and add a link to view the diff...
449 $link = $this->mTitle
->getFullUrl( array(
450 'diff' => $this->mNewid
,
451 'oldid' => $this->mOldid
,
454 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
455 $wgOut->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n", array( $msg, $link ) );
457 # Otherwise, output a regular diff...
459 # Add deletion notice if the user is viewing deleted content
462 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
463 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" . wfMsgExt( $msg, 'parseinline' ) . "</div>\n";
465 $this->showDiff( $oldHeader, $newHeader, $notice );
467 $this->renderNewRevision();
470 wfProfileOut( __METHOD__
);
474 * @param $rev Revision
477 protected function revisionDeleteLink( $rev ) {
480 $canHide = $wgUser->isAllowed( 'deleterevision' );
481 // Show del/undel link if:
482 // (a) the user can delete revisions, or
483 // (b) the user can view deleted revision *and* this one is deleted
484 if ( $canHide ||
( $rev->getVisibility() && $wgUser->isAllowed( 'deletedhistory' ) ) ) {
485 $sk = $wgUser->getSkin();
486 if ( !$rev->userCan( Revision
::DELETED_RESTRICTED
) ) {
487 $link = $sk->revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
490 'type' => 'revision',
491 'target' => $rev->mTitle
->getPrefixedDbkey(),
492 'ids' => $rev->getId()
494 $link = $sk->revDeleteLink( $query,
495 $rev->isDeleted( Revision
::DELETED_RESTRICTED
), $canHide );
497 $link = '   ' . $link . ' ';
503 * Show the new revision of the page.
505 function renderNewRevision() {
506 global $wgOut, $wgUser;
507 wfProfileIn( __METHOD__
);
508 # Add "current version as of X" title
509 $wgOut->addHTML( "<hr class='diff-hr' />
510 <h2 class='diff-currentversion-title'>{$this->mPagetitle}</h2>\n" );
511 # Page content may be handled by a hooked call instead...
512 if ( wfRunHooks( 'ArticleContentOnDiff', array( $this, $wgOut ) ) ) {
513 # Use the current version parser cache if applicable
515 if ( !$this->mNewRev
->isCurrent() ) {
516 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
520 $this->loadNewText();
521 $wgOut->setRevisionId( $this->mNewRev
->getId() );
523 if ( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
524 // Stolen from Article::view --AG 2007-10-11
525 // Give hooks a chance to customise the output
526 // @TODO: standardize this crap into one function
527 if ( wfRunHooks( 'ShowRawCssJs', array( $this->mNewtext
, $this->mTitle
, $wgOut ) ) ) {
528 // Wrap the whole lot in a <pre> and don't parse
530 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
531 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
532 $wgOut->addHTML( htmlspecialchars( $this->mNewtext
) );
533 $wgOut->addHTML( "\n</pre>\n" );
535 } elseif ( $pCache ) {
536 $article = new Article( $this->mTitle
, 0 );
537 $pOutput = ParserCache
::singleton()->get( $article, $wgOut->parserOptions() );
539 $wgOut->addParserOutput( $pOutput );
541 $article->doViewParse();
544 $wgOut->addWikiTextTidy( $this->mNewtext
);
547 if ( !$this->mNewRev
->isCurrent() ) {
548 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
551 # Add redundant patrol link on bottom...
552 if ( $this->mRcidMarkPatrolled
&& $this->mTitle
->quickUserCan( 'patrol' ) ) {
553 $sk = $wgUser->getSkin();
554 $token = $wgUser->editToken( $this->mRcidMarkPatrolled
);
555 $wgOut->preventClickjacking();
557 "<div class='patrollink'>[" . $sk->link(
559 wfMsgHtml( 'markaspatrolleddiff' ),
562 'action' => 'markpatrolled',
563 'rcid' => $this->mRcidMarkPatrolled
,
570 wfProfileOut( __METHOD__
);
574 * Show the first revision of an article. Uses normal diff headers in
575 * contrast to normal "old revision" display style.
577 function showFirstRevision() {
578 global $wgOut, $wgUser;
579 wfProfileIn( __METHOD__
);
581 # Get article text from the DB
583 if ( ! $this->loadNewText() ) {
584 $t = $this->mTitle
->getPrefixedText();
585 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ),
586 $this->deletedIdMarker( $this->mOldid
),
587 $this->deletedIdMarker( $this->mNewid
) );
588 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
589 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", "<span class='plainlinks'>$d</span>" );
590 wfProfileOut( __METHOD__
);
593 if ( $this->mNewRev
->isCurrent() ) {
594 $wgOut->setArticleFlag( true );
597 # Check if user is allowed to look at this page. If not, bail out.
599 if ( !$this->mTitle
->userCanRead() ) {
600 $wgOut->loginToUse();
602 wfProfileOut( __METHOD__
);
603 throw new MWException( "Permission Error: you do not have access to view this page" );
606 # Prepare the header box
608 $sk = $wgUser->getSkin();
610 $next = $this->mTitle
->getNextRevisionID( $this->mNewid
);
614 $nextlink = '<br />' . $sk->link(
616 wfMsgHtml( 'nextdiff' ),
618 'id' => 'differences-nextlink'
622 'oldid' => $this->mNewid
,
630 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\">" .
631 $sk->revUserTools( $this->mNewRev
) . "<br />" . $sk->revComment( $this->mNewRev
) . $nextlink . "</div>\n";
633 $wgOut->addHTML( $header );
635 $wgOut->setSubtitle( wfMsgExt( 'difference', array( 'parseinline' ) ) );
636 $wgOut->setRobotPolicy( 'noindex,nofollow' );
638 wfProfileOut( __METHOD__
);
642 * Get the diff text, send it to $wgOut
643 * Returns false if the diff could not be generated, otherwise returns true
647 function showDiff( $otitle, $ntitle, $notice = '' ) {
649 $diff = $this->getDiff( $otitle, $ntitle, $notice );
650 if ( $diff === false ) {
651 $wgOut->addWikiMsg( 'missing-article', "<nowiki>(fixme, bug)</nowiki>", '' );
654 $this->showDiffStyle();
655 $wgOut->addHTML( $diff );
661 * Add style sheets and supporting JS for diff display.
663 function showDiffStyle() {
665 $wgOut->addModuleStyles( 'mediawiki.legacy.diff' );
669 * Get complete diff table, including header
671 * @param $otitle Title: old title
672 * @param $ntitle Title: new title
673 * @param $notice String: HTML between diff header and body
676 function getDiff( $otitle, $ntitle, $notice = '' ) {
677 $body = $this->getDiffBody();
678 if ( $body === false ) {
681 $multi = $this->getMultiNotice();
682 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
687 * Get the diff table body, without header
689 * @return mixed (string/false)
691 public function getDiffBody() {
693 wfProfileIn( __METHOD__
);
694 $this->mCacheHit
= true;
695 // Check if the diff should be hidden from this user
696 if ( !$this->loadRevisionData() ) {
697 wfProfileOut( __METHOD__
);
699 } elseif ( $this->mOldRev
&& !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
) ) {
700 wfProfileOut( __METHOD__
);
702 } elseif ( $this->mNewRev
&& !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
) ) {
703 wfProfileOut( __METHOD__
);
707 if ( $this->mOldRev
&& $this->mNewRev
708 && $this->mOldRev
->getID() == $this->mNewRev
->getID() )
710 wfProfileOut( __METHOD__
);
715 if ( $this->mOldid
&& $this->mNewid
) {
716 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
,
717 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
719 if ( !$this->mRefreshCache
) {
720 $difftext = $wgMemc->get( $key );
722 wfIncrStats( 'diff_cache_hit' );
723 $difftext = $this->localiseLineNumbers( $difftext );
724 $difftext .= "\n<!-- diff cache key $key -->\n";
725 wfProfileOut( __METHOD__
);
728 } // don't try to load but save the result
730 $this->mCacheHit
= false;
732 // Loadtext is permission safe, this just clears out the diff
733 if ( !$this->loadText() ) {
734 wfProfileOut( __METHOD__
);
738 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
740 // Save to cache for 7 days
741 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
742 wfIncrStats( 'diff_uncacheable' );
743 } elseif ( $key !== false && $difftext !== false ) {
744 wfIncrStats( 'diff_cache_miss' );
745 $wgMemc->set( $key, $difftext, 7 * 86400 );
747 wfIncrStats( 'diff_uncacheable' );
749 // Replace line numbers with the text in the user's language
750 if ( $difftext !== false ) {
751 $difftext = $this->localiseLineNumbers( $difftext );
753 wfProfileOut( __METHOD__
);
758 * Make sure the proper modules are loaded before we try to
761 private function initDiffEngines() {
762 global $wgExternalDiffEngine;
763 if ( $wgExternalDiffEngine == 'wikidiff' && !function_exists( 'wikidiff_do_diff' ) ) {
764 wfProfileIn( __METHOD__
. '-php_wikidiff.so' );
765 wfDl( 'php_wikidiff' );
766 wfProfileOut( __METHOD__
. '-php_wikidiff.so' );
768 elseif ( $wgExternalDiffEngine == 'wikidiff2' && !function_exists( 'wikidiff2_do_diff' ) ) {
769 wfProfileIn( __METHOD__
. '-php_wikidiff2.so' );
771 wfProfileOut( __METHOD__
. '-php_wikidiff2.so' );
776 * Generate a diff, no caching
778 * @param $otext String: old text, must be already segmented
779 * @param $ntext String: new text, must be already segmented
781 function generateDiffBody( $otext, $ntext ) {
782 global $wgExternalDiffEngine, $wgContLang;
784 $otext = str_replace( "\r\n", "\n", $otext );
785 $ntext = str_replace( "\r\n", "\n", $ntext );
787 $this->initDiffEngines();
789 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
790 # For historical reasons, external diff engine expects
791 # input text to be HTML-escaped already
792 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
793 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
794 return $wgContLang->unsegmentForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
795 $this->debug( 'wikidiff1' );
798 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
799 # Better external diff engine, the 2 may some day be dropped
800 # This one does the escaping and segmenting itself
801 wfProfileIn( 'wikidiff2_do_diff' );
802 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
803 $text .= $this->debug( 'wikidiff2' );
804 wfProfileOut( 'wikidiff2_do_diff' );
807 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
809 global $wgTmpDirectory;
810 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
811 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
813 $tempFile1 = fopen( $tempName1, "w" );
815 wfProfileOut( __METHOD__
);
818 $tempFile2 = fopen( $tempName2, "w" );
820 wfProfileOut( __METHOD__
);
823 fwrite( $tempFile1, $otext );
824 fwrite( $tempFile2, $ntext );
825 fclose( $tempFile1 );
826 fclose( $tempFile2 );
827 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
828 wfProfileIn( __METHOD__
. "-shellexec" );
829 $difftext = wfShellExec( $cmd );
830 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
831 wfProfileOut( __METHOD__
. "-shellexec" );
832 unlink( $tempName1 );
833 unlink( $tempName2 );
834 wfProfileOut( __METHOD__
);
839 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
840 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
841 $diffs = new Diff( $ota, $nta );
842 $formatter = new TableDiffFormatter();
843 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
844 wfProfileOut( __METHOD__
);
849 * Generate a debug comment indicating diff generating time,
850 * server node, and generator backend.
852 protected function debug( $generator = "internal" ) {
853 global $wgShowHostnames;
854 if ( !$this->enableDebugComment
) {
857 $data = array( $generator );
858 if ( $wgShowHostnames ) {
859 $data[] = wfHostname();
861 $data[] = wfTimestamp( TS_DB
);
862 return "<!-- diff generator: " .
871 * Replace line numbers with the text in the user's language
873 function localiseLineNumbers( $text ) {
874 return preg_replace_callback( '/<!--LINE (\d+)-->/',
875 array( &$this, 'localiseLineNumbersCb' ), $text );
878 function localiseLineNumbersCb( $matches ) {
880 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) return '';
881 return wfMsgExt( 'lineno', 'escape', $wgLang->formatNum( $matches[1] ) );
886 * If there are revisions between the ones being compared, return a note saying so.
889 function getMultiNotice() {
890 if ( !is_object( $this->mOldRev
) ||
!is_object( $this->mNewRev
) ) {
892 } elseif ( !$this->mOldPage
->equals( $this->mNewPage
) ) {
893 // Comparing two different pages? Count would be meaningless.
897 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
898 $oldRev = $this->mNewRev
; // flip
899 $newRev = $this->mOldRev
; // flip
900 } else { // normal case
901 $oldRev = $this->mOldRev
;
902 $newRev = $this->mNewRev
;
905 $nEdits = $this->mTitle
->countRevisionsBetween( $oldRev, $newRev );
907 $limit = 100; // use diff-multi-manyusers if too many users
908 $numUsers = $this->mTitle
->countAuthorsBetween( $oldRev, $newRev, $limit );
909 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
911 return ''; // nothing
915 * Get a notice about how many intermediate edits and users there are
916 * @param $numEdits int
917 * @param $numUsers int
921 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
923 if ( $numUsers > $limit ) {
924 $msg = 'diff-multi-manyusers';
929 return wfMsgExt( $msg, 'parseinline',
930 $wgLang->formatnum( $numEdits ), $wgLang->formatnum( $numUsers ) );
934 * Add the header to a diff body
938 static function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
939 global $wgBetterDirectionality, $wgTitle;
940 $tableClass = 'diff';
941 if( $wgBetterDirectionality ) {
942 // shared.css sets diff in interface language/dir,
943 // but the actual content should be in the page language/dir
944 $pageLang = $wgTitle->getPageLanguage();
945 $tableClass .= ' diff-contentalign-' . htmlspecialchars( $pageLang->alignStart() );
947 $header = "<table class='$tableClass'>";
948 if ( $diff ) { // Safari/Chrome show broken output if cols not used
950 <col class='diff-marker' />
951 <col class='diff-content' />
952 <col class='diff-marker' />
953 <col class='diff-content' />";
962 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
963 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
966 if ( $multi != '' ) {
967 $header .= "<tr><td colspan='{$multiColspan}' align='center' class='diff-multi'>{$multi}</td></tr>";
969 if ( $notice != '' ) {
970 $header .= "<tr><td colspan='{$multiColspan}' align='center'>{$notice}</td></tr>";
973 return $header . $diff . "</table>";
977 * Use specified text instead of loading from the database
979 function setText( $oldText, $newText ) {
980 $this->mOldtext
= $oldText;
981 $this->mNewtext
= $newText;
982 $this->mTextLoaded
= 2;
983 $this->mRevisionsLoaded
= true;
987 * Load revision metadata for the specified articles. If newid is 0, then compare
988 * the old article in oldid to the current article; if oldid is 0, then
989 * compare the current article to the immediately previous one (ignoring the
992 * If oldid is false, leave the corresponding revision object set
993 * to false. This is impossible via ordinary user input, and is provided for
998 function loadRevisionData() {
999 global $wgLang, $wgUser;
1000 if ( $this->mRevisionsLoaded
) {
1003 // Whether it succeeds or fails, we don't want to try again
1004 $this->mRevisionsLoaded
= true;
1007 // Load the new revision object
1008 $this->mNewRev
= $this->mNewid
1009 ? Revision
::newFromId( $this->mNewid
)
1010 : Revision
::newFromTitle( $this->mTitle
);
1011 if ( !$this->mNewRev
instanceof Revision
) {
1015 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1016 $this->mNewid
= $this->mNewRev
->getId();
1018 // Check if page is editable
1019 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
1021 // Set assorted variables
1022 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
1023 $dateofrev = $wgLang->date( $this->mNewRev
->getTimestamp(), true );
1024 $timeofrev = $wgLang->time( $this->mNewRev
->getTimestamp(), true );
1025 $this->mNewPage
= $this->mNewRev
->getTitle();
1026 if ( $this->mNewRev
->isCurrent() ) {
1027 $newLink = $this->mNewPage
->escapeLocalUrl( array(
1028 'oldid' => $this->mNewid
1030 $this->mPagetitle
= htmlspecialchars( wfMsg(
1036 $newEdit = $this->mNewPage
->escapeLocalUrl( array(
1040 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
1041 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
1043 $newLink = $this->mNewPage
->escapeLocalUrl( array(
1044 'oldid' => $this->mNewid
1046 $newEdit = $this->mNewPage
->escapeLocalUrl( array(
1048 'oldid' => $this->mNewid
1050 $this->mPagetitle
= htmlspecialchars( wfMsg(
1057 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
1058 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
1060 if ( !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
) ) {
1061 $this->mNewtitle
= "<span class='history-deleted'>{$this->mPagetitle}</span>";
1062 } elseif ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
1063 $this->mNewtitle
= "<span class='history-deleted'>{$this->mNewtitle}</span>";
1066 // Load the old revision object
1067 $this->mOldRev
= false;
1068 if ( $this->mOldid
) {
1069 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1070 } elseif ( $this->mOldid
=== 0 ) {
1071 $rev = $this->mNewRev
->getPrevious();
1073 $this->mOldid
= $rev->getId();
1074 $this->mOldRev
= $rev;
1076 // No previous revision; mark to show as first-version only.
1077 $this->mOldid
= false;
1078 $this->mOldRev
= false;
1080 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1082 if ( is_null( $this->mOldRev
) ) {
1086 if ( $this->mOldRev
) {
1087 $this->mOldPage
= $this->mOldRev
->getTitle();
1089 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
1090 $dateofrev = $wgLang->date( $this->mOldRev
->getTimestamp(), true );
1091 $timeofrev = $wgLang->time( $this->mOldRev
->getTimestamp(), true );
1092 $oldLink = $this->mOldPage
->escapeLocalUrl( array(
1093 'oldid' => $this->mOldid
1095 $oldEdit = $this->mOldPage
->escapeLocalUrl( array(
1097 'oldid' => $this->mOldid
1099 $this->mOldPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t, $dateofrev, $timeofrev ) );
1101 $this->mOldtitle
= "<a href='$oldLink'>{$this->mOldPagetitle}</a>"
1102 . " (<a href='$oldEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
1103 // Add an "undo" link
1104 if ( $editable && !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
1105 $undoLink = Html
::element( 'a', array(
1106 'href' => $this->mNewPage
->getLocalUrl( array(
1108 'undoafter' => $this->mOldid
,
1109 'undo' => $this->mNewid
) ),
1110 'title' => $wgUser->getSkin()->titleAttrib( 'undo' )
1111 ), wfMsg( 'editundo' ) );
1112 $this->mNewtitle
.= ' (' . $undoLink . ')';
1115 if ( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
) ) {
1116 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldPagetitle
. '</span>';
1117 } elseif ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
1118 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldtitle
. '</span>';
1126 * Load the text of the revisions, as well as revision data.
1130 function loadText() {
1131 if ( $this->mTextLoaded
== 2 ) {
1134 // Whether it succeeds or fails, we don't want to try again
1135 $this->mTextLoaded
= 2;
1138 if ( !$this->loadRevisionData() ) {
1141 if ( $this->mOldRev
) {
1142 $this->mOldtext
= $this->mOldRev
->getText( Revision
::FOR_THIS_USER
);
1143 if ( $this->mOldtext
=== false ) {
1147 if ( $this->mNewRev
) {
1148 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);
1149 if ( $this->mNewtext
=== false ) {
1157 * Load the text of the new revision, not the old one
1161 function loadNewText() {
1162 if ( $this->mTextLoaded
>= 1 ) {
1165 $this->mTextLoaded
= 1;
1167 if ( !$this->loadRevisionData() ) {
1170 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);