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
{
67 /** @var bool Have the revisions IDs been loaded */
68 private $mRevisionsIdsLoaded = false;
70 /** @var bool Have the revisions been loaded */
71 public $mRevisionsLoaded = false;
73 /** @var int How many text blobs have been loaded, 0, 1 or 2? */
74 public $mTextLoaded = 0;
76 /** @var bool Was the diff fetched from cache? */
77 public $mCacheHit = false;
80 * Set this to true to add debug info to the HTML output.
81 * Warning: this may cause RSS readers to spuriously mark articles as "new"
84 public $enableDebugComment = false;
86 /** @var bool If true, line X is not displayed when X is 1, for example
87 * to increase readability and conserve space with many small diffs.
89 protected $mReducedLineNumbers = false;
91 /** @var string Link to action=markpatrolled */
92 protected $mMarkPatrolledLink = null;
94 /** @var bool Show rev_deleted content if allowed */
95 protected $unhide = false;
100 * @param $context IContextSource context to use, anything else will be ignored
101 * @param $old Integer old ID we want to show and diff with.
102 * @param $new String|int either revision ID or 'prev' or 'next'. Default: 0.
103 * @param $rcid Integer Deprecated, no longer used!
104 * @param $refreshCache boolean If set, refreshes the diff cache
105 * @param $unhide boolean If set, allow viewing deleted revs
107 function __construct( $context = null, $old = 0, $new = 0, $rcid = 0,
108 $refreshCache = false, $unhide = false
110 if ( $context instanceof IContextSource
) {
111 $this->setContext( $context );
114 wfDebug( "DifferenceEngine old '$old' new '$new' rcid '$rcid'\n" );
116 $this->mOldid
= $old;
117 $this->mNewid
= $new;
118 $this->mRefreshCache
= $refreshCache;
119 $this->unhide
= $unhide;
125 function setReducedLineNumbers( $value = true ) {
126 $this->mReducedLineNumbers
= $value;
132 function getDiffLang() {
133 if ( $this->mDiffLang
=== null ) {
134 # Default language in which the diff text is written.
135 $this->mDiffLang
= $this->getTitle()->getPageLanguage();
138 return $this->mDiffLang
;
144 function wasCacheHit() {
145 return $this->mCacheHit
;
151 function getOldid() {
152 $this->loadRevisionIds();
154 return $this->mOldid
;
160 function getNewid() {
161 $this->loadRevisionIds();
163 return $this->mNewid
;
167 * Look up a special:Undelete link to the given deleted revision id,
168 * as a workaround for being unable to load deleted diffs in currently.
170 * @param int $id revision ID
171 * @return mixed URL or false
173 function deletedLink( $id ) {
174 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
175 $dbr = wfGetDB( DB_SLAVE
);
176 $row = $dbr->selectRow( 'archive', '*',
177 array( 'ar_rev_id' => $id ),
180 $rev = Revision
::newFromArchiveRow( $row );
181 $title = Title
::makeTitleSafe( $row->ar_namespace
, $row->ar_title
);
183 return SpecialPage
::getTitleFor( 'Undelete' )->getFullURL( array(
184 'target' => $title->getPrefixedText(),
185 'timestamp' => $rev->getTimestamp()
194 * Build a wikitext link toward a deleted revision, if viewable.
196 * @param int $id revision ID
197 * @return string wikitext fragment
199 function deletedIdMarker( $id ) {
200 $link = $this->deletedLink( $id );
202 return "[$link $id]";
208 private function showMissingRevision() {
209 $out = $this->getOutput();
212 if ( $this->mOldRev
=== null ||
213 ( $this->mOldRev
&& $this->mOldContent
=== null )
215 $missing[] = $this->deletedIdMarker( $this->mOldid
);
217 if ( $this->mNewRev
=== null ||
218 ( $this->mNewRev
&& $this->mNewContent
=== null )
220 $missing[] = $this->deletedIdMarker( $this->mNewid
);
223 $out->setPageTitle( $this->msg( 'errorpagetitle' ) );
224 $out->addWikiMsg( 'difference-missing-revision',
225 $this->getLanguage()->listToText( $missing ), count( $missing ) );
228 function showDiffPage( $diffOnly = false ) {
229 wfProfileIn( __METHOD__
);
231 # Allow frames except in certain special cases
232 $out = $this->getOutput();
233 $out->allowClickjacking();
234 $out->setRobotPolicy( 'noindex,nofollow' );
236 if ( !$this->loadRevisionData() ) {
237 $this->showMissingRevision();
238 wfProfileOut( __METHOD__
);
243 $user = $this->getUser();
244 $permErrors = $this->mNewPage
->getUserPermissionsErrors( 'read', $user );
245 if ( $this->mOldPage
) { # mOldPage might not be set, see below.
246 $permErrors = wfMergeErrorArrays( $permErrors,
247 $this->mOldPage
->getUserPermissionsErrors( 'read', $user ) );
249 if ( count( $permErrors ) ) {
250 wfProfileOut( __METHOD__
);
251 throw new PermissionsError( 'read', $permErrors );
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 $revisionTools = array();
272 # mOldRev is false if the difference engine is called with a "vague" query for
273 # a diff between a version V and its previous version V' AND the version V
274 # is the first version of that article. In that case, V' does not exist.
275 if ( $this->mOldRev
=== false ) {
276 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
280 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
282 if ( $this->mNewPage
->equals( $this->mOldPage
) ) {
283 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
286 $out->setPageTitle( $this->msg( 'difference-title-multipage',
287 $this->mOldPage
->getPrefixedText(), $this->mNewPage
->getPrefixedText() ) );
288 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
292 if ( $samePage && $this->mNewPage
->quickUserCan( 'edit', $user ) ) {
293 if ( $this->mNewRev
->isCurrent() && $this->mNewPage
->userCan( 'rollback', $user ) ) {
294 $rollbackLink = Linker
::generateRollback( $this->mNewRev
, $this->getContext() );
295 if ( $rollbackLink ) {
296 $out->preventClickjacking();
297 $rollback = '   ' . $rollbackLink;
301 if ( !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) &&
302 !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
)
304 $undoLink = Html
::element( 'a', array(
305 'href' => $this->mNewPage
->getLocalURL( array(
307 'undoafter' => $this->mOldid
,
308 'undo' => $this->mNewid
310 'title' => Linker
::titleAttrib( 'undo' )
312 $this->msg( 'editundo' )->text()
314 $revisionTools[] = $undoLink;
318 # Make "previous revision link"
319 if ( $samePage && $this->mOldRev
->getPrevious() ) {
320 $prevlink = Linker
::linkKnown(
322 $this->msg( 'previousdiff' )->escaped(),
323 array( 'id' => 'differences-prevlink' ),
324 array( 'diff' => 'prev', 'oldid' => $this->mOldid
) +
$query
327 $prevlink = ' ';
330 if ( $this->mOldRev
->isMinor() ) {
331 $oldminor = ChangesList
::flag( 'minor' );
336 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
337 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev
, 'complete' );
338 $oldChangeTags = ChangeTags
::formatSummaryRow( $this->mOldTags
, 'diff' );
340 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
341 '<div id="mw-diff-otitle2">' .
342 Linker
::revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
343 '<div id="mw-diff-otitle3">' . $oldminor .
344 Linker
::revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
345 '<div id="mw-diff-otitle5">' . $oldChangeTags[0] . '</div>' .
346 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
348 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
349 $deleted = true; // old revisions text is hidden
350 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
351 $suppressed = true; // also suppressed
355 # Check if this user can see the revisions
356 if ( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $user ) ) {
361 # Make "next revision link"
362 # Skip next link on the top revision
363 if ( $samePage && !$this->mNewRev
->isCurrent() ) {
364 $nextlink = Linker
::linkKnown(
366 $this->msg( 'nextdiff' )->escaped(),
367 array( 'id' => 'differences-nextlink' ),
368 array( 'diff' => 'next', 'oldid' => $this->mNewid
) +
$query
371 $nextlink = ' ';
374 if ( $this->mNewRev
->isMinor() ) {
375 $newminor = ChangesList
::flag( 'minor' );
380 # Handle RevisionDelete links...
381 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
383 # Allow extensions to define their own revision tools
384 wfRunHooks( 'DiffRevisionTools', array( $this->mNewRev
, &$revisionTools, $this->mOldRev
) );
385 $formattedRevisionTools = array();
386 // Put each one in parentheses (poor man's button)
387 foreach ( $revisionTools as $tool ) {
388 $formattedRevisionTools[] = $this->msg( 'parentheses' )->rawParams( $tool )->escaped();
390 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev
, 'complete' ) .
391 ' ' . implode( ' ', $formattedRevisionTools );
392 $newChangeTags = ChangeTags
::formatSummaryRow( $this->mNewTags
, 'diff' );
394 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
395 '<div id="mw-diff-ntitle2">' . Linker
::revUserTools( $this->mNewRev
, !$this->unhide
) .
397 '<div id="mw-diff-ntitle3">' . $newminor .
398 Linker
::revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
399 '<div id="mw-diff-ntitle5">' . $newChangeTags[0] . '</div>' .
400 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
402 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
403 $deleted = true; // new revisions text is hidden
404 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
405 $suppressed = true; // also suppressed
409 # If the diff cannot be shown due to a deleted revision, then output
410 # the diff header and links to unhide (if available)...
411 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
412 $this->showDiffStyle();
413 $multi = $this->getMultiNotice();
414 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
416 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
417 # Give explanation for why revision is not visible
418 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
421 # Give explanation and add a link to view the diff...
422 $query = $this->getRequest()->appendQueryValue( 'unhide', '1', true );
423 $link = $this->getTitle()->getFullURL( $query );
424 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
426 "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
430 # Otherwise, output a regular diff...
432 # Add deletion notice if the user is viewing deleted content
435 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
436 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" .
437 $this->msg( $msg )->parse() .
440 $this->showDiff( $oldHeader, $newHeader, $notice );
442 $this->renderNewRevision();
445 wfProfileOut( __METHOD__
);
449 * Get a link to mark the change as patrolled, or '' if there's either no
450 * revision to patrol or the user is not allowed to to it.
451 * Side effect: When the patrol link is build, this method will call
452 * OutputPage::preventClickjacking() and load mediawiki.page.patrol.ajax.
456 protected function markPatrolledLink() {
457 global $wgUseRCPatrol, $wgEnableAPI, $wgEnableWriteAPI;
458 $user = $this->getUser();
460 if ( $this->mMarkPatrolledLink
=== null ) {
461 // Prepare a change patrol link, if applicable
463 // Is patrolling enabled and the user allowed to?
464 $wgUseRCPatrol && $this->mNewPage
->quickUserCan( 'patrol', $user ) &&
465 // Only do this if the revision isn't more than 6 hours older
466 // than the Max RC age (6h because the RC might not be cleaned out regularly)
467 RecentChange
::isInRCLifespan( $this->mNewRev
->getTimestamp(), 21600 )
469 // Look for an unpatrolled change corresponding to this diff
471 $db = wfGetDB( DB_SLAVE
);
472 $change = RecentChange
::newFromConds(
474 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
475 'rc_this_oldid' => $this->mNewid
,
479 array( 'USE INDEX' => 'rc_timestamp' )
482 if ( $change && $change->getPerformer()->getName() !== $user->getName() ) {
483 $rcid = $change->getAttribute( 'rc_id' );
485 // None found or the page has been created by the current user.
486 // If the user could patrol this it already would be patrolled
491 $this->getOutput()->preventClickjacking();
492 if ( $wgEnableAPI && $wgEnableWriteAPI
493 && $user->isAllowed( 'writeapi' )
495 $this->getOutput()->addModules( 'mediawiki.page.patrol.ajax' );
498 $token = $user->getEditToken( $rcid );
499 $this->mMarkPatrolledLink
= ' <span class="patrollink">[' . Linker
::linkKnown(
501 $this->msg( 'markaspatrolleddiff' )->escaped(),
504 'action' => 'markpatrolled',
510 $this->mMarkPatrolledLink
= '';
513 $this->mMarkPatrolledLink
= '';
517 return $this->mMarkPatrolledLink
;
521 * @param $rev Revision
524 protected function revisionDeleteLink( $rev ) {
525 $link = Linker
::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
526 if ( $link !== '' ) {
527 $link = '   ' . $link . ' ';
534 * Show the new revision of the page.
536 function renderNewRevision() {
537 wfProfileIn( __METHOD__
);
538 $out = $this->getOutput();
539 $revHeader = $this->getRevisionHeader( $this->mNewRev
);
540 # Add "current version as of X" title
541 $out->addHTML( "<hr class='diff-hr' />
542 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
543 # Page content may be handled by a hooked call instead...
544 # @codingStandardsIgnoreStart Ignoring long lines.
545 if ( wfRunHooks( 'ArticleContentOnDiff', array( $this, $out ) ) ) {
546 $this->loadNewText();
547 $out->setRevisionId( $this->mNewid
);
548 $out->setRevisionTimestamp( $this->mNewRev
->getTimestamp() );
549 $out->setArticleFlag( true );
551 // NOTE: only needed for B/C: custom rendering of JS/CSS via hook
552 if ( $this->mNewPage
->isCssJsSubpage() ||
$this->mNewPage
->isCssOrJsPage() ) {
553 // Stolen from Article::view --AG 2007-10-11
554 // Give hooks a chance to customise the output
555 // @todo standardize this crap into one function
556 if ( ContentHandler
::runLegacyHooks( 'ShowRawCssJs', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
557 // NOTE: deprecated hook, B/C only
558 // use the content object's own rendering
559 $cnt = $this->mNewRev
->getContent();
560 $po = $cnt ?
$cnt->getParserOutput( $this->mNewRev
->getTitle(), $this->mNewRev
->getId() ) : null;
561 $txt = $po ?
$po->getText() : '';
562 $out->addHTML( $txt );
564 } elseif ( !wfRunHooks( 'ArticleContentViewCustom', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
565 // Handled by extension
566 } elseif ( !ContentHandler
::runLegacyHooks( 'ArticleViewCustom', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
567 // NOTE: deprecated hook, B/C only
568 // Handled by extension
571 if ( $this->getTitle()->equals( $this->mNewPage
) ) {
572 // If the Title stored in the context is the same as the one
573 // of the new revision, we can use its associated WikiPage
575 $wikiPage = $this->getWikiPage();
577 // Otherwise we need to create our own WikiPage object
578 $wikiPage = WikiPage
::factory( $this->mNewPage
);
581 $parserOutput = $this->getParserOutput( $wikiPage, $this->mNewRev
);
583 # WikiPage::getParserOutput() should not return false, but just in case
584 if ( $parserOutput ) {
585 $out->addParserOutput( $parserOutput );
589 # @codingStandardsIgnoreEnd
591 # Add redundant patrol link on bottom...
592 $out->addHTML( $this->markPatrolledLink() );
594 wfProfileOut( __METHOD__
);
597 protected function getParserOutput( WikiPage
$page, Revision
$rev ) {
598 $parserOptions = $page->makeParserOptions( $this->getContext() );
600 if ( !$rev->isCurrent() ||
!$rev->getTitle()->quickUserCan( "edit" ) ) {
601 $parserOptions->setEditSection( false );
604 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
606 return $parserOutput;
610 * Get the diff text, send it to the OutputPage object
611 * Returns false if the diff could not be generated, otherwise returns true
613 * @param string|bool $otitle Header for old text or false
614 * @param string|bool $ntitle Header for new text or false
615 * @param string $notice HTML between diff header and body
619 function showDiff( $otitle, $ntitle, $notice = '' ) {
620 $diff = $this->getDiff( $otitle, $ntitle, $notice );
621 if ( $diff === false ) {
622 $this->showMissingRevision();
626 $this->showDiffStyle();
627 $this->getOutput()->addHTML( $diff );
634 * Add style sheets and supporting JS for diff display.
636 function showDiffStyle() {
637 $this->getOutput()->addModuleStyles( 'mediawiki.action.history.diff' );
641 * Get complete diff table, including header
643 * @param string|bool $otitle Header for old text or false
644 * @param string|bool $ntitle Header for new text or false
645 * @param string $notice HTML between diff header and body
648 function getDiff( $otitle, $ntitle, $notice = '' ) {
649 $body = $this->getDiffBody();
650 if ( $body === false ) {
654 $multi = $this->getMultiNotice();
655 // Display a message when the diff is empty
656 if ( $body === '' ) {
657 $notice .= '<div class="mw-diff-empty">' .
658 $this->msg( 'diff-empty' )->parse() .
662 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
666 * Get the diff table body, without header
668 * @return mixed (string/false)
670 public function getDiffBody() {
672 wfProfileIn( __METHOD__
);
673 $this->mCacheHit
= true;
674 // Check if the diff should be hidden from this user
675 if ( !$this->loadRevisionData() ) {
676 wfProfileOut( __METHOD__
);
679 } elseif ( $this->mOldRev
&&
680 !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
682 wfProfileOut( __METHOD__
);
685 } elseif ( $this->mNewRev
&&
686 !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
688 wfProfileOut( __METHOD__
);
693 if ( $this->mOldRev
=== false ||
( $this->mOldRev
&& $this->mNewRev
694 && $this->mOldRev
->getID() == $this->mNewRev
->getID() )
696 wfProfileOut( __METHOD__
);
702 if ( $this->mOldid
&& $this->mNewid
) {
703 $key = $this->getDiffBodyCacheKey();
706 if ( !$this->mRefreshCache
) {
707 $difftext = $wgMemc->get( $key );
709 wfIncrStats( 'diff_cache_hit' );
710 $difftext = $this->localiseLineNumbers( $difftext );
711 $difftext .= "\n<!-- diff cache key $key -->\n";
712 wfProfileOut( __METHOD__
);
716 } // don't try to load but save the result
718 $this->mCacheHit
= false;
720 // Loadtext is permission safe, this just clears out the diff
721 if ( !$this->loadText() ) {
722 wfProfileOut( __METHOD__
);
727 $difftext = $this->generateContentDiffBody( $this->mOldContent
, $this->mNewContent
);
729 // Save to cache for 7 days
730 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
731 wfIncrStats( 'diff_uncacheable' );
732 } elseif ( $key !== false && $difftext !== false ) {
733 wfIncrStats( 'diff_cache_miss' );
734 $wgMemc->set( $key, $difftext, 7 * 86400 );
736 wfIncrStats( 'diff_uncacheable' );
738 // Replace line numbers with the text in the user's language
739 if ( $difftext !== false ) {
740 $difftext = $this->localiseLineNumbers( $difftext );
742 wfProfileOut( __METHOD__
);
748 * Returns the cache key for diff body text or content.
752 * @throws MWException
754 protected function getDiffBodyCacheKey() {
755 if ( !$this->mOldid ||
!$this->mNewid
) {
756 throw new MWException( 'mOldid and mNewid must be set to get diff cache key.' );
759 return wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
,
760 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
764 * Generate a diff, no caching.
766 * This implementation uses generateTextDiffBody() to generate a diff based on the default
767 * serialization of the given Content objects. This will fail if $old or $new are not
768 * instances of TextContent.
770 * Subclasses may override this to provide a different rendering for the diff,
771 * perhaps taking advantage of the content's native form. This is required for all content
772 * models that are not text based.
774 * @param $old Content: old content
775 * @param $new Content: new content
777 * @return bool|string
779 * @throws MWException if $old or $new are not instances of TextContent.
781 function generateContentDiffBody( Content
$old, Content
$new ) {
782 if ( !( $old instanceof TextContent
) ) {
783 throw new MWException( "Diff not implemented for " . get_class( $old ) . "; " .
784 "override generateContentDiffBody to fix this." );
787 if ( !( $new instanceof TextContent
) ) {
788 throw new MWException( "Diff not implemented for " . get_class( $new ) . "; "
789 . "override generateContentDiffBody to fix this." );
792 $otext = $old->serialize();
793 $ntext = $new->serialize();
795 return $this->generateTextDiffBody( $otext, $ntext );
799 * Generate a diff, no caching
801 * @param string $otext old text, must be already segmented
802 * @param string $ntext new text, must be already segmented
803 * @return bool|string
804 * @deprecated since 1.21, use generateContentDiffBody() instead!
806 function generateDiffBody( $otext, $ntext ) {
807 ContentHandler
::deprecated( __METHOD__
, "1.21" );
809 return $this->generateTextDiffBody( $otext, $ntext );
813 * Generate a diff, no caching
815 * @todo move this to TextDifferenceEngine, make DifferenceEngine abstract. At some point.
817 * @param string $otext old text, must be already segmented
818 * @param string $ntext new text, must be already segmented
819 * @return bool|string
821 function generateTextDiffBody( $otext, $ntext ) {
822 global $wgExternalDiffEngine, $wgContLang;
824 wfProfileIn( __METHOD__
);
826 $otext = str_replace( "\r\n", "\n", $otext );
827 $ntext = str_replace( "\r\n", "\n", $ntext );
829 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
830 # For historical reasons, external diff engine expects
831 # input text to be HTML-escaped already
832 $otext = htmlspecialchars( $wgContLang->segmentForDiff( $otext ) );
833 $ntext = htmlspecialchars( $wgContLang->segmentForDiff( $ntext ) );
834 wfProfileOut( __METHOD__
);
836 return $wgContLang->unsegmentForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
837 $this->debug( 'wikidiff1' );
840 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
841 # Better external diff engine, the 2 may some day be dropped
842 # This one does the escaping and segmenting itself
843 wfProfileIn( 'wikidiff2_do_diff' );
844 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
845 $text .= $this->debug( 'wikidiff2' );
846 wfProfileOut( 'wikidiff2_do_diff' );
847 wfProfileOut( __METHOD__
);
851 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
853 $tmpDir = wfTempDir();
854 $tempName1 = tempnam( $tmpDir, 'diff_' );
855 $tempName2 = tempnam( $tmpDir, 'diff_' );
857 $tempFile1 = fopen( $tempName1, "w" );
859 wfProfileOut( __METHOD__
);
863 $tempFile2 = fopen( $tempName2, "w" );
865 wfProfileOut( __METHOD__
);
869 fwrite( $tempFile1, $otext );
870 fwrite( $tempFile2, $ntext );
871 fclose( $tempFile1 );
872 fclose( $tempFile2 );
873 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
874 wfProfileIn( __METHOD__
. "-shellexec" );
875 $difftext = wfShellExec( $cmd );
876 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
877 wfProfileOut( __METHOD__
. "-shellexec" );
878 unlink( $tempName1 );
879 unlink( $tempName2 );
880 wfProfileOut( __METHOD__
);
886 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
887 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
888 $diffs = new Diff( $ota, $nta );
889 $formatter = new TableDiffFormatter();
890 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
891 wfProfileOut( __METHOD__
);
897 * Generate a debug comment indicating diff generating time,
898 * server node, and generator backend.
900 * @param String $generator : What diff engine was used
904 protected function debug( $generator = "internal" ) {
905 global $wgShowHostnames;
906 if ( !$this->enableDebugComment
) {
909 $data = array( $generator );
910 if ( $wgShowHostnames ) {
911 $data[] = wfHostname();
913 $data[] = wfTimestamp( TS_DB
);
915 return "<!-- diff generator: " .
916 implode( " ", array_map( "htmlspecialchars", $data ) ) .
921 * Replace line numbers with the text in the user's language
923 * @param String $text
927 function localiseLineNumbers( $text ) {
928 return preg_replace_callback(
929 '/<!--LINE (\d+)-->/',
930 array( &$this, 'localiseLineNumbersCb' ),
935 function localiseLineNumbersCb( $matches ) {
936 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) {
940 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
944 * If there are revisions between the ones being compared, return a note saying so.
947 function getMultiNotice() {
948 if ( !is_object( $this->mOldRev
) ||
!is_object( $this->mNewRev
) ) {
950 } elseif ( !$this->mOldPage
->equals( $this->mNewPage
) ) {
951 // Comparing two different pages? Count would be meaningless.
955 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
956 $oldRev = $this->mNewRev
; // flip
957 $newRev = $this->mOldRev
; // flip
958 } else { // normal case
959 $oldRev = $this->mOldRev
;
960 $newRev = $this->mNewRev
;
963 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev );
965 $limit = 100; // use diff-multi-manyusers if too many users
966 $numUsers = $this->mNewPage
->countAuthorsBetween( $oldRev, $newRev, $limit );
968 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
971 return ''; // nothing
975 * Get a notice about how many intermediate edits and users there are
976 * @param $numEdits int
977 * @param $numUsers int
981 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
982 if ( $numUsers > $limit ) {
983 $msg = 'diff-multi-manyusers';
989 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
993 * Get a header for a specified revision.
995 * @param $rev Revision
996 * @param string $complete 'complete' to get the header wrapped depending
997 * the visibility of the revision and a link to edit the page.
998 * @return String HTML fragment
1000 protected function getRevisionHeader( Revision
$rev, $complete = '' ) {
1001 $lang = $this->getLanguage();
1002 $user = $this->getUser();
1003 $revtimestamp = $rev->getTimestamp();
1004 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
1005 $dateofrev = $lang->userDate( $revtimestamp, $user );
1006 $timeofrev = $lang->userTime( $revtimestamp, $user );
1008 $header = $this->msg(
1009 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
1015 if ( $complete !== 'complete' ) {
1019 $title = $rev->getTitle();
1021 $header = Linker
::linkKnown( $title, $header, array(),
1022 array( 'oldid' => $rev->getID() ) );
1024 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
1025 $editQuery = array( 'action' => 'edit' );
1026 if ( !$rev->isCurrent() ) {
1027 $editQuery['oldid'] = $rev->getID();
1030 $key = $title->quickUserCan( 'edit', $user ) ?
'editold' : 'viewsourceold';
1031 $msg = $this->msg( $key )->escaped();
1032 $header .= ' ' . $this->msg( 'parentheses' )->rawParams(
1033 Linker
::linkKnown( $title, $msg, array(), $editQuery ) )->plain();
1034 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
1035 $header = Html
::rawElement(
1037 array( 'class' => 'history-deleted' ),
1042 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
1049 * Add the header to a diff body
1051 * @param string $diff Diff body
1052 * @param string $otitle Old revision header
1053 * @param string $ntitle New revision header
1054 * @param string $multi Notice telling user that there are intermediate
1055 * revisions between the ones being compared
1056 * @param string $notice Other notices, e.g. that user is viewing deleted content
1060 function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
1061 // shared.css sets diff in interface language/dir, but the actual content
1062 // is often in a different language, mostly the page content language/dir
1063 $tableClass = 'diff diff-contentalign-' . htmlspecialchars( $this->getDiffLang()->alignStart() );
1064 $header = "<table class='$tableClass'>";
1066 if ( !$diff && !$otitle ) {
1068 <tr style='vertical-align: top;'>
1069 <td class='diff-ntitle'>{$ntitle}</td>
1073 if ( $diff ) { // Safari/Chrome show broken output if cols not used
1075 <col class='diff-marker' />
1076 <col class='diff-content' />
1077 <col class='diff-marker' />
1078 <col class='diff-content' />";
1085 if ( $otitle ||
$ntitle ) {
1087 <tr style='vertical-align: top;'>
1088 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
1089 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
1094 if ( $multi != '' ) {
1095 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;' " .
1096 "class='diff-multi'>{$multi}</td></tr>";
1098 if ( $notice != '' ) {
1099 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;'>{$notice}</td></tr>";
1102 return $header . $diff . "</table>";
1106 * Use specified text instead of loading from the database
1107 * @deprecated since 1.21, use setContent() instead.
1109 function setText( $oldText, $newText ) {
1110 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1112 $oldContent = ContentHandler
::makeContent( $oldText, $this->getTitle() );
1113 $newContent = ContentHandler
::makeContent( $newText, $this->getTitle() );
1115 $this->setContent( $oldContent, $newContent );
1119 * Use specified text instead of loading from the database
1122 function setContent( Content
$oldContent, Content
$newContent ) {
1123 $this->mOldContent
= $oldContent;
1124 $this->mNewContent
= $newContent;
1126 $this->mTextLoaded
= 2;
1127 $this->mRevisionsLoaded
= true;
1131 * Set the language in which the diff text is written
1132 * (Defaults to page content language).
1135 function setTextLanguage( $lang ) {
1136 $this->mDiffLang
= wfGetLangObj( $lang );
1140 * Maps a revision pair definition as accepted by DifferenceEngine constructor
1141 * to a pair of actual integers representing revision ids.
1143 * @param int $old Revision id, e.g. from URL parameter 'oldid'
1144 * @param int|string $new Revision id or strings 'next' or 'prev', e.g. from URL parameter 'diff'
1145 * @return array Array of two revision ids, older first, later second.
1146 * Zero signifies invalid argument passed.
1147 * false signifies that there is no previous/next revision ($old is the oldest/newest one).
1149 public function mapDiffPrevNext( $old, $new ) {
1150 if ( $new === 'prev' ) {
1151 // Show diff between revision $old and the previous one. Get previous one from DB.
1152 $newid = intval( $old );
1153 $oldid = $this->getTitle()->getPreviousRevisionID( $newid );
1154 } elseif ( $new === 'next' ) {
1155 // Show diff between revision $old and the next one. Get next one from DB.
1156 $oldid = intval( $old );
1157 $newid = $this->getTitle()->getNextRevisionID( $oldid );
1159 $oldid = intval( $old );
1160 $newid = intval( $new );
1163 return array( $oldid, $newid );
1169 private function loadRevisionIds() {
1170 if ( $this->mRevisionsIdsLoaded
) {
1174 $this->mRevisionsIdsLoaded
= true;
1176 $old = $this->mOldid
;
1177 $new = $this->mNewid
;
1179 list( $this->mOldid
, $this->mNewid
) = self
::mapDiffPrevNext( $old, $new );
1180 if ( $new === 'next' && $this->mNewid
=== false ) {
1181 # if no result, NewId points to the newest old revision. The only newer
1182 # revision is cur, which is "0".
1187 'NewDifferenceEngine',
1188 array( $this->getTitle(), &$this->mOldid
, &$this->mNewid
, $old, $new )
1193 * Load revision metadata for the specified articles. If newid is 0, then compare
1194 * the old article in oldid to the current article; if oldid is 0, then
1195 * compare the current article to the immediately previous one (ignoring the
1198 * If oldid is false, leave the corresponding revision object set
1199 * to false. This is impossible via ordinary user input, and is provided for
1204 function loadRevisionData() {
1205 if ( $this->mRevisionsLoaded
) {
1209 // Whether it succeeds or fails, we don't want to try again
1210 $this->mRevisionsLoaded
= true;
1212 $this->loadRevisionIds();
1214 // Load the new revision object
1215 if ( $this->mNewid
) {
1216 $this->mNewRev
= Revision
::newFromId( $this->mNewid
);
1218 $this->mNewRev
= Revision
::newFromTitle(
1221 Revision
::READ_NORMAL
1225 if ( !$this->mNewRev
instanceof Revision
) {
1229 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1230 $this->mNewid
= $this->mNewRev
->getId();
1231 $this->mNewPage
= $this->mNewRev
->getTitle();
1233 // Load the old revision object
1234 $this->mOldRev
= false;
1235 if ( $this->mOldid
) {
1236 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1237 } elseif ( $this->mOldid
=== 0 ) {
1238 $rev = $this->mNewRev
->getPrevious();
1240 $this->mOldid
= $rev->getId();
1241 $this->mOldRev
= $rev;
1243 // No previous revision; mark to show as first-version only.
1244 $this->mOldid
= false;
1245 $this->mOldRev
= false;
1247 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1249 if ( is_null( $this->mOldRev
) ) {
1253 if ( $this->mOldRev
) {
1254 $this->mOldPage
= $this->mOldRev
->getTitle();
1257 // Load tags information for both revisions
1258 $dbr = wfGetDB( DB_SLAVE
);
1259 if ( $this->mOldid
!== false ) {
1260 $this->mOldTags
= $dbr->selectField(
1263 array( 'ts_rev_id' => $this->mOldid
),
1267 $this->mOldTags
= false;
1269 $this->mNewTags
= $dbr->selectField(
1272 array( 'ts_rev_id' => $this->mNewid
),
1280 * Load the text of the revisions, as well as revision data.
1284 function loadText() {
1285 if ( $this->mTextLoaded
== 2 ) {
1289 // Whether it succeeds or fails, we don't want to try again
1290 $this->mTextLoaded
= 2;
1292 if ( !$this->loadRevisionData() ) {
1296 if ( $this->mOldRev
) {
1297 $this->mOldContent
= $this->mOldRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1298 if ( $this->mOldContent
=== null ) {
1303 if ( $this->mNewRev
) {
1304 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1305 if ( $this->mNewContent
=== null ) {
1314 * Load the text of the new revision, not the old one
1318 function loadNewText() {
1319 if ( $this->mTextLoaded
>= 1 ) {
1323 $this->mTextLoaded
= 1;
1325 if ( !$this->loadRevisionData() ) {
1329 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );