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
{
41 var $mOldTags, $mNewTags;
45 var $mOldContent, $mNewContent;
51 var $mOldPage, $mNewPage;
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 Deprecated, no longer used!
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->mRefreshCache
= $refreshCache;
100 $this->unhide
= $unhide;
106 function setReducedLineNumbers( $value = true ) {
107 $this->mReducedLineNumbers
= $value;
113 function getDiffLang() {
114 if ( $this->mDiffLang
=== null ) {
115 # Default language in which the diff text is written.
116 $this->mDiffLang
= $this->getTitle()->getPageLanguage();
118 return $this->mDiffLang
;
124 function wasCacheHit() {
125 return $this->mCacheHit
;
131 function getOldid() {
132 $this->loadRevisionIds();
133 return $this->mOldid
;
139 function getNewid() {
140 $this->loadRevisionIds();
141 return $this->mNewid
;
145 * Look up a special:Undelete link to the given deleted revision id,
146 * as a workaround for being unable to load deleted diffs in currently.
148 * @param int $id revision ID
149 * @return mixed URL or false
151 function deletedLink( $id ) {
152 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
153 $dbr = wfGetDB( DB_SLAVE
);
154 $row = $dbr->selectRow( 'archive', '*',
155 array( 'ar_rev_id' => $id ),
158 $rev = Revision
::newFromArchiveRow( $row );
159 $title = Title
::makeTitleSafe( $row->ar_namespace
, $row->ar_title
);
160 return SpecialPage
::getTitleFor( 'Undelete' )->getFullURL( array(
161 'target' => $title->getPrefixedText(),
162 'timestamp' => $rev->getTimestamp()
170 * Build a wikitext link toward a deleted revision, if viewable.
172 * @param int $id revision ID
173 * @return string wikitext fragment
175 function deletedIdMarker( $id ) {
176 $link = $this->deletedLink( $id );
178 return "[$link $id]";
184 private function showMissingRevision() {
185 $out = $this->getOutput();
188 if ( $this->mOldRev
=== null ||
189 ( $this->mOldRev
&& $this->mOldContent
=== null )
191 $missing[] = $this->deletedIdMarker( $this->mOldid
);
193 if ( $this->mNewRev
=== null ||
194 ( $this->mNewRev
&& $this->mNewContent
=== null )
196 $missing[] = $this->deletedIdMarker( $this->mNewid
);
199 $out->setPageTitle( $this->msg( 'errorpagetitle' ) );
200 $out->addWikiMsg( 'difference-missing-revision',
201 $this->getLanguage()->listToText( $missing ), count( $missing ) );
204 function showDiffPage( $diffOnly = false ) {
205 wfProfileIn( __METHOD__
);
207 # Allow frames except in certain special cases
208 $out = $this->getOutput();
209 $out->allowClickjacking();
210 $out->setRobotPolicy( 'noindex,nofollow' );
212 if ( !$this->loadRevisionData() ) {
213 $this->showMissingRevision();
214 wfProfileOut( __METHOD__
);
218 $user = $this->getUser();
219 $permErrors = $this->mNewPage
->getUserPermissionsErrors( 'read', $user );
220 if ( $this->mOldPage
) { # mOldPage might not be set, see below.
221 $permErrors = wfMergeErrorArrays( $permErrors,
222 $this->mOldPage
->getUserPermissionsErrors( 'read', $user ) );
224 if ( count( $permErrors ) ) {
225 wfProfileOut( __METHOD__
);
226 throw new PermissionsError( 'read', $permErrors );
233 # Carry over 'diffonly' param via navigation links
234 if ( $diffOnly != $user->getBoolOption( 'diffonly' ) ) {
235 $query['diffonly'] = $diffOnly;
237 # Cascade unhide param in links for easy deletion browsing
238 if ( $this->unhide
) {
239 $query['unhide'] = 1;
242 # Check if one of the revisions is deleted/suppressed
243 $deleted = $suppressed = false;
244 $allowed = $this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $user );
246 $revisionTools = array();
248 # mOldRev is false if the difference engine is called with a "vague" query for
249 # a diff between a version V and its previous version V' AND the version V
250 # is the first version of that article. In that case, V' does not exist.
251 if ( $this->mOldRev
=== false ) {
252 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
256 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
258 if ( $this->mNewPage
->equals( $this->mOldPage
) ) {
259 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
262 $out->setPageTitle( $this->msg( 'difference-title-multipage', $this->mOldPage
->getPrefixedText(),
263 $this->mNewPage
->getPrefixedText() ) );
264 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
268 if ( $samePage && $this->mNewPage
->quickUserCan( 'edit', $user ) ) {
269 if ( $this->mNewRev
->isCurrent() && $this->mNewPage
->userCan( 'rollback', $user ) ) {
270 $rollbackLink = Linker
::generateRollback( $this->mNewRev
, $this->getContext() );
271 if ( $rollbackLink ) {
272 $out->preventClickjacking();
273 $rollback = '   ' . $rollbackLink;
276 if ( !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
277 $undoLink = Html
::element( 'a', array(
278 'href' => $this->mNewPage
->getLocalURL( array(
280 'undoafter' => $this->mOldid
,
281 'undo' => $this->mNewid
) ),
282 'title' => Linker
::titleAttrib( 'undo' )
284 $this->msg( 'editundo' )->text()
286 $revisionTools[] = $undoLink;
290 # Make "previous revision link"
291 if ( $samePage && $this->mOldRev
->getPrevious() ) {
292 $prevlink = Linker
::linkKnown(
294 $this->msg( 'previousdiff' )->escaped(),
295 array( 'id' => 'differences-prevlink' ),
296 array( 'diff' => 'prev', 'oldid' => $this->mOldid
) +
$query
299 $prevlink = ' ';
302 if ( $this->mOldRev
->isMinor() ) {
303 $oldminor = ChangesList
::flag( 'minor' );
308 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
309 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev
, 'complete' );
310 $oldChangeTags = ChangeTags
::formatSummaryRow( $this->mOldTags
, 'diff' );
312 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
313 '<div id="mw-diff-otitle2">' .
314 Linker
::revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
315 '<div id="mw-diff-otitle3">' . $oldminor .
316 Linker
::revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
317 '<div id="mw-diff-otitle5">' . $oldChangeTags[0] . '</div>' .
318 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
320 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
321 $deleted = true; // old revisions text is hidden
322 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
323 $suppressed = true; // also suppressed
327 # Check if this user can see the revisions
328 if ( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $user ) ) {
333 # Make "next revision link"
334 # Skip next link on the top revision
335 if ( $samePage && !$this->mNewRev
->isCurrent() ) {
336 $nextlink = Linker
::linkKnown(
338 $this->msg( 'nextdiff' )->escaped(),
339 array( 'id' => 'differences-nextlink' ),
340 array( 'diff' => 'next', 'oldid' => $this->mNewid
) +
$query
343 $nextlink = ' ';
346 if ( $this->mNewRev
->isMinor() ) {
347 $newminor = ChangesList
::flag( 'minor' );
352 # Handle RevisionDelete links...
353 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
355 # Allow extensions to define their own revision tools
356 wfRunHooks( 'DiffRevisionTools', array( $this->mNewRev
, &$revisionTools ) );
357 $formattedRevisionTools = array();
358 // Put each one in parentheses (poor man's button)
359 foreach ( $revisionTools as $tool ) {
360 $formattedRevisionTools[] = $this->msg( 'parentheses' )->rawParams( $tool )->escaped();
362 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev
, 'complete' ) . ' ' . implode( ' ', $formattedRevisionTools );
363 $newChangeTags = ChangeTags
::formatSummaryRow( $this->mNewTags
, 'diff' );
365 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
366 '<div id="mw-diff-ntitle2">' . Linker
::revUserTools( $this->mNewRev
, !$this->unhide
) .
368 '<div id="mw-diff-ntitle3">' . $newminor .
369 Linker
::revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
370 '<div id="mw-diff-ntitle5">' . $newChangeTags[0] . '</div>' .
371 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
373 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
374 $deleted = true; // new revisions text is hidden
375 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
376 $suppressed = true; // also suppressed
380 # If the diff cannot be shown due to a deleted revision, then output
381 # the diff header and links to unhide (if available)...
382 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
383 $this->showDiffStyle();
384 $multi = $this->getMultiNotice();
385 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
387 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
388 # Give explanation for why revision is not visible
389 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
392 # Give explanation and add a link to view the diff...
393 $link = $this->getTitle()->getFullURL( $this->getRequest()->appendQueryValue( 'unhide', '1', true ) );
394 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
395 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n", array( $msg, $link ) );
397 # Otherwise, output a regular diff...
399 # Add deletion notice if the user is viewing deleted content
402 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
403 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" . $this->msg( $msg )->parse() . "</div>\n";
405 $this->showDiff( $oldHeader, $newHeader, $notice );
407 $this->renderNewRevision();
410 wfProfileOut( __METHOD__
);
414 * Get a link to mark the change as patrolled, or '' if there's either no
415 * revision to patrol or the user is not allowed to to it.
416 * Side effect: When the patrol link is build, this method will call
417 * OutputPage::preventClickjacking() and load mediawiki.page.patrol.ajax.
421 protected function markPatrolledLink() {
422 global $wgUseRCPatrol, $wgEnableAPI, $wgEnableWriteAPI;
423 $user = $this->getUser();
425 if ( $this->mMarkPatrolledLink
=== null ) {
426 // Prepare a change patrol link, if applicable
428 // Is patrolling enabled and the user allowed to?
429 $wgUseRCPatrol && $this->mNewPage
->quickUserCan( 'patrol', $user ) &&
430 // Only do this if the revision isn't more than 6 hours older
431 // than the Max RC age (6h because the RC might not be cleaned out regularly)
432 RecentChange
::isInRCLifespan( $this->mNewRev
->getTimestamp(), 21600 )
434 // Look for an unpatrolled change corresponding to this diff
436 $db = wfGetDB( DB_SLAVE
);
437 $change = RecentChange
::newFromConds(
439 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
440 'rc_this_oldid' => $this->mNewid
,
444 array( 'USE INDEX' => 'rc_timestamp' )
447 if ( $change && $change->getPerformer()->getName() !== $user->getName() ) {
448 $rcid = $change->getAttribute( 'rc_id' );
450 // None found or the page has been created by the current user.
451 // If the user could patrol this it already would be patrolled
456 $this->getOutput()->preventClickjacking();
457 if ( $wgEnableAPI && $wgEnableWriteAPI
458 && $user->isAllowed( 'writeapi' )
460 $this->getOutput()->addModules( 'mediawiki.page.patrol.ajax' );
463 $token = $user->getEditToken( $rcid );
464 $this->mMarkPatrolledLink
= ' <span class="patrollink">[' . Linker
::linkKnown(
466 $this->msg( 'markaspatrolleddiff' )->escaped(),
469 'action' => 'markpatrolled',
475 $this->mMarkPatrolledLink
= '';
478 $this->mMarkPatrolledLink
= '';
482 return $this->mMarkPatrolledLink
;
486 * @param $rev Revision
489 protected function revisionDeleteLink( $rev ) {
490 $link = Linker
::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
491 if ( $link !== '' ) {
492 $link = '   ' . $link . ' ';
498 * Show the new revision of the page.
500 function renderNewRevision() {
501 wfProfileIn( __METHOD__
);
502 $out = $this->getOutput();
503 $revHeader = $this->getRevisionHeader( $this->mNewRev
);
504 # Add "current version as of X" title
505 $out->addHTML( "<hr class='diff-hr' />
506 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
507 # Page content may be handled by a hooked call instead...
508 if ( wfRunHooks( 'ArticleContentOnDiff', array( $this, $out ) ) ) {
509 $this->loadNewText();
510 $out->setRevisionId( $this->mNewid
);
511 $out->setRevisionTimestamp( $this->mNewRev
->getTimestamp() );
512 $out->setArticleFlag( true );
514 // NOTE: only needed for B/C: custom rendering of JS/CSS via hook
515 if ( $this->mNewPage
->isCssJsSubpage() ||
$this->mNewPage
->isCssOrJsPage() ) {
516 // Stolen from Article::view --AG 2007-10-11
517 // Give hooks a chance to customise the output
518 // @todo standardize this crap into one function
519 if ( ContentHandler
::runLegacyHooks( 'ShowRawCssJs', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
520 // NOTE: deprecated hook, B/C only
521 // use the content object's own rendering
522 $cnt = $this->mNewRev
->getContent();
523 $po = $cnt ?
$cnt->getParserOutput( $this->mNewRev
->getTitle(), $this->mNewRev
->getId() ) : null;
524 $txt = $po ?
$po->getText() : '';
525 $out->addHTML( $txt );
527 } elseif ( !wfRunHooks( 'ArticleContentViewCustom', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
528 // Handled by extension
529 } elseif ( !ContentHandler
::runLegacyHooks( 'ArticleViewCustom', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
530 // NOTE: deprecated hook, B/C only
531 // Handled by extension
534 if ( $this->getTitle()->equals( $this->mNewPage
) ) {
535 // If the Title stored in the context is the same as the one
536 // of the new revision, we can use its associated WikiPage
538 $wikiPage = $this->getWikiPage();
540 // Otherwise we need to create our own WikiPage object
541 $wikiPage = WikiPage
::factory( $this->mNewPage
);
544 $parserOutput = $this->getParserOutput( $wikiPage, $this->mNewRev
);
546 # Also try to load it as a redirect
547 $rt = $this->mNewContent ?
$this->mNewContent
->getRedirectTarget() : null;
550 $article = Article
::newFromTitle( $this->mNewPage
, $this->getContext() );
551 $out->addHTML( $article->viewRedirect( $rt ) );
553 # WikiPage::getParserOutput() should not return false, but just in case
554 if ( $parserOutput ) {
555 # Show categories etc.
556 $out->addParserOutputNoText( $parserOutput );
558 } elseif ( $parserOutput ) {
559 $out->addParserOutput( $parserOutput );
563 # Add redundant patrol link on bottom...
564 $out->addHTML( $this->markPatrolledLink() );
566 wfProfileOut( __METHOD__
);
569 protected function getParserOutput( WikiPage
$page, Revision
$rev ) {
570 $parserOptions = $page->makeParserOptions( $this->getContext() );
572 if ( !$rev->isCurrent() ||
!$rev->getTitle()->quickUserCan( "edit" ) ) {
573 $parserOptions->setEditSection( false );
576 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
577 return $parserOutput;
581 * Get the diff text, send it to the OutputPage object
582 * Returns false if the diff could not be generated, otherwise returns true
586 function showDiff( $otitle, $ntitle, $notice = '' ) {
587 $diff = $this->getDiff( $otitle, $ntitle, $notice );
588 if ( $diff === false ) {
589 $this->showMissingRevision();
592 $this->showDiffStyle();
593 $this->getOutput()->addHTML( $diff );
599 * Add style sheets and supporting JS for diff display.
601 function showDiffStyle() {
602 $this->getOutput()->addModuleStyles( 'mediawiki.action.history.diff' );
606 * Get complete diff table, including header
608 * @param string|bool $otitle Header for old text or false
609 * @param string|bool $ntitle Header for new text or false
610 * @param string $notice HTML between diff header and body
613 function getDiff( $otitle, $ntitle, $notice = '' ) {
614 $body = $this->getDiffBody();
615 if ( $body === false ) {
618 $multi = $this->getMultiNotice();
619 // Display a message when the diff is empty
620 if ( $body === '' ) {
621 $notice .= '<div class="mw-diff-empty">' . $this->msg( 'diff-empty' )->parse() . "</div>\n";
623 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
628 * Get the diff table body, without header
630 * @return mixed (string/false)
632 public function getDiffBody() {
634 wfProfileIn( __METHOD__
);
635 $this->mCacheHit
= true;
636 // Check if the diff should be hidden from this user
637 if ( !$this->loadRevisionData() ) {
638 wfProfileOut( __METHOD__
);
640 } elseif ( $this->mOldRev
&& !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
641 wfProfileOut( __METHOD__
);
643 } elseif ( $this->mNewRev
&& !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
644 wfProfileOut( __METHOD__
);
648 if ( $this->mOldRev
=== false ||
( $this->mOldRev
&& $this->mNewRev
649 && $this->mOldRev
->getID() == $this->mNewRev
->getID() ) )
651 wfProfileOut( __METHOD__
);
656 if ( $this->mOldid
&& $this->mNewid
) {
657 $key = $this->getDiffBodyCacheKey();
660 if ( !$this->mRefreshCache
) {
661 $difftext = $wgMemc->get( $key );
663 wfIncrStats( 'diff_cache_hit' );
664 $difftext = $this->localiseLineNumbers( $difftext );
665 $difftext .= "\n<!-- diff cache key $key -->\n";
666 wfProfileOut( __METHOD__
);
669 } // don't try to load but save the result
671 $this->mCacheHit
= false;
673 // Loadtext is permission safe, this just clears out the diff
674 if ( !$this->loadText() ) {
675 wfProfileOut( __METHOD__
);
679 $difftext = $this->generateContentDiffBody( $this->mOldContent
, $this->mNewContent
);
681 // Save to cache for 7 days
682 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
683 wfIncrStats( 'diff_uncacheable' );
684 } elseif ( $key !== false && $difftext !== false ) {
685 wfIncrStats( 'diff_cache_miss' );
686 $wgMemc->set( $key, $difftext, 7 * 86400 );
688 wfIncrStats( 'diff_uncacheable' );
690 // Replace line numbers with the text in the user's language
691 if ( $difftext !== false ) {
692 $difftext = $this->localiseLineNumbers( $difftext );
694 wfProfileOut( __METHOD__
);
699 * Returns the cache key for diff body text or content.
703 * @throws MWException
705 protected function getDiffBodyCacheKey() {
706 if ( !$this->mOldid ||
!$this->mNewid
) {
707 throw new MWException( 'mOldid and mNewid must be set to get diff cache key.' );
710 return wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
,
711 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
715 * Generate a diff, no caching.
717 * This implementation uses generateTextDiffBody() to generate a diff based on the default
718 * serialization of the given Content objects. This will fail if $old or $new are not
719 * instances of TextContent.
721 * Subclasses may override this to provide a different rendering for the diff,
722 * perhaps taking advantage of the content's native form. This is required for all content
723 * models that are not text based.
725 * @param $old Content: old content
726 * @param $new Content: new content
728 * @return bool|string
730 * @throws MWException if $old or $new are not instances of TextContent.
732 function generateContentDiffBody( Content
$old, Content
$new ) {
733 if ( !( $old instanceof TextContent
) ) {
734 throw new MWException( "Diff not implemented for " . get_class( $old ) . "; "
735 . "override generateContentDiffBody to fix this." );
738 if ( !( $new instanceof TextContent
) ) {
739 throw new MWException( "Diff not implemented for " . get_class( $new ) . "; "
740 . "override generateContentDiffBody to fix this." );
743 $otext = $old->serialize();
744 $ntext = $new->serialize();
746 return $this->generateTextDiffBody( $otext, $ntext );
750 * Generate a diff, no caching
752 * @param string $otext old text, must be already segmented
753 * @param string $ntext new text, must be already segmented
754 * @return bool|string
755 * @deprecated since 1.21, use generateContentDiffBody() instead!
757 function generateDiffBody( $otext, $ntext ) {
758 ContentHandler
::deprecated( __METHOD__
, "1.21" );
760 return $this->generateTextDiffBody( $otext, $ntext );
764 * Generate a diff, no caching
766 * @todo move this to TextDifferenceEngine, make DifferenceEngine abstract. At some point.
768 * @param string $otext old text, must be already segmented
769 * @param string $ntext new text, must be already segmented
770 * @return bool|string
772 function generateTextDiffBody( $otext, $ntext ) {
773 global $wgExternalDiffEngine, $wgContLang;
775 wfProfileIn( __METHOD__
);
777 $otext = str_replace( "\r\n", "\n", $otext );
778 $ntext = str_replace( "\r\n", "\n", $ntext );
780 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
781 # For historical reasons, external diff engine expects
782 # input text to be HTML-escaped already
783 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
784 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
785 wfProfileOut( __METHOD__
);
786 return $wgContLang->unsegmentForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
787 $this->debug( 'wikidiff1' );
790 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
791 # Better external diff engine, the 2 may some day be dropped
792 # This one does the escaping and segmenting itself
793 wfProfileIn( 'wikidiff2_do_diff' );
794 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
795 $text .= $this->debug( 'wikidiff2' );
796 wfProfileOut( 'wikidiff2_do_diff' );
797 wfProfileOut( __METHOD__
);
800 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
802 $tmpDir = wfTempDir();
803 $tempName1 = tempnam( $tmpDir, 'diff_' );
804 $tempName2 = tempnam( $tmpDir, 'diff_' );
806 $tempFile1 = fopen( $tempName1, "w" );
808 wfProfileOut( __METHOD__
);
811 $tempFile2 = fopen( $tempName2, "w" );
813 wfProfileOut( __METHOD__
);
816 fwrite( $tempFile1, $otext );
817 fwrite( $tempFile2, $ntext );
818 fclose( $tempFile1 );
819 fclose( $tempFile2 );
820 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
821 wfProfileIn( __METHOD__
. "-shellexec" );
822 $difftext = wfShellExec( $cmd );
823 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
824 wfProfileOut( __METHOD__
. "-shellexec" );
825 unlink( $tempName1 );
826 unlink( $tempName2 );
827 wfProfileOut( __METHOD__
);
832 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
833 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
834 $diffs = new Diff( $ota, $nta );
835 $formatter = new TableDiffFormatter();
836 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
837 wfProfileOut( __METHOD__
);
842 * Generate a debug comment indicating diff generating time,
843 * server node, and generator backend.
846 protected function debug( $generator = "internal" ) {
847 global $wgShowHostnames;
848 if ( !$this->enableDebugComment
) {
851 $data = array( $generator );
852 if ( $wgShowHostnames ) {
853 $data[] = wfHostname();
855 $data[] = wfTimestamp( TS_DB
);
856 return "<!-- diff generator: " .
865 * Replace line numbers with the text in the user's language
868 function localiseLineNumbers( $text ) {
869 return preg_replace_callback( '/<!--LINE (\d+)-->/',
870 array( &$this, 'localiseLineNumbersCb' ), $text );
873 function localiseLineNumbersCb( $matches ) {
874 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) {
877 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
881 * If there are revisions between the ones being compared, return a note saying so.
884 function getMultiNotice() {
885 if ( !is_object( $this->mOldRev
) ||
!is_object( $this->mNewRev
) ) {
887 } elseif ( !$this->mOldPage
->equals( $this->mNewPage
) ) {
888 // Comparing two different pages? Count would be meaningless.
892 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
893 $oldRev = $this->mNewRev
; // flip
894 $newRev = $this->mOldRev
; // flip
895 } else { // normal case
896 $oldRev = $this->mOldRev
;
897 $newRev = $this->mNewRev
;
900 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev );
902 $limit = 100; // use diff-multi-manyusers if too many users
903 $numUsers = $this->mNewPage
->countAuthorsBetween( $oldRev, $newRev, $limit );
904 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
906 return ''; // nothing
910 * Get a notice about how many intermediate edits and users there are
911 * @param $numEdits int
912 * @param $numUsers int
916 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
917 if ( $numUsers > $limit ) {
918 $msg = 'diff-multi-manyusers';
923 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
927 * Get a header for a specified revision.
929 * @param $rev Revision
930 * @param string $complete 'complete' to get the header wrapped depending
931 * the visibility of the revision and a link to edit the page.
932 * @return String HTML fragment
934 protected function getRevisionHeader( Revision
$rev, $complete = '' ) {
935 $lang = $this->getLanguage();
936 $user = $this->getUser();
937 $revtimestamp = $rev->getTimestamp();
938 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
939 $dateofrev = $lang->userDate( $revtimestamp, $user );
940 $timeofrev = $lang->userTime( $revtimestamp, $user );
942 $header = $this->msg(
943 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
949 if ( $complete !== 'complete' ) {
953 $title = $rev->getTitle();
955 $header = Linker
::linkKnown( $title, $header, array(),
956 array( 'oldid' => $rev->getID() ) );
958 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
959 $editQuery = array( 'action' => 'edit' );
960 if ( !$rev->isCurrent() ) {
961 $editQuery['oldid'] = $rev->getID();
964 $msg = $this->msg( $title->quickUserCan( 'edit', $user ) ?
'editold' : 'viewsourceold' )->escaped();
965 $header .= ' ' . $this->msg( 'parentheses' )->rawParams(
966 Linker
::linkKnown( $title, $msg, array(), $editQuery ) )->plain();
967 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
968 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
971 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
978 * Add the header to a diff body
982 function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
983 // shared.css sets diff in interface language/dir, but the actual content
984 // is often in a different language, mostly the page content language/dir
985 $tableClass = 'diff diff-contentalign-' . htmlspecialchars( $this->getDiffLang()->alignStart() );
986 $header = "<table class='$tableClass'>";
988 if ( !$diff && !$otitle ) {
990 <tr style='vertical-align: top;'>
991 <td class='diff-ntitle'>{$ntitle}</td>
995 if ( $diff ) { // Safari/Chrome show broken output if cols not used
997 <col class='diff-marker' />
998 <col class='diff-content' />
999 <col class='diff-marker' />
1000 <col class='diff-content' />";
1007 if ( $otitle ||
$ntitle ) {
1009 <tr style='vertical-align: top;'>
1010 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
1011 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
1016 if ( $multi != '' ) {
1017 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;' class='diff-multi'>{$multi}</td></tr>";
1019 if ( $notice != '' ) {
1020 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;'>{$notice}</td></tr>";
1023 return $header . $diff . "</table>";
1027 * Use specified text instead of loading from the database
1028 * @deprecated since 1.21, use setContent() instead.
1030 function setText( $oldText, $newText ) {
1031 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1033 $oldContent = ContentHandler
::makeContent( $oldText, $this->getTitle() );
1034 $newContent = ContentHandler
::makeContent( $newText, $this->getTitle() );
1036 $this->setContent( $oldContent, $newContent );
1040 * Use specified text instead of loading from the database
1043 function setContent( Content
$oldContent, Content
$newContent ) {
1044 $this->mOldContent
= $oldContent;
1045 $this->mNewContent
= $newContent;
1047 $this->mTextLoaded
= 2;
1048 $this->mRevisionsLoaded
= true;
1052 * Set the language in which the diff text is written
1053 * (Defaults to page content language).
1056 function setTextLanguage( $lang ) {
1057 $this->mDiffLang
= wfGetLangObj( $lang );
1061 * Maps a revision pair definition as accepted by DifferenceEngine constructor
1062 * to a pair of actual integers representing revision ids.
1064 * @param int $old Revision id, e.g. from URL parameter 'oldid'
1065 * @param int|string $new Revision id or strings 'next' or 'prev', e.g. from URL parameter 'diff'
1066 * @return array Array of two revision ids, older first, later second.
1067 * Zero signifies invalid argument passed.
1068 * false signifies that there is no previous/next revision ($old is the oldest/newest one).
1070 public function mapDiffPrevNext( $old, $new ) {
1071 if ( $new === 'prev' ) {
1072 // Show diff between revision $old and the previous one. Get previous one from DB.
1073 $newid = intval( $old );
1074 $oldid = $this->getTitle()->getPreviousRevisionID( $newid );
1075 } elseif ( $new === 'next' ) {
1076 // Show diff between revision $old and the next one. Get next one from DB.
1077 $oldid = intval( $old );
1078 $newid = $this->getTitle()->getNextRevisionID( $oldid );
1080 $oldid = intval( $old );
1081 $newid = intval( $new );
1084 return array( $oldid, $newid );
1090 private function loadRevisionIds() {
1091 if ( $this->mRevisionsIdsLoaded
) {
1095 $this->mRevisionsIdsLoaded
= true;
1097 $old = $this->mOldid
;
1098 $new = $this->mNewid
;
1100 list( $this->mOldid
, $this->mNewid
) = self
::mapDiffPrevNext( $old, $new );
1101 if ( $new === 'next' && $this->mNewid
=== false ) {
1102 # if no result, NewId points to the newest old revision. The only newer
1103 # revision is cur, which is "0".
1107 wfRunHooks( 'NewDifferenceEngine', array( $this->getTitle(), &$this->mOldid
, &$this->mNewid
, $old, $new ) );
1111 * Load revision metadata for the specified articles. If newid is 0, then compare
1112 * the old article in oldid to the current article; if oldid is 0, then
1113 * compare the current article to the immediately previous one (ignoring the
1116 * If oldid is false, leave the corresponding revision object set
1117 * to false. This is impossible via ordinary user input, and is provided for
1122 function loadRevisionData() {
1123 if ( $this->mRevisionsLoaded
) {
1127 // Whether it succeeds or fails, we don't want to try again
1128 $this->mRevisionsLoaded
= true;
1130 $this->loadRevisionIds();
1132 // Load the new revision object
1133 $this->mNewRev
= $this->mNewid
1134 ? Revision
::newFromId( $this->mNewid
)
1135 : Revision
::newFromTitle( $this->getTitle(), false, Revision
::READ_NORMAL
);
1137 if ( !$this->mNewRev
instanceof Revision
) {
1141 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1142 $this->mNewid
= $this->mNewRev
->getId();
1143 $this->mNewPage
= $this->mNewRev
->getTitle();
1145 // Load the old revision object
1146 $this->mOldRev
= false;
1147 if ( $this->mOldid
) {
1148 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1149 } elseif ( $this->mOldid
=== 0 ) {
1150 $rev = $this->mNewRev
->getPrevious();
1152 $this->mOldid
= $rev->getId();
1153 $this->mOldRev
= $rev;
1155 // No previous revision; mark to show as first-version only.
1156 $this->mOldid
= false;
1157 $this->mOldRev
= false;
1159 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1161 if ( is_null( $this->mOldRev
) ) {
1165 if ( $this->mOldRev
) {
1166 $this->mOldPage
= $this->mOldRev
->getTitle();
1169 // Load tags information for both revisions
1170 $dbr = wfGetDB( DB_SLAVE
);
1171 if ( $this->mOldid
!== false ) {
1172 $this->mOldTags
= $dbr->selectField(
1175 array( 'ts_rev_id' => $this->mOldid
),
1179 $this->mOldTags
= false;
1181 $this->mNewTags
= $dbr->selectField(
1184 array( 'ts_rev_id' => $this->mNewid
),
1192 * Load the text of the revisions, as well as revision data.
1196 function loadText() {
1197 if ( $this->mTextLoaded
== 2 ) {
1201 // Whether it succeeds or fails, we don't want to try again
1202 $this->mTextLoaded
= 2;
1204 if ( !$this->loadRevisionData() ) {
1208 if ( $this->mOldRev
) {
1209 $this->mOldContent
= $this->mOldRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1210 if ( $this->mOldContent
=== null ) {
1215 if ( $this->mNewRev
) {
1216 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1217 if ( $this->mNewContent
=== null ) {
1226 * Load the text of the new revision, not the old one
1230 function loadNewText() {
1231 if ( $this->mTextLoaded
>= 1 ) {
1235 $this->mTextLoaded
= 1;
1237 if ( !$this->loadRevisionData() ) {
1241 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );