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
23 use MediaWiki\MediaWikiServices
;
25 /** @deprecated use class constant instead */
26 define( 'MW_DIFF_VERSION', '1.11a' );
30 * @ingroup DifferenceEngine
32 class DifferenceEngine
extends ContextSource
{
34 * Constant to indicate diff cache compatibility.
35 * Bump this when changing the diff formatting in a way that
36 * fixes important bugs or such to force cached diff views to
39 const DIFF_VERSION
= MW_DIFF_VERSION
;
71 /** @var bool Have the revisions IDs been loaded */
72 private $mRevisionsIdsLoaded = false;
74 /** @var bool Have the revisions been loaded */
75 public $mRevisionsLoaded = false;
77 /** @var int How many text blobs have been loaded, 0, 1 or 2? */
78 public $mTextLoaded = 0;
80 /** @var bool Was the diff fetched from cache? */
81 public $mCacheHit = false;
84 * Set this to true to add debug info to the HTML output.
85 * Warning: this may cause RSS readers to spuriously mark articles as "new"
88 public $enableDebugComment = false;
90 /** @var bool If true, line X is not displayed when X is 1, for example
91 * to increase readability and conserve space with many small diffs.
93 protected $mReducedLineNumbers = false;
95 /** @var string Link to action=markpatrolled */
96 protected $mMarkPatrolledLink = null;
98 /** @var bool Show rev_deleted content if allowed */
99 protected $unhide = false;
101 /** @var bool Refresh the diff cache */
102 protected $mRefreshCache = false;
107 * @param IContextSource $context Context to use, anything else will be ignored
108 * @param int $old Old ID we want to show and diff with.
109 * @param string|int $new Either revision ID or 'prev' or 'next'. Default: 0.
110 * @param int $rcid Deprecated, no longer used!
111 * @param bool $refreshCache If set, refreshes the diff cache
112 * @param bool $unhide If set, allow viewing deleted revs
114 public function __construct( $context = null, $old = 0, $new = 0, $rcid = 0,
115 $refreshCache = false, $unhide = false
117 if ( $context instanceof IContextSource
) {
118 $this->setContext( $context );
121 wfDebug( "DifferenceEngine old '$old' new '$new' rcid '$rcid'\n" );
123 $this->mOldid
= $old;
124 $this->mNewid
= $new;
125 $this->mRefreshCache
= $refreshCache;
126 $this->unhide
= $unhide;
132 public function setReducedLineNumbers( $value = true ) {
133 $this->mReducedLineNumbers
= $value;
139 public function getDiffLang() {
140 if ( $this->mDiffLang
=== null ) {
141 # Default language in which the diff text is written.
142 $this->mDiffLang
= $this->getTitle()->getPageLanguage();
145 return $this->mDiffLang
;
151 public function wasCacheHit() {
152 return $this->mCacheHit
;
158 public function getOldid() {
159 $this->loadRevisionIds();
161 return $this->mOldid
;
167 public function getNewid() {
168 $this->loadRevisionIds();
170 return $this->mNewid
;
174 * Look up a special:Undelete link to the given deleted revision id,
175 * as a workaround for being unable to load deleted diffs in currently.
177 * @param int $id Revision ID
179 * @return string|bool Link HTML or false
181 public function deletedLink( $id ) {
182 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
183 $dbr = wfGetDB( DB_REPLICA
);
184 $row = $dbr->selectRow( 'archive', '*',
185 [ 'ar_rev_id' => $id ],
188 $rev = Revision
::newFromArchiveRow( $row );
189 $title = Title
::makeTitleSafe( $row->ar_namespace
, $row->ar_title
);
191 return SpecialPage
::getTitleFor( 'Undelete' )->getFullURL( [
192 'target' => $title->getPrefixedText(),
193 'timestamp' => $rev->getTimestamp()
202 * Build a wikitext link toward a deleted revision, if viewable.
204 * @param int $id Revision ID
206 * @return string Wikitext fragment
208 public function deletedIdMarker( $id ) {
209 $link = $this->deletedLink( $id );
211 return "[$link $id]";
217 private function showMissingRevision() {
218 $out = $this->getOutput();
221 if ( $this->mOldRev
=== null ||
222 ( $this->mOldRev
&& $this->mOldContent
=== null )
224 $missing[] = $this->deletedIdMarker( $this->mOldid
);
226 if ( $this->mNewRev
=== null ||
227 ( $this->mNewRev
&& $this->mNewContent
=== null )
229 $missing[] = $this->deletedIdMarker( $this->mNewid
);
232 $out->setPageTitle( $this->msg( 'errorpagetitle' ) );
233 $msg = $this->msg( 'difference-missing-revision' )
234 ->params( $this->getLanguage()->listToText( $missing ) )
235 ->numParams( count( $missing ) )
237 $out->addHTML( $msg );
240 public function showDiffPage( $diffOnly = false ) {
241 # Allow frames except in certain special cases
242 $out = $this->getOutput();
243 $out->allowClickjacking();
244 $out->setRobotPolicy( 'noindex,nofollow' );
246 // Allow extensions to add any extra output here
247 Hooks
::run( 'DifferenceEngineShowDiffPage', [ $out ] );
249 if ( !$this->loadRevisionData() ) {
250 if ( Hooks
::run( 'DifferenceEngineShowDiffPageMaybeShowMissingRevision', [ $this ] ) ) {
251 $this->showMissingRevision();
256 $user = $this->getUser();
257 $permErrors = $this->mNewPage
->getUserPermissionsErrors( 'read', $user );
258 if ( $this->mOldPage
) { # mOldPage might not be set, see below.
259 $permErrors = wfMergeErrorArrays( $permErrors,
260 $this->mOldPage
->getUserPermissionsErrors( 'read', $user ) );
262 if ( count( $permErrors ) ) {
263 throw new PermissionsError( 'read', $permErrors );
269 # Carry over 'diffonly' param via navigation links
270 if ( $diffOnly != $user->getBoolOption( 'diffonly' ) ) {
271 $query['diffonly'] = $diffOnly;
273 # Cascade unhide param in links for easy deletion browsing
274 if ( $this->unhide
) {
275 $query['unhide'] = 1;
278 # Check if one of the revisions is deleted/suppressed
279 $deleted = $suppressed = false;
280 $allowed = $this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $user );
284 # mOldRev is false if the difference engine is called with a "vague" query for
285 # a diff between a version V and its previous version V' AND the version V
286 # is the first version of that article. In that case, V' does not exist.
287 if ( $this->mOldRev
=== false ) {
288 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
291 // Allow extensions to change the $oldHeader variable
292 Hooks
::run( 'DifferenceEngineOldHeaderNoOldRev', [ &$oldHeader ] );
294 Hooks
::run( 'DiffViewHeader', [ $this, $this->mOldRev
, $this->mNewRev
] );
296 if ( $this->mNewPage
->equals( $this->mOldPage
) ) {
297 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
300 $out->setPageTitle( $this->msg( 'difference-title-multipage',
301 $this->mOldPage
->getPrefixedText(), $this->mNewPage
->getPrefixedText() ) );
302 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
306 if ( $samePage && $this->mNewPage
->quickUserCan( 'edit', $user ) ) {
307 if ( $this->mNewRev
->isCurrent() && $this->mNewPage
->userCan( 'rollback', $user ) ) {
308 $rollbackLink = Linker
::generateRollback( $this->mNewRev
, $this->getContext() );
309 if ( $rollbackLink ) {
310 $out->preventClickjacking();
311 $rollback = '   ' . $rollbackLink;
315 if ( !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) &&
316 !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
)
318 $undoLink = Html
::element( 'a', [
319 'href' => $this->mNewPage
->getLocalURL( [
321 'undoafter' => $this->mOldid
,
322 'undo' => $this->mNewid
324 'title' => Linker
::titleAttrib( 'undo' ),
326 $this->msg( 'editundo' )->text()
328 $revisionTools['mw-diff-undo'] = $undoLink;
332 # Make "previous revision link"
333 if ( $samePage && $this->mOldRev
->getPrevious() ) {
334 $prevlink = Linker
::linkKnown(
336 $this->msg( 'previousdiff' )->escaped(),
337 [ 'id' => 'differences-prevlink' ],
338 [ 'diff' => 'prev', 'oldid' => $this->mOldid
] +
$query
341 $prevlink = ' ';
344 if ( $this->mOldRev
->isMinor() ) {
345 $oldminor = ChangesList
::flag( 'minor' );
350 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
351 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev
, 'complete' );
352 $oldChangeTags = ChangeTags
::formatSummaryRow( $this->mOldTags
, 'diff', $this->getContext() );
354 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
355 '<div id="mw-diff-otitle2">' .
356 Linker
::revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
357 '<div id="mw-diff-otitle3">' . $oldminor .
358 Linker
::revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
359 '<div id="mw-diff-otitle5">' . $oldChangeTags[0] . '</div>' .
360 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
362 // Allow extensions to change the $oldHeader variable
363 Hooks
::run( 'DifferenceEngineOldHeader', [ $this, &$oldHeader, $prevlink, $oldminor,
364 $diffOnly, $ldel, $this->unhide
] );
366 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
367 $deleted = true; // old revisions text is hidden
368 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
369 $suppressed = true; // also suppressed
373 # Check if this user can see the revisions
374 if ( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $user ) ) {
379 # Make "next revision link"
380 # Skip next link on the top revision
381 if ( $samePage && !$this->mNewRev
->isCurrent() ) {
382 $nextlink = Linker
::linkKnown(
384 $this->msg( 'nextdiff' )->escaped(),
385 [ 'id' => 'differences-nextlink' ],
386 [ 'diff' => 'next', 'oldid' => $this->mNewid
] +
$query
389 $nextlink = ' ';
392 if ( $this->mNewRev
->isMinor() ) {
393 $newminor = ChangesList
::flag( 'minor' );
398 # Handle RevisionDelete links...
399 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
401 # Allow extensions to define their own revision tools
402 Hooks
::run( 'DiffRevisionTools',
403 [ $this->mNewRev
, &$revisionTools, $this->mOldRev
, $user ] );
404 $formattedRevisionTools = [];
405 // Put each one in parentheses (poor man's button)
406 foreach ( $revisionTools as $key => $tool ) {
407 $toolClass = is_string( $key ) ?
$key : 'mw-diff-tool';
408 $element = Html
::rawElement(
410 [ 'class' => $toolClass ],
411 $this->msg( 'parentheses' )->rawParams( $tool )->escaped()
413 $formattedRevisionTools[] = $element;
415 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev
, 'complete' ) .
416 ' ' . implode( ' ', $formattedRevisionTools );
417 $newChangeTags = ChangeTags
::formatSummaryRow( $this->mNewTags
, 'diff', $this->getContext() );
419 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
420 '<div id="mw-diff-ntitle2">' . Linker
::revUserTools( $this->mNewRev
, !$this->unhide
) .
422 '<div id="mw-diff-ntitle3">' . $newminor .
423 Linker
::revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
424 '<div id="mw-diff-ntitle5">' . $newChangeTags[0] . '</div>' .
425 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
427 // Allow extensions to change the $newHeader variable
428 Hooks
::run( 'DifferenceEngineNewHeader', [ $this, &$newHeader, $formattedRevisionTools,
429 $nextlink, $rollback, $newminor, $diffOnly, $rdel, $this->unhide
] );
431 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
432 $deleted = true; // new revisions text is hidden
433 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
434 $suppressed = true; // also suppressed
438 # If the diff cannot be shown due to a deleted revision, then output
439 # the diff header and links to unhide (if available)...
440 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
441 $this->showDiffStyle();
442 $multi = $this->getMultiNotice();
443 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
445 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
446 # Give explanation for why revision is not visible
447 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
450 # Give explanation and add a link to view the diff...
451 $query = $this->getRequest()->appendQueryValue( 'unhide', '1' );
452 $link = $this->getTitle()->getFullURL( $query );
453 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
455 "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
459 # Otherwise, output a regular diff...
461 # Add deletion notice if the user is viewing deleted content
464 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
465 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" .
466 $this->msg( $msg )->parse() .
469 $this->showDiff( $oldHeader, $newHeader, $notice );
471 $this->renderNewRevision();
477 * Build a link to mark a change as patrolled.
479 * Returns empty string if there's either no revision to patrol or the user is not allowed to.
480 * Side effect: When the patrol link is build, this method will call
481 * OutputPage::preventClickjacking() and load mediawiki.page.patrol.ajax.
483 * @return string HTML or empty string
485 public function markPatrolledLink() {
486 if ( $this->mMarkPatrolledLink
=== null ) {
487 $linkInfo = $this->getMarkPatrolledLinkInfo();
488 // If false, there is no patrol link needed/allowed
490 $this->mMarkPatrolledLink
= '';
492 $this->mMarkPatrolledLink
= ' <span class="patrollink" data-mw="interface">[' .
495 $this->msg( 'markaspatrolleddiff' )->escaped(),
498 'action' => 'markpatrolled',
499 'rcid' => $linkInfo['rcid'],
502 // Allow extensions to change the markpatrolled link
503 Hooks
::run( 'DifferenceEngineMarkPatrolledLink', [ $this,
504 &$this->mMarkPatrolledLink
, $linkInfo['rcid'] ] );
507 return $this->mMarkPatrolledLink
;
511 * Returns an array of meta data needed to build a "mark as patrolled" link and
512 * adds the mediawiki.page.patrol.ajax to the output.
514 * @return array|false An array of meta data for a patrol link (rcid only)
515 * or false if no link is needed
517 protected function getMarkPatrolledLinkInfo() {
518 global $wgUseRCPatrol, $wgEnableAPI, $wgEnableWriteAPI;
520 $user = $this->getUser();
522 // Prepare a change patrol link, if applicable
524 // Is patrolling enabled and the user allowed to?
525 $wgUseRCPatrol && $this->mNewPage
->quickUserCan( 'patrol', $user ) &&
526 // Only do this if the revision isn't more than 6 hours older
527 // than the Max RC age (6h because the RC might not be cleaned out regularly)
528 RecentChange
::isInRCLifespan( $this->mNewRev
->getTimestamp(), 21600 )
530 // Look for an unpatrolled change corresponding to this diff
531 $db = wfGetDB( DB_REPLICA
);
532 $change = RecentChange
::newFromConds(
534 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
535 'rc_this_oldid' => $this->mNewid
,
541 if ( $change && !$change->getPerformer()->equals( $user ) ) {
542 $rcid = $change->getAttribute( 'rc_id' );
544 // None found or the page has been created by the current user.
545 // If the user could patrol this it already would be patrolled
549 // Allow extensions to possibly change the rcid here
550 // For example the rcid might be set to zero due to the user
551 // being the same as the performer of the change but an extension
552 // might still want to show it under certain conditions
553 Hooks
::run( 'DifferenceEngineMarkPatrolledRCID', [ &$rcid, $this, $change, $user ] );
557 $this->getOutput()->preventClickjacking();
558 if ( $wgEnableAPI && $wgEnableWriteAPI
559 && $user->isAllowed( 'writeapi' )
561 $this->getOutput()->addModules( 'mediawiki.page.patrol.ajax' );
570 // No mark as patrolled link applicable
575 * @param Revision $rev
579 protected function revisionDeleteLink( $rev ) {
580 $link = Linker
::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
581 if ( $link !== '' ) {
582 $link = '   ' . $link . ' ';
589 * Show the new revision of the page.
591 public function renderNewRevision() {
592 $out = $this->getOutput();
593 $revHeader = $this->getRevisionHeader( $this->mNewRev
);
594 # Add "current version as of X" title
595 $out->addHTML( "<hr class='diff-hr' id='mw-oldid' />
596 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
597 # Page content may be handled by a hooked call instead...
598 # @codingStandardsIgnoreStart Ignoring long lines.
599 if ( Hooks
::run( 'ArticleContentOnDiff', [ $this, $out ] ) ) {
600 $this->loadNewText();
601 $out->setRevisionId( $this->mNewid
);
602 $out->setRevisionTimestamp( $this->mNewRev
->getTimestamp() );
603 $out->setArticleFlag( true );
605 if ( !Hooks
::run( 'ArticleContentViewCustom', [ $this->mNewContent
, $this->mNewPage
, $out ] ) ) {
606 // Handled by extension
609 if ( $this->getTitle()->equals( $this->mNewPage
) ) {
610 // If the Title stored in the context is the same as the one
611 // of the new revision, we can use its associated WikiPage
613 $wikiPage = $this->getWikiPage();
615 // Otherwise we need to create our own WikiPage object
616 $wikiPage = WikiPage
::factory( $this->mNewPage
);
619 $parserOutput = $this->getParserOutput( $wikiPage, $this->mNewRev
);
621 # WikiPage::getParserOutput() should not return false, but just in case
622 if ( $parserOutput ) {
623 // Allow extensions to change parser output here
624 if ( Hooks
::run( 'DifferenceEngineRenderRevisionAddParserOutput', [ $this, $out, $parserOutput, $wikiPage ] ) ) {
625 $out->addParserOutput( $parserOutput );
630 # @codingStandardsIgnoreEnd
632 // Allow extensions to optionally not show the final patrolled link
633 if ( Hooks
::run( 'DifferenceEngineRenderRevisionShowFinalPatrolLink' ) ) {
634 # Add redundant patrol link on bottom...
635 $out->addHTML( $this->markPatrolledLink() );
639 protected function getParserOutput( WikiPage
$page, Revision
$rev ) {
640 $parserOptions = $page->makeParserOptions( $this->getContext() );
642 if ( !$rev->isCurrent() ||
!$rev->getTitle()->quickUserCan( 'edit', $this->getUser() ) ) {
643 $parserOptions->setEditSection( false );
646 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
648 return $parserOutput;
652 * Get the diff text, send it to the OutputPage object
653 * Returns false if the diff could not be generated, otherwise returns true
655 * @param string|bool $otitle Header for old text or false
656 * @param string|bool $ntitle Header for new text or false
657 * @param string $notice HTML between diff header and body
661 public function showDiff( $otitle, $ntitle, $notice = '' ) {
662 // Allow extensions to affect the output here
663 Hooks
::run( 'DifferenceEngineShowDiff', [ $this ] );
665 $diff = $this->getDiff( $otitle, $ntitle, $notice );
666 if ( $diff === false ) {
667 $this->showMissingRevision();
671 $this->showDiffStyle();
672 $this->getOutput()->addHTML( $diff );
679 * Add style sheets for diff display.
681 public function showDiffStyle() {
682 $this->getOutput()->addModuleStyles( 'mediawiki.diff.styles' );
686 * Get complete diff table, including header
688 * @param string|bool $otitle Header for old text or false
689 * @param string|bool $ntitle Header for new text or false
690 * @param string $notice HTML between diff header and body
694 public function getDiff( $otitle, $ntitle, $notice = '' ) {
695 $body = $this->getDiffBody();
696 if ( $body === false ) {
700 $multi = $this->getMultiNotice();
701 // Display a message when the diff is empty
702 if ( $body === '' ) {
703 $notice .= '<div class="mw-diff-empty">' .
704 $this->msg( 'diff-empty' )->parse() .
708 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
712 * Get the diff table body, without header
714 * @return mixed (string/false)
716 public function getDiffBody() {
717 $this->mCacheHit
= true;
718 // Check if the diff should be hidden from this user
719 if ( !$this->loadRevisionData() ) {
721 } elseif ( $this->mOldRev
&&
722 !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
725 } elseif ( $this->mNewRev
&&
726 !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
731 if ( $this->mOldRev
=== false ||
( $this->mOldRev
&& $this->mNewRev
732 && $this->mOldRev
->getId() == $this->mNewRev
->getId() )
734 if ( Hooks
::run( 'DifferenceEngineShowEmptyOldContent', [ $this ] ) ) {
740 $cache = ObjectCache
::getMainWANInstance();
741 if ( $this->mOldid
&& $this->mNewid
) {
742 $key = $this->getDiffBodyCacheKey();
745 if ( !$this->mRefreshCache
) {
746 $difftext = $cache->get( $key );
748 wfIncrStats( 'diff_cache.hit' );
749 $difftext = $this->localiseLineNumbers( $difftext );
750 $difftext .= "\n<!-- diff cache key $key -->\n";
754 } // don't try to load but save the result
756 $this->mCacheHit
= false;
758 // Loadtext is permission safe, this just clears out the diff
759 if ( !$this->loadText() ) {
763 $difftext = $this->generateContentDiffBody( $this->mOldContent
, $this->mNewContent
);
765 // Avoid PHP 7.1 warning from passing $this by reference
768 // Save to cache for 7 days
769 if ( !Hooks
::run( 'AbortDiffCache', [ &$diffEngine ] ) ) {
770 wfIncrStats( 'diff_cache.uncacheable' );
771 } elseif ( $key !== false && $difftext !== false ) {
772 wfIncrStats( 'diff_cache.miss' );
773 $cache->set( $key, $difftext, 7 * 86400 );
775 wfIncrStats( 'diff_cache.uncacheable' );
777 // Replace line numbers with the text in the user's language
778 if ( $difftext !== false ) {
779 $difftext = $this->localiseLineNumbers( $difftext );
786 * Returns the cache key for diff body text or content.
790 * @throws MWException
793 protected function getDiffBodyCacheKey() {
794 if ( !$this->mOldid ||
!$this->mNewid
) {
795 throw new MWException( 'mOldid and mNewid must be set to get diff cache key.' );
798 return wfMemcKey( 'diff', 'version', self
::DIFF_VERSION
,
799 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
803 * Generate a diff, no caching.
805 * This implementation uses generateTextDiffBody() to generate a diff based on the default
806 * serialization of the given Content objects. This will fail if $old or $new are not
807 * instances of TextContent.
809 * Subclasses may override this to provide a different rendering for the diff,
810 * perhaps taking advantage of the content's native form. This is required for all content
811 * models that are not text based.
815 * @param Content $old Old content
816 * @param Content $new New content
818 * @throws MWException If old or new content is not an instance of TextContent.
819 * @return bool|string
821 public function generateContentDiffBody( Content
$old, Content
$new ) {
822 if ( !( $old instanceof TextContent
) ) {
823 throw new MWException( "Diff not implemented for " . get_class( $old ) . "; " .
824 "override generateContentDiffBody to fix this." );
827 if ( !( $new instanceof TextContent
) ) {
828 throw new MWException( "Diff not implemented for " . get_class( $new ) . "; "
829 . "override generateContentDiffBody to fix this." );
832 $otext = $old->serialize();
833 $ntext = $new->serialize();
835 return $this->generateTextDiffBody( $otext, $ntext );
839 * Generate a diff, no caching
841 * @todo move this to TextDifferenceEngine, make DifferenceEngine abstract. At some point.
843 * @param string $otext Old text, must be already segmented
844 * @param string $ntext New text, must be already segmented
846 * @return bool|string
848 public function generateTextDiffBody( $otext, $ntext ) {
849 $diff = function () use ( $otext, $ntext ) {
850 $time = microtime( true );
852 $result = $this->textDiff( $otext, $ntext );
854 $time = intval( ( microtime( true ) - $time ) * 1000 );
855 MediaWikiServices
::getInstance()->getStatsdDataFactory()->timing( 'diff_time', $time );
856 // Log requests slower than 99th percentile
857 if ( $time > 100 && $this->mOldPage
&& $this->mNewPage
) {
859 "$time ms diff: {$this->mOldid} -> {$this->mNewid} {$this->mNewPage}" );
866 * @param Status $status
869 $error = function ( $status ) {
870 throw new FatalError( $status->getWikiText() );
873 // Use PoolCounter if the diff looks like it can be expensive
874 if ( strlen( $otext ) +
strlen( $ntext ) > 20000 ) {
875 $work = new PoolCounterWorkViaCallback( 'diff',
876 md5( $otext ) . md5( $ntext ),
877 [ 'doWork' => $diff, 'error' => $error ]
879 return $work->execute();
886 * Generates diff, to be wrapped internally in a logging/instrumentation
888 * @param string $otext Old text, must be already segmented
889 * @param string $ntext New text, must be already segmented
890 * @return bool|string
892 protected function textDiff( $otext, $ntext ) {
893 global $wgExternalDiffEngine, $wgContLang;
895 $otext = str_replace( "\r\n", "\n", $otext );
896 $ntext = str_replace( "\r\n", "\n", $ntext );
898 if ( $wgExternalDiffEngine == 'wikidiff' ||
$wgExternalDiffEngine == 'wikidiff3' ) {
899 wfDeprecated( "\$wgExternalDiffEngine = '{$wgExternalDiffEngine}'", '1.27' );
900 $wgExternalDiffEngine = false;
901 } elseif ( $wgExternalDiffEngine == 'wikidiff2' ) {
902 // Same as above, but with no deprecation warnings
903 $wgExternalDiffEngine = false;
904 } elseif ( !is_string( $wgExternalDiffEngine ) && $wgExternalDiffEngine !== false ) {
905 // And prevent people from shooting themselves in the foot...
906 wfWarn( '$wgExternalDiffEngine is set to a non-string value, forcing it to false' );
907 $wgExternalDiffEngine = false;
910 if ( function_exists( 'wikidiff2_do_diff' ) && $wgExternalDiffEngine === false ) {
911 # Better external diff engine, the 2 may some day be dropped
912 # This one does the escaping and segmenting itself
913 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
914 $text .= $this->debug( 'wikidiff2' );
917 } elseif ( $wgExternalDiffEngine !== false && is_executable( $wgExternalDiffEngine ) ) {
919 $tmpDir = wfTempDir();
920 $tempName1 = tempnam( $tmpDir, 'diff_' );
921 $tempName2 = tempnam( $tmpDir, 'diff_' );
923 $tempFile1 = fopen( $tempName1, "w" );
927 $tempFile2 = fopen( $tempName2, "w" );
931 fwrite( $tempFile1, $otext );
932 fwrite( $tempFile2, $ntext );
933 fclose( $tempFile1 );
934 fclose( $tempFile2 );
935 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
936 $difftext = wfShellExec( $cmd );
937 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
938 unlink( $tempName1 );
939 unlink( $tempName2 );
945 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
946 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
947 $diffs = new Diff( $ota, $nta );
948 $formatter = new TableDiffFormatter();
949 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) );
955 * Generate a debug comment indicating diff generating time,
956 * server node, and generator backend.
958 * @param string $generator : What diff engine was used
962 protected function debug( $generator = "internal" ) {
963 global $wgShowHostnames;
964 if ( !$this->enableDebugComment
) {
967 $data = [ $generator ];
968 if ( $wgShowHostnames ) {
969 $data[] = wfHostname();
971 $data[] = wfTimestamp( TS_DB
);
973 return "<!-- diff generator: " .
974 implode( " ", array_map( "htmlspecialchars", $data ) ) .
979 * Replace line numbers with the text in the user's language
981 * @param string $text
985 public function localiseLineNumbers( $text ) {
986 return preg_replace_callback(
987 '/<!--LINE (\d+)-->/',
988 [ $this, 'localiseLineNumbersCb' ],
993 public function localiseLineNumbersCb( $matches ) {
994 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) {
998 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
1002 * If there are revisions between the ones being compared, return a note saying so.
1006 public function getMultiNotice() {
1007 if ( !is_object( $this->mOldRev
) ||
!is_object( $this->mNewRev
) ) {
1009 } elseif ( !$this->mOldPage
->equals( $this->mNewPage
) ) {
1010 // Comparing two different pages? Count would be meaningless.
1014 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
1015 $oldRev = $this->mNewRev
; // flip
1016 $newRev = $this->mOldRev
; // flip
1017 } else { // normal case
1018 $oldRev = $this->mOldRev
;
1019 $newRev = $this->mNewRev
;
1022 // Sanity: don't show the notice if too many rows must be scanned
1023 // @todo show some special message for that case
1024 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev, 1000 );
1025 if ( $nEdits > 0 && $nEdits <= 1000 ) {
1026 $limit = 100; // use diff-multi-manyusers if too many users
1027 $users = $this->mNewPage
->getAuthorsBetween( $oldRev, $newRev, $limit );
1028 $numUsers = count( $users );
1030 if ( $numUsers == 1 && $users[0] == $newRev->getUserText( Revision
::RAW
) ) {
1031 $numUsers = 0; // special case to say "by the same user" instead of "by one other user"
1034 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
1037 return ''; // nothing
1041 * Get a notice about how many intermediate edits and users there are
1043 * @param int $numEdits
1044 * @param int $numUsers
1049 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
1050 if ( $numUsers === 0 ) {
1051 $msg = 'diff-multi-sameuser';
1052 } elseif ( $numUsers > $limit ) {
1053 $msg = 'diff-multi-manyusers';
1056 $msg = 'diff-multi-otherusers';
1059 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
1063 * Get a header for a specified revision.
1065 * @param Revision $rev
1066 * @param string $complete 'complete' to get the header wrapped depending
1067 * the visibility of the revision and a link to edit the page.
1069 * @return string HTML fragment
1071 public function getRevisionHeader( Revision
$rev, $complete = '' ) {
1072 $lang = $this->getLanguage();
1073 $user = $this->getUser();
1074 $revtimestamp = $rev->getTimestamp();
1075 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
1076 $dateofrev = $lang->userDate( $revtimestamp, $user );
1077 $timeofrev = $lang->userTime( $revtimestamp, $user );
1079 $header = $this->msg(
1080 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
1086 if ( $complete !== 'complete' ) {
1090 $title = $rev->getTitle();
1092 $header = Linker
::linkKnown( $title, $header, [],
1093 [ 'oldid' => $rev->getId() ] );
1095 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
1096 $editQuery = [ 'action' => 'edit' ];
1097 if ( !$rev->isCurrent() ) {
1098 $editQuery['oldid'] = $rev->getId();
1101 $key = $title->quickUserCan( 'edit', $user ) ?
'editold' : 'viewsourceold';
1102 $msg = $this->msg( $key )->escaped();
1103 $editLink = $this->msg( 'parentheses' )->rawParams(
1104 Linker
::linkKnown( $title, $msg, [], $editQuery ) )->escaped();
1105 $header .= ' ' . Html
::rawElement(
1107 [ 'class' => 'mw-diff-edit' ],
1110 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
1111 $header = Html
::rawElement(
1113 [ 'class' => 'history-deleted' ],
1118 $header = Html
::rawElement( 'span', [ 'class' => 'history-deleted' ], $header );
1125 * Add the header to a diff body
1127 * @param string $diff Diff body
1128 * @param string $otitle Old revision header
1129 * @param string $ntitle New revision header
1130 * @param string $multi Notice telling user that there are intermediate
1131 * revisions between the ones being compared
1132 * @param string $notice Other notices, e.g. that user is viewing deleted content
1136 public function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
1137 // shared.css sets diff in interface language/dir, but the actual content
1138 // is often in a different language, mostly the page content language/dir
1139 $header = Html
::openElement( 'table', [
1140 'class' => [ 'diff', 'diff-contentalign-' . $this->getDiffLang()->alignStart() ],
1141 'data-mw' => 'interface',
1143 $userLang = htmlspecialchars( $this->getLanguage()->getHtmlCode() );
1145 if ( !$diff && !$otitle ) {
1147 <tr style='vertical-align: top;' lang='{$userLang}'>
1148 <td class='diff-ntitle'>{$ntitle}</td>
1152 if ( $diff ) { // Safari/Chrome show broken output if cols not used
1154 <col class='diff-marker' />
1155 <col class='diff-content' />
1156 <col class='diff-marker' />
1157 <col class='diff-content' />";
1164 if ( $otitle ||
$ntitle ) {
1166 <tr style='vertical-align: top;' lang='{$userLang}'>
1167 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
1168 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
1173 if ( $multi != '' ) {
1174 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;' " .
1175 "class='diff-multi' lang='{$userLang}'>{$multi}</td></tr>";
1177 if ( $notice != '' ) {
1178 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;' " .
1179 "lang='{$userLang}'>{$notice}</td></tr>";
1182 return $header . $diff . "</table>";
1186 * Use specified text instead of loading from the database
1187 * @param Content $oldContent
1188 * @param Content $newContent
1191 public function setContent( Content
$oldContent, Content
$newContent ) {
1192 $this->mOldContent
= $oldContent;
1193 $this->mNewContent
= $newContent;
1195 $this->mTextLoaded
= 2;
1196 $this->mRevisionsLoaded
= true;
1200 * Set the language in which the diff text is written
1201 * (Defaults to page content language).
1202 * @param Language|string $lang
1205 public function setTextLanguage( $lang ) {
1206 $this->mDiffLang
= wfGetLangObj( $lang );
1210 * Maps a revision pair definition as accepted by DifferenceEngine constructor
1211 * to a pair of actual integers representing revision ids.
1213 * @param int $old Revision id, e.g. from URL parameter 'oldid'
1214 * @param int|string $new Revision id or strings 'next' or 'prev', e.g. from URL parameter 'diff'
1216 * @return int[] List of two revision ids, older first, later second.
1217 * Zero signifies invalid argument passed.
1218 * false signifies that there is no previous/next revision ($old is the oldest/newest one).
1220 public function mapDiffPrevNext( $old, $new ) {
1221 if ( $new === 'prev' ) {
1222 // Show diff between revision $old and the previous one. Get previous one from DB.
1223 $newid = intval( $old );
1224 $oldid = $this->getTitle()->getPreviousRevisionID( $newid );
1225 } elseif ( $new === 'next' ) {
1226 // Show diff between revision $old and the next one. Get next one from DB.
1227 $oldid = intval( $old );
1228 $newid = $this->getTitle()->getNextRevisionID( $oldid );
1230 $oldid = intval( $old );
1231 $newid = intval( $new );
1234 return [ $oldid, $newid ];
1240 private function loadRevisionIds() {
1241 if ( $this->mRevisionsIdsLoaded
) {
1245 $this->mRevisionsIdsLoaded
= true;
1247 $old = $this->mOldid
;
1248 $new = $this->mNewid
;
1250 list( $this->mOldid
, $this->mNewid
) = self
::mapDiffPrevNext( $old, $new );
1251 if ( $new === 'next' && $this->mNewid
=== false ) {
1252 # if no result, NewId points to the newest old revision. The only newer
1253 # revision is cur, which is "0".
1258 'NewDifferenceEngine',
1259 [ $this->getTitle(), &$this->mOldid
, &$this->mNewid
, $old, $new ]
1264 * Load revision metadata for the specified articles. If newid is 0, then compare
1265 * the old article in oldid to the current article; if oldid is 0, then
1266 * compare the current article to the immediately previous one (ignoring the
1269 * If oldid is false, leave the corresponding revision object set
1270 * to false. This is impossible via ordinary user input, and is provided for
1275 public function loadRevisionData() {
1276 if ( $this->mRevisionsLoaded
) {
1280 // Whether it succeeds or fails, we don't want to try again
1281 $this->mRevisionsLoaded
= true;
1283 $this->loadRevisionIds();
1285 // Load the new revision object
1286 if ( $this->mNewid
) {
1287 $this->mNewRev
= Revision
::newFromId( $this->mNewid
);
1289 $this->mNewRev
= Revision
::newFromTitle(
1292 Revision
::READ_NORMAL
1296 if ( !$this->mNewRev
instanceof Revision
) {
1300 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1301 $this->mNewid
= $this->mNewRev
->getId();
1302 $this->mNewPage
= $this->mNewRev
->getTitle();
1304 // Load the old revision object
1305 $this->mOldRev
= false;
1306 if ( $this->mOldid
) {
1307 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1308 } elseif ( $this->mOldid
=== 0 ) {
1309 $rev = $this->mNewRev
->getPrevious();
1311 $this->mOldid
= $rev->getId();
1312 $this->mOldRev
= $rev;
1314 // No previous revision; mark to show as first-version only.
1315 $this->mOldid
= false;
1316 $this->mOldRev
= false;
1318 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1320 if ( is_null( $this->mOldRev
) ) {
1324 if ( $this->mOldRev
) {
1325 $this->mOldPage
= $this->mOldRev
->getTitle();
1328 // Load tags information for both revisions
1329 $dbr = wfGetDB( DB_REPLICA
);
1330 if ( $this->mOldid
!== false ) {
1331 $this->mOldTags
= $dbr->selectField(
1334 [ 'ts_rev_id' => $this->mOldid
],
1338 $this->mOldTags
= false;
1340 $this->mNewTags
= $dbr->selectField(
1343 [ 'ts_rev_id' => $this->mNewid
],
1351 * Load the text of the revisions, as well as revision data.
1355 public function loadText() {
1356 if ( $this->mTextLoaded
== 2 ) {
1360 // Whether it succeeds or fails, we don't want to try again
1361 $this->mTextLoaded
= 2;
1363 if ( !$this->loadRevisionData() ) {
1367 if ( $this->mOldRev
) {
1368 $this->mOldContent
= $this->mOldRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1369 if ( $this->mOldContent
=== null ) {
1374 if ( $this->mNewRev
) {
1375 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1376 Hooks
::run( 'DifferenceEngineLoadTextAfterNewContentIsLoaded', [ $this ] );
1377 if ( $this->mNewContent
=== null ) {
1386 * Load the text of the new revision, not the old one
1390 public function loadNewText() {
1391 if ( $this->mTextLoaded
>= 1 ) {
1395 $this->mTextLoaded
= 1;
1397 if ( !$this->loadRevisionData() ) {
1401 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1403 Hooks
::run( 'DifferenceEngineAfterLoadNewText', [ $this ] );