3 * User interface for the difference engine.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup DifferenceEngine
25 * Constant to indicate diff cache compatibility.
26 * Bump this when changing the diff formatting in a way that
27 * fixes important bugs or such to force cached diff views to
30 define( 'MW_DIFF_VERSION', '1.11a' );
34 * @ingroup DifferenceEngine
36 class DifferenceEngine
extends ContextSource
{
44 var $mOldContent, $mNewContent;
50 var $mOldPage, $mNewPage;
51 var $mRcidMarkPatrolled;
56 var $mOldRev, $mNewRev;
57 private $mRevisionsIdsLoaded = false; // Have the revisions IDs been loaded
58 var $mRevisionsLoaded = false; // Have the revisions been loaded
59 var $mTextLoaded = 0; // How many text blobs have been loaded, 0, 1 or 2?
60 var $mCacheHit = false; // Was the diff fetched from cache?
63 * Set this to true to add debug info to the HTML output.
64 * Warning: this may cause RSS readers to spuriously mark articles as "new"
67 var $enableDebugComment = false;
69 // If true, line X is not displayed when X is 1, for example to increase
70 // readability and conserve space with many small diffs.
71 protected $mReducedLineNumbers = false;
73 // Link to action=markpatrolled
74 protected $mMarkPatrolledLink = null;
76 protected $unhide = false; # show rev_deleted content if allowed
81 * @param $context IContextSource context to use, anything else will be ignored
82 * @param $old Integer old ID we want to show and diff with.
83 * @param $new String either 'prev' or 'next'.
84 * @param $rcid Integer ??? FIXME (default 0)
85 * @param $refreshCache boolean If set, refreshes the diff cache
86 * @param $unhide boolean If set, allow viewing deleted revs
88 function __construct( $context = null, $old = 0, $new = 0, $rcid = 0,
89 $refreshCache = false, $unhide = false )
91 if ( $context instanceof IContextSource
) {
92 $this->setContext( $context );
95 wfDebug( "DifferenceEngine old '$old' new '$new' rcid '$rcid'\n" );
99 $this->mRcidMarkPatrolled
= intval( $rcid ); # force it to be an integer
100 $this->mRefreshCache
= $refreshCache;
101 $this->unhide
= $unhide;
107 function setReducedLineNumbers( $value = true ) {
108 $this->mReducedLineNumbers
= $value;
114 function getDiffLang() {
115 if ( $this->mDiffLang
=== null ) {
116 # Default language in which the diff text is written.
117 $this->mDiffLang
= $this->getTitle()->getPageLanguage();
119 return $this->mDiffLang
;
125 function wasCacheHit() {
126 return $this->mCacheHit
;
132 function getOldid() {
133 $this->loadRevisionIds();
134 return $this->mOldid
;
140 function getNewid() {
141 $this->loadRevisionIds();
142 return $this->mNewid
;
146 * Look up a special:Undelete link to the given deleted revision id,
147 * as a workaround for being unable to load deleted diffs in currently.
149 * @param int $id revision ID
150 * @return mixed URL or false
152 function deletedLink( $id ) {
153 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
154 $dbr = wfGetDB( DB_SLAVE
);
155 $row = $dbr->selectRow('archive', '*',
156 array( 'ar_rev_id' => $id ),
159 $rev = Revision
::newFromArchiveRow( $row );
160 $title = Title
::makeTitleSafe( $row->ar_namespace
, $row->ar_title
);
161 return SpecialPage
::getTitleFor( 'Undelete' )->getFullURL( array(
162 'target' => $title->getPrefixedText(),
163 'timestamp' => $rev->getTimestamp()
171 * Build a wikitext link toward a deleted revision, if viewable.
173 * @param int $id revision ID
174 * @return string wikitext fragment
176 function deletedIdMarker( $id ) {
177 $link = $this->deletedLink( $id );
179 return "[$link $id]";
185 private function showMissingRevision() {
186 $out = $this->getOutput();
189 if ( $this->mOldRev
=== null ) {
190 $missing[] = $this->deletedIdMarker( $this->mOldid
);
192 if ( $this->mNewRev
=== null ) {
193 $missing[] = $this->deletedIdMarker( $this->mNewid
);
196 $out->setPageTitle( $this->msg( 'errorpagetitle' ) );
197 $out->addWikiMsg( 'difference-missing-revision',
198 $this->getLanguage()->listToText( $missing ), count( $missing ) );
201 function showDiffPage( $diffOnly = false ) {
202 wfProfileIn( __METHOD__
);
204 # Allow frames except in certain special cases
205 $out = $this->getOutput();
206 $out->allowClickjacking();
207 $out->setRobotPolicy( 'noindex,nofollow' );
209 if ( !$this->loadRevisionData() ) {
210 $this->showMissingRevision();
211 wfProfileOut( __METHOD__
);
215 $user = $this->getUser();
216 $permErrors = $this->mNewPage
->getUserPermissionsErrors( 'read', $user );
217 if ( $this->mOldPage
) { # mOldPage might not be set, see below.
218 $permErrors = wfMergeErrorArrays( $permErrors,
219 $this->mOldPage
->getUserPermissionsErrors( 'read', $user ) );
221 if ( count( $permErrors ) ) {
222 wfProfileOut( __METHOD__
);
223 throw new PermissionsError( 'read', $permErrors );
226 # If external diffs are enabled both globally and for the user,
227 # we'll use the application/x-external-editor interface to call
228 # an external diff tool like kompare, kdiff3, etc.
229 if ( ExternalEdit
::useExternalEngine( $this->getContext(), 'diff' ) ) {
230 //TODO: come up with a good solution for non-text content here.
231 // at least, the content format needs to be passed to the client somehow.
232 // Currently, action=raw will just fail for non-text content.
235 'File' => array( 'Extension' => 'wiki', 'URL' =>
236 # This should be mOldPage, but it may not be set, see below.
237 $this->mNewPage
->getCanonicalURL( array(
238 'action' => 'raw', 'oldid' => $this->mOldid
) )
240 'File2' => array( 'Extension' => 'wiki', 'URL' =>
241 $this->mNewPage
->getCanonicalURL( array(
242 'action' => 'raw', 'oldid' => $this->mNewid
) )
246 $externalEditor = new ExternalEdit( $this->getContext(), $urls );
247 $externalEditor->execute();
249 wfProfileOut( __METHOD__
);
257 # Carry over 'diffonly' param via navigation links
258 if ( $diffOnly != $user->getBoolOption( 'diffonly' ) ) {
259 $query['diffonly'] = $diffOnly;
261 # Cascade unhide param in links for easy deletion browsing
262 if ( $this->unhide
) {
263 $query['unhide'] = 1;
266 # Check if one of the revisions is deleted/suppressed
267 $deleted = $suppressed = false;
268 $allowed = $this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $user );
270 # mOldRev is false if the difference engine is called with a "vague" query for
271 # a diff between a version V and its previous version V' AND the version V
272 # is the first version of that article. In that case, V' does not exist.
273 if ( $this->mOldRev
=== false ) {
274 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
278 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
280 $sk = $this->getSkin();
281 if ( method_exists( $sk, 'suppressQuickbar' ) ) {
282 $sk->suppressQuickbar();
285 if ( $this->mNewPage
->equals( $this->mOldPage
) ) {
286 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
289 $out->setPageTitle( $this->msg( 'difference-title-multipage', $this->mOldPage
->getPrefixedText(),
290 $this->mNewPage
->getPrefixedText() ) );
291 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
295 if ( $samePage && $this->mNewPage
->quickUserCan( 'edit', $user ) ) {
296 if ( $this->mNewRev
->isCurrent() && $this->mNewPage
->userCan( 'rollback', $user ) ) {
297 $rollbackLink = Linker
::generateRollback( $this->mNewRev
, $this->getContext() );
298 if ( $rollbackLink ) {
299 $out->preventClickjacking();
300 $rollback = '   ' . $rollbackLink;
303 if ( !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
304 $undoLink = ' ' . $this->msg( 'parentheses' )->rawParams(
305 Html
::element( 'a', array(
306 'href' => $this->mNewPage
->getLocalUrl( array(
308 'undoafter' => $this->mOldid
,
309 'undo' => $this->mNewid
) ),
310 'title' => Linker
::titleAttrib( 'undo' )
312 $this->msg( 'editundo' )->text()
317 # Make "previous revision link"
318 if ( $samePage && $this->mOldRev
->getPrevious() ) {
319 $prevlink = Linker
::linkKnown(
321 $this->msg( 'previousdiff' )->escaped(),
322 array( 'id' => 'differences-prevlink' ),
323 array( 'diff' => 'prev', 'oldid' => $this->mOldid
) +
$query
326 $prevlink = ' ';
329 if ( $this->mOldRev
->isMinor() ) {
330 $oldminor = ChangesList
::flag( 'minor' );
335 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
336 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev
, 'complete' );
338 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
339 '<div id="mw-diff-otitle2">' .
340 Linker
::revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
341 '<div id="mw-diff-otitle3">' . $oldminor .
342 Linker
::revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
343 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
345 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
346 $deleted = true; // old revisions text is hidden
347 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
348 $suppressed = true; // also suppressed
352 # Check if this user can see the revisions
353 if ( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $user ) ) {
358 # Make "next revision link"
359 # Skip next link on the top revision
360 if ( $samePage && !$this->mNewRev
->isCurrent() ) {
361 $nextlink = Linker
::linkKnown(
363 $this->msg( 'nextdiff' )->escaped(),
364 array( 'id' => 'differences-nextlink' ),
365 array( 'diff' => 'next', 'oldid' => $this->mNewid
) +
$query
368 $nextlink = ' ';
371 if ( $this->mNewRev
->isMinor() ) {
372 $newminor = ChangesList
::flag( 'minor' );
377 # Handle RevisionDelete links...
378 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
379 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev
, 'complete' ) . $undoLink;
381 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
382 '<div id="mw-diff-ntitle2">' . Linker
::revUserTools( $this->mNewRev
, !$this->unhide
) .
384 '<div id="mw-diff-ntitle3">' . $newminor .
385 Linker
::revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
386 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
388 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
389 $deleted = true; // new revisions text is hidden
390 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
391 $suppressed = true; // also suppressed
394 # If the diff cannot be shown due to a deleted revision, then output
395 # the diff header and links to unhide (if available)...
396 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
397 $this->showDiffStyle();
398 $multi = $this->getMultiNotice();
399 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
401 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
402 # Give explanation for why revision is not visible
403 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
406 # Give explanation and add a link to view the diff...
407 $link = $this->getTitle()->getFullUrl( $this->getRequest()->appendQueryValue( 'unhide', '1', true ) );
408 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
409 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n", array( $msg, $link ) );
411 # Otherwise, output a regular diff...
413 # Add deletion notice if the user is viewing deleted content
416 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
417 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" . $this->msg( $msg )->parse() . "</div>\n";
419 $this->showDiff( $oldHeader, $newHeader, $notice );
421 $this->renderNewRevision();
424 wfProfileOut( __METHOD__
);
428 * Get a link to mark the change as patrolled, or '' if there's either no
429 * revision to patrol or the user is not allowed to to it.
430 * Side effect: When the patrol link is build, this method will call
431 * OutputPage::preventClickjacking() and load mediawiki.page.patrol.ajax.
435 protected function markPatrolledLink() {
436 global $wgUseRCPatrol;
438 if ( $this->mMarkPatrolledLink
=== null ) {
439 // Prepare a change patrol link, if applicable
440 if ( $wgUseRCPatrol && $this->mNewPage
->quickUserCan( 'patrol', $this->getUser() ) ) {
441 // If we've been given an explicit change identifier, use it; saves time
442 if ( $this->mRcidMarkPatrolled
) {
443 $rcid = $this->mRcidMarkPatrolled
;
444 $rc = RecentChange
::newFromId( $rcid );
445 // Already patrolled?
446 $rcid = is_object( $rc ) && !$rc->getAttribute( 'rc_patrolled' ) ?
$rcid : 0;
448 // Look for an unpatrolled change corresponding to this diff
449 $db = wfGetDB( DB_SLAVE
);
450 $change = RecentChange
::newFromConds(
452 // Redundant user,timestamp condition so we can use the existing index
453 'rc_user_text' => $this->mNewRev
->getRawUserText(),
454 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
455 'rc_this_oldid' => $this->mNewid
,
456 'rc_last_oldid' => $this->mOldid
,
461 if ( $change instanceof RecentChange
) {
462 $rcid = $change->mAttribs
['rc_id'];
463 $this->mRcidMarkPatrolled
= $rcid;
471 $this->getOutput()->preventClickjacking();
472 $this->getOutput()->addModules( 'mediawiki.page.patrol.ajax' );
474 $token = $this->getUser()->getEditToken( $rcid );
475 $this->mMarkPatrolledLink
= ' <span class="patrollink">[' . Linker
::linkKnown(
477 $this->msg( 'markaspatrolleddiff' )->escaped(),
480 'action' => 'markpatrolled',
486 $this->mMarkPatrolledLink
= '';
489 $this->mMarkPatrolledLink
= '';
493 return $this->mMarkPatrolledLink
;
497 * @param $rev Revision
500 protected function revisionDeleteLink( $rev ) {
501 $link = Linker
::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
502 if ( $link !== '' ) {
503 $link = '   ' . $link . ' ';
509 * Show the new revision of the page.
511 function renderNewRevision() {
512 wfProfileIn( __METHOD__
);
513 $out = $this->getOutput();
514 $revHeader = $this->getRevisionHeader( $this->mNewRev
);
515 # Add "current version as of X" title
516 $out->addHTML( "<hr class='diff-hr' />
517 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
518 # Page content may be handled by a hooked call instead...
519 if ( wfRunHooks( 'ArticleContentOnDiff', array( $this, $out ) ) ) {
520 $this->loadNewText();
521 $out->setRevisionId( $this->mNewid
);
522 $out->setRevisionTimestamp( $this->mNewRev
->getTimestamp() );
523 $out->setArticleFlag( true );
525 // NOTE: only needed for B/C: custom rendering of JS/CSS via hook
526 if ( $this->mNewPage
->isCssJsSubpage() ||
$this->mNewPage
->isCssOrJsPage() ) {
527 // Stolen from Article::view --AG 2007-10-11
528 // Give hooks a chance to customise the output
529 // @TODO: standardize this crap into one function
530 if ( ContentHandler
::runLegacyHooks( 'ShowRawCssJs', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
531 // NOTE: deprecated hook, B/C only
532 // use the content object's own rendering
533 $cnt = $this->mNewRev
->getContent();
534 $po = $cnt ?
$cnt->getParserOutput( $this->mNewRev
->getTitle(), $this->mNewRev
->getId() ) : null;
535 $txt = $po ?
$po->getText() : '';
536 $out->addHTML( $txt );
538 } elseif( !wfRunHooks( 'ArticleContentViewCustom', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
539 // Handled by extension
540 } elseif( !ContentHandler
::runLegacyHooks( 'ArticleViewCustom', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
541 // NOTE: deprecated hook, B/C only
542 // Handled by extension
545 if ( $this->getTitle()->equals( $this->mNewPage
) ) {
546 // If the Title stored in the context is the same as the one
547 // of the new revision, we can use its associated WikiPage
549 $wikiPage = $this->getWikiPage();
551 // Otherwise we need to create our own WikiPage object
552 $wikiPage = WikiPage
::factory( $this->mNewPage
);
555 $parserOutput = $this->getParserOutput( $wikiPage, $this->mNewRev
);
557 # Also try to load it as a redirect
558 $rt = $this->mNewContent ?
$this->mNewContent
->getRedirectTarget() : null;
561 $article = Article
::newFromTitle( $this->mNewPage
, $this->getContext() );
562 $out->addHTML( $article->viewRedirect( $rt ) );
564 # WikiPage::getParserOutput() should not return false, but just in case
565 if ( $parserOutput ) {
566 # Show categories etc.
567 $out->addParserOutputNoText( $parserOutput );
569 } else if ( $parserOutput ) {
570 $out->addParserOutput( $parserOutput );
574 # Add redundant patrol link on bottom...
575 $out->addHTML( $this->markPatrolledLink() );
577 wfProfileOut( __METHOD__
);
580 protected function getParserOutput( WikiPage
$page, Revision
$rev ) {
581 $parserOptions = $page->makeParserOptions( $this->getContext() );
583 if ( !$rev->isCurrent() ||
!$rev->getTitle()->quickUserCan( "edit" ) ) {
584 $parserOptions->setEditSection( false );
587 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
588 return $parserOutput;
592 * Get the diff text, send it to the OutputPage object
593 * Returns false if the diff could not be generated, otherwise returns true
597 function showDiff( $otitle, $ntitle, $notice = '' ) {
598 $diff = $this->getDiff( $otitle, $ntitle, $notice );
599 if ( $diff === false ) {
600 $this->showMissingRevision();
603 $this->showDiffStyle();
604 $this->getOutput()->addHTML( $diff );
610 * Add style sheets and supporting JS for diff display.
612 function showDiffStyle() {
613 $this->getOutput()->addModuleStyles( 'mediawiki.action.history.diff' );
617 * Get complete diff table, including header
619 * @param string|bool $otitle Header for old text or false
620 * @param string|bool $ntitle Header for new text or false
621 * @param $notice String: HTML between diff header and body
624 function getDiff( $otitle, $ntitle, $notice = '' ) {
625 $body = $this->getDiffBody();
626 if ( $body === false ) {
629 $multi = $this->getMultiNotice();
630 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
635 * Get the diff table body, without header
637 * @return mixed (string/false)
639 public function getDiffBody() {
641 wfProfileIn( __METHOD__
);
642 $this->mCacheHit
= true;
643 // Check if the diff should be hidden from this user
644 if ( !$this->loadRevisionData() ) {
645 wfProfileOut( __METHOD__
);
647 } elseif ( $this->mOldRev
&& !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
648 wfProfileOut( __METHOD__
);
650 } elseif ( $this->mNewRev
&& !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
651 wfProfileOut( __METHOD__
);
655 // If mOldRev is false, it means that the
656 if ( $this->mOldRev
=== false ||
( $this->mOldRev
&& $this->mNewRev
657 && $this->mOldRev
->getID() == $this->mNewRev
->getID() ) )
659 wfProfileOut( __METHOD__
);
664 if ( $this->mOldid
&& $this->mNewid
) {
665 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
,
666 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
668 if ( !$this->mRefreshCache
) {
669 $difftext = $wgMemc->get( $key );
671 wfIncrStats( 'diff_cache_hit' );
672 $difftext = $this->localiseLineNumbers( $difftext );
673 $difftext .= "\n<!-- diff cache key $key -->\n";
674 wfProfileOut( __METHOD__
);
677 } // don't try to load but save the result
679 $this->mCacheHit
= false;
681 // Loadtext is permission safe, this just clears out the diff
682 if ( !$this->loadText() ) {
683 wfProfileOut( __METHOD__
);
687 $difftext = $this->generateContentDiffBody( $this->mOldContent
, $this->mNewContent
);
689 // Save to cache for 7 days
690 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
691 wfIncrStats( 'diff_uncacheable' );
692 } elseif ( $key !== false && $difftext !== false ) {
693 wfIncrStats( 'diff_cache_miss' );
694 $wgMemc->set( $key, $difftext, 7 * 86400 );
696 wfIncrStats( 'diff_uncacheable' );
698 // Replace line numbers with the text in the user's language
699 if ( $difftext !== false ) {
700 $difftext = $this->localiseLineNumbers( $difftext );
702 wfProfileOut( __METHOD__
);
707 * Make sure the proper modules are loaded before we try to
710 private function initDiffEngines() {
711 global $wgExternalDiffEngine;
712 if ( $wgExternalDiffEngine == 'wikidiff' && !function_exists( 'wikidiff_do_diff' ) ) {
713 wfProfileIn( __METHOD__
. '-php_wikidiff.so' );
714 wfDl( 'php_wikidiff' );
715 wfProfileOut( __METHOD__
. '-php_wikidiff.so' );
717 elseif ( $wgExternalDiffEngine == 'wikidiff2' && !function_exists( 'wikidiff2_do_diff' ) ) {
718 wfProfileIn( __METHOD__
. '-php_wikidiff2.so' );
720 wfProfileOut( __METHOD__
. '-php_wikidiff2.so' );
725 * Generate a diff, no caching.
727 * This implementation uses generateTextDiffBody() to generate a diff based on the default
728 * serialization of the given Content objects. This will fail if $old or $new are not
729 * instances of TextContent.
731 * Subclasses may override this to provide a different rendering for the diff,
732 * perhaps taking advantage of the content's native form. This is required for all content
733 * models that are not text based.
735 * @param $old Content: old content
736 * @param $new Content: new content
739 * @throws MWException if $old or $new are not instances of TextContent.
741 function generateContentDiffBody( Content
$old, Content
$new ) {
742 if ( !( $old instanceof TextContent
) ) {
743 throw new MWException( "Diff not implemented for " . get_class( $old ) . "; "
744 . "override generateContentDiffBody to fix this." );
747 if ( !( $new instanceof TextContent
) ) {
748 throw new MWException( "Diff not implemented for " . get_class( $new ) . "; "
749 . "override generateContentDiffBody to fix this." );
752 $otext = $old->serialize();
753 $ntext = $new->serialize();
755 return $this->generateTextDiffBody( $otext, $ntext );
759 * Generate a diff, no caching
761 * @param $otext String: old text, must be already segmented
762 * @param $ntext String: new text, must be already segmented
763 * @deprecated since 1.21, use generateContentDiffBody() instead!
765 function generateDiffBody( $otext, $ntext ) {
766 ContentHandler
::deprecated( __METHOD__
, "1.21" );
768 return $this->generateTextDiffBody( $otext, $ntext );
772 * Generate a diff, no caching
774 * @todo move this to TextDifferenceEngine, make DifferenceEngine abstract. At some point.
776 * @param $otext String: old text, must be already segmented
777 * @param $ntext String: new text, must be already segmented
778 * @return bool|string
780 function generateTextDiffBody( $otext, $ntext ) {
781 global $wgExternalDiffEngine, $wgContLang;
783 wfProfileIn( __METHOD__
);
785 $otext = str_replace( "\r\n", "\n", $otext );
786 $ntext = str_replace( "\r\n", "\n", $ntext );
788 $this->initDiffEngines();
790 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
791 # For historical reasons, external diff engine expects
792 # input text to be HTML-escaped already
793 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
794 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
795 wfProfileOut( __METHOD__
);
796 return $wgContLang->unsegmentForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
797 $this->debug( 'wikidiff1' );
800 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
801 # Better external diff engine, the 2 may some day be dropped
802 # This one does the escaping and segmenting itself
803 wfProfileIn( 'wikidiff2_do_diff' );
804 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
805 $text .= $this->debug( 'wikidiff2' );
806 wfProfileOut( 'wikidiff2_do_diff' );
807 wfProfileOut( __METHOD__
);
810 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
812 $tmpDir = wfTempDir();
813 $tempName1 = tempnam( $tmpDir, 'diff_' );
814 $tempName2 = tempnam( $tmpDir, 'diff_' );
816 $tempFile1 = fopen( $tempName1, "w" );
818 wfProfileOut( __METHOD__
);
821 $tempFile2 = fopen( $tempName2, "w" );
823 wfProfileOut( __METHOD__
);
826 fwrite( $tempFile1, $otext );
827 fwrite( $tempFile2, $ntext );
828 fclose( $tempFile1 );
829 fclose( $tempFile2 );
830 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
831 wfProfileIn( __METHOD__
. "-shellexec" );
832 $difftext = wfShellExec( $cmd );
833 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
834 wfProfileOut( __METHOD__
. "-shellexec" );
835 unlink( $tempName1 );
836 unlink( $tempName2 );
837 wfProfileOut( __METHOD__
);
842 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
843 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
844 $diffs = new Diff( $ota, $nta );
845 $formatter = new TableDiffFormatter();
846 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
847 wfProfileOut( __METHOD__
);
852 * Generate a debug comment indicating diff generating time,
853 * server node, and generator backend.
856 protected function debug( $generator = "internal" ) {
857 global $wgShowHostnames;
858 if ( !$this->enableDebugComment
) {
861 $data = array( $generator );
862 if ( $wgShowHostnames ) {
863 $data[] = wfHostname();
865 $data[] = wfTimestamp( TS_DB
);
866 return "<!-- diff generator: " .
875 * Replace line numbers with the text in the user's language
878 function localiseLineNumbers( $text ) {
879 return preg_replace_callback( '/<!--LINE (\d+)-->/',
880 array( &$this, 'localiseLineNumbersCb' ), $text );
883 function localiseLineNumbersCb( $matches ) {
884 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) return '';
885 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
890 * If there are revisions between the ones being compared, return a note saying so.
893 function getMultiNotice() {
894 if ( !is_object( $this->mOldRev
) ||
!is_object( $this->mNewRev
) ) {
896 } elseif ( !$this->mOldPage
->equals( $this->mNewPage
) ) {
897 // Comparing two different pages? Count would be meaningless.
901 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
902 $oldRev = $this->mNewRev
; // flip
903 $newRev = $this->mOldRev
; // flip
904 } else { // normal case
905 $oldRev = $this->mOldRev
;
906 $newRev = $this->mNewRev
;
909 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev );
911 $limit = 100; // use diff-multi-manyusers if too many users
912 $numUsers = $this->mNewPage
->countAuthorsBetween( $oldRev, $newRev, $limit );
913 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
915 return ''; // nothing
919 * Get a notice about how many intermediate edits and users there are
920 * @param $numEdits int
921 * @param $numUsers int
925 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
926 if ( $numUsers > $limit ) {
927 $msg = 'diff-multi-manyusers';
932 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
936 * Get a header for a specified revision.
938 * @param $rev Revision
939 * @param $complete String: 'complete' to get the header wrapped depending
940 * the visibility of the revision and a link to edit the page.
941 * @return String HTML fragment
943 protected function getRevisionHeader( Revision
$rev, $complete = '' ) {
944 $lang = $this->getLanguage();
945 $user = $this->getUser();
946 $revtimestamp = $rev->getTimestamp();
947 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
948 $dateofrev = $lang->userDate( $revtimestamp, $user );
949 $timeofrev = $lang->userTime( $revtimestamp, $user );
951 $header = $this->msg(
952 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
958 if ( $complete !== 'complete' ) {
962 $title = $rev->getTitle();
964 $header = Linker
::linkKnown( $title, $header, array(),
965 array( 'oldid' => $rev->getID() ) );
967 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
968 $editQuery = array( 'action' => 'edit' );
969 if ( !$rev->isCurrent() ) {
970 $editQuery['oldid'] = $rev->getID();
973 $msg = $this->msg( $title->quickUserCan( 'edit', $user ) ?
'editold' : 'viewsourceold' )->escaped();
974 $header .= ' ' . $this->msg( 'parentheses' )->rawParams(
975 Linker
::linkKnown( $title, $msg, array(), $editQuery ) )->plain();
976 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
977 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
980 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
987 * Add the header to a diff body
991 function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
992 // shared.css sets diff in interface language/dir, but the actual content
993 // is often in a different language, mostly the page content language/dir
994 $tableClass = 'diff diff-contentalign-' . htmlspecialchars( $this->getDiffLang()->alignStart() );
995 $header = "<table class='$tableClass'>";
997 if ( !$diff && !$otitle ) {
999 <tr style='vertical-align: top;'>
1000 <td class='diff-ntitle'>{$ntitle}</td>
1004 if ( $diff ) { // Safari/Chrome show broken output if cols not used
1006 <col class='diff-marker' />
1007 <col class='diff-content' />
1008 <col class='diff-marker' />
1009 <col class='diff-content' />";
1017 <tr style='vertical-align: top;'>
1018 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
1019 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
1023 if ( $multi != '' ) {
1024 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;' class='diff-multi'>{$multi}</td></tr>";
1026 if ( $notice != '' ) {
1027 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;'>{$notice}</td></tr>";
1030 return $header . $diff . "</table>";
1034 * Use specified text instead of loading from the database
1035 * @deprecated since 1.21, use setContent() instead.
1037 function setText( $oldText, $newText ) {
1038 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1040 $oldContent = ContentHandler
::makeContent( $oldText, $this->getTitle() );
1041 $newContent = ContentHandler
::makeContent( $newText, $this->getTitle() );
1043 $this->setContent( $oldContent, $newContent );
1047 * Use specified text instead of loading from the database
1050 function setContent( Content
$oldContent, Content
$newContent ) {
1051 $this->mOldContent
= $oldContent;
1052 $this->mNewContent
= $newContent;
1054 $this->mTextLoaded
= 2;
1055 $this->mRevisionsLoaded
= true;
1059 * Set the language in which the diff text is written
1060 * (Defaults to page content language).
1063 function setTextLanguage( $lang ) {
1064 $this->mDiffLang
= wfGetLangObj( $lang );
1070 private function loadRevisionIds() {
1071 if ( $this->mRevisionsIdsLoaded
) {
1075 $this->mRevisionsIdsLoaded
= true;
1077 $old = $this->mOldid
;
1078 $new = $this->mNewid
;
1080 if ( $new === 'prev' ) {
1081 # Show diff between revision $old and the previous one.
1082 # Get previous one from DB.
1083 $this->mNewid
= intval( $old );
1084 $this->mOldid
= $this->getTitle()->getPreviousRevisionID( $this->mNewid
);
1085 } elseif ( $new === 'next' ) {
1086 # Show diff between revision $old and the next one.
1087 # Get next one from DB.
1088 $this->mOldid
= intval( $old );
1089 $this->mNewid
= $this->getTitle()->getNextRevisionID( $this->mOldid
);
1090 if ( $this->mNewid
=== false ) {
1091 # if no result, NewId points to the newest old revision. The only newer
1092 # revision is cur, which is "0".
1096 $this->mOldid
= intval( $old );
1097 $this->mNewid
= intval( $new );
1098 wfRunHooks( 'NewDifferenceEngine', array( $this->getTitle(), &$this->mOldid
, &$this->mNewid
, $old, $new ) );
1103 * Load revision metadata for the specified articles. If newid is 0, then compare
1104 * the old article in oldid to the current article; if oldid is 0, then
1105 * compare the current article to the immediately previous one (ignoring the
1108 * If oldid is false, leave the corresponding revision object set
1109 * to false. This is impossible via ordinary user input, and is provided for
1114 function loadRevisionData() {
1115 if ( $this->mRevisionsLoaded
) {
1119 // Whether it succeeds or fails, we don't want to try again
1120 $this->mRevisionsLoaded
= true;
1122 $this->loadRevisionIds();
1124 // Load the new revision object
1125 $this->mNewRev
= $this->mNewid
1126 ? Revision
::newFromId( $this->mNewid
)
1127 : Revision
::newFromTitle( $this->getTitle(), false, Revision
::READ_NORMAL
);
1129 if ( !$this->mNewRev
instanceof Revision
) {
1133 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1134 $this->mNewid
= $this->mNewRev
->getId();
1135 $this->mNewPage
= $this->mNewRev
->getTitle();
1137 // Load the old revision object
1138 $this->mOldRev
= false;
1139 if ( $this->mOldid
) {
1140 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1141 } elseif ( $this->mOldid
=== 0 ) {
1142 $rev = $this->mNewRev
->getPrevious();
1144 $this->mOldid
= $rev->getId();
1145 $this->mOldRev
= $rev;
1147 // No previous revision; mark to show as first-version only.
1148 $this->mOldid
= false;
1149 $this->mOldRev
= false;
1151 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1153 if ( is_null( $this->mOldRev
) ) {
1157 if ( $this->mOldRev
) {
1158 $this->mOldPage
= $this->mOldRev
->getTitle();
1165 * Load the text of the revisions, as well as revision data.
1169 function loadText() {
1170 if ( $this->mTextLoaded
== 2 ) {
1173 // Whether it succeeds or fails, we don't want to try again
1174 $this->mTextLoaded
= 2;
1177 if ( !$this->loadRevisionData() ) {
1180 if ( $this->mOldRev
) {
1181 $this->mOldContent
= $this->mOldRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1182 if ( $this->mOldContent
=== null ) {
1186 if ( $this->mNewRev
) {
1187 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1188 if ( $this->mNewContent
=== null ) {
1196 * Load the text of the new revision, not the old one
1200 function loadNewText() {
1201 if ( $this->mTextLoaded
>= 1 ) {
1204 $this->mTextLoaded
= 1;
1206 if ( !$this->loadRevisionData() ) {
1209 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );