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 ) );
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 # Also try to load it as a redirect
584 $rt = $this->mNewContent ?
$this->mNewContent
->getRedirectTarget() : null;
587 $article = Article
::newFromTitle( $this->mNewPage
, $this->getContext() );
588 $out->addHTML( $article->viewRedirect( $rt ) );
590 # WikiPage::getParserOutput() should not return false, but just in case
591 if ( $parserOutput ) {
592 # Show categories etc.
593 $out->addParserOutputNoText( $parserOutput );
595 } elseif ( $parserOutput ) {
596 $out->addParserOutput( $parserOutput );
600 # @codingStandardsIgnoreEnd
602 # Add redundant patrol link on bottom...
603 $out->addHTML( $this->markPatrolledLink() );
605 wfProfileOut( __METHOD__
);
608 protected function getParserOutput( WikiPage
$page, Revision
$rev ) {
609 $parserOptions = $page->makeParserOptions( $this->getContext() );
611 if ( !$rev->isCurrent() ||
!$rev->getTitle()->quickUserCan( "edit" ) ) {
612 $parserOptions->setEditSection( false );
615 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
617 return $parserOutput;
621 * Get the diff text, send it to the OutputPage object
622 * Returns false if the diff could not be generated, otherwise returns true
624 * @param string|bool $otitle Header for old text or false
625 * @param string|bool $ntitle Header for new text or false
626 * @param string $notice HTML between diff header and body
630 function showDiff( $otitle, $ntitle, $notice = '' ) {
631 $diff = $this->getDiff( $otitle, $ntitle, $notice );
632 if ( $diff === false ) {
633 $this->showMissingRevision();
637 $this->showDiffStyle();
638 $this->getOutput()->addHTML( $diff );
645 * Add style sheets and supporting JS for diff display.
647 function showDiffStyle() {
648 $this->getOutput()->addModuleStyles( 'mediawiki.action.history.diff' );
652 * Get complete diff table, including header
654 * @param string|bool $otitle Header for old text or false
655 * @param string|bool $ntitle Header for new text or false
656 * @param string $notice HTML between diff header and body
659 function getDiff( $otitle, $ntitle, $notice = '' ) {
660 $body = $this->getDiffBody();
661 if ( $body === false ) {
665 $multi = $this->getMultiNotice();
666 // Display a message when the diff is empty
667 if ( $body === '' ) {
668 $notice .= '<div class="mw-diff-empty">' .
669 $this->msg( 'diff-empty' )->parse() .
673 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
677 * Get the diff table body, without header
679 * @return mixed (string/false)
681 public function getDiffBody() {
683 wfProfileIn( __METHOD__
);
684 $this->mCacheHit
= true;
685 // Check if the diff should be hidden from this user
686 if ( !$this->loadRevisionData() ) {
687 wfProfileOut( __METHOD__
);
690 } elseif ( $this->mOldRev
&&
691 !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
693 wfProfileOut( __METHOD__
);
696 } elseif ( $this->mNewRev
&&
697 !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
699 wfProfileOut( __METHOD__
);
704 if ( $this->mOldRev
=== false ||
( $this->mOldRev
&& $this->mNewRev
705 && $this->mOldRev
->getID() == $this->mNewRev
->getID() )
707 wfProfileOut( __METHOD__
);
713 if ( $this->mOldid
&& $this->mNewid
) {
714 $key = $this->getDiffBodyCacheKey();
717 if ( !$this->mRefreshCache
) {
718 $difftext = $wgMemc->get( $key );
720 wfIncrStats( 'diff_cache_hit' );
721 $difftext = $this->localiseLineNumbers( $difftext );
722 $difftext .= "\n<!-- diff cache key $key -->\n";
723 wfProfileOut( __METHOD__
);
727 } // don't try to load but save the result
729 $this->mCacheHit
= false;
731 // Loadtext is permission safe, this just clears out the diff
732 if ( !$this->loadText() ) {
733 wfProfileOut( __METHOD__
);
738 $difftext = $this->generateContentDiffBody( $this->mOldContent
, $this->mNewContent
);
740 // Save to cache for 7 days
741 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
742 wfIncrStats( 'diff_uncacheable' );
743 } elseif ( $key !== false && $difftext !== false ) {
744 wfIncrStats( 'diff_cache_miss' );
745 $wgMemc->set( $key, $difftext, 7 * 86400 );
747 wfIncrStats( 'diff_uncacheable' );
749 // Replace line numbers with the text in the user's language
750 if ( $difftext !== false ) {
751 $difftext = $this->localiseLineNumbers( $difftext );
753 wfProfileOut( __METHOD__
);
759 * Returns the cache key for diff body text or content.
763 * @throws MWException
765 protected function getDiffBodyCacheKey() {
766 if ( !$this->mOldid ||
!$this->mNewid
) {
767 throw new MWException( 'mOldid and mNewid must be set to get diff cache key.' );
770 return wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
,
771 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
775 * Generate a diff, no caching.
777 * This implementation uses generateTextDiffBody() to generate a diff based on the default
778 * serialization of the given Content objects. This will fail if $old or $new are not
779 * instances of TextContent.
781 * Subclasses may override this to provide a different rendering for the diff,
782 * perhaps taking advantage of the content's native form. This is required for all content
783 * models that are not text based.
785 * @param $old Content: old content
786 * @param $new Content: new content
788 * @return bool|string
790 * @throws MWException if $old or $new are not instances of TextContent.
792 function generateContentDiffBody( Content
$old, Content
$new ) {
793 if ( !( $old instanceof TextContent
) ) {
794 throw new MWException( "Diff not implemented for " . get_class( $old ) . "; " .
795 "override generateContentDiffBody to fix this." );
798 if ( !( $new instanceof TextContent
) ) {
799 throw new MWException( "Diff not implemented for " . get_class( $new ) . "; "
800 . "override generateContentDiffBody to fix this." );
803 $otext = $old->serialize();
804 $ntext = $new->serialize();
806 return $this->generateTextDiffBody( $otext, $ntext );
810 * Generate a diff, no caching
812 * @param string $otext old text, must be already segmented
813 * @param string $ntext new text, must be already segmented
814 * @return bool|string
815 * @deprecated since 1.21, use generateContentDiffBody() instead!
817 function generateDiffBody( $otext, $ntext ) {
818 ContentHandler
::deprecated( __METHOD__
, "1.21" );
820 return $this->generateTextDiffBody( $otext, $ntext );
824 * Generate a diff, no caching
826 * @todo move this to TextDifferenceEngine, make DifferenceEngine abstract. At some point.
828 * @param string $otext old text, must be already segmented
829 * @param string $ntext new text, must be already segmented
830 * @return bool|string
832 function generateTextDiffBody( $otext, $ntext ) {
833 global $wgExternalDiffEngine, $wgContLang;
835 wfProfileIn( __METHOD__
);
837 $otext = str_replace( "\r\n", "\n", $otext );
838 $ntext = str_replace( "\r\n", "\n", $ntext );
840 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
841 # For historical reasons, external diff engine expects
842 # input text to be HTML-escaped already
843 $otext = htmlspecialchars( $wgContLang->segmentForDiff( $otext ) );
844 $ntext = htmlspecialchars( $wgContLang->segmentForDiff( $ntext ) );
845 wfProfileOut( __METHOD__
);
847 return $wgContLang->unsegmentForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
848 $this->debug( 'wikidiff1' );
851 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
852 # Better external diff engine, the 2 may some day be dropped
853 # This one does the escaping and segmenting itself
854 wfProfileIn( 'wikidiff2_do_diff' );
855 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
856 $text .= $this->debug( 'wikidiff2' );
857 wfProfileOut( 'wikidiff2_do_diff' );
858 wfProfileOut( __METHOD__
);
862 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
864 $tmpDir = wfTempDir();
865 $tempName1 = tempnam( $tmpDir, 'diff_' );
866 $tempName2 = tempnam( $tmpDir, 'diff_' );
868 $tempFile1 = fopen( $tempName1, "w" );
870 wfProfileOut( __METHOD__
);
874 $tempFile2 = fopen( $tempName2, "w" );
876 wfProfileOut( __METHOD__
);
880 fwrite( $tempFile1, $otext );
881 fwrite( $tempFile2, $ntext );
882 fclose( $tempFile1 );
883 fclose( $tempFile2 );
884 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
885 wfProfileIn( __METHOD__
. "-shellexec" );
886 $difftext = wfShellExec( $cmd );
887 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
888 wfProfileOut( __METHOD__
. "-shellexec" );
889 unlink( $tempName1 );
890 unlink( $tempName2 );
891 wfProfileOut( __METHOD__
);
897 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
898 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
899 $diffs = new Diff( $ota, $nta );
900 $formatter = new TableDiffFormatter();
901 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
902 wfProfileOut( __METHOD__
);
908 * Generate a debug comment indicating diff generating time,
909 * server node, and generator backend.
911 * @param String $generator : What diff engine was used
915 protected function debug( $generator = "internal" ) {
916 global $wgShowHostnames;
917 if ( !$this->enableDebugComment
) {
920 $data = array( $generator );
921 if ( $wgShowHostnames ) {
922 $data[] = wfHostname();
924 $data[] = wfTimestamp( TS_DB
);
926 return "<!-- diff generator: " .
927 implode( " ", array_map( "htmlspecialchars", $data ) ) .
932 * Replace line numbers with the text in the user's language
934 * @param String $text
938 function localiseLineNumbers( $text ) {
939 return preg_replace_callback(
940 '/<!--LINE (\d+)-->/',
941 array( &$this, 'localiseLineNumbersCb' ),
946 function localiseLineNumbersCb( $matches ) {
947 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) {
951 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
955 * If there are revisions between the ones being compared, return a note saying so.
958 function getMultiNotice() {
959 if ( !is_object( $this->mOldRev
) ||
!is_object( $this->mNewRev
) ) {
961 } elseif ( !$this->mOldPage
->equals( $this->mNewPage
) ) {
962 // Comparing two different pages? Count would be meaningless.
966 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
967 $oldRev = $this->mNewRev
; // flip
968 $newRev = $this->mOldRev
; // flip
969 } else { // normal case
970 $oldRev = $this->mOldRev
;
971 $newRev = $this->mNewRev
;
974 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev );
976 $limit = 100; // use diff-multi-manyusers if too many users
977 $numUsers = $this->mNewPage
->countAuthorsBetween( $oldRev, $newRev, $limit );
979 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
982 return ''; // nothing
986 * Get a notice about how many intermediate edits and users there are
987 * @param $numEdits int
988 * @param $numUsers int
992 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
993 if ( $numUsers > $limit ) {
994 $msg = 'diff-multi-manyusers';
1000 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
1004 * Get a header for a specified revision.
1006 * @param $rev Revision
1007 * @param string $complete 'complete' to get the header wrapped depending
1008 * the visibility of the revision and a link to edit the page.
1009 * @return String HTML fragment
1011 protected function getRevisionHeader( Revision
$rev, $complete = '' ) {
1012 $lang = $this->getLanguage();
1013 $user = $this->getUser();
1014 $revtimestamp = $rev->getTimestamp();
1015 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
1016 $dateofrev = $lang->userDate( $revtimestamp, $user );
1017 $timeofrev = $lang->userTime( $revtimestamp, $user );
1019 $header = $this->msg(
1020 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
1026 if ( $complete !== 'complete' ) {
1030 $title = $rev->getTitle();
1032 $header = Linker
::linkKnown( $title, $header, array(),
1033 array( 'oldid' => $rev->getID() ) );
1035 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
1036 $editQuery = array( 'action' => 'edit' );
1037 if ( !$rev->isCurrent() ) {
1038 $editQuery['oldid'] = $rev->getID();
1041 $key = $title->quickUserCan( 'edit', $user ) ?
'editold' : 'viewsourceold';
1042 $msg = $this->msg( $key )->escaped();
1043 $header .= ' ' . $this->msg( 'parentheses' )->rawParams(
1044 Linker
::linkKnown( $title, $msg, array(), $editQuery ) )->plain();
1045 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
1046 $header = Html
::rawElement(
1048 array( 'class' => 'history-deleted' ),
1053 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
1060 * Add the header to a diff body
1062 * @param string $diff Diff body
1063 * @param string $otitle Old revision header
1064 * @param string $ntitle New revision header
1065 * @param string $multi Notice telling user that there are intermediate
1066 * revisions between the ones being compared
1067 * @param string $notice Other notices, e.g. that user is viewing deleted content
1071 function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
1072 // shared.css sets diff in interface language/dir, but the actual content
1073 // is often in a different language, mostly the page content language/dir
1074 $tableClass = 'diff diff-contentalign-' . htmlspecialchars( $this->getDiffLang()->alignStart() );
1075 $header = "<table class='$tableClass'>";
1077 if ( !$diff && !$otitle ) {
1079 <tr style='vertical-align: top;'>
1080 <td class='diff-ntitle'>{$ntitle}</td>
1084 if ( $diff ) { // Safari/Chrome show broken output if cols not used
1086 <col class='diff-marker' />
1087 <col class='diff-content' />
1088 <col class='diff-marker' />
1089 <col class='diff-content' />";
1096 if ( $otitle ||
$ntitle ) {
1098 <tr style='vertical-align: top;'>
1099 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
1100 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
1105 if ( $multi != '' ) {
1106 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;' " .
1107 "class='diff-multi'>{$multi}</td></tr>";
1109 if ( $notice != '' ) {
1110 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;'>{$notice}</td></tr>";
1113 return $header . $diff . "</table>";
1117 * Use specified text instead of loading from the database
1118 * @deprecated since 1.21, use setContent() instead.
1120 function setText( $oldText, $newText ) {
1121 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1123 $oldContent = ContentHandler
::makeContent( $oldText, $this->getTitle() );
1124 $newContent = ContentHandler
::makeContent( $newText, $this->getTitle() );
1126 $this->setContent( $oldContent, $newContent );
1130 * Use specified text instead of loading from the database
1133 function setContent( Content
$oldContent, Content
$newContent ) {
1134 $this->mOldContent
= $oldContent;
1135 $this->mNewContent
= $newContent;
1137 $this->mTextLoaded
= 2;
1138 $this->mRevisionsLoaded
= true;
1142 * Set the language in which the diff text is written
1143 * (Defaults to page content language).
1146 function setTextLanguage( $lang ) {
1147 $this->mDiffLang
= wfGetLangObj( $lang );
1151 * Maps a revision pair definition as accepted by DifferenceEngine constructor
1152 * to a pair of actual integers representing revision ids.
1154 * @param int $old Revision id, e.g. from URL parameter 'oldid'
1155 * @param int|string $new Revision id or strings 'next' or 'prev', e.g. from URL parameter 'diff'
1156 * @return array Array of two revision ids, older first, later second.
1157 * Zero signifies invalid argument passed.
1158 * false signifies that there is no previous/next revision ($old is the oldest/newest one).
1160 public function mapDiffPrevNext( $old, $new ) {
1161 if ( $new === 'prev' ) {
1162 // Show diff between revision $old and the previous one. Get previous one from DB.
1163 $newid = intval( $old );
1164 $oldid = $this->getTitle()->getPreviousRevisionID( $newid );
1165 } elseif ( $new === 'next' ) {
1166 // Show diff between revision $old and the next one. Get next one from DB.
1167 $oldid = intval( $old );
1168 $newid = $this->getTitle()->getNextRevisionID( $oldid );
1170 $oldid = intval( $old );
1171 $newid = intval( $new );
1174 return array( $oldid, $newid );
1180 private function loadRevisionIds() {
1181 if ( $this->mRevisionsIdsLoaded
) {
1185 $this->mRevisionsIdsLoaded
= true;
1187 $old = $this->mOldid
;
1188 $new = $this->mNewid
;
1190 list( $this->mOldid
, $this->mNewid
) = self
::mapDiffPrevNext( $old, $new );
1191 if ( $new === 'next' && $this->mNewid
=== false ) {
1192 # if no result, NewId points to the newest old revision. The only newer
1193 # revision is cur, which is "0".
1198 'NewDifferenceEngine',
1199 array( $this->getTitle(), &$this->mOldid
, &$this->mNewid
, $old, $new )
1204 * Load revision metadata for the specified articles. If newid is 0, then compare
1205 * the old article in oldid to the current article; if oldid is 0, then
1206 * compare the current article to the immediately previous one (ignoring the
1209 * If oldid is false, leave the corresponding revision object set
1210 * to false. This is impossible via ordinary user input, and is provided for
1215 function loadRevisionData() {
1216 if ( $this->mRevisionsLoaded
) {
1220 // Whether it succeeds or fails, we don't want to try again
1221 $this->mRevisionsLoaded
= true;
1223 $this->loadRevisionIds();
1225 // Load the new revision object
1226 if ( $this->mNewid
) {
1227 $this->mNewRev
= Revision
::newFromId( $this->mNewid
);
1229 $this->mNewRev
= Revision
::newFromTitle(
1232 Revision
::READ_NORMAL
1236 if ( !$this->mNewRev
instanceof Revision
) {
1240 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1241 $this->mNewid
= $this->mNewRev
->getId();
1242 $this->mNewPage
= $this->mNewRev
->getTitle();
1244 // Load the old revision object
1245 $this->mOldRev
= false;
1246 if ( $this->mOldid
) {
1247 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1248 } elseif ( $this->mOldid
=== 0 ) {
1249 $rev = $this->mNewRev
->getPrevious();
1251 $this->mOldid
= $rev->getId();
1252 $this->mOldRev
= $rev;
1254 // No previous revision; mark to show as first-version only.
1255 $this->mOldid
= false;
1256 $this->mOldRev
= false;
1258 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1260 if ( is_null( $this->mOldRev
) ) {
1264 if ( $this->mOldRev
) {
1265 $this->mOldPage
= $this->mOldRev
->getTitle();
1268 // Load tags information for both revisions
1269 $dbr = wfGetDB( DB_SLAVE
);
1270 if ( $this->mOldid
!== false ) {
1271 $this->mOldTags
= $dbr->selectField(
1274 array( 'ts_rev_id' => $this->mOldid
),
1278 $this->mOldTags
= false;
1280 $this->mNewTags
= $dbr->selectField(
1283 array( 'ts_rev_id' => $this->mNewid
),
1291 * Load the text of the revisions, as well as revision data.
1295 function loadText() {
1296 if ( $this->mTextLoaded
== 2 ) {
1300 // Whether it succeeds or fails, we don't want to try again
1301 $this->mTextLoaded
= 2;
1303 if ( !$this->loadRevisionData() ) {
1307 if ( $this->mOldRev
) {
1308 $this->mOldContent
= $this->mOldRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1309 if ( $this->mOldContent
=== null ) {
1314 if ( $this->mNewRev
) {
1315 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1316 if ( $this->mNewContent
=== null ) {
1325 * Load the text of the new revision, not the old one
1329 function loadNewText() {
1330 if ( $this->mTextLoaded
>= 1 ) {
1334 $this->mTextLoaded
= 1;
1336 if ( !$this->loadRevisionData() ) {
1340 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );