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
{
68 /** @var bool Have the revisions IDs been loaded */
69 private $mRevisionsIdsLoaded = false;
71 /** @var bool Have the revisions been loaded */
72 public $mRevisionsLoaded = false;
74 /** @var int How many text blobs have been loaded, 0, 1 or 2? */
75 public $mTextLoaded = 0;
77 /** @var bool Was the diff fetched from cache? */
78 public $mCacheHit = false;
81 * Set this to true to add debug info to the HTML output.
82 * Warning: this may cause RSS readers to spuriously mark articles as "new"
85 public $enableDebugComment = false;
87 /** @var bool If true, line X is not displayed when X is 1, for example
88 * to increase readability and conserve space with many small diffs.
90 protected $mReducedLineNumbers = false;
92 /** @var string Link to action=markpatrolled */
93 protected $mMarkPatrolledLink = null;
95 /** @var bool Show rev_deleted content if allowed */
96 protected $unhide = false;
101 * @param IContextSource $context context to use, anything else will be ignored
102 * @param int $old old ID we want to show and diff with.
103 * @param string|int $new either revision ID or 'prev' or 'next'. Default: 0.
104 * @param int $rcid Deprecated, no longer used!
105 * @param bool $refreshCache If set, refreshes the diff cache
106 * @param bool $unhide If set, allow viewing deleted revs
108 public function __construct( $context = null, $old = 0, $new = 0, $rcid = 0,
109 $refreshCache = false, $unhide = false
111 if ( $context instanceof IContextSource
) {
112 $this->setContext( $context );
115 wfDebug( "DifferenceEngine old '$old' new '$new' rcid '$rcid'\n" );
117 $this->mOldid
= $old;
118 $this->mNewid
= $new;
119 $this->mRefreshCache
= $refreshCache;
120 $this->unhide
= $unhide;
126 public function setReducedLineNumbers( $value = true ) {
127 $this->mReducedLineNumbers
= $value;
133 public function getDiffLang() {
134 if ( $this->mDiffLang
=== null ) {
135 # Default language in which the diff text is written.
136 $this->mDiffLang
= $this->getTitle()->getPageLanguage();
139 return $this->mDiffLang
;
145 public function wasCacheHit() {
146 return $this->mCacheHit
;
152 public function getOldid() {
153 $this->loadRevisionIds();
155 return $this->mOldid
;
161 public function getNewid() {
162 $this->loadRevisionIds();
164 return $this->mNewid
;
168 * Look up a special:Undelete link to the given deleted revision id,
169 * as a workaround for being unable to load deleted diffs in currently.
171 * @param int $id Revision ID
173 * @return mixed URL or false
175 public function deletedLink( $id ) {
176 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
177 $dbr = wfGetDB( DB_SLAVE
);
178 $row = $dbr->selectRow( 'archive', '*',
179 array( 'ar_rev_id' => $id ),
182 $rev = Revision
::newFromArchiveRow( $row );
183 $title = Title
::makeTitleSafe( $row->ar_namespace
, $row->ar_title
);
185 return SpecialPage
::getTitleFor( 'Undelete' )->getFullURL( array(
186 'target' => $title->getPrefixedText(),
187 'timestamp' => $rev->getTimestamp()
196 * Build a wikitext link toward a deleted revision, if viewable.
198 * @param int $id Revision ID
200 * @return string Wikitext fragment
202 public function deletedIdMarker( $id ) {
203 $link = $this->deletedLink( $id );
205 return "[$link $id]";
211 private function showMissingRevision() {
212 $out = $this->getOutput();
215 if ( $this->mOldRev
=== null ||
216 ( $this->mOldRev
&& $this->mOldContent
=== null )
218 $missing[] = $this->deletedIdMarker( $this->mOldid
);
220 if ( $this->mNewRev
=== null ||
221 ( $this->mNewRev
&& $this->mNewContent
=== null )
223 $missing[] = $this->deletedIdMarker( $this->mNewid
);
226 $out->setPageTitle( $this->msg( 'errorpagetitle' ) );
227 $out->addWikiMsg( 'difference-missing-revision',
228 $this->getLanguage()->listToText( $missing ), count( $missing ) );
231 public function showDiffPage( $diffOnly = false ) {
232 wfProfileIn( __METHOD__
);
234 # Allow frames except in certain special cases
235 $out = $this->getOutput();
236 $out->allowClickjacking();
237 $out->setRobotPolicy( 'noindex,nofollow' );
239 if ( !$this->loadRevisionData() ) {
240 $this->showMissingRevision();
241 wfProfileOut( __METHOD__
);
246 $user = $this->getUser();
247 $permErrors = $this->mNewPage
->getUserPermissionsErrors( 'read', $user );
248 if ( $this->mOldPage
) { # mOldPage might not be set, see below.
249 $permErrors = wfMergeErrorArrays( $permErrors,
250 $this->mOldPage
->getUserPermissionsErrors( 'read', $user ) );
252 if ( count( $permErrors ) ) {
253 wfProfileOut( __METHOD__
);
254 throw new PermissionsError( 'read', $permErrors );
260 # Carry over 'diffonly' param via navigation links
261 if ( $diffOnly != $user->getBoolOption( 'diffonly' ) ) {
262 $query['diffonly'] = $diffOnly;
264 # Cascade unhide param in links for easy deletion browsing
265 if ( $this->unhide
) {
266 $query['unhide'] = 1;
269 # Check if one of the revisions is deleted/suppressed
270 $deleted = $suppressed = false;
271 $allowed = $this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $user );
273 $revisionTools = array();
275 # mOldRev is false if the difference engine is called with a "vague" query for
276 # a diff between a version V and its previous version V' AND the version V
277 # is the first version of that article. In that case, V' does not exist.
278 if ( $this->mOldRev
=== false ) {
279 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
283 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
285 if ( $this->mNewPage
->equals( $this->mOldPage
) ) {
286 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
289 $out->setPageTitle( $this->msg( 'difference-title-multipage',
290 $this->mOldPage
->getPrefixedText(), $this->mNewPage
->getPrefixedText() ) );
291 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
295 if ( $samePage && $this->mNewPage
->quickUserCan( 'edit', $user ) ) {
296 if ( $this->mNewRev
->isCurrent() && $this->mNewPage
->userCan( 'rollback', $user ) ) {
297 $rollbackLink = Linker
::generateRollback( $this->mNewRev
, $this->getContext() );
298 if ( $rollbackLink ) {
299 $out->preventClickjacking();
300 $rollback = '   ' . $rollbackLink;
304 if ( !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) &&
305 !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
)
307 $undoLink = Html
::element( 'a', array(
308 'href' => $this->mNewPage
->getLocalURL( array(
310 'undoafter' => $this->mOldid
,
311 'undo' => $this->mNewid
313 'title' => Linker
::titleAttrib( 'undo' )
315 $this->msg( 'editundo' )->text()
317 $revisionTools[] = $undoLink;
321 # Make "previous revision link"
322 if ( $samePage && $this->mOldRev
->getPrevious() ) {
323 $prevlink = Linker
::linkKnown(
325 $this->msg( 'previousdiff' )->escaped(),
326 array( 'id' => 'differences-prevlink' ),
327 array( 'diff' => 'prev', 'oldid' => $this->mOldid
) +
$query
330 $prevlink = ' ';
333 if ( $this->mOldRev
->isMinor() ) {
334 $oldminor = ChangesList
::flag( 'minor' );
339 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
340 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev
, 'complete' );
341 $oldChangeTags = ChangeTags
::formatSummaryRow( $this->mOldTags
, 'diff' );
343 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
344 '<div id="mw-diff-otitle2">' .
345 Linker
::revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
346 '<div id="mw-diff-otitle3">' . $oldminor .
347 Linker
::revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
348 '<div id="mw-diff-otitle5">' . $oldChangeTags[0] . '</div>' .
349 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
351 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
352 $deleted = true; // old revisions text is hidden
353 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
354 $suppressed = true; // also suppressed
358 # Check if this user can see the revisions
359 if ( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $user ) ) {
364 # Make "next revision link"
365 # Skip next link on the top revision
366 if ( $samePage && !$this->mNewRev
->isCurrent() ) {
367 $nextlink = Linker
::linkKnown(
369 $this->msg( 'nextdiff' )->escaped(),
370 array( 'id' => 'differences-nextlink' ),
371 array( 'diff' => 'next', 'oldid' => $this->mNewid
) +
$query
374 $nextlink = ' ';
377 if ( $this->mNewRev
->isMinor() ) {
378 $newminor = ChangesList
::flag( 'minor' );
383 # Handle RevisionDelete links...
384 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
386 # Allow extensions to define their own revision tools
387 wfRunHooks( 'DiffRevisionTools', array( $this->mNewRev
, &$revisionTools, $this->mOldRev
) );
388 $formattedRevisionTools = array();
389 // Put each one in parentheses (poor man's button)
390 foreach ( $revisionTools as $tool ) {
391 $formattedRevisionTools[] = $this->msg( 'parentheses' )->rawParams( $tool )->escaped();
393 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev
, 'complete' ) .
394 ' ' . implode( ' ', $formattedRevisionTools );
395 $newChangeTags = ChangeTags
::formatSummaryRow( $this->mNewTags
, 'diff' );
397 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
398 '<div id="mw-diff-ntitle2">' . Linker
::revUserTools( $this->mNewRev
, !$this->unhide
) .
400 '<div id="mw-diff-ntitle3">' . $newminor .
401 Linker
::revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
402 '<div id="mw-diff-ntitle5">' . $newChangeTags[0] . '</div>' .
403 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
405 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
406 $deleted = true; // new revisions text is hidden
407 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
408 $suppressed = true; // also suppressed
412 # If the diff cannot be shown due to a deleted revision, then output
413 # the diff header and links to unhide (if available)...
414 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
415 $this->showDiffStyle();
416 $multi = $this->getMultiNotice();
417 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
419 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
420 # Give explanation for why revision is not visible
421 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
424 # Give explanation and add a link to view the diff...
425 $query = $this->getRequest()->appendQueryValue( 'unhide', '1', true );
426 $link = $this->getTitle()->getFullURL( $query );
427 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
429 "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
433 # Otherwise, output a regular diff...
435 # Add deletion notice if the user is viewing deleted content
438 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
439 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" .
440 $this->msg( $msg )->parse() .
443 $this->showDiff( $oldHeader, $newHeader, $notice );
445 $this->renderNewRevision();
448 wfProfileOut( __METHOD__
);
452 * Get a link to mark the change as patrolled, or '' if there's either no
453 * revision to patrol or the user is not allowed to to it.
454 * Side effect: When the patrol link is build, this method will call
455 * OutputPage::preventClickjacking() and load mediawiki.page.patrol.ajax.
459 protected function markPatrolledLink() {
460 global $wgUseRCPatrol, $wgEnableAPI, $wgEnableWriteAPI;
461 $user = $this->getUser();
463 if ( $this->mMarkPatrolledLink
=== null ) {
464 // Prepare a change patrol link, if applicable
466 // Is patrolling enabled and the user allowed to?
467 $wgUseRCPatrol && $this->mNewPage
->quickUserCan( 'patrol', $user ) &&
468 // Only do this if the revision isn't more than 6 hours older
469 // than the Max RC age (6h because the RC might not be cleaned out regularly)
470 RecentChange
::isInRCLifespan( $this->mNewRev
->getTimestamp(), 21600 )
472 // Look for an unpatrolled change corresponding to this diff
474 $db = wfGetDB( DB_SLAVE
);
475 $change = RecentChange
::newFromConds(
477 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
478 'rc_this_oldid' => $this->mNewid
,
482 array( 'USE INDEX' => 'rc_timestamp' )
485 if ( $change && $change->getPerformer()->getName() !== $user->getName() ) {
486 $rcid = $change->getAttribute( 'rc_id' );
488 // None found or the page has been created by the current user.
489 // If the user could patrol this it already would be patrolled
494 $this->getOutput()->preventClickjacking();
495 if ( $wgEnableAPI && $wgEnableWriteAPI
496 && $user->isAllowed( 'writeapi' )
498 $this->getOutput()->addModules( 'mediawiki.page.patrol.ajax' );
501 $token = $user->getEditToken( $rcid );
502 $this->mMarkPatrolledLink
= ' <span class="patrollink">[' . Linker
::linkKnown(
504 $this->msg( 'markaspatrolleddiff' )->escaped(),
507 'action' => 'markpatrolled',
513 $this->mMarkPatrolledLink
= '';
516 $this->mMarkPatrolledLink
= '';
520 return $this->mMarkPatrolledLink
;
524 * @param Revision $rev
528 protected function revisionDeleteLink( $rev ) {
529 $link = Linker
::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
530 if ( $link !== '' ) {
531 $link = '   ' . $link . ' ';
538 * Show the new revision of the page.
540 public function renderNewRevision() {
541 wfProfileIn( __METHOD__
);
542 $out = $this->getOutput();
543 $revHeader = $this->getRevisionHeader( $this->mNewRev
);
544 # Add "current version as of X" title
545 $out->addHTML( "<hr class='diff-hr' />
546 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
547 # Page content may be handled by a hooked call instead...
548 # @codingStandardsIgnoreStart Ignoring long lines.
549 if ( wfRunHooks( 'ArticleContentOnDiff', array( $this, $out ) ) ) {
550 $this->loadNewText();
551 $out->setRevisionId( $this->mNewid
);
552 $out->setRevisionTimestamp( $this->mNewRev
->getTimestamp() );
553 $out->setArticleFlag( true );
555 // NOTE: only needed for B/C: custom rendering of JS/CSS via hook
556 if ( $this->mNewPage
->isCssJsSubpage() ||
$this->mNewPage
->isCssOrJsPage() ) {
557 // Stolen from Article::view --AG 2007-10-11
558 // Give hooks a chance to customise the output
559 // @todo standardize this crap into one function
560 if ( ContentHandler
::runLegacyHooks( 'ShowRawCssJs', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
561 // NOTE: deprecated hook, B/C only
562 // use the content object's own rendering
563 $cnt = $this->mNewRev
->getContent();
564 $po = $cnt ?
$cnt->getParserOutput( $this->mNewRev
->getTitle(), $this->mNewRev
->getId() ) : null;
565 $txt = $po ?
$po->getText() : '';
566 $out->addHTML( $txt );
568 } elseif ( !wfRunHooks( 'ArticleContentViewCustom', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
569 // Handled by extension
570 } elseif ( !ContentHandler
::runLegacyHooks( 'ArticleViewCustom', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
571 // NOTE: deprecated hook, B/C only
572 // Handled by extension
575 if ( $this->getTitle()->equals( $this->mNewPage
) ) {
576 // If the Title stored in the context is the same as the one
577 // of the new revision, we can use its associated WikiPage
579 $wikiPage = $this->getWikiPage();
581 // Otherwise we need to create our own WikiPage object
582 $wikiPage = WikiPage
::factory( $this->mNewPage
);
585 $parserOutput = $this->getParserOutput( $wikiPage, $this->mNewRev
);
587 # WikiPage::getParserOutput() should not return false, but just in case
588 if ( $parserOutput ) {
589 $out->addParserOutput( $parserOutput );
593 # @codingStandardsIgnoreEnd
595 # Add redundant patrol link on bottom...
596 $out->addHTML( $this->markPatrolledLink() );
598 wfProfileOut( __METHOD__
);
601 protected function getParserOutput( WikiPage
$page, Revision
$rev ) {
602 $parserOptions = $page->makeParserOptions( $this->getContext() );
604 if ( !$rev->isCurrent() ||
!$rev->getTitle()->quickUserCan( "edit" ) ) {
605 $parserOptions->setEditSection( false );
608 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
610 return $parserOutput;
614 * Get the diff text, send it to the OutputPage object
615 * Returns false if the diff could not be generated, otherwise returns true
617 * @param string|bool $otitle Header for old text or false
618 * @param string|bool $ntitle Header for new text or false
619 * @param string $notice HTML between diff header and body
623 public function showDiff( $otitle, $ntitle, $notice = '' ) {
624 $diff = $this->getDiff( $otitle, $ntitle, $notice );
625 if ( $diff === false ) {
626 $this->showMissingRevision();
630 $this->showDiffStyle();
631 $this->getOutput()->addHTML( $diff );
638 * Add style sheets and supporting JS for diff display.
640 public function showDiffStyle() {
641 $this->getOutput()->addModuleStyles( 'mediawiki.action.history.diff' );
645 * Get complete diff table, including header
647 * @param string|bool $otitle Header for old text or false
648 * @param string|bool $ntitle Header for new text or false
649 * @param string $notice HTML between diff header and body
653 public function getDiff( $otitle, $ntitle, $notice = '' ) {
654 $body = $this->getDiffBody();
655 if ( $body === false ) {
659 $multi = $this->getMultiNotice();
660 // Display a message when the diff is empty
661 if ( $body === '' ) {
662 $notice .= '<div class="mw-diff-empty">' .
663 $this->msg( 'diff-empty' )->parse() .
667 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
671 * Get the diff table body, without header
673 * @return mixed (string/false)
675 public function getDiffBody() {
677 wfProfileIn( __METHOD__
);
678 $this->mCacheHit
= true;
679 // Check if the diff should be hidden from this user
680 if ( !$this->loadRevisionData() ) {
681 wfProfileOut( __METHOD__
);
684 } elseif ( $this->mOldRev
&&
685 !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
687 wfProfileOut( __METHOD__
);
690 } elseif ( $this->mNewRev
&&
691 !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
693 wfProfileOut( __METHOD__
);
698 if ( $this->mOldRev
=== false ||
( $this->mOldRev
&& $this->mNewRev
699 && $this->mOldRev
->getID() == $this->mNewRev
->getID() )
701 wfProfileOut( __METHOD__
);
707 if ( $this->mOldid
&& $this->mNewid
) {
708 $key = $this->getDiffBodyCacheKey();
711 if ( !$this->mRefreshCache
) {
712 $difftext = $wgMemc->get( $key );
714 wfIncrStats( 'diff_cache_hit' );
715 $difftext = $this->localiseLineNumbers( $difftext );
716 $difftext .= "\n<!-- diff cache key $key -->\n";
717 wfProfileOut( __METHOD__
);
721 } // don't try to load but save the result
723 $this->mCacheHit
= false;
725 // Loadtext is permission safe, this just clears out the diff
726 if ( !$this->loadText() ) {
727 wfProfileOut( __METHOD__
);
732 $difftext = $this->generateContentDiffBody( $this->mOldContent
, $this->mNewContent
);
734 // Save to cache for 7 days
735 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
736 wfIncrStats( 'diff_uncacheable' );
737 } elseif ( $key !== false && $difftext !== false ) {
738 wfIncrStats( 'diff_cache_miss' );
739 $wgMemc->set( $key, $difftext, 7 * 86400 );
741 wfIncrStats( 'diff_uncacheable' );
743 // Replace line numbers with the text in the user's language
744 if ( $difftext !== false ) {
745 $difftext = $this->localiseLineNumbers( $difftext );
747 wfProfileOut( __METHOD__
);
753 * Returns the cache key for diff body text or content.
757 * @throws MWException
760 protected function getDiffBodyCacheKey() {
761 if ( !$this->mOldid ||
!$this->mNewid
) {
762 throw new MWException( 'mOldid and mNewid must be set to get diff cache key.' );
765 return wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
,
766 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
770 * Generate a diff, no caching.
772 * This implementation uses generateTextDiffBody() to generate a diff based on the default
773 * serialization of the given Content objects. This will fail if $old or $new are not
774 * instances of TextContent.
776 * Subclasses may override this to provide a different rendering for the diff,
777 * perhaps taking advantage of the content's native form. This is required for all content
778 * models that are not text based.
782 * @param Content $old Old content
783 * @param Content $new New content
785 * @throws MWException If old or new content is not an instance of TextContent.
786 * @return bool|string
788 public function generateContentDiffBody( Content
$old, Content
$new ) {
789 if ( !( $old instanceof TextContent
) ) {
790 throw new MWException( "Diff not implemented for " . get_class( $old ) . "; " .
791 "override generateContentDiffBody to fix this." );
794 if ( !( $new instanceof TextContent
) ) {
795 throw new MWException( "Diff not implemented for " . get_class( $new ) . "; "
796 . "override generateContentDiffBody to fix this." );
799 $otext = $old->serialize();
800 $ntext = $new->serialize();
802 return $this->generateTextDiffBody( $otext, $ntext );
806 * Generate a diff, no caching
808 * @param string $otext Old text, must be already segmented
809 * @param string $ntext New text, must be already segmented
811 * @return bool|string
812 * @deprecated since 1.21, use generateContentDiffBody() instead!
814 public function generateDiffBody( $otext, $ntext ) {
815 ContentHandler
::deprecated( __METHOD__
, "1.21" );
817 return $this->generateTextDiffBody( $otext, $ntext );
821 * Generate a diff, no caching
823 * @todo move this to TextDifferenceEngine, make DifferenceEngine abstract. At some point.
825 * @param string $otext old text, must be already segmented
826 * @param string $ntext new text, must be already segmented
828 * @return bool|string
830 public function generateTextDiffBody( $otext, $ntext ) {
831 global $wgExternalDiffEngine, $wgContLang;
833 wfProfileIn( __METHOD__
);
835 $otext = str_replace( "\r\n", "\n", $otext );
836 $ntext = str_replace( "\r\n", "\n", $ntext );
838 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
839 # For historical reasons, external diff engine expects
840 # input text to be HTML-escaped already
841 $otext = htmlspecialchars( $wgContLang->segmentForDiff( $otext ) );
842 $ntext = htmlspecialchars( $wgContLang->segmentForDiff( $ntext ) );
843 wfProfileOut( __METHOD__
);
845 return $wgContLang->unsegmentForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
846 $this->debug( 'wikidiff1' );
849 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
850 # Better external diff engine, the 2 may some day be dropped
851 # This one does the escaping and segmenting itself
852 wfProfileIn( 'wikidiff2_do_diff' );
853 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
854 $text .= $this->debug( 'wikidiff2' );
855 wfProfileOut( 'wikidiff2_do_diff' );
856 wfProfileOut( __METHOD__
);
860 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
862 $tmpDir = wfTempDir();
863 $tempName1 = tempnam( $tmpDir, 'diff_' );
864 $tempName2 = tempnam( $tmpDir, 'diff_' );
866 $tempFile1 = fopen( $tempName1, "w" );
868 wfProfileOut( __METHOD__
);
872 $tempFile2 = fopen( $tempName2, "w" );
874 wfProfileOut( __METHOD__
);
878 fwrite( $tempFile1, $otext );
879 fwrite( $tempFile2, $ntext );
880 fclose( $tempFile1 );
881 fclose( $tempFile2 );
882 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
883 wfProfileIn( __METHOD__
. "-shellexec" );
884 $difftext = wfShellExec( $cmd );
885 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
886 wfProfileOut( __METHOD__
. "-shellexec" );
887 unlink( $tempName1 );
888 unlink( $tempName2 );
889 wfProfileOut( __METHOD__
);
895 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
896 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
897 $diffs = new Diff( $ota, $nta );
898 $formatter = new TableDiffFormatter();
899 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
900 wfProfileOut( __METHOD__
);
906 * Generate a debug comment indicating diff generating time,
907 * server node, and generator backend.
909 * @param string $generator : What diff engine was used
913 protected function debug( $generator = "internal" ) {
914 global $wgShowHostnames;
915 if ( !$this->enableDebugComment
) {
918 $data = array( $generator );
919 if ( $wgShowHostnames ) {
920 $data[] = wfHostname();
922 $data[] = wfTimestamp( TS_DB
);
924 return "<!-- diff generator: " .
925 implode( " ", array_map( "htmlspecialchars", $data ) ) .
930 * Replace line numbers with the text in the user's language
932 * @param string $text
936 public function localiseLineNumbers( $text ) {
937 return preg_replace_callback(
938 '/<!--LINE (\d+)-->/',
939 array( &$this, 'localiseLineNumbersCb' ),
944 public function localiseLineNumbersCb( $matches ) {
945 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) {
949 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
953 * If there are revisions between the ones being compared, return a note saying so.
957 public function getMultiNotice() {
958 if ( !is_object( $this->mOldRev
) ||
!is_object( $this->mNewRev
) ) {
960 } elseif ( !$this->mOldPage
->equals( $this->mNewPage
) ) {
961 // Comparing two different pages? Count would be meaningless.
965 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
966 $oldRev = $this->mNewRev
; // flip
967 $newRev = $this->mOldRev
; // flip
968 } else { // normal case
969 $oldRev = $this->mOldRev
;
970 $newRev = $this->mNewRev
;
973 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev );
975 $limit = 100; // use diff-multi-manyusers if too many users
976 $users = $this->mNewPage
->getAuthorsBetween( $oldRev, $newRev, $limit );
977 $numUsers = count( $users );
979 if ( $numUsers == 1 && $users[0] == $newRev->getRawUserText() ) {
980 $numUsers = 0; // special case to say "by the same user" instead of "by one other user"
983 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
986 return ''; // nothing
990 * Get a notice about how many intermediate edits and users there are
992 * @param int $numEdits
993 * @param int $numUsers
998 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
999 if ( $numUsers === 0 ) {
1000 $msg = 'diff-multi-sameuser';
1001 } elseif ( $numUsers > $limit ) {
1002 $msg = 'diff-multi-manyusers';
1005 $msg = 'diff-multi-otherusers';
1008 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
1012 * Get a header for a specified revision.
1014 * @param Revision $rev
1015 * @param string $complete 'complete' to get the header wrapped depending
1016 * the visibility of the revision and a link to edit the page.
1018 * @return string HTML fragment
1020 protected function getRevisionHeader( Revision
$rev, $complete = '' ) {
1021 $lang = $this->getLanguage();
1022 $user = $this->getUser();
1023 $revtimestamp = $rev->getTimestamp();
1024 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
1025 $dateofrev = $lang->userDate( $revtimestamp, $user );
1026 $timeofrev = $lang->userTime( $revtimestamp, $user );
1028 $header = $this->msg(
1029 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
1035 if ( $complete !== 'complete' ) {
1039 $title = $rev->getTitle();
1041 $header = Linker
::linkKnown( $title, $header, array(),
1042 array( 'oldid' => $rev->getID() ) );
1044 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
1045 $editQuery = array( 'action' => 'edit' );
1046 if ( !$rev->isCurrent() ) {
1047 $editQuery['oldid'] = $rev->getID();
1050 $key = $title->quickUserCan( 'edit', $user ) ?
'editold' : 'viewsourceold';
1051 $msg = $this->msg( $key )->escaped();
1052 $header .= ' ' . $this->msg( 'parentheses' )->rawParams(
1053 Linker
::linkKnown( $title, $msg, array(), $editQuery ) )->plain();
1054 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
1055 $header = Html
::rawElement(
1057 array( 'class' => 'history-deleted' ),
1062 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
1069 * Add the header to a diff body
1071 * @param string $diff Diff body
1072 * @param string $otitle Old revision header
1073 * @param string $ntitle New revision header
1074 * @param string $multi Notice telling user that there are intermediate
1075 * revisions between the ones being compared
1076 * @param string $notice Other notices, e.g. that user is viewing deleted content
1080 public function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
1081 // shared.css sets diff in interface language/dir, but the actual content
1082 // is often in a different language, mostly the page content language/dir
1083 $tableClass = 'diff diff-contentalign-' . htmlspecialchars( $this->getDiffLang()->alignStart() );
1084 $header = "<table class='$tableClass'>";
1086 if ( !$diff && !$otitle ) {
1088 <tr style='vertical-align: top;'>
1089 <td class='diff-ntitle'>{$ntitle}</td>
1093 if ( $diff ) { // Safari/Chrome show broken output if cols not used
1095 <col class='diff-marker' />
1096 <col class='diff-content' />
1097 <col class='diff-marker' />
1098 <col class='diff-content' />";
1105 if ( $otitle ||
$ntitle ) {
1107 <tr style='vertical-align: top;'>
1108 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
1109 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
1114 if ( $multi != '' ) {
1115 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;' " .
1116 "class='diff-multi'>{$multi}</td></tr>";
1118 if ( $notice != '' ) {
1119 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;'>{$notice}</td></tr>";
1122 return $header . $diff . "</table>";
1126 * Use specified text instead of loading from the database
1127 * @deprecated since 1.21, use setContent() instead.
1129 public function setText( $oldText, $newText ) {
1130 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1132 $oldContent = ContentHandler
::makeContent( $oldText, $this->getTitle() );
1133 $newContent = ContentHandler
::makeContent( $newText, $this->getTitle() );
1135 $this->setContent( $oldContent, $newContent );
1139 * Use specified text instead of loading from the database
1142 public function setContent( Content
$oldContent, Content
$newContent ) {
1143 $this->mOldContent
= $oldContent;
1144 $this->mNewContent
= $newContent;
1146 $this->mTextLoaded
= 2;
1147 $this->mRevisionsLoaded
= true;
1151 * Set the language in which the diff text is written
1152 * (Defaults to page content language).
1155 public function setTextLanguage( $lang ) {
1156 $this->mDiffLang
= wfGetLangObj( $lang );
1160 * Maps a revision pair definition as accepted by DifferenceEngine constructor
1161 * to a pair of actual integers representing revision ids.
1163 * @param int $old Revision id, e.g. from URL parameter 'oldid'
1164 * @param int|string $new Revision id or strings 'next' or 'prev', e.g. from URL parameter 'diff'
1166 * @return int[] List of two revision ids, older first, later second.
1167 * Zero signifies invalid argument passed.
1168 * false signifies that there is no previous/next revision ($old is the oldest/newest one).
1170 public function mapDiffPrevNext( $old, $new ) {
1171 if ( $new === 'prev' ) {
1172 // Show diff between revision $old and the previous one. Get previous one from DB.
1173 $newid = intval( $old );
1174 $oldid = $this->getTitle()->getPreviousRevisionID( $newid );
1175 } elseif ( $new === 'next' ) {
1176 // Show diff between revision $old and the next one. Get next one from DB.
1177 $oldid = intval( $old );
1178 $newid = $this->getTitle()->getNextRevisionID( $oldid );
1180 $oldid = intval( $old );
1181 $newid = intval( $new );
1184 return array( $oldid, $newid );
1190 private function loadRevisionIds() {
1191 if ( $this->mRevisionsIdsLoaded
) {
1195 $this->mRevisionsIdsLoaded
= true;
1197 $old = $this->mOldid
;
1198 $new = $this->mNewid
;
1200 list( $this->mOldid
, $this->mNewid
) = self
::mapDiffPrevNext( $old, $new );
1201 if ( $new === 'next' && $this->mNewid
=== false ) {
1202 # if no result, NewId points to the newest old revision. The only newer
1203 # revision is cur, which is "0".
1208 'NewDifferenceEngine',
1209 array( $this->getTitle(), &$this->mOldid
, &$this->mNewid
, $old, $new )
1214 * Load revision metadata for the specified articles. If newid is 0, then compare
1215 * the old article in oldid to the current article; if oldid is 0, then
1216 * compare the current article to the immediately previous one (ignoring the
1219 * If oldid is false, leave the corresponding revision object set
1220 * to false. This is impossible via ordinary user input, and is provided for
1225 public function loadRevisionData() {
1226 if ( $this->mRevisionsLoaded
) {
1230 // Whether it succeeds or fails, we don't want to try again
1231 $this->mRevisionsLoaded
= true;
1233 $this->loadRevisionIds();
1235 // Load the new revision object
1236 if ( $this->mNewid
) {
1237 $this->mNewRev
= Revision
::newFromId( $this->mNewid
);
1239 $this->mNewRev
= Revision
::newFromTitle(
1242 Revision
::READ_NORMAL
1246 if ( !$this->mNewRev
instanceof Revision
) {
1250 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1251 $this->mNewid
= $this->mNewRev
->getId();
1252 $this->mNewPage
= $this->mNewRev
->getTitle();
1254 // Load the old revision object
1255 $this->mOldRev
= false;
1256 if ( $this->mOldid
) {
1257 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1258 } elseif ( $this->mOldid
=== 0 ) {
1259 $rev = $this->mNewRev
->getPrevious();
1261 $this->mOldid
= $rev->getId();
1262 $this->mOldRev
= $rev;
1264 // No previous revision; mark to show as first-version only.
1265 $this->mOldid
= false;
1266 $this->mOldRev
= false;
1268 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1270 if ( is_null( $this->mOldRev
) ) {
1274 if ( $this->mOldRev
) {
1275 $this->mOldPage
= $this->mOldRev
->getTitle();
1278 // Load tags information for both revisions
1279 $dbr = wfGetDB( DB_SLAVE
);
1280 if ( $this->mOldid
!== false ) {
1281 $this->mOldTags
= $dbr->selectField(
1284 array( 'ts_rev_id' => $this->mOldid
),
1288 $this->mOldTags
= false;
1290 $this->mNewTags
= $dbr->selectField(
1293 array( 'ts_rev_id' => $this->mNewid
),
1301 * Load the text of the revisions, as well as revision data.
1305 public function loadText() {
1306 if ( $this->mTextLoaded
== 2 ) {
1310 // Whether it succeeds or fails, we don't want to try again
1311 $this->mTextLoaded
= 2;
1313 if ( !$this->loadRevisionData() ) {
1317 if ( $this->mOldRev
) {
1318 $this->mOldContent
= $this->mOldRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1319 if ( $this->mOldContent
=== null ) {
1324 if ( $this->mNewRev
) {
1325 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1326 if ( $this->mNewContent
=== null ) {
1335 * Load the text of the new revision, not the old one
1339 public function loadNewText() {
1340 if ( $this->mTextLoaded
>= 1 ) {
1344 $this->mTextLoaded
= 1;
1346 if ( !$this->loadRevisionData() ) {
1350 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );