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
24 use MediaWiki\MediaWikiServices
;
25 use MediaWiki\Permissions\PermissionManager
;
26 use MediaWiki\Revision\RevisionRecord
;
27 use MediaWiki\Revision\SlotRecord
;
28 use MediaWiki\Storage\NameTableAccessException
;
31 * DifferenceEngine is responsible for rendering the difference between two revisions as HTML.
32 * This includes interpreting URL parameters, retrieving revision data, checking access permissions,
33 * selecting and invoking the diff generator class for the individual slots, doing post-processing
34 * on the generated diff, adding the rest of the HTML (such as headers) and writing the whole thing
37 * DifferenceEngine can be subclassed by extensions, by customizing
38 * ContentHandler::createDifferenceEngine; the content handler will be selected based on the
39 * content model of the main slot (of the new revision, when the two are different).
40 * That might change after PageTypeHandler gets introduced.
42 * In the past, the class was also used for slot-level diff generation, and extensions might still
43 * subclass it and add such functionality. When that is the case (sepcifically, when a
44 * ContentHandler returns a standard SlotDiffRenderer but a nonstandard DifferenceEngine)
45 * DifferenceEngineSlotDiffRenderer will be used to convert the old behavior into the new one.
47 * @ingroup DifferenceEngine
49 * @todo This class is huge and poorly defined. It should be split into a controller responsible
50 * for interpreting query parameters, retrieving data and checking permissions; and a HTML renderer.
52 class DifferenceEngine
extends ContextSource
{
54 use DeprecationHelper
;
57 * Constant to indicate diff cache compatibility.
58 * Bump this when changing the diff formatting in a way that
59 * fixes important bugs or such to force cached diff views to
62 const DIFF_VERSION
= '1.12';
65 * Revision ID for the old revision. 0 for the revision previous to $mNewid, false
66 * if the diff does not have an old revision (e.g. 'oldid=<first revision of page>&diff=prev'),
67 * or the revision does not exist, null if the revision is unsaved.
73 * Revision ID for the new revision. 0 for the last revision of the current page
74 * (as defined by the request context), false if the revision does not exist, null
75 * if it is unsaved, or an alias such as 'next'.
76 * @var int|string|false|null
81 * Old revision (left pane).
82 * Allowed to be an unsaved revision, unlikely that's ever needed though.
83 * False when the old revision does not exist; this can happen when using
84 * diff=prev on the first revision. Null when the revision should exist but
85 * doesn't (e.g. load failure); loadRevisionData() will return false in that
86 * case. Also null until lazy-loaded. Ignored completely when isContentOverridden
88 * Since 1.32 public access is deprecated.
89 * @var Revision|null|false
94 * New revision (right pane).
95 * Note that this might be an unsaved revision (e.g. for edit preview).
96 * Null in case of load failure; diff methods will just return an error message in that case,
97 * and loadRevisionData() will return false. Also null until lazy-loaded. Ignored completely
98 * when isContentOverridden is set.
99 * Since 1.32 public access is deprecated.
105 * Title of $mOldRev or null if the old revision does not exist or does not belong to a page.
106 * Since 1.32 public access is deprecated and the property can be null.
112 * Title of $mNewRev or null if the new revision does not exist or does not belong to a page.
113 * Since 1.32 public access is deprecated and the property can be null.
119 * Change tags of $mOldRev or null if it does not exist / is not saved.
125 * Change tags of $mNewRev or null if it does not exist / is not saved.
132 * @deprecated since 1.32, content slots are now handled by the corresponding SlotDiffRenderer.
133 * This property is set to the content of the main slot, but not actually used for the main diff.
135 private $mOldContent;
139 * @deprecated since 1.32, content slots are now handled by the corresponding SlotDiffRenderer.
140 * This property is set to the content of the main slot, but not actually used for the main diff.
142 private $mNewContent;
145 protected $mDiffLang;
147 /** @var bool Have the revisions IDs been loaded */
148 private $mRevisionsIdsLoaded = false;
150 /** @var bool Have the revisions been loaded */
151 protected $mRevisionsLoaded = false;
153 /** @var int How many text blobs have been loaded, 0, 1 or 2? */
154 protected $mTextLoaded = 0;
157 * Was the content overridden via setContent()?
158 * If the content was overridden, most internal state (e.g. mOldid or mOldRev) should be ignored
159 * and only mOldContent and mNewContent is reliable.
160 * (Note that setRevisions() does not set this flag as in that case all properties are
161 * overriden and remain consistent with each other, so no special handling is needed.)
164 protected $isContentOverridden = false;
166 /** @var bool Was the diff fetched from cache? */
167 protected $mCacheHit = false;
170 * Set this to true to add debug info to the HTML output.
171 * Warning: this may cause RSS readers to spuriously mark articles as "new"
174 public $enableDebugComment = false;
176 /** @var bool If true, line X is not displayed when X is 1, for example
177 * to increase readability and conserve space with many small diffs.
179 protected $mReducedLineNumbers = false;
181 /** @var string Link to action=markpatrolled */
182 protected $mMarkPatrolledLink = null;
184 /** @var bool Show rev_deleted content if allowed */
185 protected $unhide = false;
187 /** @var bool Refresh the diff cache */
188 protected $mRefreshCache = false;
190 /** @var SlotDiffRenderer[] DifferenceEngine classes for the slots, keyed by role name. */
191 protected $slotDiffRenderers = null;
194 * Temporary hack for B/C while slot diff related methods of DifferenceEngine are being
195 * deprecated. When true, we are inside a DifferenceEngineSlotDiffRenderer and
196 * $slotDiffRenderers should not be used.
199 protected $isSlotDiffRenderer = false;
204 * @param IContextSource|null $context Context to use, anything else will be ignored
205 * @param int $old Old ID we want to show and diff with.
206 * @param string|int $new Either revision ID or 'prev' or 'next'. Default: 0.
207 * @param int $rcid Deprecated, no longer used!
208 * @param bool $refreshCache If set, refreshes the diff cache
209 * @param bool $unhide If set, allow viewing deleted revs
211 public function __construct( $context = null, $old = 0, $new = 0, $rcid = 0,
212 $refreshCache = false, $unhide = false
214 $this->deprecatePublicProperty( 'mOldid', '1.32', __CLASS__
);
215 $this->deprecatePublicProperty( 'mNewid', '1.32', __CLASS__
);
216 $this->deprecatePublicProperty( 'mOldRev', '1.32', __CLASS__
);
217 $this->deprecatePublicProperty( 'mNewRev', '1.32', __CLASS__
);
218 $this->deprecatePublicProperty( 'mOldPage', '1.32', __CLASS__
);
219 $this->deprecatePublicProperty( 'mNewPage', '1.32', __CLASS__
);
220 $this->deprecatePublicProperty( 'mOldContent', '1.32', __CLASS__
);
221 $this->deprecatePublicProperty( 'mNewContent', '1.32', __CLASS__
);
222 $this->deprecatePublicProperty( 'mRevisionsLoaded', '1.32', __CLASS__
);
223 $this->deprecatePublicProperty( 'mTextLoaded', '1.32', __CLASS__
);
224 $this->deprecatePublicProperty( 'mCacheHit', '1.32', __CLASS__
);
226 if ( $context instanceof IContextSource
) {
227 $this->setContext( $context );
230 wfDebug( "DifferenceEngine old '$old' new '$new' rcid '$rcid'\n" );
232 $this->mOldid
= $old;
233 $this->mNewid
= $new;
234 $this->mRefreshCache
= $refreshCache;
235 $this->unhide
= $unhide;
239 * @return SlotDiffRenderer[] Diff renderers for each slot, keyed by role name.
240 * Includes slots only present in one of the revisions.
242 protected function getSlotDiffRenderers() {
243 if ( $this->isSlotDiffRenderer
) {
244 throw new LogicException( __METHOD__
. ' called in slot diff renderer mode' );
247 if ( $this->slotDiffRenderers
=== null ) {
248 if ( !$this->loadRevisionData() ) {
252 $slotContents = $this->getSlotContents();
253 $this->slotDiffRenderers
= array_map( function ( $contents ) {
254 /** @var Content $content */
255 $content = $contents['new'] ?
: $contents['old'];
256 return $content->getContentHandler()->getSlotDiffRenderer( $this->getContext() );
259 return $this->slotDiffRenderers
;
263 * Mark this DifferenceEngine as a slot renderer (as opposed to a page renderer).
264 * This is used in legacy mode when the DifferenceEngine is wrapped in a
265 * DifferenceEngineSlotDiffRenderer.
266 * @internal For use by DifferenceEngineSlotDiffRenderer only.
268 public function markAsSlotDiffRenderer() {
269 $this->isSlotDiffRenderer
= true;
273 * Get the old and new content objects for all slots.
274 * This method does not do any permission checks.
275 * @return array [ role => [ 'old' => SlotRecord|null, 'new' => SlotRecord|null ], ... ]
277 protected function getSlotContents() {
278 if ( $this->isContentOverridden
) {
280 SlotRecord
::MAIN
=> [
281 'old' => $this->mOldContent
,
282 'new' => $this->mNewContent
,
285 } elseif ( !$this->loadRevisionData() ) {
289 $newSlots = $this->mNewRev
->getRevisionRecord()->getSlots()->getSlots();
290 if ( $this->mOldRev
) {
291 $oldSlots = $this->mOldRev
->getRevisionRecord()->getSlots()->getSlots();
295 // The order here will determine the visual order of the diff. The current logic is
296 // slots of the new revision first in natural order, then deleted ones. This is ad hoc
297 // and should not be relied on - in the future we may want the ordering to depend
299 $roles = array_merge( array_keys( $newSlots ), array_keys( $oldSlots ) );
302 foreach ( $roles as $role ) {
304 'old' => isset( $oldSlots[$role] ) ?
$oldSlots[$role]->getContent() : null,
305 'new' => isset( $newSlots[$role] ) ?
$newSlots[$role]->getContent() : null,
308 // move main slot to front
309 if ( isset( $slots[SlotRecord
::MAIN
] ) ) {
310 $slots = [ SlotRecord
::MAIN
=> $slots[SlotRecord
::MAIN
] ] +
$slots;
315 public function getTitle() {
316 // T202454 avoid errors when there is no title
317 return parent
::getTitle() ?
: Title
::makeTitle( NS_SPECIAL
, 'BadTitle/DifferenceEngine' );
321 * Set reduced line numbers mode.
322 * When set, line X is not displayed when X is 1, for example to increase readability and
323 * conserve space with many small diffs.
326 public function setReducedLineNumbers( $value = true ) {
327 $this->mReducedLineNumbers
= $value;
331 * Get the language of the difference engine, defaults to page content language
335 public function getDiffLang() {
336 if ( $this->mDiffLang
=== null ) {
337 # Default language in which the diff text is written.
338 $this->mDiffLang
= $this->getTitle()->getPageLanguage();
341 return $this->mDiffLang
;
347 public function wasCacheHit() {
348 return $this->mCacheHit
;
352 * Get the ID of old revision (left pane) of the diff. 0 for the revision
353 * previous to getNewid(), false if the old revision does not exist, null
355 * To get a real revision ID instead of 0, call loadRevisionData() first.
356 * @return int|false|null
358 public function getOldid() {
359 $this->loadRevisionIds();
361 return $this->mOldid
;
365 * Get the ID of new revision (right pane) of the diff. 0 for the current revision,
366 * false if the new revision does not exist, null if it's unsaved.
367 * To get a real revision ID instead of 0, call loadRevisionData() first.
368 * @return int|false|null
370 public function getNewid() {
371 $this->loadRevisionIds();
373 return $this->mNewid
;
377 * Get the left side of the diff.
378 * Could be null when the first revision of the page is diffed to 'prev' (or in the case of
380 * @return RevisionRecord|null
382 public function getOldRevision() {
383 return $this->mOldRev ?
$this->mOldRev
->getRevisionRecord() : null;
387 * Get the right side of the diff.
388 * Should not be null but can still happen in the case of load failure.
389 * @return RevisionRecord|null
391 public function getNewRevision() {
392 return $this->mNewRev ?
$this->mNewRev
->getRevisionRecord() : null;
396 * Look up a special:Undelete link to the given deleted revision id,
397 * as a workaround for being unable to load deleted diffs in currently.
399 * @param int $id Revision ID
401 * @return string|bool Link HTML or false
403 public function deletedLink( $id ) {
404 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
405 $dbr = wfGetDB( DB_REPLICA
);
406 $arQuery = Revision
::getArchiveQueryInfo();
407 $row = $dbr->selectRow(
409 array_merge( $arQuery['fields'], [ 'ar_namespace', 'ar_title' ] ),
410 [ 'ar_rev_id' => $id ],
416 $rev = Revision
::newFromArchiveRow( $row );
417 $title = Title
::makeTitleSafe( $row->ar_namespace
, $row->ar_title
);
419 return SpecialPage
::getTitleFor( 'Undelete' )->getFullURL( [
420 'target' => $title->getPrefixedText(),
421 'timestamp' => $rev->getTimestamp()
430 * Build a wikitext link toward a deleted revision, if viewable.
432 * @param int $id Revision ID
434 * @return string Wikitext fragment
436 public function deletedIdMarker( $id ) {
437 $link = $this->deletedLink( $id );
439 return "[$link $id]";
445 private function showMissingRevision() {
446 $out = $this->getOutput();
449 if ( $this->mOldRev
=== null ||
450 ( $this->mOldRev
&& $this->mOldContent
=== null )
452 $missing[] = $this->deletedIdMarker( $this->mOldid
);
454 if ( $this->mNewRev
=== null ||
455 ( $this->mNewRev
&& $this->mNewContent
=== null )
457 $missing[] = $this->deletedIdMarker( $this->mNewid
);
460 $out->setPageTitle( $this->msg( 'errorpagetitle' ) );
461 $msg = $this->msg( 'difference-missing-revision' )
462 ->params( $this->getLanguage()->listToText( $missing ) )
463 ->numParams( count( $missing ) )
465 $out->addHTML( $msg );
468 public function showDiffPage( $diffOnly = false ) {
469 # Allow frames except in certain special cases
470 $out = $this->getOutput();
471 $out->allowClickjacking();
472 $out->setRobotPolicy( 'noindex,nofollow' );
474 // Allow extensions to add any extra output here
475 Hooks
::run( 'DifferenceEngineShowDiffPage', [ $out ] );
477 if ( !$this->loadRevisionData() ) {
478 if ( Hooks
::run( 'DifferenceEngineShowDiffPageMaybeShowMissingRevision', [ $this ] ) ) {
479 $this->showMissingRevision();
484 $user = $this->getUser();
486 if ( $this->mNewPage
) {
487 $permErrors = $this->mNewPage
->getUserPermissionsErrors( 'read', $user );
489 if ( $this->mOldPage
) {
490 $permErrors = wfMergeErrorArrays( $permErrors,
491 $this->mOldPage
->getUserPermissionsErrors( 'read', $user ) );
493 if ( count( $permErrors ) ) {
494 throw new PermissionsError( 'read', $permErrors );
500 # Carry over 'diffonly' param via navigation links
501 if ( $diffOnly != $user->getBoolOption( 'diffonly' ) ) {
502 $query['diffonly'] = $diffOnly;
504 # Cascade unhide param in links for easy deletion browsing
505 if ( $this->unhide
) {
506 $query['unhide'] = 1;
509 # Check if one of the revisions is deleted/suppressed
510 $deleted = $suppressed = false;
511 $allowed = $this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $user );
515 # mOldRev is false if the difference engine is called with a "vague" query for
516 # a diff between a version V and its previous version V' AND the version V
517 # is the first version of that article. In that case, V' does not exist.
518 if ( $this->mOldRev
=== false ) {
519 if ( $this->mNewPage
) {
520 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
524 // Allow extensions to change the $oldHeader variable
525 Hooks
::run( 'DifferenceEngineOldHeaderNoOldRev', [ &$oldHeader ] );
527 Hooks
::run( 'DiffViewHeader', [ $this, $this->mOldRev
, $this->mNewRev
] );
529 if ( !$this->mOldPage ||
!$this->mNewPage
) {
530 // XXX say something to the user?
532 } elseif ( $this->mNewPage
->equals( $this->mOldPage
) ) {
533 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
536 $out->setPageTitle( $this->msg( 'difference-title-multipage',
537 $this->mOldPage
->getPrefixedText(), $this->mNewPage
->getPrefixedText() ) );
538 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
542 $permissionManager = MediaWikiServices
::getInstance()->getPermissionManager();
544 if ( $samePage && $this->mNewPage
&& $permissionManager->userCan(
545 'edit', $user, $this->mNewPage
, PermissionManager
::RIGOR_QUICK
547 if ( $this->mNewRev
->isCurrent() && $permissionManager->userCan(
548 'rollback', $user, $this->mNewPage
550 $rollbackLink = Linker
::generateRollback( $this->mNewRev
, $this->getContext() );
551 if ( $rollbackLink ) {
552 $out->preventClickjacking();
553 $rollback = "\u{00A0}\u{00A0}\u{00A0}" . $rollbackLink;
557 if ( !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) &&
558 !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
)
560 $undoLink = Html
::element( 'a', [
561 'href' => $this->mNewPage
->getLocalURL( [
563 'undoafter' => $this->mOldid
,
564 'undo' => $this->mNewid
566 'title' => Linker
::titleAttrib( 'undo' ),
568 $this->msg( 'editundo' )->text()
570 $revisionTools['mw-diff-undo'] = $undoLink;
574 # Make "previous revision link"
575 if ( $samePage && $this->mOldPage
&& $this->mOldRev
->getPrevious() ) {
576 $prevlink = Linker
::linkKnown(
578 $this->msg( 'previousdiff' )->escaped(),
579 [ 'id' => 'differences-prevlink' ],
580 [ 'diff' => 'prev', 'oldid' => $this->mOldid
] +
$query
583 $prevlink = "\u{00A0}";
586 if ( $this->mOldRev
->isMinor() ) {
587 $oldminor = ChangesList
::flag( 'minor' );
592 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
593 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev
, 'complete' );
594 $oldChangeTags = ChangeTags
::formatSummaryRow( $this->mOldTags
, 'diff', $this->getContext() );
596 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
597 '<div id="mw-diff-otitle2">' .
598 Linker
::revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
599 '<div id="mw-diff-otitle3">' . $oldminor .
600 Linker
::revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
601 '<div id="mw-diff-otitle5">' . $oldChangeTags[0] . '</div>' .
602 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
604 // Allow extensions to change the $oldHeader variable
605 Hooks
::run( 'DifferenceEngineOldHeader', [ $this, &$oldHeader, $prevlink, $oldminor,
606 $diffOnly, $ldel, $this->unhide
] );
608 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
609 $deleted = true; // old revisions text is hidden
610 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
611 $suppressed = true; // also suppressed
615 # Check if this user can see the revisions
616 if ( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $user ) ) {
621 $out->addJsConfigVars( [
622 'wgDiffOldId' => $this->mOldid
,
623 'wgDiffNewId' => $this->mNewid
,
626 # Make "next revision link"
627 # Skip next link on the top revision
628 if ( $samePage && $this->mNewPage
&& !$this->mNewRev
->isCurrent() ) {
629 $nextlink = Linker
::linkKnown(
631 $this->msg( 'nextdiff' )->escaped(),
632 [ 'id' => 'differences-nextlink' ],
633 [ 'diff' => 'next', 'oldid' => $this->mNewid
] +
$query
636 $nextlink = "\u{00A0}";
639 if ( $this->mNewRev
->isMinor() ) {
640 $newminor = ChangesList
::flag( 'minor' );
645 # Handle RevisionDelete links...
646 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
648 # Allow extensions to define their own revision tools
649 Hooks
::run( 'DiffRevisionTools',
650 [ $this->mNewRev
, &$revisionTools, $this->mOldRev
, $user ] );
651 $formattedRevisionTools = [];
652 // Put each one in parentheses (poor man's button)
653 foreach ( $revisionTools as $key => $tool ) {
654 $toolClass = is_string( $key ) ?
$key : 'mw-diff-tool';
655 $element = Html
::rawElement(
657 [ 'class' => $toolClass ],
658 $this->msg( 'parentheses' )->rawParams( $tool )->escaped()
660 $formattedRevisionTools[] = $element;
662 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev
, 'complete' ) .
663 ' ' . implode( ' ', $formattedRevisionTools );
664 $newChangeTags = ChangeTags
::formatSummaryRow( $this->mNewTags
, 'diff', $this->getContext() );
666 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
667 '<div id="mw-diff-ntitle2">' . Linker
::revUserTools( $this->mNewRev
, !$this->unhide
) .
669 '<div id="mw-diff-ntitle3">' . $newminor .
670 Linker
::revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
671 '<div id="mw-diff-ntitle5">' . $newChangeTags[0] . '</div>' .
672 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
674 // Allow extensions to change the $newHeader variable
675 Hooks
::run( 'DifferenceEngineNewHeader', [ $this, &$newHeader, $formattedRevisionTools,
676 $nextlink, $rollback, $newminor, $diffOnly, $rdel, $this->unhide
] );
678 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
679 $deleted = true; // new revisions text is hidden
680 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
681 $suppressed = true; // also suppressed
685 # If the diff cannot be shown due to a deleted revision, then output
686 # the diff header and links to unhide (if available)...
687 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
688 $this->showDiffStyle();
689 $multi = $this->getMultiNotice();
690 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
692 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
693 # Give explanation for why revision is not visible
694 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
697 # Give explanation and add a link to view the diff...
698 $query = $this->getRequest()->appendQueryValue( 'unhide', '1' );
699 $link = $this->getTitle()->getFullURL( $query );
700 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
702 "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
706 # Otherwise, output a regular diff...
708 # Add deletion notice if the user is viewing deleted content
711 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
712 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" .
713 $this->msg( $msg )->parse() .
716 $this->showDiff( $oldHeader, $newHeader, $notice );
718 $this->renderNewRevision();
724 * Build a link to mark a change as patrolled.
726 * Returns empty string if there's either no revision to patrol or the user is not allowed to.
727 * Side effect: When the patrol link is build, this method will call
728 * OutputPage::preventClickjacking() and load mediawiki.page.patrol.ajax.
730 * @return string HTML or empty string
732 public function markPatrolledLink() {
733 if ( $this->mMarkPatrolledLink
=== null ) {
734 $linkInfo = $this->getMarkPatrolledLinkInfo();
735 // If false, there is no patrol link needed/allowed
736 if ( !$linkInfo ||
!$this->mNewPage
) {
737 $this->mMarkPatrolledLink
= '';
739 $this->mMarkPatrolledLink
= ' <span class="patrollink" data-mw="interface">[' .
742 $this->msg( 'markaspatrolleddiff' )->escaped(),
745 'action' => 'markpatrolled',
746 'rcid' => $linkInfo['rcid'],
749 // Allow extensions to change the markpatrolled link
750 Hooks
::run( 'DifferenceEngineMarkPatrolledLink', [ $this,
751 &$this->mMarkPatrolledLink
, $linkInfo['rcid'] ] );
754 return $this->mMarkPatrolledLink
;
758 * Returns an array of meta data needed to build a "mark as patrolled" link and
759 * adds the mediawiki.page.patrol.ajax to the output.
761 * @return array|false An array of meta data for a patrol link (rcid only)
762 * or false if no link is needed
764 protected function getMarkPatrolledLinkInfo() {
765 $user = $this->getUser();
766 $config = $this->getConfig();
768 // Prepare a change patrol link, if applicable
770 // Is patrolling enabled and the user allowed to?
771 $config->get( 'UseRCPatrol' ) &&
772 $this->mNewPage
&& $this->mNewPage
->quickUserCan( 'patrol', $user ) &&
773 // Only do this if the revision isn't more than 6 hours older
774 // than the Max RC age (6h because the RC might not be cleaned out regularly)
775 RecentChange
::isInRCLifespan( $this->mNewRev
->getTimestamp(), 21600 )
777 // Look for an unpatrolled change corresponding to this diff
778 $db = wfGetDB( DB_REPLICA
);
779 $change = RecentChange
::newFromConds(
781 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
782 'rc_this_oldid' => $this->mNewid
,
783 'rc_patrolled' => RecentChange
::PRC_UNPATROLLED
788 if ( $change && !$change->getPerformer()->equals( $user ) ) {
789 $rcid = $change->getAttribute( 'rc_id' );
791 // None found or the page has been created by the current user.
792 // If the user could patrol this it already would be patrolled
796 // Allow extensions to possibly change the rcid here
797 // For example the rcid might be set to zero due to the user
798 // being the same as the performer of the change but an extension
799 // might still want to show it under certain conditions
800 Hooks
::run( 'DifferenceEngineMarkPatrolledRCID', [ &$rcid, $this, $change, $user ] );
804 $this->getOutput()->preventClickjacking();
805 if ( $user->isAllowed( 'writeapi' ) ) {
806 $this->getOutput()->addModules( 'mediawiki.page.patrol.ajax' );
815 // No mark as patrolled link applicable
820 * @param Revision $rev
824 protected function revisionDeleteLink( $rev ) {
825 $link = Linker
::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
826 if ( $link !== '' ) {
827 $link = "\u{00A0}\u{00A0}\u{00A0}" . $link . ' ';
834 * Show the new revision of the page.
836 * @note Not supported after calling setContent().
838 public function renderNewRevision() {
839 if ( $this->isContentOverridden
) {
840 // The code below only works with a Revision object. We could construct a fake revision
841 // (here or in setContent), but since this does not seem needed at the moment,
842 // we'll just fail for now.
843 throw new LogicException(
845 . ' is not supported after calling setContent(). Use setRevisions() instead.'
849 $out = $this->getOutput();
850 $revHeader = $this->getRevisionHeader( $this->mNewRev
);
851 # Add "current version as of X" title
852 $out->addHTML( "<hr class='diff-hr' id='mw-oldid' />
853 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
854 # Page content may be handled by a hooked call instead...
855 if ( Hooks
::run( 'ArticleContentOnDiff', [ $this, $out ] ) ) {
856 $this->loadNewText();
857 if ( !$this->mNewPage
) {
858 // New revision is unsaved; bail out.
859 // TODO in theory rendering the new revision is a meaningful thing to do
860 // even if it's unsaved, but a lot of untangling is required to do it safely.
864 $out->setRevisionId( $this->mNewid
);
865 $out->setRevisionTimestamp( $this->mNewRev
->getTimestamp() );
866 $out->setArticleFlag( true );
868 if ( !Hooks
::run( 'ArticleRevisionViewCustom',
869 [ $this->mNewRev
->getRevisionRecord(), $this->mNewPage
, $out ] )
871 // Handled by extension
872 // NOTE: sync with hooks called in Article::view()
873 } elseif ( !Hooks
::run( 'ArticleContentViewCustom',
874 [ $this->mNewContent
, $this->mNewPage
, $out ], '1.32' )
876 // Handled by extension
877 // NOTE: sync with hooks called in Article::view()
880 if ( $this->getTitle()->equals( $this->mNewPage
) ) {
881 // If the Title stored in the context is the same as the one
882 // of the new revision, we can use its associated WikiPage
884 $wikiPage = $this->getWikiPage();
886 // Otherwise we need to create our own WikiPage object
887 $wikiPage = WikiPage
::factory( $this->mNewPage
);
890 $parserOutput = $this->getParserOutput( $wikiPage, $this->mNewRev
);
892 # WikiPage::getParserOutput() should not return false, but just in case
893 if ( $parserOutput ) {
894 // Allow extensions to change parser output here
895 if ( Hooks
::run( 'DifferenceEngineRenderRevisionAddParserOutput',
896 [ $this, $out, $parserOutput, $wikiPage ] )
898 $out->addParserOutput( $parserOutput, [
899 'enableSectionEditLinks' => $this->mNewRev
->isCurrent()
900 && $this->mNewRev
->getTitle()->quickUserCan( 'edit', $this->getUser() ),
907 // Allow extensions to optionally not show the final patrolled link
908 if ( Hooks
::run( 'DifferenceEngineRenderRevisionShowFinalPatrolLink' ) ) {
909 # Add redundant patrol link on bottom...
910 $out->addHTML( $this->markPatrolledLink() );
915 * @param WikiPage $page
916 * @param Revision $rev
918 * @return ParserOutput|bool False if the revision was not found
920 protected function getParserOutput( WikiPage
$page, Revision
$rev ) {
921 if ( !$rev->getId() ) {
922 // WikiPage::getParserOutput wants a revision ID. Passing 0 will incorrectly show
923 // the current revision, so fail instead. If need be, WikiPage::getParserOutput
924 // could be made to accept a Revision or RevisionRecord instead of the id.
928 $parserOptions = $page->makeParserOptions( $this->getContext() );
929 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
931 return $parserOutput;
935 * Get the diff text, send it to the OutputPage object
936 * Returns false if the diff could not be generated, otherwise returns true
938 * @param string|bool $otitle Header for old text or false
939 * @param string|bool $ntitle Header for new text or false
940 * @param string $notice HTML between diff header and body
944 public function showDiff( $otitle, $ntitle, $notice = '' ) {
945 // Allow extensions to affect the output here
946 Hooks
::run( 'DifferenceEngineShowDiff', [ $this ] );
948 $diff = $this->getDiff( $otitle, $ntitle, $notice );
949 if ( $diff === false ) {
950 $this->showMissingRevision();
954 $this->showDiffStyle();
955 $this->getOutput()->addHTML( $diff );
962 * Add style sheets for diff display.
964 public function showDiffStyle() {
965 if ( !$this->isSlotDiffRenderer
) {
966 $this->getOutput()->addModuleStyles( [
967 'mediawiki.interface.helpers.styles',
968 'mediawiki.diff.styles'
970 foreach ( $this->getSlotDiffRenderers() as $slotDiffRenderer ) {
971 $slotDiffRenderer->addModules( $this->getOutput() );
977 * Get complete diff table, including header
979 * @param string|bool $otitle Header for old text or false
980 * @param string|bool $ntitle Header for new text or false
981 * @param string $notice HTML between diff header and body
985 public function getDiff( $otitle, $ntitle, $notice = '' ) {
986 $body = $this->getDiffBody();
987 if ( $body === false ) {
991 $multi = $this->getMultiNotice();
992 // Display a message when the diff is empty
993 if ( $body === '' ) {
994 $notice .= '<div class="mw-diff-empty">' .
995 $this->msg( 'diff-empty' )->parse() .
999 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
1003 * Get the diff table body, without header
1005 * @return mixed (string/false)
1007 public function getDiffBody() {
1008 $this->mCacheHit
= true;
1009 // Check if the diff should be hidden from this user
1010 if ( !$this->isContentOverridden
) {
1011 if ( !$this->loadRevisionData() ) {
1013 } elseif ( $this->mOldRev
&&
1014 !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
1017 } elseif ( $this->mNewRev
&&
1018 !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
1023 if ( $this->mOldRev
=== false ||
( $this->mOldRev
&& $this->mNewRev
&&
1024 $this->mOldRev
->getId() && $this->mOldRev
->getId() == $this->mNewRev
->getId() )
1026 if ( Hooks
::run( 'DifferenceEngineShowEmptyOldContent', [ $this ] ) ) {
1034 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1035 if ( $this->mOldid
&& $this->mNewid
) {
1036 // Check if subclass is still using the old way
1037 // for backwards-compatibility
1038 $key = $this->getDiffBodyCacheKey();
1039 if ( $key === null ) {
1040 $key = $cache->makeKey( ...$this->getDiffBodyCacheKeyParams() );
1044 if ( !$this->mRefreshCache
) {
1045 $difftext = $cache->get( $key );
1046 if ( is_string( $difftext ) ) {
1047 wfIncrStats( 'diff_cache.hit' );
1048 $difftext = $this->localiseDiff( $difftext );
1049 $difftext .= "\n<!-- diff cache key $key -->\n";
1053 } // don't try to load but save the result
1055 $this->mCacheHit
= false;
1057 // Loadtext is permission safe, this just clears out the diff
1058 if ( !$this->loadText() ) {
1063 // We've checked for revdelete at the beginning of this method; it's OK to ignore
1064 // read permissions here.
1065 $slotContents = $this->getSlotContents();
1066 foreach ( $this->getSlotDiffRenderers() as $role => $slotDiffRenderer ) {
1067 $slotDiff = $slotDiffRenderer->getDiff( $slotContents[$role]['old'],
1068 $slotContents[$role]['new'] );
1069 if ( $slotDiff && $role !== SlotRecord
::MAIN
) {
1070 // FIXME: ask SlotRoleHandler::getSlotNameMessage
1072 $difftext .= $this->getSlotHeader( $slotTitle );
1074 $difftext .= $slotDiff;
1077 // Avoid PHP 7.1 warning from passing $this by reference
1078 $diffEngine = $this;
1080 // Save to cache for 7 days
1081 if ( !Hooks
::run( 'AbortDiffCache', [ &$diffEngine ] ) ) {
1082 wfIncrStats( 'diff_cache.uncacheable' );
1083 } elseif ( $key !== false && $difftext !== false ) {
1084 wfIncrStats( 'diff_cache.miss' );
1085 $cache->set( $key, $difftext, 7 * 86400 );
1087 wfIncrStats( 'diff_cache.uncacheable' );
1089 // localise line numbers and title attribute text
1090 if ( $difftext !== false ) {
1091 $difftext = $this->localiseDiff( $difftext );
1098 * Get the diff table body for one slot, without header
1100 * @param string $role
1101 * @return string|false
1103 public function getDiffBodyForRole( $role ) {
1104 $diffRenderers = $this->getSlotDiffRenderers();
1105 if ( !isset( $diffRenderers[$role] ) ) {
1109 $slotContents = $this->getSlotContents();
1110 $slotDiff = $diffRenderers[$role]->getDiff( $slotContents[$role]['old'],
1111 $slotContents[$role]['new'] );
1116 if ( $role !== SlotRecord
::MAIN
) {
1117 // TODO use human-readable role name at least
1119 $slotDiff = $this->getSlotHeader( $slotTitle ) . $slotDiff;
1122 return $this->localiseDiff( $slotDiff );
1126 * Get a slot header for inclusion in a diff body (as a table row).
1128 * @param string $headerText The text of the header
1132 protected function getSlotHeader( $headerText ) {
1133 // The old revision is missing on oldid=<first>&diff=prev; only 2 columns in that case.
1134 $columnCount = $this->mOldRev ?
4 : 2;
1135 $userLang = $this->getLanguage()->getHtmlCode();
1136 return Html
::rawElement( 'tr', [ 'class' => 'mw-diff-slot-header', 'lang' => $userLang ],
1137 Html
::element( 'th', [ 'colspan' => $columnCount ], $headerText ) );
1141 * Returns the cache key for diff body text or content.
1143 * @deprecated since 1.31, use getDiffBodyCacheKeyParams() instead
1146 * @throws MWException
1147 * @return string|null
1149 protected function getDiffBodyCacheKey() {
1154 * Get the cache key parameters
1156 * Subclasses can replace the first element in the array to something
1157 * more specific to the type of diff (e.g. "inline-diff"), or append
1158 * if the cache should vary on more things. Overriding entirely should
1164 * @throws MWException
1166 protected function getDiffBodyCacheKeyParams() {
1167 if ( !$this->mOldid ||
!$this->mNewid
) {
1168 throw new MWException( 'mOldid and mNewid must be set to get diff cache key.' );
1171 $engine = $this->getEngine();
1176 "old-{$this->mOldid}",
1177 "rev-{$this->mNewid}"
1180 if ( $engine === 'wikidiff2' ) {
1181 $params[] = phpversion( 'wikidiff2' );
1184 if ( !$this->isSlotDiffRenderer
) {
1185 foreach ( $this->getSlotDiffRenderers() as $slotDiffRenderer ) {
1186 $params = array_merge( $params, $slotDiffRenderer->getExtraCacheKeys() );
1194 * Implements DifferenceEngineSlotDiffRenderer::getExtraCacheKeys(). Only used when
1195 * DifferenceEngine is wrapped in DifferenceEngineSlotDiffRenderer.
1197 * @internal for use by DifferenceEngineSlotDiffRenderer only
1200 public function getExtraCacheKeys() {
1201 // This method is called when the DifferenceEngine is used for a slot diff. We only care
1202 // about special things, not the revision IDs, which are added to the cache key by the
1203 // page-level DifferenceEngine, and which might not have a valid value for this object.
1204 $this->mOldid
= 123456789;
1205 $this->mNewid
= 987654321;
1207 // This will repeat a bunch of unnecessary key fields for each slot. Not nice but harmless.
1208 $cacheString = $this->getDiffBodyCacheKey();
1209 if ( $cacheString ) {
1210 return [ $cacheString ];
1213 $params = $this->getDiffBodyCacheKeyParams();
1215 // Try to get rid of the standard keys to keep the cache key human-readable:
1216 // call the getDiffBodyCacheKeyParams implementation of the base class, and if
1217 // the child class includes the same keys, drop them.
1218 // Uses an obscure PHP feature where static calls to non-static methods are allowed
1219 // as long as we are already in a non-static method of the same class, and the call context
1220 // ($this) will be inherited.
1221 // phpcs:ignore Squiz.Classes.SelfMemberReference.NotUsed
1222 $standardParams = DifferenceEngine
::getDiffBodyCacheKeyParams();
1223 if ( array_slice( $params, 0, count( $standardParams ) ) === $standardParams ) {
1224 $params = array_slice( $params, count( $standardParams ) );
1231 * Generate a diff, no caching.
1235 * @param Content $old Old content
1236 * @param Content $new New content
1238 * @throws Exception If old or new content is not an instance of TextContent.
1239 * @return bool|string
1241 * @deprecated since 1.32, use a SlotDiffRenderer instead.
1243 public function generateContentDiffBody( Content
$old, Content
$new ) {
1244 $slotDiffRenderer = $new->getContentHandler()->getSlotDiffRenderer( $this->getContext() );
1246 $slotDiffRenderer instanceof DifferenceEngineSlotDiffRenderer
1247 && $this->isSlotDiffRenderer
1249 // Oops, we are just about to enter an infinite loop (the slot-level DifferenceEngine
1250 // called a DifferenceEngineSlotDiffRenderer that wraps the same DifferenceEngine class).
1251 // This will happen when a content model has no custom slot diff renderer, it does have
1252 // a custom difference engine, but that does not override this method.
1253 throw new Exception( get_class( $this ) . ': could not maintain backwards compatibility. '
1254 . 'Please use a SlotDiffRenderer.' );
1256 return $slotDiffRenderer->getDiff( $old, $new ) . $this->getDebugString();
1260 * Generate a diff, no caching
1262 * @param string $otext Old text, must be already segmented
1263 * @param string $ntext New text, must be already segmented
1265 * @throws Exception If content handling for text content is configured in a way
1266 * that makes maintaining B/C hard.
1267 * @return bool|string
1269 * @deprecated since 1.32, use a TextSlotDiffRenderer instead.
1271 public function generateTextDiffBody( $otext, $ntext ) {
1272 $slotDiffRenderer = ContentHandler
::getForModelID( CONTENT_MODEL_TEXT
)
1273 ->getSlotDiffRenderer( $this->getContext() );
1274 if ( !( $slotDiffRenderer instanceof TextSlotDiffRenderer
) ) {
1275 // Someone used the GetSlotDiffRenderer hook to replace the renderer.
1276 // This is too unlikely to happen to bother handling properly.
1277 throw new Exception( 'The slot diff renderer for text content should be a '
1278 . 'TextSlotDiffRenderer subclass' );
1280 return $slotDiffRenderer->getTextDiff( $otext, $ntext ) . $this->getDebugString();
1284 * Process $wgExternalDiffEngine and get a sane, usable engine
1286 * @return bool|string 'wikidiff2', path to an executable, or false
1287 * @internal For use by this class and TextSlotDiffRenderer only.
1289 public static function getEngine() {
1290 global $wgExternalDiffEngine;
1291 // We use the global here instead of Config because we write to the value,
1292 // and Config is not mutable.
1293 if ( $wgExternalDiffEngine == 'wikidiff' ||
$wgExternalDiffEngine == 'wikidiff3' ) {
1294 wfDeprecated( "\$wgExternalDiffEngine = '{$wgExternalDiffEngine}'", '1.27' );
1295 $wgExternalDiffEngine = false;
1296 } elseif ( $wgExternalDiffEngine == 'wikidiff2' ) {
1297 wfDeprecated( "\$wgExternalDiffEngine = '{$wgExternalDiffEngine}'", '1.32' );
1298 $wgExternalDiffEngine = false;
1299 } elseif ( !is_string( $wgExternalDiffEngine ) && $wgExternalDiffEngine !== false ) {
1300 // And prevent people from shooting themselves in the foot...
1301 wfWarn( '$wgExternalDiffEngine is set to a non-string value, forcing it to false' );
1302 $wgExternalDiffEngine = false;
1305 if ( is_string( $wgExternalDiffEngine ) && is_executable( $wgExternalDiffEngine ) ) {
1306 return $wgExternalDiffEngine;
1307 } elseif ( $wgExternalDiffEngine === false && function_exists( 'wikidiff2_do_diff' ) ) {
1316 * Generates diff, to be wrapped internally in a logging/instrumentation
1318 * @param string $otext Old text, must be already segmented
1319 * @param string $ntext New text, must be already segmented
1321 * @throws Exception If content handling for text content is configured in a way
1322 * that makes maintaining B/C hard.
1323 * @return bool|string
1325 * @deprecated since 1.32, use a TextSlotDiffRenderer instead.
1327 protected function textDiff( $otext, $ntext ) {
1328 $slotDiffRenderer = ContentHandler
::getForModelID( CONTENT_MODEL_TEXT
)
1329 ->getSlotDiffRenderer( $this->getContext() );
1330 if ( !( $slotDiffRenderer instanceof TextSlotDiffRenderer
) ) {
1331 // Someone used the GetSlotDiffRenderer hook to replace the renderer.
1332 // This is too unlikely to happen to bother handling properly.
1333 throw new Exception( 'The slot diff renderer for text content should be a '
1334 . 'TextSlotDiffRenderer subclass' );
1336 return $slotDiffRenderer->getTextDiff( $otext, $ntext ) . $this->getDebugString();
1340 * Generate a debug comment indicating diff generating time,
1341 * server node, and generator backend.
1343 * @param string $generator : What diff engine was used
1347 protected function debug( $generator = "internal" ) {
1348 if ( !$this->enableDebugComment
) {
1351 $data = [ $generator ];
1352 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1353 $data[] = wfHostname();
1355 $data[] = wfTimestamp( TS_DB
);
1357 return "<!-- diff generator: " .
1358 implode( " ", array_map( "htmlspecialchars", $data ) ) .
1362 private function getDebugString() {
1363 $engine = self
::getEngine();
1364 if ( $engine === 'wikidiff2' ) {
1365 return $this->debug( 'wikidiff2' );
1366 } elseif ( $engine === false ) {
1367 return $this->debug( 'native PHP' );
1369 return $this->debug( "external $engine" );
1374 * Localise diff output
1376 * @param string $text
1379 private function localiseDiff( $text ) {
1380 $text = $this->localiseLineNumbers( $text );
1381 if ( $this->getEngine() === 'wikidiff2' &&
1382 version_compare( phpversion( 'wikidiff2' ), '1.5.1', '>=' )
1384 $text = $this->addLocalisedTitleTooltips( $text );
1390 * Replace line numbers with the text in the user's language
1392 * @param string $text
1396 public function localiseLineNumbers( $text ) {
1397 return preg_replace_callback(
1398 '/<!--LINE (\d+)-->/',
1399 [ $this, 'localiseLineNumbersCb' ],
1404 public function localiseLineNumbersCb( $matches ) {
1405 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) {
1409 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
1413 * Add title attributes for tooltips on moved paragraph indicators
1415 * @param string $text
1418 private function addLocalisedTitleTooltips( $text ) {
1419 return preg_replace_callback(
1420 '/class="mw-diff-movedpara-(left|right)"/',
1421 [ $this, 'addLocalisedTitleTooltipsCb' ],
1427 * @param array $matches
1430 private function addLocalisedTitleTooltipsCb( array $matches ) {
1431 $key = $matches[1] === 'right' ?
1432 'diff-paragraph-moved-toold' :
1433 'diff-paragraph-moved-tonew';
1434 return $matches[0] . ' title="' . $this->msg( $key )->escaped() . '"';
1438 * If there are revisions between the ones being compared, return a note saying so.
1442 public function getMultiNotice() {
1443 // The notice only make sense if we are diffing two saved revisions of the same page.
1445 !$this->mOldRev ||
!$this->mNewRev
1446 ||
!$this->mOldPage ||
!$this->mNewPage
1447 ||
!$this->mOldPage
->equals( $this->mNewPage
)
1452 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
1453 $oldRev = $this->mNewRev
; // flip
1454 $newRev = $this->mOldRev
; // flip
1455 } else { // normal case
1456 $oldRev = $this->mOldRev
;
1457 $newRev = $this->mNewRev
;
1460 // Sanity: don't show the notice if too many rows must be scanned
1461 // @todo show some special message for that case
1462 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev, 1000 );
1463 if ( $nEdits > 0 && $nEdits <= 1000 ) {
1464 $limit = 100; // use diff-multi-manyusers if too many users
1465 $users = $this->mNewPage
->getAuthorsBetween( $oldRev, $newRev, $limit );
1466 $numUsers = count( $users );
1468 if ( $numUsers == 1 && $users[0] == $newRev->getUserText( Revision
::RAW
) ) {
1469 $numUsers = 0; // special case to say "by the same user" instead of "by one other user"
1472 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
1479 * Get a notice about how many intermediate edits and users there are
1481 * @param int $numEdits
1482 * @param int $numUsers
1487 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
1488 if ( $numUsers === 0 ) {
1489 $msg = 'diff-multi-sameuser';
1490 } elseif ( $numUsers > $limit ) {
1491 $msg = 'diff-multi-manyusers';
1494 $msg = 'diff-multi-otherusers';
1497 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
1501 * Get a header for a specified revision.
1503 * @param Revision $rev
1504 * @param string $complete 'complete' to get the header wrapped depending
1505 * the visibility of the revision and a link to edit the page.
1507 * @return string HTML fragment
1509 public function getRevisionHeader( Revision
$rev, $complete = '' ) {
1510 $lang = $this->getLanguage();
1511 $user = $this->getUser();
1512 $revtimestamp = $rev->getTimestamp();
1513 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
1514 $dateofrev = $lang->userDate( $revtimestamp, $user );
1515 $timeofrev = $lang->userTime( $revtimestamp, $user );
1517 $header = $this->msg(
1518 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
1524 if ( $complete !== 'complete' ) {
1528 $title = $rev->getTitle();
1530 $header = Linker
::linkKnown( $title, $header, [],
1531 [ 'oldid' => $rev->getId() ] );
1533 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
1534 $editQuery = [ 'action' => 'edit' ];
1535 if ( !$rev->isCurrent() ) {
1536 $editQuery['oldid'] = $rev->getId();
1539 $key = $title->quickUserCan( 'edit', $user ) ?
'editold' : 'viewsourceold';
1540 $msg = $this->msg( $key )->escaped();
1541 $editLink = $this->msg( 'parentheses' )->rawParams(
1542 Linker
::linkKnown( $title, $msg, [], $editQuery ) )->escaped();
1543 $header .= ' ' . Html
::rawElement(
1545 [ 'class' => 'mw-diff-edit' ],
1548 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
1549 $header = Html
::rawElement(
1551 [ 'class' => 'history-deleted' ],
1556 $header = Html
::rawElement( 'span', [ 'class' => 'history-deleted' ], $header );
1563 * Add the header to a diff body
1565 * @param string $diff Diff body
1566 * @param string $otitle Old revision header
1567 * @param string $ntitle New revision header
1568 * @param string $multi Notice telling user that there are intermediate
1569 * revisions between the ones being compared
1570 * @param string $notice Other notices, e.g. that user is viewing deleted content
1574 public function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
1575 // shared.css sets diff in interface language/dir, but the actual content
1576 // is often in a different language, mostly the page content language/dir
1577 $header = Html
::openElement( 'table', [
1578 'class' => [ 'diff', 'diff-contentalign-' . $this->getDiffLang()->alignStart() ],
1579 'data-mw' => 'interface',
1581 $userLang = htmlspecialchars( $this->getLanguage()->getHtmlCode() );
1583 if ( !$diff && !$otitle ) {
1585 <tr class=\"diff-title\" lang=\"{$userLang}\">
1586 <td class=\"diff-ntitle\">{$ntitle}</td>
1590 if ( $diff ) { // Safari/Chrome show broken output if cols not used
1592 <col class=\"diff-marker\" />
1593 <col class=\"diff-content\" />
1594 <col class=\"diff-marker\" />
1595 <col class=\"diff-content\" />";
1602 if ( $otitle ||
$ntitle ) {
1604 <tr class=\"diff-title\" lang=\"{$userLang}\">
1605 <td colspan=\"$colspan\" class=\"diff-otitle\">{$otitle}</td>
1606 <td colspan=\"$colspan\" class=\"diff-ntitle\">{$ntitle}</td>
1611 if ( $multi != '' ) {
1612 $header .= "<tr><td colspan=\"{$multiColspan}\" " .
1613 "class=\"diff-multi\" lang=\"{$userLang}\">{$multi}</td></tr>";
1615 if ( $notice != '' ) {
1616 $header .= "<tr><td colspan=\"{$multiColspan}\" " .
1617 "class=\"diff-notice\" lang=\"{$userLang}\">{$notice}</td></tr>";
1620 return $header . $diff . "</table>";
1624 * Use specified text instead of loading from the database
1625 * @param Content $oldContent
1626 * @param Content $newContent
1628 * @deprecated since 1.32, use setRevisions or ContentHandler::getSlotDiffRenderer.
1630 public function setContent( Content
$oldContent, Content
$newContent ) {
1631 $this->mOldContent
= $oldContent;
1632 $this->mNewContent
= $newContent;
1634 $this->mTextLoaded
= 2;
1635 $this->mRevisionsLoaded
= true;
1636 $this->isContentOverridden
= true;
1637 $this->slotDiffRenderers
= null;
1641 * Use specified text instead of loading from the database.
1642 * @param RevisionRecord|null $oldRevision
1643 * @param RevisionRecord $newRevision
1645 public function setRevisions(
1646 RevisionRecord
$oldRevision = null, RevisionRecord
$newRevision
1648 if ( $oldRevision ) {
1649 $this->mOldRev
= new Revision( $oldRevision );
1650 $this->mOldid
= $oldRevision->getId();
1651 $this->mOldPage
= Title
::newFromLinkTarget( $oldRevision->getPageAsLinkTarget() );
1652 // This method is meant for edit diffs and such so there is no reason to provide a
1653 // revision that's not readable to the user, but check it just in case.
1654 $this->mOldContent
= $oldRevision->getContent( SlotRecord
::MAIN
,
1655 RevisionRecord
::FOR_THIS_USER
, $this->getUser() );
1657 $this->mOldPage
= null;
1658 $this->mOldRev
= $this->mOldid
= false;
1660 $this->mNewRev
= new Revision( $newRevision );
1661 $this->mNewid
= $newRevision->getId();
1662 $this->mNewPage
= Title
::newFromLinkTarget( $newRevision->getPageAsLinkTarget() );
1663 $this->mNewContent
= $newRevision->getContent( SlotRecord
::MAIN
,
1664 RevisionRecord
::FOR_THIS_USER
, $this->getUser() );
1666 $this->mRevisionsIdsLoaded
= $this->mRevisionsLoaded
= true;
1667 $this->mTextLoaded
= $oldRevision ?
2 : 1;
1668 $this->isContentOverridden
= false;
1669 $this->slotDiffRenderers
= null;
1673 * Set the language in which the diff text is written
1675 * @param Language $lang
1678 public function setTextLanguage( Language
$lang ) {
1679 $this->mDiffLang
= $lang;
1683 * Maps a revision pair definition as accepted by DifferenceEngine constructor
1684 * to a pair of actual integers representing revision ids.
1686 * @param int $old Revision id, e.g. from URL parameter 'oldid'
1687 * @param int|string $new Revision id or strings 'next' or 'prev', e.g. from URL parameter 'diff'
1689 * @return array List of two revision ids, older first, later second.
1690 * Zero signifies invalid argument passed.
1691 * false signifies that there is no previous/next revision ($old is the oldest/newest one).
1693 public function mapDiffPrevNext( $old, $new ) {
1694 if ( $new === 'prev' ) {
1695 // Show diff between revision $old and the previous one. Get previous one from DB.
1696 $newid = intval( $old );
1697 $oldid = $this->getTitle()->getPreviousRevisionID( $newid );
1698 } elseif ( $new === 'next' ) {
1699 // Show diff between revision $old and the next one. Get next one from DB.
1700 $oldid = intval( $old );
1701 $newid = $this->getTitle()->getNextRevisionID( $oldid );
1703 $oldid = intval( $old );
1704 $newid = intval( $new );
1707 return [ $oldid, $newid ];
1713 private function loadRevisionIds() {
1714 if ( $this->mRevisionsIdsLoaded
) {
1718 $this->mRevisionsIdsLoaded
= true;
1720 $old = $this->mOldid
;
1721 $new = $this->mNewid
;
1723 list( $this->mOldid
, $this->mNewid
) = self
::mapDiffPrevNext( $old, $new );
1724 if ( $new === 'next' && $this->mNewid
=== false ) {
1725 # if no result, NewId points to the newest old revision. The only newer
1726 # revision is cur, which is "0".
1731 'NewDifferenceEngine',
1732 [ $this->getTitle(), &$this->mOldid
, &$this->mNewid
, $old, $new ]
1737 * Load revision metadata for the specified revisions. If newid is 0, then compare
1738 * the old revision in oldid to the current revision of the current page (as defined
1739 * by the request context); if oldid is 0, then compare the revision in newid to the
1740 * immediately previous one.
1742 * If oldid is false, leave the corresponding revision object set to false. This can
1743 * happen with 'diff=prev' pointing to a non-existent revision, and is also used directly
1746 * @return bool Whether both revisions were loaded successfully. Setting mOldRev
1747 * to false counts as successful loading.
1749 public function loadRevisionData() {
1750 if ( $this->mRevisionsLoaded
) {
1751 return $this->isContentOverridden ||
( $this->mOldRev
!== null && $this->mNewRev
!== null );
1754 // Whether it succeeds or fails, we don't want to try again
1755 $this->mRevisionsLoaded
= true;
1757 $this->loadRevisionIds();
1759 // Load the new revision object
1760 if ( $this->mNewid
) {
1761 $this->mNewRev
= Revision
::newFromId( $this->mNewid
);
1763 $this->mNewRev
= Revision
::newFromTitle(
1766 Revision
::READ_NORMAL
1770 if ( !$this->mNewRev
instanceof Revision
) {
1774 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1775 $this->mNewid
= $this->mNewRev
->getId();
1776 if ( $this->mNewid
) {
1777 $this->mNewPage
= $this->mNewRev
->getTitle();
1779 $this->mNewPage
= null;
1782 // Load the old revision object
1783 $this->mOldRev
= false;
1784 if ( $this->mOldid
) {
1785 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1786 } elseif ( $this->mOldid
=== 0 ) {
1787 $rev = $this->mNewRev
->getPrevious();
1789 $this->mOldid
= $rev->getId();
1790 $this->mOldRev
= $rev;
1792 // No previous revision; mark to show as first-version only.
1793 $this->mOldid
= false;
1794 $this->mOldRev
= false;
1796 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1798 if ( is_null( $this->mOldRev
) ) {
1802 if ( $this->mOldRev
&& $this->mOldRev
->getId() ) {
1803 $this->mOldPage
= $this->mOldRev
->getTitle();
1805 $this->mOldPage
= null;
1808 // Load tags information for both revisions
1809 $dbr = wfGetDB( DB_REPLICA
);
1810 $changeTagDefStore = MediaWikiServices
::getInstance()->getChangeTagDefStore();
1811 if ( $this->mOldid
!== false ) {
1812 $tagIds = $dbr->selectFieldValues(
1815 [ 'ct_rev_id' => $this->mOldid
],
1819 foreach ( $tagIds as $tagId ) {
1821 $tags[] = $changeTagDefStore->getName( (int)$tagId );
1822 } catch ( NameTableAccessException
$exception ) {
1826 $this->mOldTags
= implode( ',', $tags );
1828 $this->mOldTags
= false;
1831 $tagIds = $dbr->selectFieldValues(
1834 [ 'ct_rev_id' => $this->mNewid
],
1838 foreach ( $tagIds as $tagId ) {
1840 $tags[] = $changeTagDefStore->getName( (int)$tagId );
1841 } catch ( NameTableAccessException
$exception ) {
1845 $this->mNewTags
= implode( ',', $tags );
1851 * Load the text of the revisions, as well as revision data.
1852 * When the old revision is missing (mOldRev is false), loading mOldContent is not attempted.
1854 * @return bool Whether the content of both revisions could be loaded successfully.
1855 * (When mOldRev is false, that still counts as a success.)
1858 public function loadText() {
1859 if ( $this->mTextLoaded
== 2 ) {
1860 return $this->loadRevisionData() && ( $this->mOldRev
=== false ||
$this->mOldContent
)
1861 && $this->mNewContent
;
1864 // Whether it succeeds or fails, we don't want to try again
1865 $this->mTextLoaded
= 2;
1867 if ( !$this->loadRevisionData() ) {
1871 if ( $this->mOldRev
) {
1872 $this->mOldContent
= $this->mOldRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1873 if ( $this->mOldContent
=== null ) {
1878 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1879 Hooks
::run( 'DifferenceEngineLoadTextAfterNewContentIsLoaded', [ $this ] );
1880 if ( $this->mNewContent
=== null ) {
1888 * Load the text of the new revision, not the old one
1890 * @return bool Whether the content of the new revision could be loaded successfully.
1892 public function loadNewText() {
1893 if ( $this->mTextLoaded
>= 1 ) {
1894 return $this->loadRevisionData();
1897 $this->mTextLoaded
= 1;
1899 if ( !$this->loadRevisionData() ) {
1903 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1905 Hooks
::run( 'DifferenceEngineAfterLoadNewText', [ $this ] );