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\Storage\RevisionRecord
;
27 * DifferenceEngine is responsible for rendering the difference between two revisions as HTML.
28 * This includes interpreting URL parameters, retrieving revision data, checking access permissions,
29 * selecting and invoking the diff generator class for the individual slots, doing post-processing
30 * on the generated diff, adding the rest of the HTML (such as headers) and writing the whole thing
33 * DifferenceEngine can be subclassed by extensions, by customizing
34 * ContentHandler::createDifferenceEngine; the content handler will be selected based on the
35 * content model of the main slot (of the new revision, when the two are different).
36 * That might change after PageTypeHandler gets introduced.
38 * In the past, the class was also used for slot-level diff generation, and extensions might still
39 * subclass it and add such functionality. When that is the case (sepcifically, when a
40 * ContentHandler returns a standard SlotDiffRenderer but a nonstandard DifferenceEngine)
41 * DifferenceEngineSlotDiffRenderer will be used to convert the old behavior into the new one.
43 * @ingroup DifferenceEngine
45 * @todo This class is huge and poorly defined. It should be split into a controller responsible
46 * for interpreting query parameters, retrieving data and checking permissions; and a HTML renderer.
48 class DifferenceEngine
extends ContextSource
{
50 use DeprecationHelper
;
53 * Constant to indicate diff cache compatibility.
54 * Bump this when changing the diff formatting in a way that
55 * fixes important bugs or such to force cached diff views to
58 const DIFF_VERSION
= '1.12';
61 * Revision ID for the old revision. 0 for the revision previous to $mNewid, false
62 * if the diff does not have an old revision (e.g. 'oldid=<first revision of page>&diff=prev'),
63 * or the revision does not exist, null if the revision is unsaved.
69 * Revision ID for the new revision. 0 for the last revision of the current page
70 * (as defined by the request context), false if the revision does not exist, null
71 * if it is unsaved, or an alias such as 'next'.
72 * @var int|string|false|null
77 * Old revision (left pane).
78 * Allowed to be an unsaved revision, unlikely that's ever needed though.
79 * False when the old revision does not exist; this can happen when using
80 * diff=prev on the first revision. Null when the revision should exist but
81 * doesn't (e.g. load failure); loadRevisionData() will return false in that
82 * case. Also null until lazy-loaded. Ignored completely when isContentOverridden
84 * Since 1.32 public access is deprecated.
85 * @var Revision|null|false
90 * New revision (right pane).
91 * Note that this might be an unsaved revision (e.g. for edit preview).
92 * Null in case of load failure; diff methods will just return an error message in that case,
93 * and loadRevisionData() will return false. Also null until lazy-loaded. Ignored completely
94 * when isContentOverridden is set.
95 * Since 1.32 public access is deprecated.
101 * Title of $mOldRev or null if the old revision does not exist or does not belong to a page.
102 * Since 1.32 public access is deprecated and the property can be null.
108 * Title of $mNewRev or null if the new revision does not exist or does not belong to a page.
109 * Since 1.32 public access is deprecated and the property can be null.
115 * Change tags of $mOldRev or null if it does not exist / is not saved.
121 * Change tags of $mNewRev or null if it does not exist / is not saved.
128 * @deprecated since 1.32, content slots are now handled by the corresponding SlotDiffRenderer.
129 * This property is set to the content of the main slot, but not actually used for the main diff.
131 private $mOldContent;
135 * @deprecated since 1.32, content slots are now handled by the corresponding SlotDiffRenderer.
136 * This property is set to the content of the main slot, but not actually used for the main diff.
138 private $mNewContent;
141 protected $mDiffLang;
143 /** @var bool Have the revisions IDs been loaded */
144 private $mRevisionsIdsLoaded = false;
146 /** @var bool Have the revisions been loaded */
147 protected $mRevisionsLoaded = false;
149 /** @var int How many text blobs have been loaded, 0, 1 or 2? */
150 protected $mTextLoaded = 0;
153 * Was the content overridden via setContent()?
154 * If the content was overridden, most internal state (e.g. mOldid or mOldRev) should be ignored
155 * and only mOldContent and mNewContent is reliable.
156 * (Note that setRevisions() does not set this flag as in that case all properties are
157 * overriden and remain consistent with each other, so no special handling is needed.)
160 protected $isContentOverridden = false;
162 /** @var bool Was the diff fetched from cache? */
163 protected $mCacheHit = false;
166 * Set this to true to add debug info to the HTML output.
167 * Warning: this may cause RSS readers to spuriously mark articles as "new"
170 public $enableDebugComment = false;
172 /** @var bool If true, line X is not displayed when X is 1, for example
173 * to increase readability and conserve space with many small diffs.
175 protected $mReducedLineNumbers = false;
177 /** @var string Link to action=markpatrolled */
178 protected $mMarkPatrolledLink = null;
180 /** @var bool Show rev_deleted content if allowed */
181 protected $unhide = false;
183 /** @var bool Refresh the diff cache */
184 protected $mRefreshCache = false;
186 /** @var SlotDiffRenderer[] DifferenceEngine classes for the slots, keyed by role name. */
187 protected $slotDiffRenderers = null;
190 * Temporary hack for B/C while slot diff related methods of DifferenceEngine are being
191 * deprecated. When true, we are inside a DifferenceEngineSlotDiffRenderer and
192 * $slotDiffRenderers should not be used.
195 protected $isSlotDiffRenderer = false;
200 * @param IContextSource|null $context Context to use, anything else will be ignored
201 * @param int $old Old ID we want to show and diff with.
202 * @param string|int $new Either revision ID or 'prev' or 'next'. Default: 0.
203 * @param int $rcid Deprecated, no longer used!
204 * @param bool $refreshCache If set, refreshes the diff cache
205 * @param bool $unhide If set, allow viewing deleted revs
207 public function __construct( $context = null, $old = 0, $new = 0, $rcid = 0,
208 $refreshCache = false, $unhide = false
210 $this->deprecatePublicProperty( 'mOldid', '1.32', __CLASS__
);
211 $this->deprecatePublicProperty( 'mNewid', '1.32', __CLASS__
);
212 $this->deprecatePublicProperty( 'mOldRev', '1.32', __CLASS__
);
213 $this->deprecatePublicProperty( 'mNewRev', '1.32', __CLASS__
);
214 $this->deprecatePublicProperty( 'mOldPage', '1.32', __CLASS__
);
215 $this->deprecatePublicProperty( 'mNewPage', '1.32', __CLASS__
);
216 $this->deprecatePublicProperty( 'mOldContent', '1.32', __CLASS__
);
217 $this->deprecatePublicProperty( 'mNewContent', '1.32', __CLASS__
);
218 $this->deprecatePublicProperty( 'mRevisionsLoaded', '1.32', __CLASS__
);
219 $this->deprecatePublicProperty( 'mTextLoaded', '1.32', __CLASS__
);
220 $this->deprecatePublicProperty( 'mCacheHit', '1.32', __CLASS__
);
222 if ( $context instanceof IContextSource
) {
223 $this->setContext( $context );
226 wfDebug( "DifferenceEngine old '$old' new '$new' rcid '$rcid'\n" );
228 $this->mOldid
= $old;
229 $this->mNewid
= $new;
230 $this->mRefreshCache
= $refreshCache;
231 $this->unhide
= $unhide;
235 * @return SlotDiffRenderer[] Diff renderers for each slot, keyed by role name.
236 * Includes slots only present in one of the revisions.
238 protected function getSlotDiffRenderers() {
239 if ( $this->isSlotDiffRenderer
) {
240 throw new LogicException( __METHOD__
. ' called in slot diff renderer mode' );
243 if ( $this->slotDiffRenderers
=== null ) {
244 if ( !$this->loadRevisionData() ) {
248 $slotContents = $this->getSlotContents();
249 $this->slotDiffRenderers
= array_map( function ( $contents ) {
250 /** @var $content Content */
251 $content = $contents['new'] ?
: $contents['old'];
252 return $content->getContentHandler()->getSlotDiffRenderer( $this->getContext() );
255 return $this->slotDiffRenderers
;
259 * Mark this DifferenceEngine as a slot renderer (as opposed to a page renderer).
260 * This is used in legacy mode when the DifferenceEngine is wrapped in a
261 * DifferenceEngineSlotDiffRenderer.
262 * @internal For use by DifferenceEngineSlotDiffRenderer only.
264 public function markAsSlotDiffRenderer() {
265 $this->isSlotDiffRenderer
= true;
269 * Get the old and new content objects for all slots.
270 * This method does not do any permission checks.
271 * @return array [ role => [ 'old' => SlotRecord|null, 'new' => SlotRecord|null ], ... ]
273 protected function getSlotContents() {
274 if ( $this->isContentOverridden
) {
277 'old' => $this->mOldContent
,
278 'new' => $this->mNewContent
,
281 } elseif ( !$this->loadRevisionData() ) {
285 $newSlots = $this->mNewRev
->getRevisionRecord()->getSlots()->getSlots();
286 if ( $this->mOldRev
) {
287 $oldSlots = $this->mOldRev
->getRevisionRecord()->getSlots()->getSlots();
291 // The order here will determine the visual order of the diff. The current logic is
292 // slots of the new revision first in natural order, then deleted ones. This is ad hoc
293 // and should not be relied on - in the future we may want the ordering to depend
295 $roles = array_merge( array_keys( $newSlots ), array_keys( $oldSlots ) );
298 foreach ( $roles as $role ) {
300 'old' => isset( $oldSlots[$role] ) ?
$oldSlots[$role]->getContent() : null,
301 'new' => isset( $newSlots[$role] ) ?
$newSlots[$role]->getContent() : null,
304 // move main slot to front
305 if ( isset( $slots['main'] ) ) {
306 $slots = [ 'main' => $slots['main'] ] +
$slots;
311 public function getTitle() {
312 // T202454 avoid errors when there is no title
313 return parent
::getTitle() ?
: Title
::makeTitle( NS_SPECIAL
, 'BadTitle/DifferenceEngine' );
317 * Set reduced line numbers mode.
318 * When set, line X is not displayed when X is 1, for example to increase readability and
319 * conserve space with many small diffs.
322 public function setReducedLineNumbers( $value = true ) {
323 $this->mReducedLineNumbers
= $value;
327 * Get the language of the difference engine, defaults to page content language
331 public function getDiffLang() {
332 if ( $this->mDiffLang
=== null ) {
333 # Default language in which the diff text is written.
334 $this->mDiffLang
= $this->getTitle()->getPageLanguage();
337 return $this->mDiffLang
;
343 public function wasCacheHit() {
344 return $this->mCacheHit
;
348 * Get the ID of old revision (left pane) of the diff. 0 for the revision
349 * previous to getNewid(), false if the old revision does not exist, null
351 * To get a real revision ID instead of 0, call loadRevisionData() first.
352 * @return int|false|null
354 public function getOldid() {
355 $this->loadRevisionIds();
357 return $this->mOldid
;
361 * Get the ID of new revision (right pane) of the diff. 0 for the current revision,
362 * false if the new revision does not exist, null if it's unsaved.
363 * To get a real revision ID instead of 0, call loadRevisionData() first.
364 * @return int|false|null
366 public function getNewid() {
367 $this->loadRevisionIds();
369 return $this->mNewid
;
373 * Get the left side of the diff.
374 * Could be null when the first revision of the page is diffed to 'prev' (or in the case of
376 * @return RevisionRecord|null
378 public function getOldRevision() {
379 return $this->mOldRev ?
$this->mOldRev
->getRevisionRecord() : null;
383 * Get the right side of the diff.
384 * Should not be null but can still happen in the case of load failure.
385 * @return RevisionRecord|null
387 public function getNewRevision() {
388 return $this->mNewRev ?
$this->mNewRev
->getRevisionRecord() : null;
392 * Look up a special:Undelete link to the given deleted revision id,
393 * as a workaround for being unable to load deleted diffs in currently.
395 * @param int $id Revision ID
397 * @return string|bool Link HTML or false
399 public function deletedLink( $id ) {
400 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
401 $dbr = wfGetDB( DB_REPLICA
);
402 $arQuery = Revision
::getArchiveQueryInfo();
403 $row = $dbr->selectRow(
405 array_merge( $arQuery['fields'], [ 'ar_namespace', 'ar_title' ] ),
406 [ 'ar_rev_id' => $id ],
412 $rev = Revision
::newFromArchiveRow( $row );
413 $title = Title
::makeTitleSafe( $row->ar_namespace
, $row->ar_title
);
415 return SpecialPage
::getTitleFor( 'Undelete' )->getFullURL( [
416 'target' => $title->getPrefixedText(),
417 'timestamp' => $rev->getTimestamp()
426 * Build a wikitext link toward a deleted revision, if viewable.
428 * @param int $id Revision ID
430 * @return string Wikitext fragment
432 public function deletedIdMarker( $id ) {
433 $link = $this->deletedLink( $id );
435 return "[$link $id]";
441 private function showMissingRevision() {
442 $out = $this->getOutput();
445 if ( $this->mOldRev
=== null ||
446 ( $this->mOldRev
&& $this->mOldContent
=== null )
448 $missing[] = $this->deletedIdMarker( $this->mOldid
);
450 if ( $this->mNewRev
=== null ||
451 ( $this->mNewRev
&& $this->mNewContent
=== null )
453 $missing[] = $this->deletedIdMarker( $this->mNewid
);
456 $out->setPageTitle( $this->msg( 'errorpagetitle' ) );
457 $msg = $this->msg( 'difference-missing-revision' )
458 ->params( $this->getLanguage()->listToText( $missing ) )
459 ->numParams( count( $missing ) )
461 $out->addHTML( $msg );
464 public function showDiffPage( $diffOnly = false ) {
465 # Allow frames except in certain special cases
466 $out = $this->getOutput();
467 $out->allowClickjacking();
468 $out->setRobotPolicy( 'noindex,nofollow' );
470 // Allow extensions to add any extra output here
471 Hooks
::run( 'DifferenceEngineShowDiffPage', [ $out ] );
473 if ( !$this->loadRevisionData() ) {
474 if ( Hooks
::run( 'DifferenceEngineShowDiffPageMaybeShowMissingRevision', [ $this ] ) ) {
475 $this->showMissingRevision();
480 $user = $this->getUser();
482 if ( $this->mNewPage
) {
483 $permErrors = $this->mNewPage
->getUserPermissionsErrors( 'read', $user );
485 if ( $this->mOldPage
) {
486 $permErrors = wfMergeErrorArrays( $permErrors,
487 $this->mOldPage
->getUserPermissionsErrors( 'read', $user ) );
489 if ( count( $permErrors ) ) {
490 throw new PermissionsError( 'read', $permErrors );
496 # Carry over 'diffonly' param via navigation links
497 if ( $diffOnly != $user->getBoolOption( 'diffonly' ) ) {
498 $query['diffonly'] = $diffOnly;
500 # Cascade unhide param in links for easy deletion browsing
501 if ( $this->unhide
) {
502 $query['unhide'] = 1;
505 # Check if one of the revisions is deleted/suppressed
506 $deleted = $suppressed = false;
507 $allowed = $this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $user );
511 # mOldRev is false if the difference engine is called with a "vague" query for
512 # a diff between a version V and its previous version V' AND the version V
513 # is the first version of that article. In that case, V' does not exist.
514 if ( $this->mOldRev
=== false ) {
515 if ( $this->mNewPage
) {
516 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
520 // Allow extensions to change the $oldHeader variable
521 Hooks
::run( 'DifferenceEngineOldHeaderNoOldRev', [ &$oldHeader ] );
523 Hooks
::run( 'DiffViewHeader', [ $this, $this->mOldRev
, $this->mNewRev
] );
525 if ( !$this->mOldPage ||
!$this->mNewPage
) {
526 // XXX say something to the user?
528 } elseif ( $this->mNewPage
->equals( $this->mOldPage
) ) {
529 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
532 $out->setPageTitle( $this->msg( 'difference-title-multipage',
533 $this->mOldPage
->getPrefixedText(), $this->mNewPage
->getPrefixedText() ) );
534 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
538 if ( $samePage && $this->mNewPage
&& $this->mNewPage
->quickUserCan( 'edit', $user ) ) {
539 if ( $this->mNewRev
->isCurrent() && $this->mNewPage
->userCan( 'rollback', $user ) ) {
540 $rollbackLink = Linker
::generateRollback( $this->mNewRev
, $this->getContext() );
541 if ( $rollbackLink ) {
542 $out->preventClickjacking();
543 $rollback = "\u{00A0}\u{00A0}\u{00A0}" . $rollbackLink;
547 if ( !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) &&
548 !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
)
550 $undoLink = Html
::element( 'a', [
551 'href' => $this->mNewPage
->getLocalURL( [
553 'undoafter' => $this->mOldid
,
554 'undo' => $this->mNewid
556 'title' => Linker
::titleAttrib( 'undo' ),
558 $this->msg( 'editundo' )->text()
560 $revisionTools['mw-diff-undo'] = $undoLink;
564 # Make "previous revision link"
565 if ( $samePage && $this->mOldPage
&& $this->mOldRev
->getPrevious() ) {
566 $prevlink = Linker
::linkKnown(
568 $this->msg( 'previousdiff' )->escaped(),
569 [ 'id' => 'differences-prevlink' ],
570 [ 'diff' => 'prev', 'oldid' => $this->mOldid
] +
$query
573 $prevlink = "\u{00A0}";
576 if ( $this->mOldRev
->isMinor() ) {
577 $oldminor = ChangesList
::flag( 'minor' );
582 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
583 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev
, 'complete' );
584 $oldChangeTags = ChangeTags
::formatSummaryRow( $this->mOldTags
, 'diff', $this->getContext() );
586 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
587 '<div id="mw-diff-otitle2">' .
588 Linker
::revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
589 '<div id="mw-diff-otitle3">' . $oldminor .
590 Linker
::revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
591 '<div id="mw-diff-otitle5">' . $oldChangeTags[0] . '</div>' .
592 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
594 // Allow extensions to change the $oldHeader variable
595 Hooks
::run( 'DifferenceEngineOldHeader', [ $this, &$oldHeader, $prevlink, $oldminor,
596 $diffOnly, $ldel, $this->unhide
] );
598 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
599 $deleted = true; // old revisions text is hidden
600 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
601 $suppressed = true; // also suppressed
605 # Check if this user can see the revisions
606 if ( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $user ) ) {
611 $out->addJsConfigVars( [
612 'wgDiffOldId' => $this->mOldid
,
613 'wgDiffNewId' => $this->mNewid
,
616 # Make "next revision link"
617 # Skip next link on the top revision
618 if ( $samePage && $this->mNewPage
&& !$this->mNewRev
->isCurrent() ) {
619 $nextlink = Linker
::linkKnown(
621 $this->msg( 'nextdiff' )->escaped(),
622 [ 'id' => 'differences-nextlink' ],
623 [ 'diff' => 'next', 'oldid' => $this->mNewid
] +
$query
626 $nextlink = "\u{00A0}";
629 if ( $this->mNewRev
->isMinor() ) {
630 $newminor = ChangesList
::flag( 'minor' );
635 # Handle RevisionDelete links...
636 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
638 # Allow extensions to define their own revision tools
639 Hooks
::run( 'DiffRevisionTools',
640 [ $this->mNewRev
, &$revisionTools, $this->mOldRev
, $user ] );
641 $formattedRevisionTools = [];
642 // Put each one in parentheses (poor man's button)
643 foreach ( $revisionTools as $key => $tool ) {
644 $toolClass = is_string( $key ) ?
$key : 'mw-diff-tool';
645 $element = Html
::rawElement(
647 [ 'class' => $toolClass ],
648 $this->msg( 'parentheses' )->rawParams( $tool )->escaped()
650 $formattedRevisionTools[] = $element;
652 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev
, 'complete' ) .
653 ' ' . implode( ' ', $formattedRevisionTools );
654 $newChangeTags = ChangeTags
::formatSummaryRow( $this->mNewTags
, 'diff', $this->getContext() );
656 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
657 '<div id="mw-diff-ntitle2">' . Linker
::revUserTools( $this->mNewRev
, !$this->unhide
) .
659 '<div id="mw-diff-ntitle3">' . $newminor .
660 Linker
::revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
661 '<div id="mw-diff-ntitle5">' . $newChangeTags[0] . '</div>' .
662 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
664 // Allow extensions to change the $newHeader variable
665 Hooks
::run( 'DifferenceEngineNewHeader', [ $this, &$newHeader, $formattedRevisionTools,
666 $nextlink, $rollback, $newminor, $diffOnly, $rdel, $this->unhide
] );
668 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
669 $deleted = true; // new revisions text is hidden
670 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
671 $suppressed = true; // also suppressed
675 # If the diff cannot be shown due to a deleted revision, then output
676 # the diff header and links to unhide (if available)...
677 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
678 $this->showDiffStyle();
679 $multi = $this->getMultiNotice();
680 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
682 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
683 # Give explanation for why revision is not visible
684 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
687 # Give explanation and add a link to view the diff...
688 $query = $this->getRequest()->appendQueryValue( 'unhide', '1' );
689 $link = $this->getTitle()->getFullURL( $query );
690 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
692 "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
696 # Otherwise, output a regular diff...
698 # Add deletion notice if the user is viewing deleted content
701 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
702 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" .
703 $this->msg( $msg )->parse() .
706 $this->showDiff( $oldHeader, $newHeader, $notice );
708 $this->renderNewRevision();
714 * Build a link to mark a change as patrolled.
716 * Returns empty string if there's either no revision to patrol or the user is not allowed to.
717 * Side effect: When the patrol link is build, this method will call
718 * OutputPage::preventClickjacking() and load mediawiki.page.patrol.ajax.
720 * @return string HTML or empty string
722 public function markPatrolledLink() {
723 if ( $this->mMarkPatrolledLink
=== null ) {
724 $linkInfo = $this->getMarkPatrolledLinkInfo();
725 // If false, there is no patrol link needed/allowed
726 if ( !$linkInfo ||
!$this->mNewPage
) {
727 $this->mMarkPatrolledLink
= '';
729 $this->mMarkPatrolledLink
= ' <span class="patrollink" data-mw="interface">[' .
732 $this->msg( 'markaspatrolleddiff' )->escaped(),
735 'action' => 'markpatrolled',
736 'rcid' => $linkInfo['rcid'],
739 // Allow extensions to change the markpatrolled link
740 Hooks
::run( 'DifferenceEngineMarkPatrolledLink', [ $this,
741 &$this->mMarkPatrolledLink
, $linkInfo['rcid'] ] );
744 return $this->mMarkPatrolledLink
;
748 * Returns an array of meta data needed to build a "mark as patrolled" link and
749 * adds the mediawiki.page.patrol.ajax to the output.
751 * @return array|false An array of meta data for a patrol link (rcid only)
752 * or false if no link is needed
754 protected function getMarkPatrolledLinkInfo() {
755 global $wgUseRCPatrol;
757 $user = $this->getUser();
759 // Prepare a change patrol link, if applicable
761 // Is patrolling enabled and the user allowed to?
762 $wgUseRCPatrol && $this->mNewPage
&& $this->mNewPage
->quickUserCan( 'patrol', $user ) &&
763 // Only do this if the revision isn't more than 6 hours older
764 // than the Max RC age (6h because the RC might not be cleaned out regularly)
765 RecentChange
::isInRCLifespan( $this->mNewRev
->getTimestamp(), 21600 )
767 // Look for an unpatrolled change corresponding to this diff
768 $db = wfGetDB( DB_REPLICA
);
769 $change = RecentChange
::newFromConds(
771 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
772 'rc_this_oldid' => $this->mNewid
,
773 'rc_patrolled' => RecentChange
::PRC_UNPATROLLED
778 if ( $change && !$change->getPerformer()->equals( $user ) ) {
779 $rcid = $change->getAttribute( 'rc_id' );
781 // None found or the page has been created by the current user.
782 // If the user could patrol this it already would be patrolled
786 // Allow extensions to possibly change the rcid here
787 // For example the rcid might be set to zero due to the user
788 // being the same as the performer of the change but an extension
789 // might still want to show it under certain conditions
790 Hooks
::run( 'DifferenceEngineMarkPatrolledRCID', [ &$rcid, $this, $change, $user ] );
794 $this->getOutput()->preventClickjacking();
795 if ( $user->isAllowed( 'writeapi' ) ) {
796 $this->getOutput()->addModules( 'mediawiki.page.patrol.ajax' );
805 // No mark as patrolled link applicable
810 * @param Revision $rev
814 protected function revisionDeleteLink( $rev ) {
815 $link = Linker
::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
816 if ( $link !== '' ) {
817 $link = "\u{00A0}\u{00A0}\u{00A0}" . $link . ' ';
824 * Show the new revision of the page.
826 * @note Not supported after calling setContent().
828 public function renderNewRevision() {
829 if ( $this->isContentOverridden
) {
830 // The code below only works with a Revision object. We could construct a fake revision
831 // (here or in setContent), but since this does not seem needed at the moment,
832 // we'll just fail for now.
833 throw new LogicException(
835 . ' is not supported after calling setContent(). Use setRevisions() instead.'
839 $out = $this->getOutput();
840 $revHeader = $this->getRevisionHeader( $this->mNewRev
);
841 # Add "current version as of X" title
842 $out->addHTML( "<hr class='diff-hr' id='mw-oldid' />
843 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
844 # Page content may be handled by a hooked call instead...
845 if ( Hooks
::run( 'ArticleContentOnDiff', [ $this, $out ] ) ) {
846 $this->loadNewText();
847 if ( !$this->mNewPage
) {
848 // New revision is unsaved; bail out.
849 // TODO in theory rendering the new revision is a meaningful thing to do
850 // even if it's unsaved, but a lot of untangling is required to do it safely.
853 $out->setRevisionId( $this->mNewid
);
854 $out->setRevisionTimestamp( $this->mNewRev
->getTimestamp() );
855 $out->setArticleFlag( true );
857 if ( !Hooks
::run( 'ArticleRevisionViewCustom',
858 [ $this->mNewRev
->getRevisionRecord(), $this->mNewPage
, $out ] )
860 // Handled by extension
861 // NOTE: sync with hooks called in Article::view()
862 } elseif ( !Hooks
::run( 'ArticleContentViewCustom',
863 [ $this->mNewContent
, $this->mNewPage
, $out ], '1.32' )
865 // Handled by extension
866 // NOTE: sync with hooks called in Article::view()
869 if ( $this->getTitle()->equals( $this->mNewPage
) ) {
870 // If the Title stored in the context is the same as the one
871 // of the new revision, we can use its associated WikiPage
873 $wikiPage = $this->getWikiPage();
875 // Otherwise we need to create our own WikiPage object
876 $wikiPage = WikiPage
::factory( $this->mNewPage
);
879 $parserOutput = $this->getParserOutput( $wikiPage, $this->mNewRev
);
881 # WikiPage::getParserOutput() should not return false, but just in case
882 if ( $parserOutput ) {
883 // Allow extensions to change parser output here
884 if ( Hooks
::run( 'DifferenceEngineRenderRevisionAddParserOutput',
885 [ $this, $out, $parserOutput, $wikiPage ] )
887 $out->addParserOutput( $parserOutput, [
888 'enableSectionEditLinks' => $this->mNewRev
->isCurrent()
889 && $this->mNewRev
->getTitle()->quickUserCan( 'edit', $this->getUser() ),
896 // Allow extensions to optionally not show the final patrolled link
897 if ( Hooks
::run( 'DifferenceEngineRenderRevisionShowFinalPatrolLink' ) ) {
898 # Add redundant patrol link on bottom...
899 $out->addHTML( $this->markPatrolledLink() );
904 * @param WikiPage $page
905 * @param Revision $rev
907 * @return ParserOutput|bool False if the revision was not found
909 protected function getParserOutput( WikiPage
$page, Revision
$rev ) {
910 if ( !$rev->getId() ) {
911 // WikiPage::getParserOutput wants a revision ID. Passing 0 will incorrectly show
912 // the current revision, so fail instead. If need be, WikiPage::getParserOutput
913 // could be made to accept a Revision or RevisionRecord instead of the id.
917 $parserOptions = $page->makeParserOptions( $this->getContext() );
918 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
920 return $parserOutput;
924 * Get the diff text, send it to the OutputPage object
925 * Returns false if the diff could not be generated, otherwise returns true
927 * @param string|bool $otitle Header for old text or false
928 * @param string|bool $ntitle Header for new text or false
929 * @param string $notice HTML between diff header and body
933 public function showDiff( $otitle, $ntitle, $notice = '' ) {
934 // Allow extensions to affect the output here
935 Hooks
::run( 'DifferenceEngineShowDiff', [ $this ] );
937 $diff = $this->getDiff( $otitle, $ntitle, $notice );
938 if ( $diff === false ) {
939 $this->showMissingRevision();
943 $this->showDiffStyle();
944 $this->getOutput()->addHTML( $diff );
951 * Add style sheets for diff display.
953 public function showDiffStyle() {
954 if ( !$this->isSlotDiffRenderer
) {
955 $this->getOutput()->addModuleStyles( 'mediawiki.diff.styles' );
956 foreach ( $this->getSlotDiffRenderers() as $slotDiffRenderer ) {
957 $slotDiffRenderer->addModules( $this->getOutput() );
963 * Get complete diff table, including header
965 * @param string|bool $otitle Header for old text or false
966 * @param string|bool $ntitle Header for new text or false
967 * @param string $notice HTML between diff header and body
971 public function getDiff( $otitle, $ntitle, $notice = '' ) {
972 $body = $this->getDiffBody();
973 if ( $body === false ) {
977 $multi = $this->getMultiNotice();
978 // Display a message when the diff is empty
979 if ( $body === '' ) {
980 $notice .= '<div class="mw-diff-empty">' .
981 $this->msg( 'diff-empty' )->parse() .
985 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
989 * Get the diff table body, without header
991 * @return mixed (string/false)
993 public function getDiffBody() {
994 $this->mCacheHit
= true;
995 // Check if the diff should be hidden from this user
996 if ( !$this->isContentOverridden
) {
997 if ( !$this->loadRevisionData() ) {
999 } elseif ( $this->mOldRev
&&
1000 !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
1003 } elseif ( $this->mNewRev
&&
1004 !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
1009 if ( $this->mOldRev
=== false ||
( $this->mOldRev
&& $this->mNewRev
&&
1010 $this->mOldRev
->getId() && $this->mOldRev
->getId() == $this->mNewRev
->getId() )
1012 if ( Hooks
::run( 'DifferenceEngineShowEmptyOldContent', [ $this ] ) ) {
1020 $cache = ObjectCache
::getMainWANInstance();
1021 if ( $this->mOldid
&& $this->mNewid
) {
1022 // Check if subclass is still using the old way
1023 // for backwards-compatibility
1024 $key = $this->getDiffBodyCacheKey();
1025 if ( $key === null ) {
1026 $key = $cache->makeKey( ...$this->getDiffBodyCacheKeyParams() );
1030 if ( !$this->mRefreshCache
) {
1031 $difftext = $cache->get( $key );
1033 wfIncrStats( 'diff_cache.hit' );
1034 $difftext = $this->localiseDiff( $difftext );
1035 $difftext .= "\n<!-- diff cache key $key -->\n";
1039 } // don't try to load but save the result
1041 $this->mCacheHit
= false;
1043 // Loadtext is permission safe, this just clears out the diff
1044 if ( !$this->loadText() ) {
1049 // We've checked for revdelete at the beginning of this method; it's OK to ignore
1050 // read permissions here.
1051 $slotContents = $this->getSlotContents();
1052 foreach ( $this->getSlotDiffRenderers() as $role => $slotDiffRenderer ) {
1053 $slotDiff = $slotDiffRenderer->getDiff( $slotContents[$role]['old'],
1054 $slotContents[$role]['new'] );
1055 if ( $slotDiff && $role !== 'main' ) {
1056 // TODO use human-readable role name at least
1058 $difftext .= $this->getSlotHeader( $slotTitle );
1060 $difftext .= $slotDiff;
1063 // Avoid PHP 7.1 warning from passing $this by reference
1064 $diffEngine = $this;
1066 // Save to cache for 7 days
1067 if ( !Hooks
::run( 'AbortDiffCache', [ &$diffEngine ] ) ) {
1068 wfIncrStats( 'diff_cache.uncacheable' );
1069 } elseif ( $key !== false && $difftext !== false ) {
1070 wfIncrStats( 'diff_cache.miss' );
1071 $cache->set( $key, $difftext, 7 * 86400 );
1073 wfIncrStats( 'diff_cache.uncacheable' );
1075 // localise line numbers and title attribute text
1076 if ( $difftext !== false ) {
1077 $difftext = $this->localiseDiff( $difftext );
1084 * Get the diff table body for one slot, without header
1086 * @param string $role
1087 * @return string|false
1089 public function getDiffBodyForRole( $role ) {
1090 $diffRenderers = $this->getSlotDiffRenderers();
1091 if ( !isset( $diffRenderers[$role] ) ) {
1095 $slotContents = $this->getSlotContents();
1096 $slotDiff = $diffRenderers[$role]->getDiff( $slotContents[$role]['old'],
1097 $slotContents[$role]['new'] );
1102 if ( $role !== 'main' ) {
1103 // TODO use human-readable role name at least
1105 $slotDiff = $this->getSlotHeader( $slotTitle ) . $slotDiff;
1108 return $this->localiseDiff( $slotDiff );
1112 * Get a slot header for inclusion in a diff body (as a table row).
1114 * @param string $headerText The text of the header
1118 protected function getSlotHeader( $headerText ) {
1119 // The old revision is missing on oldid=<first>&diff=prev; only 2 columns in that case.
1120 $columnCount = $this->mOldRev ?
4 : 2;
1121 $userLang = $this->getLanguage()->getHtmlCode();
1122 return Html
::rawElement( 'tr', [ 'class' => 'mw-diff-slot-header', 'lang' => $userLang ],
1123 Html
::element( 'th', [ 'colspan' => $columnCount ], $headerText ) );
1127 * Returns the cache key for diff body text or content.
1129 * @deprecated since 1.31, use getDiffBodyCacheKeyParams() instead
1132 * @throws MWException
1133 * @return string|null
1135 protected function getDiffBodyCacheKey() {
1140 * Get the cache key parameters
1142 * Subclasses can replace the first element in the array to something
1143 * more specific to the type of diff (e.g. "inline-diff"), or append
1144 * if the cache should vary on more things. Overriding entirely should
1150 * @throws MWException
1152 protected function getDiffBodyCacheKeyParams() {
1153 if ( !$this->mOldid ||
!$this->mNewid
) {
1154 throw new MWException( 'mOldid and mNewid must be set to get diff cache key.' );
1157 $engine = $this->getEngine();
1162 "old-{$this->mOldid}",
1163 "rev-{$this->mNewid}"
1166 if ( $engine === 'wikidiff2' ) {
1167 $params[] = phpversion( 'wikidiff2' );
1168 $params[] = $this->getConfig()->get( 'WikiDiff2MovedParagraphDetectionCutoff' );
1171 if ( !$this->isSlotDiffRenderer
) {
1172 foreach ( $this->getSlotDiffRenderers() as $slotDiffRenderer ) {
1173 $params = array_merge( $params, $slotDiffRenderer->getExtraCacheKeys() );
1181 * Implements DifferenceEngineSlotDiffRenderer::getExtraCacheKeys(). Only used when
1182 * DifferenceEngine is wrapped in DifferenceEngineSlotDiffRenderer.
1184 * @internal for use by DifferenceEngineSlotDiffRenderer only
1187 public function getExtraCacheKeys() {
1188 // This method is called when the DifferenceEngine is used for a slot diff. We only care
1189 // about special things, not the revision IDs, which are added to the cache key by the
1190 // page-level DifferenceEngine, and which might not have a valid value for this object.
1191 $this->mOldid
= 123456789;
1192 $this->mNewid
= 987654321;
1194 // This will repeat a bunch of unnecessary key fields for each slot. Not nice but harmless.
1195 $cacheString = $this->getDiffBodyCacheKey();
1196 if ( $cacheString ) {
1197 return [ $cacheString ];
1200 $params = $this->getDiffBodyCacheKeyParams();
1202 // Try to get rid of the standard keys to keep the cache key human-readable:
1203 // call the getDiffBodyCacheKeyParams implementation of the base class, and if
1204 // the child class includes the same keys, drop them.
1205 // Uses an obscure PHP feature where static calls to non-static methods are allowed
1206 // as long as we are already in a non-static method of the same class, and the call context
1207 // ($this) will be inherited.
1208 // phpcs:ignore Squiz.Classes.SelfMemberReference.NotUsed
1209 $standardParams = DifferenceEngine
::getDiffBodyCacheKeyParams();
1210 if ( array_slice( $params, 0, count( $standardParams ) ) === $standardParams ) {
1211 $params = array_slice( $params, count( $standardParams ) );
1218 * Generate a diff, no caching.
1222 * @param Content $old Old content
1223 * @param Content $new New content
1225 * @throws Exception If old or new content is not an instance of TextContent.
1226 * @return bool|string
1228 * @deprecated since 1.32, use a SlotDiffRenderer instead.
1230 public function generateContentDiffBody( Content
$old, Content
$new ) {
1231 $slotDiffRenderer = $new->getContentHandler()->getSlotDiffRenderer( $this->getContext() );
1233 $slotDiffRenderer instanceof DifferenceEngineSlotDiffRenderer
1234 && $this->isSlotDiffRenderer
1236 // Oops, we are just about to enter an infinite loop (the slot-level DifferenceEngine
1237 // called a DifferenceEngineSlotDiffRenderer that wraps the same DifferenceEngine class).
1238 // This will happen when a content model has no custom slot diff renderer, it does have
1239 // a custom difference engine, but that does not override this method.
1240 throw new Exception( get_class( $this ) . ': could not maintain backwards compatibility. '
1241 . 'Please use a SlotDiffRenderer.' );
1243 return $slotDiffRenderer->getDiff( $old, $new ) . $this->getDebugString();
1247 * Generate a diff, no caching
1249 * @param string $otext Old text, must be already segmented
1250 * @param string $ntext New text, must be already segmented
1252 * @throws Exception If content handling for text content is configured in a way
1253 * that makes maintaining B/C hard.
1254 * @return bool|string
1256 * @deprecated since 1.32, use a TextSlotDiffRenderer instead.
1258 public function generateTextDiffBody( $otext, $ntext ) {
1259 $slotDiffRenderer = ContentHandler
::getForModelID( CONTENT_MODEL_TEXT
)
1260 ->getSlotDiffRenderer( $this->getContext() );
1261 if ( !( $slotDiffRenderer instanceof TextSlotDiffRenderer
) ) {
1262 // Someone used the GetSlotDiffRenderer hook to replace the renderer.
1263 // This is too unlikely to happen to bother handling properly.
1264 throw new Exception( 'The slot diff renderer for text content should be a '
1265 . 'TextSlotDiffRenderer subclass' );
1267 return $slotDiffRenderer->getTextDiff( $otext, $ntext ) . $this->getDebugString();
1271 * Process $wgExternalDiffEngine and get a sane, usable engine
1273 * @return bool|string 'wikidiff2', path to an executable, or false
1274 * @internal For use by this class and TextSlotDiffRenderer only.
1276 public static function getEngine() {
1277 global $wgExternalDiffEngine;
1278 // We use the global here instead of Config because we write to the value,
1279 // and Config is not mutable.
1280 if ( $wgExternalDiffEngine == 'wikidiff' ||
$wgExternalDiffEngine == 'wikidiff3' ) {
1281 wfDeprecated( "\$wgExternalDiffEngine = '{$wgExternalDiffEngine}'", '1.27' );
1282 $wgExternalDiffEngine = false;
1283 } elseif ( $wgExternalDiffEngine == 'wikidiff2' ) {
1284 wfDeprecated( "\$wgExternalDiffEngine = '{$wgExternalDiffEngine}'", '1.32' );
1285 $wgExternalDiffEngine = false;
1286 } elseif ( !is_string( $wgExternalDiffEngine ) && $wgExternalDiffEngine !== false ) {
1287 // And prevent people from shooting themselves in the foot...
1288 wfWarn( '$wgExternalDiffEngine is set to a non-string value, forcing it to false' );
1289 $wgExternalDiffEngine = false;
1292 if ( is_string( $wgExternalDiffEngine ) && is_executable( $wgExternalDiffEngine ) ) {
1293 return $wgExternalDiffEngine;
1294 } elseif ( $wgExternalDiffEngine === false && function_exists( 'wikidiff2_do_diff' ) ) {
1303 * Generates diff, to be wrapped internally in a logging/instrumentation
1305 * @param string $otext Old text, must be already segmented
1306 * @param string $ntext New text, must be already segmented
1308 * @throws Exception If content handling for text content is configured in a way
1309 * that makes maintaining B/C hard.
1310 * @return bool|string
1312 * @deprecated since 1.32, use a TextSlotDiffRenderer instead.
1314 protected function textDiff( $otext, $ntext ) {
1315 $slotDiffRenderer = ContentHandler
::getForModelID( CONTENT_MODEL_TEXT
)
1316 ->getSlotDiffRenderer( $this->getContext() );
1317 if ( !( $slotDiffRenderer instanceof TextSlotDiffRenderer
) ) {
1318 // Someone used the GetSlotDiffRenderer hook to replace the renderer.
1319 // This is too unlikely to happen to bother handling properly.
1320 throw new Exception( 'The slot diff renderer for text content should be a '
1321 . 'TextSlotDiffRenderer subclass' );
1323 return $slotDiffRenderer->getTextDiff( $otext, $ntext ) . $this->getDebugString();
1327 * Generate a debug comment indicating diff generating time,
1328 * server node, and generator backend.
1330 * @param string $generator : What diff engine was used
1334 protected function debug( $generator = "internal" ) {
1335 global $wgShowHostnames;
1336 if ( !$this->enableDebugComment
) {
1339 $data = [ $generator ];
1340 if ( $wgShowHostnames ) {
1341 $data[] = wfHostname();
1343 $data[] = wfTimestamp( TS_DB
);
1345 return "<!-- diff generator: " .
1346 implode( " ", array_map( "htmlspecialchars", $data ) ) .
1350 private function getDebugString() {
1351 $engine = self
::getEngine();
1352 if ( $engine === 'wikidiff2' ) {
1353 return $this->debug( 'wikidiff2' );
1354 } elseif ( $engine === false ) {
1355 return $this->debug( 'native PHP' );
1357 return $this->debug( "external $engine" );
1362 * Localise diff output
1364 * @param string $text
1367 private function localiseDiff( $text ) {
1368 $text = $this->localiseLineNumbers( $text );
1369 if ( $this->getEngine() === 'wikidiff2' &&
1370 version_compare( phpversion( 'wikidiff2' ), '1.5.1', '>=' )
1372 $text = $this->addLocalisedTitleTooltips( $text );
1378 * Replace line numbers with the text in the user's language
1380 * @param string $text
1384 public function localiseLineNumbers( $text ) {
1385 return preg_replace_callback(
1386 '/<!--LINE (\d+)-->/',
1387 [ $this, 'localiseLineNumbersCb' ],
1392 public function localiseLineNumbersCb( $matches ) {
1393 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) {
1397 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
1401 * Add title attributes for tooltips on moved paragraph indicators
1403 * @param string $text
1406 private function addLocalisedTitleTooltips( $text ) {
1407 return preg_replace_callback(
1408 '/class="mw-diff-movedpara-(left|right)"/',
1409 [ $this, 'addLocalisedTitleTooltipsCb' ],
1415 * @param array $matches
1418 private function addLocalisedTitleTooltipsCb( array $matches ) {
1419 $key = $matches[1] === 'right' ?
1420 'diff-paragraph-moved-toold' :
1421 'diff-paragraph-moved-tonew';
1422 return $matches[0] . ' title="' . $this->msg( $key )->escaped() . '"';
1426 * If there are revisions between the ones being compared, return a note saying so.
1430 public function getMultiNotice() {
1431 // The notice only make sense if we are diffing two saved revisions of the same page.
1433 !$this->mOldRev ||
!$this->mNewRev
1434 ||
!$this->mOldPage ||
!$this->mNewPage
1435 ||
!$this->mOldPage
->equals( $this->mNewPage
)
1440 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
1441 $oldRev = $this->mNewRev
; // flip
1442 $newRev = $this->mOldRev
; // flip
1443 } else { // normal case
1444 $oldRev = $this->mOldRev
;
1445 $newRev = $this->mNewRev
;
1448 // Sanity: don't show the notice if too many rows must be scanned
1449 // @todo show some special message for that case
1450 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev, 1000 );
1451 if ( $nEdits > 0 && $nEdits <= 1000 ) {
1452 $limit = 100; // use diff-multi-manyusers if too many users
1453 $users = $this->mNewPage
->getAuthorsBetween( $oldRev, $newRev, $limit );
1454 $numUsers = count( $users );
1456 if ( $numUsers == 1 && $users[0] == $newRev->getUserText( Revision
::RAW
) ) {
1457 $numUsers = 0; // special case to say "by the same user" instead of "by one other user"
1460 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
1463 return ''; // nothing
1467 * Get a notice about how many intermediate edits and users there are
1469 * @param int $numEdits
1470 * @param int $numUsers
1475 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
1476 if ( $numUsers === 0 ) {
1477 $msg = 'diff-multi-sameuser';
1478 } elseif ( $numUsers > $limit ) {
1479 $msg = 'diff-multi-manyusers';
1482 $msg = 'diff-multi-otherusers';
1485 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
1489 * Get a header for a specified revision.
1491 * @param Revision $rev
1492 * @param string $complete 'complete' to get the header wrapped depending
1493 * the visibility of the revision and a link to edit the page.
1495 * @return string HTML fragment
1497 public function getRevisionHeader( Revision
$rev, $complete = '' ) {
1498 $lang = $this->getLanguage();
1499 $user = $this->getUser();
1500 $revtimestamp = $rev->getTimestamp();
1501 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
1502 $dateofrev = $lang->userDate( $revtimestamp, $user );
1503 $timeofrev = $lang->userTime( $revtimestamp, $user );
1505 $header = $this->msg(
1506 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
1512 if ( $complete !== 'complete' ) {
1516 $title = $rev->getTitle();
1518 $header = Linker
::linkKnown( $title, $header, [],
1519 [ 'oldid' => $rev->getId() ] );
1521 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
1522 $editQuery = [ 'action' => 'edit' ];
1523 if ( !$rev->isCurrent() ) {
1524 $editQuery['oldid'] = $rev->getId();
1527 $key = $title->quickUserCan( 'edit', $user ) ?
'editold' : 'viewsourceold';
1528 $msg = $this->msg( $key )->escaped();
1529 $editLink = $this->msg( 'parentheses' )->rawParams(
1530 Linker
::linkKnown( $title, $msg, [], $editQuery ) )->escaped();
1531 $header .= ' ' . Html
::rawElement(
1533 [ 'class' => 'mw-diff-edit' ],
1536 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
1537 $header = Html
::rawElement(
1539 [ 'class' => 'history-deleted' ],
1544 $header = Html
::rawElement( 'span', [ 'class' => 'history-deleted' ], $header );
1551 * Add the header to a diff body
1553 * @param string $diff Diff body
1554 * @param string $otitle Old revision header
1555 * @param string $ntitle New revision header
1556 * @param string $multi Notice telling user that there are intermediate
1557 * revisions between the ones being compared
1558 * @param string $notice Other notices, e.g. that user is viewing deleted content
1562 public function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
1563 // shared.css sets diff in interface language/dir, but the actual content
1564 // is often in a different language, mostly the page content language/dir
1565 $header = Html
::openElement( 'table', [
1566 'class' => [ 'diff', 'diff-contentalign-' . $this->getDiffLang()->alignStart() ],
1567 'data-mw' => 'interface',
1569 $userLang = htmlspecialchars( $this->getLanguage()->getHtmlCode() );
1571 if ( !$diff && !$otitle ) {
1573 <tr class=\"diff-title\" lang=\"{$userLang}\">
1574 <td class=\"diff-ntitle\">{$ntitle}</td>
1578 if ( $diff ) { // Safari/Chrome show broken output if cols not used
1580 <col class=\"diff-marker\" />
1581 <col class=\"diff-content\" />
1582 <col class=\"diff-marker\" />
1583 <col class=\"diff-content\" />";
1590 if ( $otitle ||
$ntitle ) {
1592 <tr class=\"diff-title\" lang=\"{$userLang}\">
1593 <td colspan=\"$colspan\" class=\"diff-otitle\">{$otitle}</td>
1594 <td colspan=\"$colspan\" class=\"diff-ntitle\">{$ntitle}</td>
1599 if ( $multi != '' ) {
1600 $header .= "<tr><td colspan=\"{$multiColspan}\" " .
1601 "class=\"diff-multi\" lang=\"{$userLang}\">{$multi}</td></tr>";
1603 if ( $notice != '' ) {
1604 $header .= "<tr><td colspan=\"{$multiColspan}\" " .
1605 "class=\"diff-notice\" lang=\"{$userLang}\">{$notice}</td></tr>";
1608 return $header . $diff . "</table>";
1612 * Use specified text instead of loading from the database
1613 * @param Content $oldContent
1614 * @param Content $newContent
1616 * @deprecated since 1.32, use setRevisions or ContentHandler::getSlotDiffRenderer.
1618 public function setContent( Content
$oldContent, Content
$newContent ) {
1619 $this->mOldContent
= $oldContent;
1620 $this->mNewContent
= $newContent;
1622 $this->mTextLoaded
= 2;
1623 $this->mRevisionsLoaded
= true;
1624 $this->isContentOverridden
= true;
1625 $this->slotDiffRenderers
= null;
1629 * Use specified text instead of loading from the database.
1630 * @param RevisionRecord|null $oldRevision
1631 * @param RevisionRecord $newRevision
1633 public function setRevisions(
1634 RevisionRecord
$oldRevision = null, RevisionRecord
$newRevision
1636 if ( $oldRevision ) {
1637 $this->mOldRev
= new Revision( $oldRevision );
1638 $this->mOldid
= $oldRevision->getId();
1639 $this->mOldPage
= Title
::newFromLinkTarget( $oldRevision->getPageAsLinkTarget() );
1640 // This method is meant for edit diffs and such so there is no reason to provide a
1641 // revision that's not readable to the user, but check it just in case.
1642 $this->mOldContent
= $oldRevision ?
$oldRevision->getContent( 'main',
1643 RevisionRecord
::FOR_THIS_USER
, $this->getUser() ) : null;
1645 $this->mOldPage
= null;
1646 $this->mOldRev
= $this->mOldid
= false;
1648 $this->mNewRev
= new Revision( $newRevision );
1649 $this->mNewid
= $newRevision->getId();
1650 $this->mNewPage
= Title
::newFromLinkTarget( $newRevision->getPageAsLinkTarget() );
1651 $this->mNewContent
= $newRevision->getContent( 'main',
1652 RevisionRecord
::FOR_THIS_USER
, $this->getUser() );
1654 $this->mRevisionsIdsLoaded
= $this->mRevisionsLoaded
= true;
1655 $this->mTextLoaded
= !!$oldRevision +
1;
1656 $this->isContentOverridden
= false;
1657 $this->slotDiffRenderers
= null;
1661 * Set the language in which the diff text is written
1663 * @param Language $lang
1666 public function setTextLanguage( $lang ) {
1667 if ( !$lang instanceof Language
) {
1668 wfDeprecated( __METHOD__
. ' with other type than Language for $lang', '1.32' );
1670 $this->mDiffLang
= wfGetLangObj( $lang );
1674 * Maps a revision pair definition as accepted by DifferenceEngine constructor
1675 * to a pair of actual integers representing revision ids.
1677 * @param int $old Revision id, e.g. from URL parameter 'oldid'
1678 * @param int|string $new Revision id or strings 'next' or 'prev', e.g. from URL parameter 'diff'
1680 * @return array List of two revision ids, older first, later second.
1681 * Zero signifies invalid argument passed.
1682 * false signifies that there is no previous/next revision ($old is the oldest/newest one).
1684 public function mapDiffPrevNext( $old, $new ) {
1685 if ( $new === 'prev' ) {
1686 // Show diff between revision $old and the previous one. Get previous one from DB.
1687 $newid = intval( $old );
1688 $oldid = $this->getTitle()->getPreviousRevisionID( $newid );
1689 } elseif ( $new === 'next' ) {
1690 // Show diff between revision $old and the next one. Get next one from DB.
1691 $oldid = intval( $old );
1692 $newid = $this->getTitle()->getNextRevisionID( $oldid );
1694 $oldid = intval( $old );
1695 $newid = intval( $new );
1698 return [ $oldid, $newid ];
1704 private function loadRevisionIds() {
1705 if ( $this->mRevisionsIdsLoaded
) {
1709 $this->mRevisionsIdsLoaded
= true;
1711 $old = $this->mOldid
;
1712 $new = $this->mNewid
;
1714 list( $this->mOldid
, $this->mNewid
) = self
::mapDiffPrevNext( $old, $new );
1715 if ( $new === 'next' && $this->mNewid
=== false ) {
1716 # if no result, NewId points to the newest old revision. The only newer
1717 # revision is cur, which is "0".
1722 'NewDifferenceEngine',
1723 [ $this->getTitle(), &$this->mOldid
, &$this->mNewid
, $old, $new ]
1728 * Load revision metadata for the specified revisions. If newid is 0, then compare
1729 * the old revision in oldid to the current revision of the current page (as defined
1730 * by the request context); if oldid is 0, then compare the revision in newid to the
1731 * immediately previous one.
1733 * If oldid is false, leave the corresponding revision object set
1734 * to false. This can happen with 'diff=prev' pointing to a non-existent revision,
1735 * and is also used directly by the API.
1737 * @return bool Whether both revisions were loaded successfully. Setting mOldRev
1738 * to false counts as successful loading.
1740 public function loadRevisionData() {
1741 if ( $this->mRevisionsLoaded
) {
1742 return $this->isContentOverridden ||
$this->mNewRev
&& !is_null( $this->mOldRev
);
1745 // Whether it succeeds or fails, we don't want to try again
1746 $this->mRevisionsLoaded
= true;
1748 $this->loadRevisionIds();
1750 // Load the new revision object
1751 if ( $this->mNewid
) {
1752 $this->mNewRev
= Revision
::newFromId( $this->mNewid
);
1754 $this->mNewRev
= Revision
::newFromTitle(
1757 Revision
::READ_NORMAL
1761 if ( !$this->mNewRev
instanceof Revision
) {
1765 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1766 $this->mNewid
= $this->mNewRev
->getId();
1767 if ( $this->mNewid
) {
1768 $this->mNewPage
= $this->mNewRev
->getTitle();
1770 $this->mNewPage
= null;
1773 // Load the old revision object
1774 $this->mOldRev
= false;
1775 if ( $this->mOldid
) {
1776 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1777 } elseif ( $this->mOldid
=== 0 ) {
1778 $rev = $this->mNewRev
->getPrevious();
1780 $this->mOldid
= $rev->getId();
1781 $this->mOldRev
= $rev;
1783 // No previous revision; mark to show as first-version only.
1784 $this->mOldid
= false;
1785 $this->mOldRev
= false;
1787 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1789 if ( is_null( $this->mOldRev
) ) {
1793 if ( $this->mOldRev
&& $this->mOldRev
->getId() ) {
1794 $this->mOldPage
= $this->mOldRev
->getTitle();
1796 $this->mOldPage
= null;
1799 // Load tags information for both revisions
1800 $dbr = wfGetDB( DB_REPLICA
);
1801 if ( $this->mOldid
!== false ) {
1802 $this->mOldTags
= $dbr->selectField(
1805 [ 'ts_rev_id' => $this->mOldid
],
1809 $this->mOldTags
= false;
1811 $this->mNewTags
= $dbr->selectField(
1814 [ 'ts_rev_id' => $this->mNewid
],
1822 * Load the text of the revisions, as well as revision data.
1823 * When the old revision is missing (mOldRev is false), loading mOldContent is not attempted.
1825 * @return bool Whether the content of both revisions could be loaded successfully.
1826 * (When mOldRev is false, that still counts as a success.)
1829 public function loadText() {
1830 if ( $this->mTextLoaded
== 2 ) {
1831 return $this->loadRevisionData() && ( $this->mOldRev
=== false ||
$this->mOldContent
)
1832 && $this->mNewContent
;
1835 // Whether it succeeds or fails, we don't want to try again
1836 $this->mTextLoaded
= 2;
1838 if ( !$this->loadRevisionData() ) {
1842 if ( $this->mOldRev
) {
1843 $this->mOldContent
= $this->mOldRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1844 if ( $this->mOldContent
=== null ) {
1849 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1850 Hooks
::run( 'DifferenceEngineLoadTextAfterNewContentIsLoaded', [ $this ] );
1851 if ( $this->mNewContent
=== null ) {
1859 * Load the text of the new revision, not the old one
1861 * @return bool Whether the content of the new revision could be loaded successfully.
1863 public function loadNewText() {
1864 if ( $this->mTextLoaded
>= 1 ) {
1865 return $this->loadRevisionData();
1868 $this->mTextLoaded
= 1;
1870 if ( !$this->loadRevisionData() ) {
1874 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1876 Hooks
::run( 'DifferenceEngineAfterLoadNewText', [ $this ] );