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;
33 var $mOldPage, $mNewPage, $mTitle;
34 var $mRcidMarkPatrolled;
39 var $mOldRev, $mNewRev;
40 var $mRevisionsLoaded = false; // Have the revisions been loaded
41 var $mTextLoaded = 0; // How many text blobs have been loaded, 0, 1 or 2?
42 var $mCacheHit = false; // Was the diff fetched from cache?
45 * Set this to true to add debug info to the HTML output.
46 * Warning: this may cause RSS readers to spuriously mark articles as "new"
49 var $enableDebugComment = false;
51 // If true, line X is not displayed when X is 1, for example to increase
52 // readability and conserve space with many small diffs.
53 protected $mReducedLineNumbers = false;
55 protected $unhide = false; # show rev_deleted content if allowed
60 * @param $titleObj Title object that the diff is associated with
61 * @param $old Integer old ID we want to show and diff with.
62 * @param $new String either 'prev' or 'next'.
63 * @param $rcid Integer ??? FIXME (default 0)
64 * @param $refreshCache boolean If set, refreshes the diff cache
65 * @param $unhide boolean If set, allow viewing deleted revs
67 function __construct( $titleObj = null, $old = 0, $new = 0, $rcid = 0,
68 $refreshCache = false, $unhide = false )
71 $this->mTitle
= $titleObj;
74 $this->mTitle
= $wgTitle; // @TODO: get rid of this
76 wfDebug( "DifferenceEngine old '$old' new '$new' rcid '$rcid'\n" );
78 # Default language in which the diff text is written.
79 $this->mDiffLang
= $this->mTitle
->getPageLanguage();
81 if ( 'prev' === $new ) {
82 # Show diff between revision $old and the previous one.
83 # Get previous one from DB.
84 $this->mNewid
= intval( $old );
85 $this->mOldid
= $this->mTitle
->getPreviousRevisionID( $this->mNewid
);
86 } elseif ( 'next' === $new ) {
87 # Show diff between revision $old and the next one.
88 # Get next one from DB.
89 $this->mOldid
= intval( $old );
90 $this->mNewid
= $this->mTitle
->getNextRevisionID( $this->mOldid
);
91 if ( false === $this->mNewid
) {
92 # if no result, NewId points to the newest old revision. The only newer
93 # revision is cur, which is "0".
97 $this->mOldid
= intval( $old );
98 $this->mNewid
= intval( $new );
99 wfRunHooks( 'NewDifferenceEngine', array( &$titleObj, &$this->mOldid
, &$this->mNewid
, $old, $new ) );
101 $this->mRcidMarkPatrolled
= intval( $rcid ); # force it to be an integer
102 $this->mRefreshCache
= $refreshCache;
103 $this->unhide
= $unhide;
109 function setReducedLineNumbers( $value = true ) {
110 $this->mReducedLineNumbers
= $value;
116 function getTitle() {
117 return $this->mTitle
;
123 function wasCacheHit() {
124 return $this->mCacheHit
;
130 function getOldid() {
131 return $this->mOldid
;
137 function getNewid() {
138 return $this->mNewid
;
142 * Look up a special:Undelete link to the given deleted revision id,
143 * as a workaround for being unable to load deleted diffs in currently.
145 * @param int $id revision ID
146 * @return mixed URL or false
148 function deletedLink( $id ) {
150 if ( $wgUser->isAllowed( 'deletedhistory' ) ) {
151 $dbr = wfGetDB( DB_SLAVE
);
152 $row = $dbr->selectRow('archive', '*',
153 array( 'ar_rev_id' => $id ),
156 $rev = Revision
::newFromArchiveRow( $row );
157 $title = Title
::makeTitleSafe( $row->ar_namespace
, $row->ar_title
);
158 return SpecialPage
::getTitleFor( 'Undelete' )->getFullURL( array(
159 'target' => $title->getPrefixedText(),
160 'timestamp' => $rev->getTimestamp()
168 * Build a wikitext link toward a deleted revision, if viewable.
170 * @param int $id revision ID
171 * @return string wikitext fragment
173 function deletedIdMarker( $id ) {
174 $link = $this->deletedLink( $id );
176 return "[$link $id]";
182 function showDiffPage( $diffOnly = false ) {
183 global $wgUser, $wgOut, $wgUseExternalEditor, $wgUseRCPatrol;
184 wfProfileIn( __METHOD__
);
186 # Allow frames except in certain special cases
187 $wgOut->allowClickjacking();
189 # If external diffs are enabled both globally and for the user,
190 # we'll use the application/x-external-editor interface to call
191 # an external diff tool like kompare, kdiff3, etc.
192 if ( $wgUseExternalEditor && $wgUser->getOption( 'externaldiff' ) ) {
193 global $wgServer, $wgScript, $wgLang;
195 header ( "Content-type: application/x-external-editor; charset=UTF-8" );
196 $url1 = $this->mTitle
->getFullURL( array(
198 'oldid' => $this->mOldid
200 $url2 = $this->mTitle
->getFullURL( array(
202 'oldid' => $this->mNewid
204 $special = $wgLang->getNsText( NS_SPECIAL
);
205 $control = <<<CONTROL
209 Script={$wgServer}{$wgScript}
210 Special namespace={$special}
222 wfProfileOut( __METHOD__
);
226 $wgOut->setArticleFlag( false );
227 if ( !$this->loadRevisionData() ) {
228 // Sounds like a deleted revision... Let's see what we can do.
229 $t = $this->mTitle
->getPrefixedText();
230 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ),
231 $this->deletedIdMarker( $this->mOldid
),
232 $this->deletedIdMarker( $this->mNewid
) );
233 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
234 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", "<span class='plainlinks'>$d</span>" );
235 wfProfileOut( __METHOD__
);
239 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
241 if ( $this->mNewRev
->isCurrent() ) {
242 $wgOut->setArticleFlag( true );
245 # mOldid is false if the difference engine is called with a "vague" query for
246 # a diff between a version V and its previous version V' AND the version V
247 # is the first version of that article. In that case, V' does not exist.
248 if ( $this->mOldid
=== false ) {
249 $this->showFirstRevision();
250 $this->renderNewRevision(); // should we respect $diffOnly here or not?
251 wfProfileOut( __METHOD__
);
255 $oldTitle = $this->mOldPage
->getPrefixedText();
256 $newTitle = $this->mNewPage
->getPrefixedText();
257 if ( $oldTitle == $newTitle ) {
258 $wgOut->setPageTitle( $newTitle );
260 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
262 if ( $this->mNewPage
->equals( $this->mOldPage
) ) {
263 $wgOut->setSubtitle( wfMsgExt( 'difference', array( 'parseinline' ) ) );
265 $wgOut->setSubtitle( wfMsgExt( 'difference-multipage', array( 'parseinline' ) ) );
267 $wgOut->setRobotPolicy( 'noindex,nofollow' );
269 if ( !$this->mOldPage
->userCanRead() ||
!$this->mNewPage
->userCanRead() ) {
270 $wgOut->loginToUse();
273 wfProfileOut( __METHOD__
);
277 $sk = $wgUser->getSkin();
278 if ( method_exists( $sk, 'suppressQuickbar' ) ) {
279 $sk->suppressQuickbar();
282 // Check if page is editable
283 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
284 if ( $editable && $this->mNewRev
->isCurrent() && $wgUser->isAllowed( 'rollback' ) ) {
285 $wgOut->preventClickjacking();
286 $rollback = '   ' . $sk->generateRollback( $this->mNewRev
);
291 // Prepare a change patrol link, if applicable
292 if ( $wgUseRCPatrol && $this->mTitle
->userCan( 'patrol' ) ) {
293 // If we've been given an explicit change identifier, use it; saves time
294 if ( $this->mRcidMarkPatrolled
) {
295 $rcid = $this->mRcidMarkPatrolled
;
296 $rc = RecentChange
::newFromId( $rcid );
297 // Already patrolled?
298 $rcid = is_object( $rc ) && !$rc->getAttribute( 'rc_patrolled' ) ?
$rcid : 0;
300 // Look for an unpatrolled change corresponding to this diff
301 $db = wfGetDB( DB_SLAVE
);
302 $change = RecentChange
::newFromConds(
304 // Redundant user,timestamp condition so we can use the existing index
305 'rc_user_text' => $this->mNewRev
->getRawUserText(),
306 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
307 'rc_this_oldid' => $this->mNewid
,
308 'rc_last_oldid' => $this->mOldid
,
313 if ( $change instanceof RecentChange
) {
314 $rcid = $change->mAttribs
['rc_id'];
315 $this->mRcidMarkPatrolled
= $rcid;
323 $wgOut->preventClickjacking();
324 $token = $wgUser->editToken( $rcid );
325 $patrol = ' <span class="patrollink">[' . $sk->link(
327 wfMsgHtml( 'markaspatrolleddiff' ),
330 'action' => 'markpatrolled',
346 # Carry over 'diffonly' param via navigation links
347 if ( $diffOnly != $wgUser->getBoolOption( 'diffonly' ) ) {
348 $query['diffonly'] = $diffOnly;
351 # Make "previous revision link"
352 $query['diff'] = 'prev';
353 $query['oldid'] = $this->mOldid
;
354 # Cascade unhide param in links for easy deletion browsing
355 if ( $this->unhide
) {
356 $query['unhide'] = 1;
358 if ( !$this->mOldRev
->getPrevious() ) {
359 $prevlink = ' ';
361 $prevlink = $sk->link(
363 wfMsgHtml( 'previousdiff' ),
365 'id' => 'differences-prevlink'
375 # Make "next revision link"
376 $query['diff'] = 'next';
377 $query['oldid'] = $this->mNewid
;
378 # Skip next link on the top revision
379 if ( $this->mNewRev
->isCurrent() ) {
380 $nextlink = ' ';
382 $nextlink = $sk->link(
384 wfMsgHtml( 'nextdiff' ),
386 'id' => 'differences-nextlink'
399 if ( $this->mOldRev
->isMinor() ) {
400 $oldminor = ChangesList
::flag( 'minor' );
402 if ( $this->mNewRev
->isMinor() ) {
403 $newminor = ChangesList
::flag( 'minor' );
406 # Handle RevisionDelete links...
407 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
408 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
410 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $this->mOldtitle
. '</strong></div>' .
411 '<div id="mw-diff-otitle2">' .
412 $sk->revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
413 '<div id="mw-diff-otitle3">' . $oldminor .
414 $sk->revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
415 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
416 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $this->mNewtitle
. '</strong></div>' .
417 '<div id="mw-diff-ntitle2">' . $sk->revUserTools( $this->mNewRev
, !$this->unhide
) .
419 '<div id="mw-diff-ntitle3">' . $newminor .
420 $sk->revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
421 '<div id="mw-diff-ntitle4">' . $nextlink . $patrol . '</div>';
423 # Check if this user can see the revisions
424 $allowed = $this->mOldRev
->userCan( Revision
::DELETED_TEXT
)
425 && $this->mNewRev
->userCan( Revision
::DELETED_TEXT
);
426 # Check if one of the revisions is deleted/suppressed
427 $deleted = $suppressed = false;
428 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
429 $deleted = true; // old revisions text is hidden
430 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
431 $suppressed = true; // also suppressed
433 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
434 $deleted = true; // new revisions text is hidden
435 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
436 $suppressed = true; // also suppressed
438 # If the diff cannot be shown due to a deleted revision, then output
439 # the diff header and links to unhide (if available)...
440 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
441 $this->showDiffStyle();
442 $multi = $this->getMultiNotice();
443 $wgOut->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
445 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
446 # Give explanation for why revision is not visible
447 $wgOut->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
450 # Give explanation and add a link to view the diff...
451 $link = $this->mTitle
->getFullUrl( array(
452 'diff' => $this->mNewid
,
453 'oldid' => $this->mOldid
,
456 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
457 $wgOut->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n", array( $msg, $link ) );
459 # Otherwise, output a regular diff...
461 # Add deletion notice if the user is viewing deleted content
464 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
465 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" . wfMsgExt( $msg, 'parseinline' ) . "</div>\n";
467 $this->showDiff( $oldHeader, $newHeader, $notice );
469 $this->renderNewRevision();
472 wfProfileOut( __METHOD__
);
476 * @param $rev Revision
479 protected function revisionDeleteLink( $rev ) {
482 $canHide = $wgUser->isAllowed( 'deleterevision' );
483 // Show del/undel link if:
484 // (a) the user can delete revisions, or
485 // (b) the user can view deleted revision *and* this one is deleted
486 if ( $canHide ||
( $rev->getVisibility() && $wgUser->isAllowed( 'deletedhistory' ) ) ) {
487 $sk = $wgUser->getSkin();
488 if ( !$rev->userCan( Revision
::DELETED_RESTRICTED
) ) {
489 $link = $sk->revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
492 'type' => 'revision',
493 'target' => $rev->mTitle
->getPrefixedDbkey(),
494 'ids' => $rev->getId()
496 $link = $sk->revDeleteLink( $query,
497 $rev->isDeleted( Revision
::DELETED_RESTRICTED
), $canHide );
499 $link = '   ' . $link . ' ';
505 * Show the new revision of the page.
507 function renderNewRevision() {
508 global $wgOut, $wgUser;
509 wfProfileIn( __METHOD__
);
510 # Add "current version as of X" title
511 $wgOut->addHTML( "<hr class='diff-hr' />
512 <h2 class='diff-currentversion-title'>{$this->mPagetitle}</h2>\n" );
513 # Page content may be handled by a hooked call instead...
514 if ( wfRunHooks( 'ArticleContentOnDiff', array( $this, $wgOut ) ) ) {
515 # Use the current version parser cache if applicable
517 if ( !$this->mNewRev
->isCurrent() ) {
518 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
522 $this->loadNewText();
523 $wgOut->setRevisionId( $this->mNewRev
->getId() );
525 if ( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
526 // Stolen from Article::view --AG 2007-10-11
527 // Give hooks a chance to customise the output
528 // @TODO: standardize this crap into one function
529 if ( wfRunHooks( 'ShowRawCssJs', array( $this->mNewtext
, $this->mTitle
, $wgOut ) ) ) {
530 // Wrap the whole lot in a <pre> and don't parse
532 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
533 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
534 $wgOut->addHTML( htmlspecialchars( $this->mNewtext
) );
535 $wgOut->addHTML( "\n</pre>\n" );
537 } elseif ( $pCache ) {
538 $article = new Article( $this->mTitle
, 0 );
539 $pOutput = ParserCache
::singleton()->get( $article, $wgOut->parserOptions() );
541 $wgOut->addParserOutput( $pOutput );
543 $article->doViewParse();
546 $wgOut->addWikiTextTidy( $this->mNewtext
);
549 if ( !$this->mNewRev
->isCurrent() ) {
550 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
553 # Add redundant patrol link on bottom...
554 if ( $this->mRcidMarkPatrolled
&& $this->mTitle
->quickUserCan( 'patrol' ) ) {
555 $sk = $wgUser->getSkin();
556 $token = $wgUser->editToken( $this->mRcidMarkPatrolled
);
557 $wgOut->preventClickjacking();
559 "<div class='patrollink'>[" . $sk->link(
561 wfMsgHtml( 'markaspatrolleddiff' ),
564 'action' => 'markpatrolled',
565 'rcid' => $this->mRcidMarkPatrolled
,
572 wfProfileOut( __METHOD__
);
576 * Show the first revision of an article. Uses normal diff headers in
577 * contrast to normal "old revision" display style.
579 function showFirstRevision() {
580 global $wgOut, $wgUser;
581 wfProfileIn( __METHOD__
);
583 # Get article text from the DB
585 if ( ! $this->loadNewText() ) {
586 $t = $this->mTitle
->getPrefixedText();
587 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ),
588 $this->deletedIdMarker( $this->mOldid
),
589 $this->deletedIdMarker( $this->mNewid
) );
590 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
591 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", "<span class='plainlinks'>$d</span>" );
592 wfProfileOut( __METHOD__
);
595 if ( $this->mNewRev
->isCurrent() ) {
596 $wgOut->setArticleFlag( true );
599 # Check if user is allowed to look at this page. If not, bail out.
601 if ( !$this->mTitle
->userCanRead() ) {
602 $wgOut->loginToUse();
604 wfProfileOut( __METHOD__
);
605 throw new MWException( "Permission Error: you do not have access to view this page" );
608 # Prepare the header box
610 $sk = $wgUser->getSkin();
612 $next = $this->mTitle
->getNextRevisionID( $this->mNewid
);
616 $nextlink = '<br />' . $sk->link(
618 wfMsgHtml( 'nextdiff' ),
620 'id' => 'differences-nextlink'
624 'oldid' => $this->mNewid
,
632 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\">" .
633 $sk->revUserTools( $this->mNewRev
) . "<br />" . $sk->revComment( $this->mNewRev
) . $nextlink . "</div>\n";
635 $wgOut->addHTML( $header );
637 $wgOut->setSubtitle( wfMsgExt( 'difference', array( 'parseinline' ) ) );
638 $wgOut->setRobotPolicy( 'noindex,nofollow' );
640 wfProfileOut( __METHOD__
);
644 * Get the diff text, send it to $wgOut
645 * Returns false if the diff could not be generated, otherwise returns true
649 function showDiff( $otitle, $ntitle, $notice = '' ) {
651 $diff = $this->getDiff( $otitle, $ntitle, $notice );
652 if ( $diff === false ) {
653 $wgOut->addWikiMsg( 'missing-article', "<nowiki>(fixme, bug)</nowiki>", '' );
656 $this->showDiffStyle();
657 $wgOut->addHTML( $diff );
663 * Add style sheets and supporting JS for diff display.
665 function showDiffStyle() {
667 $wgOut->addModuleStyles( 'mediawiki.action.history.diff' );
671 * Get complete diff table, including header
673 * @param $otitle Title: old title
674 * @param $ntitle Title: new title
675 * @param $notice String: HTML between diff header and body
678 function getDiff( $otitle, $ntitle, $notice = '' ) {
679 $body = $this->getDiffBody();
680 if ( $body === false ) {
683 $multi = $this->getMultiNotice();
684 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
689 * Get the diff table body, without header
691 * @return mixed (string/false)
693 public function getDiffBody() {
695 wfProfileIn( __METHOD__
);
696 $this->mCacheHit
= true;
697 // Check if the diff should be hidden from this user
698 if ( !$this->loadRevisionData() ) {
699 wfProfileOut( __METHOD__
);
701 } elseif ( $this->mOldRev
&& !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
) ) {
702 wfProfileOut( __METHOD__
);
704 } elseif ( $this->mNewRev
&& !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
) ) {
705 wfProfileOut( __METHOD__
);
709 if ( $this->mOldRev
&& $this->mNewRev
710 && $this->mOldRev
->getID() == $this->mNewRev
->getID() )
712 wfProfileOut( __METHOD__
);
717 if ( $this->mOldid
&& $this->mNewid
) {
718 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
,
719 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
721 if ( !$this->mRefreshCache
) {
722 $difftext = $wgMemc->get( $key );
724 wfIncrStats( 'diff_cache_hit' );
725 $difftext = $this->localiseLineNumbers( $difftext );
726 $difftext .= "\n<!-- diff cache key $key -->\n";
727 wfProfileOut( __METHOD__
);
730 } // don't try to load but save the result
732 $this->mCacheHit
= false;
734 // Loadtext is permission safe, this just clears out the diff
735 if ( !$this->loadText() ) {
736 wfProfileOut( __METHOD__
);
740 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
742 // Save to cache for 7 days
743 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
744 wfIncrStats( 'diff_uncacheable' );
745 } elseif ( $key !== false && $difftext !== false ) {
746 wfIncrStats( 'diff_cache_miss' );
747 $wgMemc->set( $key, $difftext, 7 * 86400 );
749 wfIncrStats( 'diff_uncacheable' );
751 // Replace line numbers with the text in the user's language
752 if ( $difftext !== false ) {
753 $difftext = $this->localiseLineNumbers( $difftext );
755 wfProfileOut( __METHOD__
);
760 * Make sure the proper modules are loaded before we try to
763 private function initDiffEngines() {
764 global $wgExternalDiffEngine;
765 if ( $wgExternalDiffEngine == 'wikidiff' && !function_exists( 'wikidiff_do_diff' ) ) {
766 wfProfileIn( __METHOD__
. '-php_wikidiff.so' );
767 wfDl( 'php_wikidiff' );
768 wfProfileOut( __METHOD__
. '-php_wikidiff.so' );
770 elseif ( $wgExternalDiffEngine == 'wikidiff2' && !function_exists( 'wikidiff2_do_diff' ) ) {
771 wfProfileIn( __METHOD__
. '-php_wikidiff2.so' );
773 wfProfileOut( __METHOD__
. '-php_wikidiff2.so' );
778 * Generate a diff, no caching
780 * @param $otext String: old text, must be already segmented
781 * @param $ntext String: new text, must be already segmented
783 function generateDiffBody( $otext, $ntext ) {
784 global $wgExternalDiffEngine, $wgContLang;
786 wfProfileIn( __METHOD__
);
788 $otext = str_replace( "\r\n", "\n", $otext );
789 $ntext = str_replace( "\r\n", "\n", $ntext );
791 $this->initDiffEngines();
793 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
794 # For historical reasons, external diff engine expects
795 # input text to be HTML-escaped already
796 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
797 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
798 wfProfileOut( __METHOD__
);
799 return $wgContLang->unsegmentForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
800 $this->debug( 'wikidiff1' );
803 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
804 # Better external diff engine, the 2 may some day be dropped
805 # This one does the escaping and segmenting itself
806 wfProfileIn( 'wikidiff2_do_diff' );
807 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
808 $text .= $this->debug( 'wikidiff2' );
809 wfProfileOut( 'wikidiff2_do_diff' );
810 wfProfileOut( __METHOD__
);
813 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
815 global $wgTmpDirectory;
816 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
817 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
819 $tempFile1 = fopen( $tempName1, "w" );
821 wfProfileOut( __METHOD__
);
824 $tempFile2 = fopen( $tempName2, "w" );
826 wfProfileOut( __METHOD__
);
829 fwrite( $tempFile1, $otext );
830 fwrite( $tempFile2, $ntext );
831 fclose( $tempFile1 );
832 fclose( $tempFile2 );
833 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
834 wfProfileIn( __METHOD__
. "-shellexec" );
835 $difftext = wfShellExec( $cmd );
836 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
837 wfProfileOut( __METHOD__
. "-shellexec" );
838 unlink( $tempName1 );
839 unlink( $tempName2 );
840 wfProfileOut( __METHOD__
);
845 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
846 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
847 $diffs = new Diff( $ota, $nta );
848 $formatter = new TableDiffFormatter();
849 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
850 wfProfileOut( __METHOD__
);
855 * Generate a debug comment indicating diff generating time,
856 * server node, and generator backend.
858 protected function debug( $generator = "internal" ) {
859 global $wgShowHostnames;
860 if ( !$this->enableDebugComment
) {
863 $data = array( $generator );
864 if ( $wgShowHostnames ) {
865 $data[] = wfHostname();
867 $data[] = wfTimestamp( TS_DB
);
868 return "<!-- diff generator: " .
877 * Replace line numbers with the text in the user's language
879 function localiseLineNumbers( $text ) {
880 return preg_replace_callback( '/<!--LINE (\d+)-->/',
881 array( &$this, 'localiseLineNumbersCb' ), $text );
884 function localiseLineNumbersCb( $matches ) {
886 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) return '';
887 return wfMsgExt( 'lineno', 'escape', $wgLang->formatNum( $matches[1] ) );
892 * If there are revisions between the ones being compared, return a note saying so.
895 function getMultiNotice() {
896 if ( !is_object( $this->mOldRev
) ||
!is_object( $this->mNewRev
) ) {
898 } elseif ( !$this->mOldPage
->equals( $this->mNewPage
) ) {
899 // Comparing two different pages? Count would be meaningless.
903 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
904 $oldRev = $this->mNewRev
; // flip
905 $newRev = $this->mOldRev
; // flip
906 } else { // normal case
907 $oldRev = $this->mOldRev
;
908 $newRev = $this->mNewRev
;
911 $nEdits = $this->mTitle
->countRevisionsBetween( $oldRev, $newRev );
913 $limit = 100; // use diff-multi-manyusers if too many users
914 $numUsers = $this->mTitle
->countAuthorsBetween( $oldRev, $newRev, $limit );
915 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
917 return ''; // nothing
921 * Get a notice about how many intermediate edits and users there are
922 * @param $numEdits int
923 * @param $numUsers int
927 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
929 if ( $numUsers > $limit ) {
930 $msg = 'diff-multi-manyusers';
935 return wfMsgExt( $msg, 'parseinline',
936 $wgLang->formatnum( $numEdits ), $wgLang->formatnum( $numUsers ) );
940 * Add the header to a diff body
944 function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
945 // shared.css sets diff in interface language/dir, but the actual content
946 // is often in a different language, mostly the page content language/dir
947 $tableClass = 'diff diff-contentalign-' . htmlspecialchars( $this->mDiffLang
->alignStart() );
948 $header = "<table class='$tableClass'>";
949 if ( $diff ) { // Safari/Chrome show broken output if cols not used
951 <col class='diff-marker' />
952 <col class='diff-content' />
953 <col class='diff-marker' />
954 <col class='diff-content' />";
963 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
964 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
967 if ( $multi != '' ) {
968 $header .= "<tr><td colspan='{$multiColspan}' align='center' class='diff-multi'>{$multi}</td></tr>";
970 if ( $notice != '' ) {
971 $header .= "<tr><td colspan='{$multiColspan}' align='center'>{$notice}</td></tr>";
974 return $header . $diff . "</table>";
978 * Use specified text instead of loading from the database
980 function setText( $oldText, $newText ) {
981 $this->mOldtext
= $oldText;
982 $this->mNewtext
= $newText;
983 $this->mTextLoaded
= 2;
984 $this->mRevisionsLoaded
= true;
988 * Set the language in which the diff text is written
989 * (Defaults to page content language).
992 function setDiffLang( $lang ) {
993 $this->mDiffLang
= wfGetLangObj( $lang );
997 * Load revision metadata for the specified articles. If newid is 0, then compare
998 * the old article in oldid to the current article; if oldid is 0, then
999 * compare the current article to the immediately previous one (ignoring the
1002 * If oldid is false, leave the corresponding revision object set
1003 * to false. This is impossible via ordinary user input, and is provided for
1008 function loadRevisionData() {
1009 global $wgLang, $wgUser;
1010 if ( $this->mRevisionsLoaded
) {
1013 // Whether it succeeds or fails, we don't want to try again
1014 $this->mRevisionsLoaded
= true;
1017 // Load the new revision object
1018 $this->mNewRev
= $this->mNewid
1019 ? Revision
::newFromId( $this->mNewid
)
1020 : Revision
::newFromTitle( $this->mTitle
);
1021 if ( !$this->mNewRev
instanceof Revision
) {
1025 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1026 $this->mNewid
= $this->mNewRev
->getId();
1028 // Check if page is editable
1029 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
1031 // Set assorted variables
1032 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
1033 $dateofrev = $wgLang->date( $this->mNewRev
->getTimestamp(), true );
1034 $timeofrev = $wgLang->time( $this->mNewRev
->getTimestamp(), true );
1035 $this->mNewPage
= $this->mNewRev
->getTitle();
1036 if ( $this->mNewRev
->isCurrent() ) {
1037 $newLink = $this->mNewPage
->escapeLocalUrl( array(
1038 'oldid' => $this->mNewid
1040 $this->mPagetitle
= htmlspecialchars( wfMsg(
1046 $newEdit = $this->mNewPage
->escapeLocalUrl( array(
1050 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
1051 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
1053 $newLink = $this->mNewPage
->escapeLocalUrl( array(
1054 'oldid' => $this->mNewid
1056 $newEdit = $this->mNewPage
->escapeLocalUrl( array(
1058 'oldid' => $this->mNewid
1060 $this->mPagetitle
= htmlspecialchars( wfMsg(
1067 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
1068 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
1070 if ( !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
) ) {
1071 $this->mNewtitle
= "<span class='history-deleted'>{$this->mPagetitle}</span>";
1072 } elseif ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
1073 $this->mNewtitle
= "<span class='history-deleted'>{$this->mNewtitle}</span>";
1076 // Load the old revision object
1077 $this->mOldRev
= false;
1078 if ( $this->mOldid
) {
1079 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1080 } elseif ( $this->mOldid
=== 0 ) {
1081 $rev = $this->mNewRev
->getPrevious();
1083 $this->mOldid
= $rev->getId();
1084 $this->mOldRev
= $rev;
1086 // No previous revision; mark to show as first-version only.
1087 $this->mOldid
= false;
1088 $this->mOldRev
= false;
1090 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1092 if ( is_null( $this->mOldRev
) ) {
1096 if ( $this->mOldRev
) {
1097 $this->mOldPage
= $this->mOldRev
->getTitle();
1099 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
1100 $dateofrev = $wgLang->date( $this->mOldRev
->getTimestamp(), true );
1101 $timeofrev = $wgLang->time( $this->mOldRev
->getTimestamp(), true );
1102 $oldLink = $this->mOldPage
->escapeLocalUrl( array(
1103 'oldid' => $this->mOldid
1105 $oldEdit = $this->mOldPage
->escapeLocalUrl( array(
1107 'oldid' => $this->mOldid
1109 $this->mOldPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t, $dateofrev, $timeofrev ) );
1111 $this->mOldtitle
= "<a href='$oldLink'>{$this->mOldPagetitle}</a>"
1112 . " (<a href='$oldEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
1113 // Add an "undo" link
1114 if ( $editable && !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
1115 $undoLink = Html
::element( 'a', array(
1116 'href' => $this->mNewPage
->getLocalUrl( array(
1118 'undoafter' => $this->mOldid
,
1119 'undo' => $this->mNewid
) ),
1120 'title' => $wgUser->getSkin()->titleAttrib( 'undo' )
1121 ), wfMsg( 'editundo' ) );
1122 $this->mNewtitle
.= ' (' . $undoLink . ')';
1125 if ( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
) ) {
1126 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldPagetitle
. '</span>';
1127 } elseif ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
1128 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldtitle
. '</span>';
1136 * Load the text of the revisions, as well as revision data.
1140 function loadText() {
1141 if ( $this->mTextLoaded
== 2 ) {
1144 // Whether it succeeds or fails, we don't want to try again
1145 $this->mTextLoaded
= 2;
1148 if ( !$this->loadRevisionData() ) {
1151 if ( $this->mOldRev
) {
1152 $this->mOldtext
= $this->mOldRev
->getText( Revision
::FOR_THIS_USER
);
1153 if ( $this->mOldtext
=== false ) {
1157 if ( $this->mNewRev
) {
1158 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);
1159 if ( $this->mNewtext
=== false ) {
1167 * Load the text of the new revision, not the old one
1171 function loadNewText() {
1172 if ( $this->mTextLoaded
>= 1 ) {
1175 $this->mTextLoaded
= 1;
1177 if ( !$this->loadRevisionData() ) {
1180 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);