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;
102 function setReducedLineNumbers( $value = true ) {
103 $this->mReducedLineNumbers
= $value;
106 function getTitle() {
107 return $this->mTitle
;
110 function wasCacheHit() {
111 return $this->mCacheHit
;
114 function getOldid() {
115 return $this->mOldid
;
118 function getNewid() {
119 return $this->mNewid
;
123 * Look up a special:Undelete link to the given deleted revision id,
124 * as a workaround for being unable to load deleted diffs in currently.
126 * @param int $id revision ID
127 * @return mixed URL or false
129 function deletedLink( $id ) {
131 if ( $wgUser->isAllowed( 'deletedhistory' ) ) {
132 $dbr = wfGetDB( DB_SLAVE
);
133 $row = $dbr->selectRow('archive', '*',
134 array( 'ar_rev_id' => $id ),
137 $rev = Revision
::newFromArchiveRow( $row );
138 $title = Title
::makeTitleSafe( $row->ar_namespace
, $row->ar_title
);
139 return SpecialPage
::getTitleFor( 'Undelete' )->getFullURL( array(
140 'target' => $title->getPrefixedText(),
141 'timestamp' => $rev->getTimestamp()
149 * Build a wikitext link toward a deleted revision, if viewable.
151 * @param int $id revision ID
152 * @return string wikitext fragment
154 function deletedIdMarker( $id ) {
155 $link = $this->deletedLink( $id );
157 return "[$link $id]";
163 function showDiffPage( $diffOnly = false ) {
164 global $wgUser, $wgOut, $wgUseExternalEditor, $wgUseRCPatrol;
165 wfProfileIn( __METHOD__
);
167 # Allow frames except in certain special cases
168 $wgOut->allowClickjacking();
170 # If external diffs are enabled both globally and for the user,
171 # we'll use the application/x-external-editor interface to call
172 # an external diff tool like kompare, kdiff3, etc.
173 if ( $wgUseExternalEditor && $wgUser->getOption( 'externaldiff' ) ) {
174 global $wgServer, $wgScript, $wgLang;
176 header ( "Content-type: application/x-external-editor; charset=UTF-8" );
177 $url1 = $this->mTitle
->getFullURL( array(
179 'oldid' => $this->mOldid
181 $url2 = $this->mTitle
->getFullURL( array(
183 'oldid' => $this->mNewid
185 $special = $wgLang->getNsText( NS_SPECIAL
);
186 $control = <<<CONTROL
190 Script={$wgServer}{$wgScript}
191 Special namespace={$special}
203 wfProfileOut( __METHOD__
);
207 $wgOut->setArticleFlag( false );
208 if ( !$this->loadRevisionData() ) {
209 // Sounds like a deleted revision... Let's see what we can do.
210 $deletedLink = $this->deletedLink( $this->mNewid
);
212 $t = $this->mTitle
->getPrefixedText();
213 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ),
214 $this->deletedIdMarker( $this->mOldid
),
215 $this->deletedIdMarker( $this->mNewid
) );
216 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
217 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", "<span class='plainlinks'>$d</span>" );
218 wfProfileOut( __METHOD__
);
222 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
224 if ( $this->mNewRev
->isCurrent() ) {
225 $wgOut->setArticleFlag( true );
228 # mOldid is false if the difference engine is called with a "vague" query for
229 # a diff between a version V and its previous version V' AND the version V
230 # is the first version of that article. In that case, V' does not exist.
231 if ( $this->mOldid
=== false ) {
232 $this->showFirstRevision();
233 $this->renderNewRevision(); // should we respect $diffOnly here or not?
234 wfProfileOut( __METHOD__
);
238 $oldTitle = $this->mOldPage
->getPrefixedText();
239 $newTitle = $this->mNewPage
->getPrefixedText();
240 if ( $oldTitle == $newTitle ) {
241 $wgOut->setPageTitle( $newTitle );
243 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
245 if ( $this->mNewPage
->equals( $this->mOldPage
) ) {
246 $wgOut->setSubtitle( wfMsgExt( 'difference', array( 'parseinline' ) ) );
248 $wgOut->setSubtitle( wfMsgExt( 'difference-multipage', array( 'parseinline' ) ) );
250 $wgOut->setRobotPolicy( 'noindex,nofollow' );
252 if ( !$this->mOldPage
->userCanRead() ||
!$this->mNewPage
->userCanRead() ) {
253 $wgOut->loginToUse();
256 wfProfileOut( __METHOD__
);
260 $sk = $wgUser->getSkin();
261 if ( method_exists( $sk, 'suppressQuickbar' ) ) {
262 $sk->suppressQuickbar();
265 // Check if page is editable
266 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
267 if ( $editable && $this->mNewRev
->isCurrent() && $wgUser->isAllowed( 'rollback' ) ) {
268 $wgOut->preventClickjacking();
269 $rollback = '   ' . $sk->generateRollback( $this->mNewRev
);
274 // Prepare a change patrol link, if applicable
275 if ( $wgUseRCPatrol && $this->mTitle
->userCan( 'patrol' ) ) {
276 // If we've been given an explicit change identifier, use it; saves time
277 if ( $this->mRcidMarkPatrolled
) {
278 $rcid = $this->mRcidMarkPatrolled
;
279 $rc = RecentChange
::newFromId( $rcid );
280 // Already patrolled?
281 $rcid = is_object( $rc ) && !$rc->getAttribute( 'rc_patrolled' ) ?
$rcid : 0;
283 // Look for an unpatrolled change corresponding to this diff
284 $db = wfGetDB( DB_SLAVE
);
285 $change = RecentChange
::newFromConds(
287 // Redundant user,timestamp condition so we can use the existing index
288 'rc_user_text' => $this->mNewRev
->getRawUserText(),
289 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
290 'rc_this_oldid' => $this->mNewid
,
291 'rc_last_oldid' => $this->mOldid
,
296 if ( $change instanceof RecentChange
) {
297 $rcid = $change->mAttribs
['rc_id'];
298 $this->mRcidMarkPatrolled
= $rcid;
306 $wgOut->preventClickjacking();
307 $token = $wgUser->editToken( $rcid );
308 $patrol = ' <span class="patrollink">[' . $sk->link(
310 wfMsgHtml( 'markaspatrolleddiff' ),
313 'action' => 'markpatrolled',
329 # Carry over 'diffonly' param via navigation links
330 if ( $diffOnly != $wgUser->getBoolOption( 'diffonly' ) ) {
331 $query['diffonly'] = $diffOnly;
334 # Make "previous revision link"
335 $query['diff'] = 'prev';
336 $query['oldid'] = $this->mOldid
;
337 # Cascade unhide param in links for easy deletion browsing
338 if ( $this->unhide
) {
339 $query['unhide'] = 1;
341 if ( !$this->mOldRev
->getPrevious() ) {
342 $prevlink = ' ';
344 $prevlink = $sk->link(
346 wfMsgHtml( 'previousdiff' ),
348 'id' => 'differences-prevlink'
358 # Make "next revision link"
359 $query['diff'] = 'next';
360 $query['oldid'] = $this->mNewid
;
361 # Skip next link on the top revision
362 if ( $this->mNewRev
->isCurrent() ) {
363 $nextlink = ' ';
365 $nextlink = $sk->link(
367 wfMsgHtml( 'nextdiff' ),
369 'id' => 'differences-nextlink'
382 if ( $this->mOldRev
->isMinor() ) {
383 $oldminor = ChangesList
::flag( 'minor' );
385 if ( $this->mNewRev
->isMinor() ) {
386 $newminor = ChangesList
::flag( 'minor' );
389 # Handle RevisionDelete links...
390 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
391 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
393 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $this->mOldtitle
. '</strong></div>' .
394 '<div id="mw-diff-otitle2">' .
395 $sk->revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
396 '<div id="mw-diff-otitle3">' . $oldminor .
397 $sk->revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
398 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
399 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $this->mNewtitle
. '</strong></div>' .
400 '<div id="mw-diff-ntitle2">' . $sk->revUserTools( $this->mNewRev
, !$this->unhide
) .
402 '<div id="mw-diff-ntitle3">' . $newminor .
403 $sk->revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
404 '<div id="mw-diff-ntitle4">' . $nextlink . $patrol . '</div>';
406 # Check if this user can see the revisions
407 $allowed = $this->mOldRev
->userCan( Revision
::DELETED_TEXT
)
408 && $this->mNewRev
->userCan( Revision
::DELETED_TEXT
);
409 # Check if one of the revisions is deleted/suppressed
410 $deleted = $suppressed = false;
411 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
412 $deleted = true; // old revisions text is hidden
413 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
414 $suppressed = true; // also suppressed
416 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
417 $deleted = true; // new revisions text is hidden
418 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
419 $suppressed = true; // also suppressed
421 # If the diff cannot be shown due to a deleted revision, then output
422 # the diff header and links to unhide (if available)...
423 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
424 $this->showDiffStyle();
425 $multi = $this->getMultiNotice();
426 $wgOut->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
428 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
429 # Give explanation for why revision is not visible
430 $wgOut->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
433 # Give explanation and add a link to view the diff...
434 $link = $this->mTitle
->getFullUrl( array(
435 'diff' => $this->mNewid
,
436 'oldid' => $this->mOldid
,
439 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
440 $wgOut->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n", array( $msg, $link ) );
442 # Otherwise, output a regular diff...
444 # Add deletion notice if the user is viewing deleted content
447 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
448 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" . wfMsgExt( $msg, 'parseinline' ) . "</div>\n";
450 $this->showDiff( $oldHeader, $newHeader, $notice );
452 $this->renderNewRevision();
455 wfProfileOut( __METHOD__
);
459 * @param $rev Revision
462 protected function revisionDeleteLink( $rev ) {
465 $canHide = $wgUser->isAllowed( 'deleterevision' );
466 // Show del/undel link if:
467 // (a) the user can delete revisions, or
468 // (b) the user can view deleted revision *and* this one is deleted
469 if ( $canHide ||
( $rev->getVisibility() && $wgUser->isAllowed( 'deletedhistory' ) ) ) {
470 $sk = $wgUser->getSkin();
471 if ( !$rev->userCan( Revision
::DELETED_RESTRICTED
) ) {
472 $link = $sk->revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
475 'type' => 'revision',
476 'target' => $rev->mTitle
->getPrefixedDbkey(),
477 'ids' => $rev->getId()
479 $link = $sk->revDeleteLink( $query,
480 $rev->isDeleted( Revision
::DELETED_RESTRICTED
), $canHide );
482 $link = '   ' . $link . ' ';
488 * Show the new revision of the page.
490 function renderNewRevision() {
491 global $wgOut, $wgUser;
492 wfProfileIn( __METHOD__
);
493 # Add "current version as of X" title
494 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
495 # Page content may be handled by a hooked call instead...
496 if ( wfRunHooks( 'ArticleContentOnDiff', array( $this, $wgOut ) ) ) {
497 # Use the current version parser cache if applicable
499 if ( !$this->mNewRev
->isCurrent() ) {
500 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
504 $this->loadNewText();
505 $wgOut->setRevisionId( $this->mNewRev
->getId() );
507 if ( $this->mTitle
->isCssJsSubpage() ||
$this->mTitle
->isCssOrJsPage() ) {
508 // Stolen from Article::view --AG 2007-10-11
509 // Give hooks a chance to customise the output
510 // @TODO: standardize this crap into one function
511 if ( wfRunHooks( 'ShowRawCssJs', array( $this->mNewtext
, $this->mTitle
, $wgOut ) ) ) {
512 // Wrap the whole lot in a <pre> and don't parse
514 preg_match( '!\.(css|js)$!u', $this->mTitle
->getText(), $m );
515 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
516 $wgOut->addHTML( htmlspecialchars( $this->mNewtext
) );
517 $wgOut->addHTML( "\n</pre>\n" );
519 } elseif ( $pCache ) {
520 $article = new Article( $this->mTitle
, 0 );
521 $pOutput = ParserCache
::singleton()->get( $article, $wgOut->parserOptions() );
523 $wgOut->addParserOutput( $pOutput );
525 $article->doViewParse();
528 $wgOut->addWikiTextTidy( $this->mNewtext
);
531 if ( !$this->mNewRev
->isCurrent() ) {
532 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
535 # Add redundant patrol link on bottom...
536 if ( $this->mRcidMarkPatrolled
&& $this->mTitle
->quickUserCan( 'patrol' ) ) {
537 $sk = $wgUser->getSkin();
538 $token = $wgUser->editToken( $this->mRcidMarkPatrolled
);
539 $wgOut->preventClickjacking();
541 "<div class='patrollink'>[" . $sk->link(
543 wfMsgHtml( 'markaspatrolleddiff' ),
546 'action' => 'markpatrolled',
547 'rcid' => $this->mRcidMarkPatrolled
,
554 wfProfileOut( __METHOD__
);
558 * Show the first revision of an article. Uses normal diff headers in
559 * contrast to normal "old revision" display style.
561 function showFirstRevision() {
562 global $wgOut, $wgUser;
563 wfProfileIn( __METHOD__
);
565 # Get article text from the DB
567 if ( ! $this->loadNewText() ) {
568 $t = $this->mTitle
->getPrefixedText();
569 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ),
570 $this->deletedIdMarker( $this->mOldid
),
571 $this->deletedIdMarker( $this->mNewid
) );
572 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
573 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", "<span class='plainlinks'>$d</span>" );
574 wfProfileOut( __METHOD__
);
577 if ( $this->mNewRev
->isCurrent() ) {
578 $wgOut->setArticleFlag( true );
581 # Check if user is allowed to look at this page. If not, bail out.
583 if ( !$this->mTitle
->userCanRead() ) {
584 $wgOut->loginToUse();
586 wfProfileOut( __METHOD__
);
587 throw new MWException( "Permission Error: you do not have access to view this page" );
590 # Prepare the header box
592 $sk = $wgUser->getSkin();
594 $next = $this->mTitle
->getNextRevisionID( $this->mNewid
);
598 $nextlink = '<br />' . $sk->link(
600 wfMsgHtml( 'nextdiff' ),
602 'id' => 'differences-nextlink'
606 'oldid' => $this->mNewid
,
614 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\">" .
615 $sk->revUserTools( $this->mNewRev
) . "<br />" . $sk->revComment( $this->mNewRev
) . $nextlink . "</div>\n";
617 $wgOut->addHTML( $header );
619 $wgOut->setSubtitle( wfMsgExt( 'difference', array( 'parseinline' ) ) );
620 $wgOut->setRobotPolicy( 'noindex,nofollow' );
622 wfProfileOut( __METHOD__
);
626 * Get the diff text, send it to $wgOut
627 * Returns false if the diff could not be generated, otherwise returns true
629 function showDiff( $otitle, $ntitle, $notice = '' ) {
631 $diff = $this->getDiff( $otitle, $ntitle, $notice );
632 if ( $diff === false ) {
633 $wgOut->addWikiMsg( 'missing-article', "<nowiki>(fixme, bug)</nowiki>", '' );
636 $this->showDiffStyle();
637 $wgOut->addHTML( $diff );
643 * Add style sheets and supporting JS for diff display.
645 function showDiffStyle() {
647 $wgOut->addModuleStyles( 'mediawiki.legacy.diff' );
651 * Get complete diff table, including header
653 * @param $otitle Title: old title
654 * @param $ntitle Title: new title
655 * @param $notice String: HTML between diff header and body
658 function getDiff( $otitle, $ntitle, $notice = '' ) {
659 $body = $this->getDiffBody();
660 if ( $body === false ) {
663 $multi = $this->getMultiNotice();
664 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
669 * Get the diff table body, without header
671 * @return mixed (string/false)
673 public function getDiffBody() {
675 wfProfileIn( __METHOD__
);
676 $this->mCacheHit
= true;
677 // Check if the diff should be hidden from this user
678 if ( !$this->loadRevisionData() ) {
679 wfProfileOut( __METHOD__
);
681 } elseif ( $this->mOldRev
&& !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
) ) {
682 wfProfileOut( __METHOD__
);
684 } elseif ( $this->mNewRev
&& !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
) ) {
685 wfProfileOut( __METHOD__
);
689 if ( $this->mOldRev
&& $this->mNewRev
690 && $this->mOldRev
->getID() == $this->mNewRev
->getID() )
692 wfProfileOut( __METHOD__
);
697 if ( $this->mOldid
&& $this->mNewid
) {
698 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
,
699 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
701 if ( !$this->mRefreshCache
) {
702 $difftext = $wgMemc->get( $key );
704 wfIncrStats( 'diff_cache_hit' );
705 $difftext = $this->localiseLineNumbers( $difftext );
706 $difftext .= "\n<!-- diff cache key $key -->\n";
707 wfProfileOut( __METHOD__
);
710 } // don't try to load but save the result
712 $this->mCacheHit
= false;
714 // Loadtext is permission safe, this just clears out the diff
715 if ( !$this->loadText() ) {
716 wfProfileOut( __METHOD__
);
720 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
722 // Save to cache for 7 days
723 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
724 wfIncrStats( 'diff_uncacheable' );
725 } elseif ( $key !== false && $difftext !== false ) {
726 wfIncrStats( 'diff_cache_miss' );
727 $wgMemc->set( $key, $difftext, 7 * 86400 );
729 wfIncrStats( 'diff_uncacheable' );
731 // Replace line numbers with the text in the user's language
732 if ( $difftext !== false ) {
733 $difftext = $this->localiseLineNumbers( $difftext );
735 wfProfileOut( __METHOD__
);
740 * Make sure the proper modules are loaded before we try to
743 private function initDiffEngines() {
744 global $wgExternalDiffEngine;
745 if ( $wgExternalDiffEngine == 'wikidiff' && !function_exists( 'wikidiff_do_diff' ) ) {
746 wfProfileIn( __METHOD__
. '-php_wikidiff.so' );
747 wfDl( 'php_wikidiff' );
748 wfProfileOut( __METHOD__
. '-php_wikidiff.so' );
750 else if ( $wgExternalDiffEngine == 'wikidiff2' && !function_exists( 'wikidiff2_do_diff' ) ) {
751 wfProfileIn( __METHOD__
. '-php_wikidiff2.so' );
753 wfProfileOut( __METHOD__
. '-php_wikidiff2.so' );
758 * Generate a diff, no caching
760 * @param $otext String: old text, must be already segmented
761 * @param $ntext String: new text, must be already segmented
763 function generateDiffBody( $otext, $ntext ) {
764 global $wgExternalDiffEngine, $wgContLang;
766 $otext = str_replace( "\r\n", "\n", $otext );
767 $ntext = str_replace( "\r\n", "\n", $ntext );
769 $this->initDiffEngines();
771 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
772 # For historical reasons, external diff engine expects
773 # input text to be HTML-escaped already
774 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
775 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
776 return $wgContLang->unsegmentForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
777 $this->debug( 'wikidiff1' );
780 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
781 # Better external diff engine, the 2 may some day be dropped
782 # This one does the escaping and segmenting itself
783 wfProfileIn( 'wikidiff2_do_diff' );
784 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
785 $text .= $this->debug( 'wikidiff2' );
786 wfProfileOut( 'wikidiff2_do_diff' );
789 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
791 global $wgTmpDirectory;
792 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
793 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
795 $tempFile1 = fopen( $tempName1, "w" );
797 wfProfileOut( __METHOD__
);
800 $tempFile2 = fopen( $tempName2, "w" );
802 wfProfileOut( __METHOD__
);
805 fwrite( $tempFile1, $otext );
806 fwrite( $tempFile2, $ntext );
807 fclose( $tempFile1 );
808 fclose( $tempFile2 );
809 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
810 wfProfileIn( __METHOD__
. "-shellexec" );
811 $difftext = wfShellExec( $cmd );
812 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
813 wfProfileOut( __METHOD__
. "-shellexec" );
814 unlink( $tempName1 );
815 unlink( $tempName2 );
816 wfProfileOut( __METHOD__
);
821 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
822 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
823 $diffs = new Diff( $ota, $nta );
824 $formatter = new TableDiffFormatter();
825 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
826 wfProfileOut( __METHOD__
);
831 * Generate a debug comment indicating diff generating time,
832 * server node, and generator backend.
834 protected function debug( $generator = "internal" ) {
835 global $wgShowHostnames;
836 if ( !$this->enableDebugComment
) {
839 $data = array( $generator );
840 if ( $wgShowHostnames ) {
841 $data[] = wfHostname();
843 $data[] = wfTimestamp( TS_DB
);
844 return "<!-- diff generator: " .
853 * Replace line numbers with the text in the user's language
855 function localiseLineNumbers( $text ) {
856 return preg_replace_callback( '/<!--LINE (\d+)-->/',
857 array( &$this, 'localiseLineNumbersCb' ), $text );
860 function localiseLineNumbersCb( $matches ) {
862 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) return '';
863 return wfMsgExt( 'lineno', 'escape', $wgLang->formatNum( $matches[1] ) );
868 * If there are revisions between the ones being compared, return a note saying so.
871 function getMultiNotice() {
872 if ( !is_object( $this->mOldRev
) ||
!is_object( $this->mNewRev
) ) {
874 } elseif ( !$this->mOldPage
->equals( $this->mNewPage
) ) {
875 // Comparing two different pages? Count would be meaningless.
879 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
880 $oldRev = $this->mNewRev
; // flip
881 $newRev = $this->mOldRev
; // flip
882 } else { // normal case
883 $oldRev = $this->mOldRev
;
884 $newRev = $this->mNewRev
;
887 $nEdits = $this->mTitle
->countRevisionsBetween( $oldRev, $newRev );
889 $limit = 100; // use diff-multi-manyusers if too many users
890 $numUsers = $this->mTitle
->countAuthorsBetween( $oldRev, $newRev, $limit );
891 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
893 return ''; // nothing
897 * Get a notice about how many intermediate edits and users there are
898 * @param $numEdits int
899 * @param $numUsers int
903 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
905 if ( $numUsers > $limit ) {
906 $msg = 'diff-multi-manyusers';
911 return wfMsgExt( $msg, 'parseinline',
912 $wgLang->formatnum( $numEdits ), $wgLang->formatnum( $numUsers ) );
916 * Add the header to a diff body
918 static function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
919 $header = "<table class='diff'>";
920 if ( $diff ) { // Safari/Chrome show broken output if cols not used
922 <col class='diff-marker' />
923 <col class='diff-content' />
924 <col class='diff-marker' />
925 <col class='diff-content' />";
934 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
935 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
938 if ( $multi != '' ) {
939 $header .= "<tr><td colspan='{$multiColspan}' align='center' class='diff-multi'>{$multi}</td></tr>";
941 if ( $notice != '' ) {
942 $header .= "<tr><td colspan='{$multiColspan}' align='center'>{$notice}</td></tr>";
945 return $header . $diff . "</table>";
949 * Use specified text instead of loading from the database
951 function setText( $oldText, $newText ) {
952 $this->mOldtext
= $oldText;
953 $this->mNewtext
= $newText;
954 $this->mTextLoaded
= 2;
955 $this->mRevisionsLoaded
= true;
959 * Load revision metadata for the specified articles. If newid is 0, then compare
960 * the old article in oldid to the current article; if oldid is 0, then
961 * compare the current article to the immediately previous one (ignoring the
964 * If oldid is false, leave the corresponding revision object set
965 * to false. This is impossible via ordinary user input, and is provided for
968 function loadRevisionData() {
969 global $wgLang, $wgUser;
970 if ( $this->mRevisionsLoaded
) {
973 // Whether it succeeds or fails, we don't want to try again
974 $this->mRevisionsLoaded
= true;
977 // Load the new revision object
978 $this->mNewRev
= $this->mNewid
979 ? Revision
::newFromId( $this->mNewid
)
980 : Revision
::newFromTitle( $this->mTitle
);
981 if ( !$this->mNewRev
instanceof Revision
)
984 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
985 $this->mNewid
= $this->mNewRev
->getId();
987 // Check if page is editable
988 $editable = $this->mNewRev
->getTitle()->userCan( 'edit' );
990 // Set assorted variables
991 $timestamp = $wgLang->timeanddate( $this->mNewRev
->getTimestamp(), true );
992 $dateofrev = $wgLang->date( $this->mNewRev
->getTimestamp(), true );
993 $timeofrev = $wgLang->time( $this->mNewRev
->getTimestamp(), true );
994 $this->mNewPage
= $this->mNewRev
->getTitle();
995 if ( $this->mNewRev
->isCurrent() ) {
996 $newLink = $this->mNewPage
->escapeLocalUrl( array(
997 'oldid' => $this->mNewid
999 $this->mPagetitle
= htmlspecialchars( wfMsg(
1005 $newEdit = $this->mNewPage
->escapeLocalUrl( array(
1009 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
1010 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
1012 $newLink = $this->mNewPage
->escapeLocalUrl( array(
1013 'oldid' => $this->mNewid
1015 $newEdit = $this->mNewPage
->escapeLocalUrl( array(
1017 'oldid' => $this->mNewid
1019 $this->mPagetitle
= htmlspecialchars( wfMsg(
1026 $this->mNewtitle
= "<a href='$newLink'>{$this->mPagetitle}</a>";
1027 $this->mNewtitle
.= " (<a href='$newEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
1029 if ( !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
) ) {
1030 $this->mNewtitle
= "<span class='history-deleted'>{$this->mPagetitle}</span>";
1031 } else if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
1032 $this->mNewtitle
= "<span class='history-deleted'>{$this->mNewtitle}</span>";
1035 // Load the old revision object
1036 $this->mOldRev
= false;
1037 if ( $this->mOldid
) {
1038 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1039 } elseif ( $this->mOldid
=== 0 ) {
1040 $rev = $this->mNewRev
->getPrevious();
1042 $this->mOldid
= $rev->getId();
1043 $this->mOldRev
= $rev;
1045 // No previous revision; mark to show as first-version only.
1046 $this->mOldid
= false;
1047 $this->mOldRev
= false;
1049 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1051 if ( is_null( $this->mOldRev
) ) {
1055 if ( $this->mOldRev
) {
1056 $this->mOldPage
= $this->mOldRev
->getTitle();
1058 $t = $wgLang->timeanddate( $this->mOldRev
->getTimestamp(), true );
1059 $dateofrev = $wgLang->date( $this->mOldRev
->getTimestamp(), true );
1060 $timeofrev = $wgLang->time( $this->mOldRev
->getTimestamp(), true );
1061 $oldLink = $this->mOldPage
->escapeLocalUrl( array(
1062 'oldid' => $this->mOldid
1064 $oldEdit = $this->mOldPage
->escapeLocalUrl( array(
1066 'oldid' => $this->mOldid
1068 $this->mOldPagetitle
= htmlspecialchars( wfMsg( 'revisionasof', $t, $dateofrev, $timeofrev ) );
1070 $this->mOldtitle
= "<a href='$oldLink'>{$this->mOldPagetitle}</a>"
1071 . " (<a href='$oldEdit'>" . wfMsgHtml( $editable ?
'editold' : 'viewsourceold' ) . "</a>)";
1072 // Add an "undo" link
1073 if ( $editable && !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
1074 $undoLink = Html
::element( 'a', array(
1075 'href' => $this->mNewPage
->getLocalUrl( array(
1077 'undoafter' => $this->mOldid
,
1078 'undo' => $this->mNewid
) ),
1079 'title' => $wgUser->getSkin()->titleAttrib( 'undo' )
1080 ), wfMsg( 'editundo' ) );
1081 $this->mNewtitle
.= ' (' . $undoLink . ')';
1084 if ( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
) ) {
1085 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldPagetitle
. '</span>';
1086 } else if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
1087 $this->mOldtitle
= '<span class="history-deleted">' . $this->mOldtitle
. '</span>';
1095 * Load the text of the revisions, as well as revision data.
1097 function loadText() {
1098 if ( $this->mTextLoaded
== 2 ) {
1101 // Whether it succeeds or fails, we don't want to try again
1102 $this->mTextLoaded
= 2;
1105 if ( !$this->loadRevisionData() ) {
1108 if ( $this->mOldRev
) {
1109 $this->mOldtext
= $this->mOldRev
->getText( Revision
::FOR_THIS_USER
);
1110 if ( $this->mOldtext
=== false ) {
1114 if ( $this->mNewRev
) {
1115 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);
1116 if ( $this->mNewtext
=== false ) {
1124 * Load the text of the new revision, not the old one
1126 function loadNewText() {
1127 if ( $this->mTextLoaded
>= 1 ) {
1130 $this->mTextLoaded
= 1;
1132 if ( !$this->loadRevisionData() ) {
1135 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);