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 $msg = $this->msg( 'difference-missing-revision' )
228 ->params( $this->getLanguage()->listToText( $missing ) )
229 ->numParams( count( $missing ) )
231 $out->addHtml( $msg );
234 public function showDiffPage( $diffOnly = false ) {
235 wfProfileIn( __METHOD__
);
237 # Allow frames except in certain special cases
238 $out = $this->getOutput();
239 $out->allowClickjacking();
240 $out->setRobotPolicy( 'noindex,nofollow' );
242 if ( !$this->loadRevisionData() ) {
243 $this->showMissingRevision();
244 wfProfileOut( __METHOD__
);
249 $user = $this->getUser();
250 $permErrors = $this->mNewPage
->getUserPermissionsErrors( 'read', $user );
251 if ( $this->mOldPage
) { # mOldPage might not be set, see below.
252 $permErrors = wfMergeErrorArrays( $permErrors,
253 $this->mOldPage
->getUserPermissionsErrors( 'read', $user ) );
255 if ( count( $permErrors ) ) {
256 wfProfileOut( __METHOD__
);
257 throw new PermissionsError( 'read', $permErrors );
263 # Carry over 'diffonly' param via navigation links
264 if ( $diffOnly != $user->getBoolOption( 'diffonly' ) ) {
265 $query['diffonly'] = $diffOnly;
267 # Cascade unhide param in links for easy deletion browsing
268 if ( $this->unhide
) {
269 $query['unhide'] = 1;
272 # Check if one of the revisions is deleted/suppressed
273 $deleted = $suppressed = false;
274 $allowed = $this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $user );
276 $revisionTools = array();
278 # mOldRev is false if the difference engine is called with a "vague" query for
279 # a diff between a version V and its previous version V' AND the version V
280 # is the first version of that article. In that case, V' does not exist.
281 if ( $this->mOldRev
=== false ) {
282 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
286 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
288 if ( $this->mNewPage
->equals( $this->mOldPage
) ) {
289 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
292 $out->setPageTitle( $this->msg( 'difference-title-multipage',
293 $this->mOldPage
->getPrefixedText(), $this->mNewPage
->getPrefixedText() ) );
294 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
298 if ( $samePage && $this->mNewPage
->quickUserCan( 'edit', $user ) ) {
299 if ( $this->mNewRev
->isCurrent() && $this->mNewPage
->userCan( 'rollback', $user ) ) {
300 $rollbackLink = Linker
::generateRollback( $this->mNewRev
, $this->getContext() );
301 if ( $rollbackLink ) {
302 $out->preventClickjacking();
303 $rollback = '   ' . $rollbackLink;
307 if ( !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) &&
308 !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
)
310 $undoLink = Html
::element( 'a', array(
311 'href' => $this->mNewPage
->getLocalURL( array(
313 'undoafter' => $this->mOldid
,
314 'undo' => $this->mNewid
316 'title' => Linker
::titleAttrib( 'undo' ),
318 $this->msg( 'editundo' )->text()
320 $revisionTools['mw-diff-undo'] = $undoLink;
324 # Make "previous revision link"
325 if ( $samePage && $this->mOldRev
->getPrevious() ) {
326 $prevlink = Linker
::linkKnown(
328 $this->msg( 'previousdiff' )->escaped(),
329 array( 'id' => 'differences-prevlink' ),
330 array( 'diff' => 'prev', 'oldid' => $this->mOldid
) +
$query
333 $prevlink = ' ';
336 if ( $this->mOldRev
->isMinor() ) {
337 $oldminor = ChangesList
::flag( 'minor' );
342 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
343 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev
, 'complete' );
344 $oldChangeTags = ChangeTags
::formatSummaryRow( $this->mOldTags
, 'diff' );
346 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
347 '<div id="mw-diff-otitle2">' .
348 Linker
::revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
349 '<div id="mw-diff-otitle3">' . $oldminor .
350 Linker
::revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
351 '<div id="mw-diff-otitle5">' . $oldChangeTags[0] . '</div>' .
352 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
354 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
355 $deleted = true; // old revisions text is hidden
356 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
357 $suppressed = true; // also suppressed
361 # Check if this user can see the revisions
362 if ( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $user ) ) {
367 # Make "next revision link"
368 # Skip next link on the top revision
369 if ( $samePage && !$this->mNewRev
->isCurrent() ) {
370 $nextlink = Linker
::linkKnown(
372 $this->msg( 'nextdiff' )->escaped(),
373 array( 'id' => 'differences-nextlink' ),
374 array( 'diff' => 'next', 'oldid' => $this->mNewid
) +
$query
377 $nextlink = ' ';
380 if ( $this->mNewRev
->isMinor() ) {
381 $newminor = ChangesList
::flag( 'minor' );
386 # Handle RevisionDelete links...
387 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
389 # Allow extensions to define their own revision tools
390 wfRunHooks( 'DiffRevisionTools', array( $this->mNewRev
, &$revisionTools, $this->mOldRev
) );
391 $formattedRevisionTools = array();
392 // Put each one in parentheses (poor man's button)
393 foreach ( $revisionTools as $key => $tool ) {
394 $toolClass = is_string( $key ) ?
$key : 'mw-diff-tool';
395 $element = Html
::rawElement(
397 array( 'class' => $toolClass ),
398 $this->msg( 'parentheses' )->rawParams( $tool )->escaped()
400 $formattedRevisionTools[] = $element;
402 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev
, 'complete' ) .
403 ' ' . implode( ' ', $formattedRevisionTools );
404 $newChangeTags = ChangeTags
::formatSummaryRow( $this->mNewTags
, 'diff' );
406 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
407 '<div id="mw-diff-ntitle2">' . Linker
::revUserTools( $this->mNewRev
, !$this->unhide
) .
409 '<div id="mw-diff-ntitle3">' . $newminor .
410 Linker
::revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
411 '<div id="mw-diff-ntitle5">' . $newChangeTags[0] . '</div>' .
412 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
414 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
415 $deleted = true; // new revisions text is hidden
416 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
417 $suppressed = true; // also suppressed
421 # If the diff cannot be shown due to a deleted revision, then output
422 # the diff header and links to unhide (if available)...
423 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
424 $this->showDiffStyle();
425 $multi = $this->getMultiNotice();
426 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
428 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
429 # Give explanation for why revision is not visible
430 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
433 # Give explanation and add a link to view the diff...
434 $query = $this->getRequest()->appendQueryValue( 'unhide', '1', true );
435 $link = $this->getTitle()->getFullURL( $query );
436 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
438 "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
442 # Otherwise, output a regular diff...
444 # Add deletion notice if the user is viewing deleted content
447 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
448 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" .
449 $this->msg( $msg )->parse() .
452 $this->showDiff( $oldHeader, $newHeader, $notice );
454 $this->renderNewRevision();
457 wfProfileOut( __METHOD__
);
461 * Get a link to mark the change as patrolled, or '' if there's either no
462 * revision to patrol or the user is not allowed to to it.
463 * Side effect: When the patrol link is build, this method will call
464 * OutputPage::preventClickjacking() and load mediawiki.page.patrol.ajax.
468 protected function markPatrolledLink() {
469 global $wgUseRCPatrol, $wgEnableAPI, $wgEnableWriteAPI;
470 $user = $this->getUser();
472 if ( $this->mMarkPatrolledLink
=== null ) {
473 // Prepare a change patrol link, if applicable
475 // Is patrolling enabled and the user allowed to?
476 $wgUseRCPatrol && $this->mNewPage
->quickUserCan( 'patrol', $user ) &&
477 // Only do this if the revision isn't more than 6 hours older
478 // than the Max RC age (6h because the RC might not be cleaned out regularly)
479 RecentChange
::isInRCLifespan( $this->mNewRev
->getTimestamp(), 21600 )
481 // Look for an unpatrolled change corresponding to this diff
483 $db = wfGetDB( DB_SLAVE
);
484 $change = RecentChange
::newFromConds(
486 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
487 'rc_this_oldid' => $this->mNewid
,
491 array( 'USE INDEX' => 'rc_timestamp' )
494 if ( $change && $change->getPerformer()->getName() !== $user->getName() ) {
495 $rcid = $change->getAttribute( 'rc_id' );
497 // None found or the page has been created by the current user.
498 // If the user could patrol this it already would be patrolled
503 $this->getOutput()->preventClickjacking();
504 if ( $wgEnableAPI && $wgEnableWriteAPI
505 && $user->isAllowed( 'writeapi' )
507 $this->getOutput()->addModules( 'mediawiki.page.patrol.ajax' );
510 $token = $user->getEditToken( $rcid );
511 $this->mMarkPatrolledLink
= ' <span class="patrollink">[' . Linker
::linkKnown(
513 $this->msg( 'markaspatrolleddiff' )->escaped(),
516 'action' => 'markpatrolled',
522 $this->mMarkPatrolledLink
= '';
525 $this->mMarkPatrolledLink
= '';
529 return $this->mMarkPatrolledLink
;
533 * @param Revision $rev
537 protected function revisionDeleteLink( $rev ) {
538 $link = Linker
::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
539 if ( $link !== '' ) {
540 $link = '   ' . $link . ' ';
547 * Show the new revision of the page.
549 public function renderNewRevision() {
550 wfProfileIn( __METHOD__
);
551 $out = $this->getOutput();
552 $revHeader = $this->getRevisionHeader( $this->mNewRev
);
553 # Add "current version as of X" title
554 $out->addHTML( "<hr class='diff-hr' />
555 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
556 # Page content may be handled by a hooked call instead...
557 # @codingStandardsIgnoreStart Ignoring long lines.
558 if ( wfRunHooks( 'ArticleContentOnDiff', array( $this, $out ) ) ) {
559 $this->loadNewText();
560 $out->setRevisionId( $this->mNewid
);
561 $out->setRevisionTimestamp( $this->mNewRev
->getTimestamp() );
562 $out->setArticleFlag( true );
564 // NOTE: only needed for B/C: custom rendering of JS/CSS via hook
565 if ( $this->mNewPage
->isCssJsSubpage() ||
$this->mNewPage
->isCssOrJsPage() ) {
566 // This needs to be synchronised with Article::showCssOrJsPage(), which sucks
567 // Give hooks a chance to customise the output
568 // @todo standardize this crap into one function
569 if ( ContentHandler
::runLegacyHooks( 'ShowRawCssJs', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
570 // NOTE: deprecated hook, B/C only
571 // use the content object's own rendering
572 $cnt = $this->mNewRev
->getContent();
573 $po = $cnt ?
$cnt->getParserOutput( $this->mNewRev
->getTitle(), $this->mNewRev
->getId() ) : null;
575 $out->addParserOutputContent( $po );
578 } elseif ( !wfRunHooks( 'ArticleContentViewCustom', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
579 // Handled by extension
580 } elseif ( !ContentHandler
::runLegacyHooks( 'ArticleViewCustom', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
581 // NOTE: deprecated hook, B/C only
582 // Handled by extension
585 if ( $this->getTitle()->equals( $this->mNewPage
) ) {
586 // If the Title stored in the context is the same as the one
587 // of the new revision, we can use its associated WikiPage
589 $wikiPage = $this->getWikiPage();
591 // Otherwise we need to create our own WikiPage object
592 $wikiPage = WikiPage
::factory( $this->mNewPage
);
595 $parserOutput = $this->getParserOutput( $wikiPage, $this->mNewRev
);
597 # WikiPage::getParserOutput() should not return false, but just in case
598 if ( $parserOutput ) {
599 $out->addParserOutput( $parserOutput );
603 # @codingStandardsIgnoreEnd
605 # Add redundant patrol link on bottom...
606 $out->addHTML( $this->markPatrolledLink() );
608 wfProfileOut( __METHOD__
);
611 protected function getParserOutput( WikiPage
$page, Revision
$rev ) {
612 $parserOptions = $page->makeParserOptions( $this->getContext() );
614 if ( !$rev->isCurrent() ||
!$rev->getTitle()->quickUserCan( "edit" ) ) {
615 $parserOptions->setEditSection( false );
618 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
620 return $parserOutput;
624 * Get the diff text, send it to the OutputPage object
625 * Returns false if the diff could not be generated, otherwise returns true
627 * @param string|bool $otitle Header for old text or false
628 * @param string|bool $ntitle Header for new text or false
629 * @param string $notice HTML between diff header and body
633 public function showDiff( $otitle, $ntitle, $notice = '' ) {
634 $diff = $this->getDiff( $otitle, $ntitle, $notice );
635 if ( $diff === false ) {
636 $this->showMissingRevision();
640 $this->showDiffStyle();
641 $this->getOutput()->addHTML( $diff );
648 * Add style sheets and supporting JS for diff display.
650 public function showDiffStyle() {
651 $this->getOutput()->addModuleStyles( 'mediawiki.action.history.diff' );
655 * Get complete diff table, including header
657 * @param string|bool $otitle Header for old text or false
658 * @param string|bool $ntitle Header for new text or false
659 * @param string $notice HTML between diff header and body
663 public function getDiff( $otitle, $ntitle, $notice = '' ) {
664 $body = $this->getDiffBody();
665 if ( $body === false ) {
669 $multi = $this->getMultiNotice();
670 // Display a message when the diff is empty
671 if ( $body === '' ) {
672 $notice .= '<div class="mw-diff-empty">' .
673 $this->msg( 'diff-empty' )->parse() .
677 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
681 * Get the diff table body, without header
683 * @return mixed (string/false)
685 public function getDiffBody() {
687 wfProfileIn( __METHOD__
);
688 $this->mCacheHit
= true;
689 // Check if the diff should be hidden from this user
690 if ( !$this->loadRevisionData() ) {
691 wfProfileOut( __METHOD__
);
694 } elseif ( $this->mOldRev
&&
695 !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
697 wfProfileOut( __METHOD__
);
700 } elseif ( $this->mNewRev
&&
701 !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
703 wfProfileOut( __METHOD__
);
708 if ( $this->mOldRev
=== false ||
( $this->mOldRev
&& $this->mNewRev
709 && $this->mOldRev
->getID() == $this->mNewRev
->getID() )
711 wfProfileOut( __METHOD__
);
717 if ( $this->mOldid
&& $this->mNewid
) {
718 $key = $this->getDiffBodyCacheKey();
721 if ( !$this->mRefreshCache
) {
722 $difftext = $wgMemc->get( $key );
724 wfIncrStats( 'diff_cache_hit' );
725 $difftext = $this->localiseLineNumbers( $difftext );
726 $difftext .= "\n<!-- diff cache key $key -->\n";
727 wfProfileOut( __METHOD__
);
731 } // don't try to load but save the result
733 $this->mCacheHit
= false;
735 // Loadtext is permission safe, this just clears out the diff
736 if ( !$this->loadText() ) {
737 wfProfileOut( __METHOD__
);
742 $difftext = $this->generateContentDiffBody( $this->mOldContent
, $this->mNewContent
);
744 // Save to cache for 7 days
745 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
746 wfIncrStats( 'diff_uncacheable' );
747 } elseif ( $key !== false && $difftext !== false ) {
748 wfIncrStats( 'diff_cache_miss' );
749 $wgMemc->set( $key, $difftext, 7 * 86400 );
751 wfIncrStats( 'diff_uncacheable' );
753 // Replace line numbers with the text in the user's language
754 if ( $difftext !== false ) {
755 $difftext = $this->localiseLineNumbers( $difftext );
757 wfProfileOut( __METHOD__
);
763 * Returns the cache key for diff body text or content.
767 * @throws MWException
770 protected function getDiffBodyCacheKey() {
771 if ( !$this->mOldid ||
!$this->mNewid
) {
772 throw new MWException( 'mOldid and mNewid must be set to get diff cache key.' );
775 return wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
,
776 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
780 * Generate a diff, no caching.
782 * This implementation uses generateTextDiffBody() to generate a diff based on the default
783 * serialization of the given Content objects. This will fail if $old or $new are not
784 * instances of TextContent.
786 * Subclasses may override this to provide a different rendering for the diff,
787 * perhaps taking advantage of the content's native form. This is required for all content
788 * models that are not text based.
792 * @param Content $old Old content
793 * @param Content $new New content
795 * @throws MWException If old or new content is not an instance of TextContent.
796 * @return bool|string
798 public function generateContentDiffBody( Content
$old, Content
$new ) {
799 if ( !( $old instanceof TextContent
) ) {
800 throw new MWException( "Diff not implemented for " . get_class( $old ) . "; " .
801 "override generateContentDiffBody to fix this." );
804 if ( !( $new instanceof TextContent
) ) {
805 throw new MWException( "Diff not implemented for " . get_class( $new ) . "; "
806 . "override generateContentDiffBody to fix this." );
809 $otext = $old->serialize();
810 $ntext = $new->serialize();
812 return $this->generateTextDiffBody( $otext, $ntext );
816 * Generate a diff, no caching
818 * @param string $otext Old text, must be already segmented
819 * @param string $ntext New text, must be already segmented
821 * @return bool|string
822 * @deprecated since 1.21, use generateContentDiffBody() instead!
824 public function generateDiffBody( $otext, $ntext ) {
825 ContentHandler
::deprecated( __METHOD__
, "1.21" );
827 return $this->generateTextDiffBody( $otext, $ntext );
831 * Generate a diff, no caching
833 * @todo move this to TextDifferenceEngine, make DifferenceEngine abstract. At some point.
835 * @param string $otext Old text, must be already segmented
836 * @param string $ntext New text, must be already segmented
838 * @return bool|string
840 public function generateTextDiffBody( $otext, $ntext ) {
841 global $wgExternalDiffEngine, $wgContLang;
843 wfProfileIn( __METHOD__
);
845 $otext = str_replace( "\r\n", "\n", $otext );
846 $ntext = str_replace( "\r\n", "\n", $ntext );
848 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
849 # For historical reasons, external diff engine expects
850 # input text to be HTML-escaped already
851 $otext = htmlspecialchars( $wgContLang->segmentForDiff( $otext ) );
852 $ntext = htmlspecialchars( $wgContLang->segmentForDiff( $ntext ) );
853 wfProfileOut( __METHOD__
);
855 return $wgContLang->unsegmentForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
856 $this->debug( 'wikidiff1' );
859 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
860 # Better external diff engine, the 2 may some day be dropped
861 # This one does the escaping and segmenting itself
862 wfProfileIn( 'wikidiff2_do_diff' );
863 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
864 $text .= $this->debug( 'wikidiff2' );
865 wfProfileOut( 'wikidiff2_do_diff' );
866 wfProfileOut( __METHOD__
);
870 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
872 $tmpDir = wfTempDir();
873 $tempName1 = tempnam( $tmpDir, 'diff_' );
874 $tempName2 = tempnam( $tmpDir, 'diff_' );
876 $tempFile1 = fopen( $tempName1, "w" );
878 wfProfileOut( __METHOD__
);
882 $tempFile2 = fopen( $tempName2, "w" );
884 wfProfileOut( __METHOD__
);
888 fwrite( $tempFile1, $otext );
889 fwrite( $tempFile2, $ntext );
890 fclose( $tempFile1 );
891 fclose( $tempFile2 );
892 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
893 wfProfileIn( __METHOD__
. "-shellexec" );
894 $difftext = wfShellExec( $cmd );
895 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
896 wfProfileOut( __METHOD__
. "-shellexec" );
897 unlink( $tempName1 );
898 unlink( $tempName2 );
899 wfProfileOut( __METHOD__
);
905 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
906 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
907 $diffs = new Diff( $ota, $nta );
908 $formatter = new TableDiffFormatter();
909 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
910 wfProfileOut( __METHOD__
);
916 * Generate a debug comment indicating diff generating time,
917 * server node, and generator backend.
919 * @param string $generator : What diff engine was used
923 protected function debug( $generator = "internal" ) {
924 global $wgShowHostnames;
925 if ( !$this->enableDebugComment
) {
928 $data = array( $generator );
929 if ( $wgShowHostnames ) {
930 $data[] = wfHostname();
932 $data[] = wfTimestamp( TS_DB
);
934 return "<!-- diff generator: " .
935 implode( " ", array_map( "htmlspecialchars", $data ) ) .
940 * Replace line numbers with the text in the user's language
942 * @param string $text
946 public function localiseLineNumbers( $text ) {
947 return preg_replace_callback(
948 '/<!--LINE (\d+)-->/',
949 array( &$this, 'localiseLineNumbersCb' ),
954 public function localiseLineNumbersCb( $matches ) {
955 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) {
959 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
963 * If there are revisions between the ones being compared, return a note saying so.
967 public function getMultiNotice() {
968 if ( !is_object( $this->mOldRev
) ||
!is_object( $this->mNewRev
) ) {
970 } elseif ( !$this->mOldPage
->equals( $this->mNewPage
) ) {
971 // Comparing two different pages? Count would be meaningless.
975 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
976 $oldRev = $this->mNewRev
; // flip
977 $newRev = $this->mOldRev
; // flip
978 } else { // normal case
979 $oldRev = $this->mOldRev
;
980 $newRev = $this->mNewRev
;
983 // Sanity: don't show the notice if too many rows must be scanned
984 // @todo show some special message for that case
985 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev, 1000 );
986 if ( $nEdits > 0 && $nEdits <= 1000 ) {
987 $limit = 100; // use diff-multi-manyusers if too many users
988 $users = $this->mNewPage
->getAuthorsBetween( $oldRev, $newRev, $limit );
989 $numUsers = count( $users );
991 if ( $numUsers == 1 && $users[0] == $newRev->getRawUserText() ) {
992 $numUsers = 0; // special case to say "by the same user" instead of "by one other user"
995 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
998 return ''; // nothing
1002 * Get a notice about how many intermediate edits and users there are
1004 * @param int $numEdits
1005 * @param int $numUsers
1010 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
1011 if ( $numUsers === 0 ) {
1012 $msg = 'diff-multi-sameuser';
1013 } elseif ( $numUsers > $limit ) {
1014 $msg = 'diff-multi-manyusers';
1017 $msg = 'diff-multi-otherusers';
1020 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
1024 * Get a header for a specified revision.
1026 * @param Revision $rev
1027 * @param string $complete 'complete' to get the header wrapped depending
1028 * the visibility of the revision and a link to edit the page.
1030 * @return string HTML fragment
1032 protected function getRevisionHeader( Revision
$rev, $complete = '' ) {
1033 $lang = $this->getLanguage();
1034 $user = $this->getUser();
1035 $revtimestamp = $rev->getTimestamp();
1036 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
1037 $dateofrev = $lang->userDate( $revtimestamp, $user );
1038 $timeofrev = $lang->userTime( $revtimestamp, $user );
1040 $header = $this->msg(
1041 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
1047 if ( $complete !== 'complete' ) {
1051 $title = $rev->getTitle();
1053 $header = Linker
::linkKnown( $title, $header, array(),
1054 array( 'oldid' => $rev->getID() ) );
1056 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
1057 $editQuery = array( 'action' => 'edit' );
1058 if ( !$rev->isCurrent() ) {
1059 $editQuery['oldid'] = $rev->getID();
1062 $key = $title->quickUserCan( 'edit', $user ) ?
'editold' : 'viewsourceold';
1063 $msg = $this->msg( $key )->escaped();
1064 $editLink = $this->msg( 'parentheses' )->rawParams(
1065 Linker
::linkKnown( $title, $msg, array( ), $editQuery ) )->plain();
1066 $header .= ' ' . Html
::rawElement(
1068 array( 'class' => 'mw-diff-edit' ),
1071 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
1072 $header = Html
::rawElement(
1074 array( 'class' => 'history-deleted' ),
1079 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
1086 * Add the header to a diff body
1088 * @param string $diff Diff body
1089 * @param string $otitle Old revision header
1090 * @param string $ntitle New revision header
1091 * @param string $multi Notice telling user that there are intermediate
1092 * revisions between the ones being compared
1093 * @param string $notice Other notices, e.g. that user is viewing deleted content
1097 public function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
1098 // shared.css sets diff in interface language/dir, but the actual content
1099 // is often in a different language, mostly the page content language/dir
1100 $tableClass = 'diff diff-contentalign-' . htmlspecialchars( $this->getDiffLang()->alignStart() );
1101 $header = "<table class='$tableClass'>";
1103 if ( !$diff && !$otitle ) {
1105 <tr style='vertical-align: top;'>
1106 <td class='diff-ntitle'>{$ntitle}</td>
1110 if ( $diff ) { // Safari/Chrome show broken output if cols not used
1112 <col class='diff-marker' />
1113 <col class='diff-content' />
1114 <col class='diff-marker' />
1115 <col class='diff-content' />";
1122 if ( $otitle ||
$ntitle ) {
1124 <tr style='vertical-align: top;'>
1125 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
1126 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
1131 if ( $multi != '' ) {
1132 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;' " .
1133 "class='diff-multi'>{$multi}</td></tr>";
1135 if ( $notice != '' ) {
1136 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;'>{$notice}</td></tr>";
1139 return $header . $diff . "</table>";
1143 * Use specified text instead of loading from the database
1144 * @deprecated since 1.21, use setContent() instead.
1146 public function setText( $oldText, $newText ) {
1147 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1149 $oldContent = ContentHandler
::makeContent( $oldText, $this->getTitle() );
1150 $newContent = ContentHandler
::makeContent( $newText, $this->getTitle() );
1152 $this->setContent( $oldContent, $newContent );
1156 * Use specified text instead of loading from the database
1157 * @param Content $oldContent
1158 * @param Content $newContent
1161 public function setContent( Content
$oldContent, Content
$newContent ) {
1162 $this->mOldContent
= $oldContent;
1163 $this->mNewContent
= $newContent;
1165 $this->mTextLoaded
= 2;
1166 $this->mRevisionsLoaded
= true;
1170 * Set the language in which the diff text is written
1171 * (Defaults to page content language).
1172 * @param Language|string $lang
1175 public function setTextLanguage( $lang ) {
1176 $this->mDiffLang
= wfGetLangObj( $lang );
1180 * Maps a revision pair definition as accepted by DifferenceEngine constructor
1181 * to a pair of actual integers representing revision ids.
1183 * @param int $old Revision id, e.g. from URL parameter 'oldid'
1184 * @param int|string $new Revision id or strings 'next' or 'prev', e.g. from URL parameter 'diff'
1186 * @return int[] List of two revision ids, older first, later second.
1187 * Zero signifies invalid argument passed.
1188 * false signifies that there is no previous/next revision ($old is the oldest/newest one).
1190 public function mapDiffPrevNext( $old, $new ) {
1191 if ( $new === 'prev' ) {
1192 // Show diff between revision $old and the previous one. Get previous one from DB.
1193 $newid = intval( $old );
1194 $oldid = $this->getTitle()->getPreviousRevisionID( $newid );
1195 } elseif ( $new === 'next' ) {
1196 // Show diff between revision $old and the next one. Get next one from DB.
1197 $oldid = intval( $old );
1198 $newid = $this->getTitle()->getNextRevisionID( $oldid );
1200 $oldid = intval( $old );
1201 $newid = intval( $new );
1204 return array( $oldid, $newid );
1210 private function loadRevisionIds() {
1211 if ( $this->mRevisionsIdsLoaded
) {
1215 $this->mRevisionsIdsLoaded
= true;
1217 $old = $this->mOldid
;
1218 $new = $this->mNewid
;
1220 list( $this->mOldid
, $this->mNewid
) = self
::mapDiffPrevNext( $old, $new );
1221 if ( $new === 'next' && $this->mNewid
=== false ) {
1222 # if no result, NewId points to the newest old revision. The only newer
1223 # revision is cur, which is "0".
1228 'NewDifferenceEngine',
1229 array( $this->getTitle(), &$this->mOldid
, &$this->mNewid
, $old, $new )
1234 * Load revision metadata for the specified articles. If newid is 0, then compare
1235 * the old article in oldid to the current article; if oldid is 0, then
1236 * compare the current article to the immediately previous one (ignoring the
1239 * If oldid is false, leave the corresponding revision object set
1240 * to false. This is impossible via ordinary user input, and is provided for
1245 public function loadRevisionData() {
1246 if ( $this->mRevisionsLoaded
) {
1250 // Whether it succeeds or fails, we don't want to try again
1251 $this->mRevisionsLoaded
= true;
1253 $this->loadRevisionIds();
1255 // Load the new revision object
1256 if ( $this->mNewid
) {
1257 $this->mNewRev
= Revision
::newFromId( $this->mNewid
);
1259 $this->mNewRev
= Revision
::newFromTitle(
1262 Revision
::READ_NORMAL
1266 if ( !$this->mNewRev
instanceof Revision
) {
1270 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1271 $this->mNewid
= $this->mNewRev
->getId();
1272 $this->mNewPage
= $this->mNewRev
->getTitle();
1274 // Load the old revision object
1275 $this->mOldRev
= false;
1276 if ( $this->mOldid
) {
1277 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1278 } elseif ( $this->mOldid
=== 0 ) {
1279 $rev = $this->mNewRev
->getPrevious();
1281 $this->mOldid
= $rev->getId();
1282 $this->mOldRev
= $rev;
1284 // No previous revision; mark to show as first-version only.
1285 $this->mOldid
= false;
1286 $this->mOldRev
= false;
1288 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1290 if ( is_null( $this->mOldRev
) ) {
1294 if ( $this->mOldRev
) {
1295 $this->mOldPage
= $this->mOldRev
->getTitle();
1298 // Load tags information for both revisions
1299 $dbr = wfGetDB( DB_SLAVE
);
1300 if ( $this->mOldid
!== false ) {
1301 $this->mOldTags
= $dbr->selectField(
1304 array( 'ts_rev_id' => $this->mOldid
),
1308 $this->mOldTags
= false;
1310 $this->mNewTags
= $dbr->selectField(
1313 array( 'ts_rev_id' => $this->mNewid
),
1321 * Load the text of the revisions, as well as revision data.
1325 public function loadText() {
1326 if ( $this->mTextLoaded
== 2 ) {
1330 // Whether it succeeds or fails, we don't want to try again
1331 $this->mTextLoaded
= 2;
1333 if ( !$this->loadRevisionData() ) {
1337 if ( $this->mOldRev
) {
1338 $this->mOldContent
= $this->mOldRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1339 if ( $this->mOldContent
=== null ) {
1344 if ( $this->mNewRev
) {
1345 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1346 if ( $this->mNewContent
=== null ) {
1355 * Load the text of the new revision, not the old one
1359 public function loadNewText() {
1360 if ( $this->mTextLoaded
>= 1 ) {
1364 $this->mTextLoaded
= 1;
1366 if ( !$this->loadRevisionData() ) {
1370 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );