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;
312 * Set reduced line numbers mode.
313 * When set, line X is not displayed when X is 1, for example to increase readability and
314 * conserve space with many small diffs.
317 public function setReducedLineNumbers( $value = true ) {
318 $this->mReducedLineNumbers
= $value;
322 * Get the language of the difference engine, defaults to page content language
326 public function getDiffLang() {
327 if ( $this->mDiffLang
=== null ) {
328 # Default language in which the diff text is written.
329 $this->mDiffLang
= $this->getTitle()->getPageLanguage();
332 return $this->mDiffLang
;
338 public function wasCacheHit() {
339 return $this->mCacheHit
;
343 * Get the ID of old revision (left pane) of the diff. 0 for the revision
344 * previous to getNewid(), false if the old revision does not exist, null
346 * To get a real revision ID instead of 0, call loadRevisionData() first.
347 * @return int|false|null
349 public function getOldid() {
350 $this->loadRevisionIds();
352 return $this->mOldid
;
356 * Get the ID of new revision (right pane) of the diff. 0 for the current revision,
357 * false if the new revision does not exist, null if it's unsaved.
358 * To get a real revision ID instead of 0, call loadRevisionData() first.
359 * @return int|false|null
361 public function getNewid() {
362 $this->loadRevisionIds();
364 return $this->mNewid
;
368 * Get the left side of the diff.
369 * Could be null when the first revision of the page is diffed to 'prev' (or in the case of
371 * @return RevisionRecord|null
373 public function getOldRevision() {
374 return $this->mOldRev ?
$this->mOldRev
->getRevisionRecord() : null;
378 * Get the right side of the diff.
379 * Should not be null but can still happen in the case of load failure.
380 * @return RevisionRecord|null
382 public function getNewRevision() {
383 return $this->mNewRev ?
$this->mNewRev
->getRevisionRecord() : null;
387 * Look up a special:Undelete link to the given deleted revision id,
388 * as a workaround for being unable to load deleted diffs in currently.
390 * @param int $id Revision ID
392 * @return string|bool Link HTML or false
394 public function deletedLink( $id ) {
395 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
396 $dbr = wfGetDB( DB_REPLICA
);
397 $arQuery = Revision
::getArchiveQueryInfo();
398 $row = $dbr->selectRow(
400 array_merge( $arQuery['fields'], [ 'ar_namespace', 'ar_title' ] ),
401 [ 'ar_rev_id' => $id ],
407 $rev = Revision
::newFromArchiveRow( $row );
408 $title = Title
::makeTitleSafe( $row->ar_namespace
, $row->ar_title
);
410 return SpecialPage
::getTitleFor( 'Undelete' )->getFullURL( [
411 'target' => $title->getPrefixedText(),
412 'timestamp' => $rev->getTimestamp()
421 * Build a wikitext link toward a deleted revision, if viewable.
423 * @param int $id Revision ID
425 * @return string Wikitext fragment
427 public function deletedIdMarker( $id ) {
428 $link = $this->deletedLink( $id );
430 return "[$link $id]";
436 private function showMissingRevision() {
437 $out = $this->getOutput();
440 if ( $this->mOldRev
=== null ||
441 ( $this->mOldRev
&& $this->mOldContent
=== null )
443 $missing[] = $this->deletedIdMarker( $this->mOldid
);
445 if ( $this->mNewRev
=== null ||
446 ( $this->mNewRev
&& $this->mNewContent
=== null )
448 $missing[] = $this->deletedIdMarker( $this->mNewid
);
451 $out->setPageTitle( $this->msg( 'errorpagetitle' ) );
452 $msg = $this->msg( 'difference-missing-revision' )
453 ->params( $this->getLanguage()->listToText( $missing ) )
454 ->numParams( count( $missing ) )
456 $out->addHTML( $msg );
459 public function showDiffPage( $diffOnly = false ) {
460 # Allow frames except in certain special cases
461 $out = $this->getOutput();
462 $out->allowClickjacking();
463 $out->setRobotPolicy( 'noindex,nofollow' );
465 // Allow extensions to add any extra output here
466 Hooks
::run( 'DifferenceEngineShowDiffPage', [ $out ] );
468 if ( !$this->loadRevisionData() ) {
469 if ( Hooks
::run( 'DifferenceEngineShowDiffPageMaybeShowMissingRevision', [ $this ] ) ) {
470 $this->showMissingRevision();
475 $user = $this->getUser();
477 if ( $this->mNewPage
) {
478 $permErrors = $this->mNewPage
->getUserPermissionsErrors( 'read', $user );
480 if ( $this->mOldPage
) {
481 $permErrors = wfMergeErrorArrays( $permErrors,
482 $this->mOldPage
->getUserPermissionsErrors( 'read', $user ) );
484 if ( count( $permErrors ) ) {
485 throw new PermissionsError( 'read', $permErrors );
491 # Carry over 'diffonly' param via navigation links
492 if ( $diffOnly != $user->getBoolOption( 'diffonly' ) ) {
493 $query['diffonly'] = $diffOnly;
495 # Cascade unhide param in links for easy deletion browsing
496 if ( $this->unhide
) {
497 $query['unhide'] = 1;
500 # Check if one of the revisions is deleted/suppressed
501 $deleted = $suppressed = false;
502 $allowed = $this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $user );
506 # mOldRev is false if the difference engine is called with a "vague" query for
507 # a diff between a version V and its previous version V' AND the version V
508 # is the first version of that article. In that case, V' does not exist.
509 if ( $this->mOldRev
=== false ) {
510 if ( $this->mNewPage
) {
511 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
515 // Allow extensions to change the $oldHeader variable
516 Hooks
::run( 'DifferenceEngineOldHeaderNoOldRev', [ &$oldHeader ] );
518 Hooks
::run( 'DiffViewHeader', [ $this, $this->mOldRev
, $this->mNewRev
] );
520 if ( !$this->mOldPage ||
!$this->mNewPage
) {
521 // XXX say something to the user?
523 } elseif ( $this->mNewPage
->equals( $this->mOldPage
) ) {
524 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
527 $out->setPageTitle( $this->msg( 'difference-title-multipage',
528 $this->mOldPage
->getPrefixedText(), $this->mNewPage
->getPrefixedText() ) );
529 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
533 if ( $samePage && $this->mNewPage
&& $this->mNewPage
->quickUserCan( 'edit', $user ) ) {
534 if ( $this->mNewRev
->isCurrent() && $this->mNewPage
->userCan( 'rollback', $user ) ) {
535 $rollbackLink = Linker
::generateRollback( $this->mNewRev
, $this->getContext() );
536 if ( $rollbackLink ) {
537 $out->preventClickjacking();
538 $rollback = "\u{00A0}\u{00A0}\u{00A0}" . $rollbackLink;
542 if ( !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) &&
543 !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
)
545 $undoLink = Html
::element( 'a', [
546 'href' => $this->mNewPage
->getLocalURL( [
548 'undoafter' => $this->mOldid
,
549 'undo' => $this->mNewid
551 'title' => Linker
::titleAttrib( 'undo' ),
553 $this->msg( 'editundo' )->text()
555 $revisionTools['mw-diff-undo'] = $undoLink;
559 # Make "previous revision link"
560 if ( $samePage && $this->mOldPage
&& $this->mOldRev
->getPrevious() ) {
561 $prevlink = Linker
::linkKnown(
563 $this->msg( 'previousdiff' )->escaped(),
564 [ 'id' => 'differences-prevlink' ],
565 [ 'diff' => 'prev', 'oldid' => $this->mOldid
] +
$query
568 $prevlink = "\u{00A0}";
571 if ( $this->mOldRev
->isMinor() ) {
572 $oldminor = ChangesList
::flag( 'minor' );
577 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
578 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev
, 'complete' );
579 $oldChangeTags = ChangeTags
::formatSummaryRow( $this->mOldTags
, 'diff', $this->getContext() );
581 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
582 '<div id="mw-diff-otitle2">' .
583 Linker
::revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
584 '<div id="mw-diff-otitle3">' . $oldminor .
585 Linker
::revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
586 '<div id="mw-diff-otitle5">' . $oldChangeTags[0] . '</div>' .
587 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
589 // Allow extensions to change the $oldHeader variable
590 Hooks
::run( 'DifferenceEngineOldHeader', [ $this, &$oldHeader, $prevlink, $oldminor,
591 $diffOnly, $ldel, $this->unhide
] );
593 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
594 $deleted = true; // old revisions text is hidden
595 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
596 $suppressed = true; // also suppressed
600 # Check if this user can see the revisions
601 if ( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $user ) ) {
606 $out->addJsConfigVars( [
607 'wgDiffOldId' => $this->mOldid
,
608 'wgDiffNewId' => $this->mNewid
,
611 # Make "next revision link"
612 # Skip next link on the top revision
613 if ( $samePage && $this->mNewPage
&& !$this->mNewRev
->isCurrent() ) {
614 $nextlink = Linker
::linkKnown(
616 $this->msg( 'nextdiff' )->escaped(),
617 [ 'id' => 'differences-nextlink' ],
618 [ 'diff' => 'next', 'oldid' => $this->mNewid
] +
$query
621 $nextlink = "\u{00A0}";
624 if ( $this->mNewRev
->isMinor() ) {
625 $newminor = ChangesList
::flag( 'minor' );
630 # Handle RevisionDelete links...
631 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
633 # Allow extensions to define their own revision tools
634 Hooks
::run( 'DiffRevisionTools',
635 [ $this->mNewRev
, &$revisionTools, $this->mOldRev
, $user ] );
636 $formattedRevisionTools = [];
637 // Put each one in parentheses (poor man's button)
638 foreach ( $revisionTools as $key => $tool ) {
639 $toolClass = is_string( $key ) ?
$key : 'mw-diff-tool';
640 $element = Html
::rawElement(
642 [ 'class' => $toolClass ],
643 $this->msg( 'parentheses' )->rawParams( $tool )->escaped()
645 $formattedRevisionTools[] = $element;
647 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev
, 'complete' ) .
648 ' ' . implode( ' ', $formattedRevisionTools );
649 $newChangeTags = ChangeTags
::formatSummaryRow( $this->mNewTags
, 'diff', $this->getContext() );
651 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
652 '<div id="mw-diff-ntitle2">' . Linker
::revUserTools( $this->mNewRev
, !$this->unhide
) .
654 '<div id="mw-diff-ntitle3">' . $newminor .
655 Linker
::revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
656 '<div id="mw-diff-ntitle5">' . $newChangeTags[0] . '</div>' .
657 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
659 // Allow extensions to change the $newHeader variable
660 Hooks
::run( 'DifferenceEngineNewHeader', [ $this, &$newHeader, $formattedRevisionTools,
661 $nextlink, $rollback, $newminor, $diffOnly, $rdel, $this->unhide
] );
663 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
664 $deleted = true; // new revisions text is hidden
665 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
666 $suppressed = true; // also suppressed
670 # If the diff cannot be shown due to a deleted revision, then output
671 # the diff header and links to unhide (if available)...
672 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
673 $this->showDiffStyle();
674 $multi = $this->getMultiNotice();
675 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
677 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
678 # Give explanation for why revision is not visible
679 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
682 # Give explanation and add a link to view the diff...
683 $query = $this->getRequest()->appendQueryValue( 'unhide', '1' );
684 $link = $this->getTitle()->getFullURL( $query );
685 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
687 "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
691 # Otherwise, output a regular diff...
693 # Add deletion notice if the user is viewing deleted content
696 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
697 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" .
698 $this->msg( $msg )->parse() .
701 $this->showDiff( $oldHeader, $newHeader, $notice );
703 $this->renderNewRevision();
709 * Build a link to mark a change as patrolled.
711 * Returns empty string if there's either no revision to patrol or the user is not allowed to.
712 * Side effect: When the patrol link is build, this method will call
713 * OutputPage::preventClickjacking() and load mediawiki.page.patrol.ajax.
715 * @return string HTML or empty string
717 public function markPatrolledLink() {
718 if ( $this->mMarkPatrolledLink
=== null ) {
719 $linkInfo = $this->getMarkPatrolledLinkInfo();
720 // If false, there is no patrol link needed/allowed
721 if ( !$linkInfo ||
!$this->mNewPage
) {
722 $this->mMarkPatrolledLink
= '';
724 $this->mMarkPatrolledLink
= ' <span class="patrollink" data-mw="interface">[' .
727 $this->msg( 'markaspatrolleddiff' )->escaped(),
730 'action' => 'markpatrolled',
731 'rcid' => $linkInfo['rcid'],
734 // Allow extensions to change the markpatrolled link
735 Hooks
::run( 'DifferenceEngineMarkPatrolledLink', [ $this,
736 &$this->mMarkPatrolledLink
, $linkInfo['rcid'] ] );
739 return $this->mMarkPatrolledLink
;
743 * Returns an array of meta data needed to build a "mark as patrolled" link and
744 * adds the mediawiki.page.patrol.ajax to the output.
746 * @return array|false An array of meta data for a patrol link (rcid only)
747 * or false if no link is needed
749 protected function getMarkPatrolledLinkInfo() {
750 global $wgUseRCPatrol;
752 $user = $this->getUser();
754 // Prepare a change patrol link, if applicable
756 // Is patrolling enabled and the user allowed to?
757 $wgUseRCPatrol && $this->mNewPage
&& $this->mNewPage
->quickUserCan( 'patrol', $user ) &&
758 // Only do this if the revision isn't more than 6 hours older
759 // than the Max RC age (6h because the RC might not be cleaned out regularly)
760 RecentChange
::isInRCLifespan( $this->mNewRev
->getTimestamp(), 21600 )
762 // Look for an unpatrolled change corresponding to this diff
763 $db = wfGetDB( DB_REPLICA
);
764 $change = RecentChange
::newFromConds(
766 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
767 'rc_this_oldid' => $this->mNewid
,
768 'rc_patrolled' => RecentChange
::PRC_UNPATROLLED
773 if ( $change && !$change->getPerformer()->equals( $user ) ) {
774 $rcid = $change->getAttribute( 'rc_id' );
776 // None found or the page has been created by the current user.
777 // If the user could patrol this it already would be patrolled
781 // Allow extensions to possibly change the rcid here
782 // For example the rcid might be set to zero due to the user
783 // being the same as the performer of the change but an extension
784 // might still want to show it under certain conditions
785 Hooks
::run( 'DifferenceEngineMarkPatrolledRCID', [ &$rcid, $this, $change, $user ] );
789 $this->getOutput()->preventClickjacking();
790 if ( $user->isAllowed( 'writeapi' ) ) {
791 $this->getOutput()->addModules( 'mediawiki.page.patrol.ajax' );
800 // No mark as patrolled link applicable
805 * @param Revision $rev
809 protected function revisionDeleteLink( $rev ) {
810 $link = Linker
::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
811 if ( $link !== '' ) {
812 $link = "\u{00A0}\u{00A0}\u{00A0}" . $link . ' ';
819 * Show the new revision of the page.
821 public function renderNewRevision() {
822 $out = $this->getOutput();
823 $revHeader = $this->getRevisionHeader( $this->mNewRev
);
824 # Add "current version as of X" title
825 $out->addHTML( "<hr class='diff-hr' id='mw-oldid' />
826 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
827 # Page content may be handled by a hooked call instead...
828 if ( Hooks
::run( 'ArticleContentOnDiff', [ $this, $out ] ) ) {
829 $this->loadNewText();
830 if ( !$this->mNewPage
) {
831 // New revision is unsaved; bail out.
832 // TODO in theory rendering the new revision is a meaningful thing to do
833 // even if it's unsaved, but a lot of untangling is required to do it safely.
836 $out->setRevisionId( $this->mNewid
);
837 $out->setRevisionTimestamp( $this->mNewRev
->getTimestamp() );
838 $out->setArticleFlag( true );
840 if ( !Hooks
::run( 'ArticleContentViewCustom',
841 [ $this->mNewContent
, $this->mNewPage
, $out ] )
843 // Handled by extension
846 if ( $this->getTitle()->equals( $this->mNewPage
) ) {
847 // If the Title stored in the context is the same as the one
848 // of the new revision, we can use its associated WikiPage
850 $wikiPage = $this->getWikiPage();
852 // Otherwise we need to create our own WikiPage object
853 $wikiPage = WikiPage
::factory( $this->mNewPage
);
856 $parserOutput = $this->getParserOutput( $wikiPage, $this->mNewRev
);
858 # WikiPage::getParserOutput() should not return false, but just in case
859 if ( $parserOutput ) {
860 // Allow extensions to change parser output here
861 if ( Hooks
::run( 'DifferenceEngineRenderRevisionAddParserOutput',
862 [ $this, $out, $parserOutput, $wikiPage ] )
864 $out->addParserOutput( $parserOutput, [
865 'enableSectionEditLinks' => $this->mNewRev
->isCurrent()
866 && $this->mNewRev
->getTitle()->quickUserCan( 'edit', $this->getUser() ),
873 // Allow extensions to optionally not show the final patrolled link
874 if ( Hooks
::run( 'DifferenceEngineRenderRevisionShowFinalPatrolLink' ) ) {
875 # Add redundant patrol link on bottom...
876 $out->addHTML( $this->markPatrolledLink() );
881 * @param WikiPage $page
882 * @param Revision $rev
884 * @return ParserOutput|bool False if the revision was not found
886 protected function getParserOutput( WikiPage
$page, Revision
$rev ) {
887 $parserOptions = $page->makeParserOptions( $this->getContext() );
888 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
890 return $parserOutput;
894 * Get the diff text, send it to the OutputPage object
895 * Returns false if the diff could not be generated, otherwise returns true
897 * @param string|bool $otitle Header for old text or false
898 * @param string|bool $ntitle Header for new text or false
899 * @param string $notice HTML between diff header and body
903 public function showDiff( $otitle, $ntitle, $notice = '' ) {
904 // Allow extensions to affect the output here
905 Hooks
::run( 'DifferenceEngineShowDiff', [ $this ] );
907 $diff = $this->getDiff( $otitle, $ntitle, $notice );
908 if ( $diff === false ) {
909 $this->showMissingRevision();
913 $this->showDiffStyle();
914 $this->getOutput()->addHTML( $diff );
921 * Add style sheets for diff display.
923 public function showDiffStyle() {
924 if ( !$this->isSlotDiffRenderer
) {
925 $this->getOutput()->addModuleStyles( 'mediawiki.diff.styles' );
926 foreach ( $this->getSlotDiffRenderers() as $slotDiffRenderer ) {
927 $slotDiffRenderer->addModules( $this->getOutput() );
933 * Get complete diff table, including header
935 * @param string|bool $otitle Header for old text or false
936 * @param string|bool $ntitle Header for new text or false
937 * @param string $notice HTML between diff header and body
941 public function getDiff( $otitle, $ntitle, $notice = '' ) {
942 $body = $this->getDiffBody();
943 if ( $body === false ) {
947 $multi = $this->getMultiNotice();
948 // Display a message when the diff is empty
949 if ( $body === '' ) {
950 $notice .= '<div class="mw-diff-empty">' .
951 $this->msg( 'diff-empty' )->parse() .
955 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
959 * Get the diff table body, without header
961 * @return mixed (string/false)
963 public function getDiffBody() {
964 $this->mCacheHit
= true;
965 // Check if the diff should be hidden from this user
966 if ( !$this->isContentOverridden
) {
967 if ( !$this->loadRevisionData() ) {
969 } elseif ( $this->mOldRev
&&
970 !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
973 } elseif ( $this->mNewRev
&&
974 !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
979 if ( $this->mOldRev
=== false ||
( $this->mOldRev
&& $this->mNewRev
&&
980 $this->mOldRev
->getId() && $this->mOldRev
->getId() == $this->mNewRev
->getId() )
982 if ( Hooks
::run( 'DifferenceEngineShowEmptyOldContent', [ $this ] ) ) {
990 $cache = ObjectCache
::getMainWANInstance();
991 if ( $this->mOldid
&& $this->mNewid
) {
992 // Check if subclass is still using the old way
993 // for backwards-compatibility
994 $key = $this->getDiffBodyCacheKey();
995 if ( $key === null ) {
996 $key = $cache->makeKey( ...$this->getDiffBodyCacheKeyParams() );
1000 if ( !$this->mRefreshCache
) {
1001 $difftext = $cache->get( $key );
1003 wfIncrStats( 'diff_cache.hit' );
1004 $difftext = $this->localiseDiff( $difftext );
1005 $difftext .= "\n<!-- diff cache key $key -->\n";
1009 } // don't try to load but save the result
1011 $this->mCacheHit
= false;
1013 // Loadtext is permission safe, this just clears out the diff
1014 if ( !$this->loadText() ) {
1019 // We've checked for revdelete at the beginning of this method; it's OK to ignore
1020 // read permissions here.
1021 $slotContents = $this->getSlotContents();
1022 foreach ( $this->getSlotDiffRenderers() as $role => $slotDiffRenderer ) {
1023 $slotDiff = $slotDiffRenderer->getDiff( $slotContents[$role]['old'],
1024 $slotContents[$role]['new'] );
1025 if ( $slotDiff && $role !== 'main' ) {
1026 // TODO use human-readable role name at least
1028 $difftext .= $this->getSlotHeader( $slotTitle );
1030 $difftext .= $slotDiff;
1033 // Avoid PHP 7.1 warning from passing $this by reference
1034 $diffEngine = $this;
1036 // Save to cache for 7 days
1037 if ( !Hooks
::run( 'AbortDiffCache', [ &$diffEngine ] ) ) {
1038 wfIncrStats( 'diff_cache.uncacheable' );
1039 } elseif ( $key !== false && $difftext !== false ) {
1040 wfIncrStats( 'diff_cache.miss' );
1041 $cache->set( $key, $difftext, 7 * 86400 );
1043 wfIncrStats( 'diff_cache.uncacheable' );
1045 // localise line numbers and title attribute text
1046 if ( $difftext !== false ) {
1047 $difftext = $this->localiseDiff( $difftext );
1054 * Get the diff table body for one slot, without header
1056 * @param string $role
1057 * @return string|false
1059 public function getDiffBodyForRole( $role ) {
1060 $diffRenderers = $this->getSlotDiffRenderers();
1061 if ( !isset( $diffRenderers[$role] ) ) {
1065 $slotContents = $this->getSlotContents();
1066 $slotDiff = $diffRenderers[$role]->getDiff( $slotContents[$role]['old'],
1067 $slotContents[$role]['new'] );
1072 if ( $role !== 'main' ) {
1073 // TODO use human-readable role name at least
1075 $slotDiff = $this->getSlotHeader( $slotTitle ) . $slotDiff;
1078 return $this->localiseDiff( $slotDiff );
1082 * Get a slot header for inclusion in a diff body (as a table row).
1084 * @param string $headerText The text of the header
1088 protected function getSlotHeader( $headerText ) {
1089 // The old revision is missing on oldid=<first>&diff=prev; only 2 columns in that case.
1090 $columnCount = $this->mOldRev ?
4 : 2;
1091 $userLang = $this->getLanguage()->getHtmlCode();
1092 return Html
::rawElement( 'tr', [ 'class' => 'mw-diff-slot-header', 'lang' => $userLang ],
1093 Html
::element( 'th', [ 'colspan' => $columnCount ], $headerText ) );
1097 * Returns the cache key for diff body text or content.
1099 * @deprecated since 1.31, use getDiffBodyCacheKeyParams() instead
1102 * @throws MWException
1103 * @return string|null
1105 protected function getDiffBodyCacheKey() {
1110 * Get the cache key parameters
1112 * Subclasses can replace the first element in the array to something
1113 * more specific to the type of diff (e.g. "inline-diff"), or append
1114 * if the cache should vary on more things. Overriding entirely should
1120 * @throws MWException
1122 protected function getDiffBodyCacheKeyParams() {
1123 if ( !$this->mOldid ||
!$this->mNewid
) {
1124 throw new MWException( 'mOldid and mNewid must be set to get diff cache key.' );
1127 $engine = $this->getEngine();
1132 "old-{$this->mOldid}",
1133 "rev-{$this->mNewid}"
1136 if ( $engine === 'wikidiff2' ) {
1137 $params[] = phpversion( 'wikidiff2' );
1138 $params[] = $this->getConfig()->get( 'WikiDiff2MovedParagraphDetectionCutoff' );
1141 if ( !$this->isSlotDiffRenderer
) {
1142 foreach ( $this->getSlotDiffRenderers() as $slotDiffRenderer ) {
1143 $params = array_merge( $params, $slotDiffRenderer->getExtraCacheKeys() );
1151 * Implements DifferenceEngineSlotDiffRenderer::getExtraCacheKeys(). Only used when
1152 * DifferenceEngine is wrapped in DifferenceEngineSlotDiffRenderer.
1154 * @internal for use by DifferenceEngineSlotDiffRenderer only
1157 public function getExtraCacheKeys() {
1158 // This method is called when the DifferenceEngine is used for a slot diff. We only care
1159 // about special things, not the revision IDs, which are added to the cache key by the
1160 // page-level DifferenceEngine, and which might not have a valid value for this object.
1161 $this->mOldid
= 123456789;
1162 $this->mNewid
= 987654321;
1164 // This will repeat a bunch of unnecessary key fields for each slot. Not nice but harmless.
1165 $cacheString = $this->getDiffBodyCacheKey();
1166 if ( $cacheString ) {
1167 return [ $cacheString ];
1170 $params = $this->getDiffBodyCacheKeyParams();
1172 // Try to get rid of the standard keys to keep the cache key human-readable:
1173 // call the getDiffBodyCacheKeyParams implementation of the base class, and if
1174 // the child class includes the same keys, drop them.
1175 // Uses an obscure PHP feature where static calls to non-static methods are allowed
1176 // as long as we are already in a non-static method of the same class, and the call context
1177 // ($this) will be inherited.
1178 // phpcs:ignore Squiz.Classes.SelfMemberReference.NotUsed
1179 $standardParams = DifferenceEngine
::getDiffBodyCacheKeyParams();
1180 if ( array_slice( $params, 0, count( $standardParams ) ) === $standardParams ) {
1181 $params = array_slice( $params, count( $standardParams ) );
1188 * Generate a diff, no caching.
1192 * @param Content $old Old content
1193 * @param Content $new New content
1195 * @throws Exception If old or new content is not an instance of TextContent.
1196 * @return bool|string
1198 * @deprecated since 1.32, use a SlotDiffRenderer instead.
1200 public function generateContentDiffBody( Content
$old, Content
$new ) {
1201 $slotDiffRenderer = $new->getContentHandler()->getSlotDiffRenderer( $this->getContext() );
1203 $slotDiffRenderer instanceof DifferenceEngineSlotDiffRenderer
1204 && $this->isSlotDiffRenderer
1206 // Oops, we are just about to enter an infinite loop (the slot-level DifferenceEngine
1207 // called a DifferenceEngineSlotDiffRenderer that wraps the same DifferenceEngine class).
1208 // This will happen when a content model has no custom slot diff renderer, it does have
1209 // a custom difference engine, but that does not override this method.
1210 throw new Exception( get_class( $this ) . ': could not maintain backwards compatibility. '
1211 . 'Please use a SlotDiffRenderer.' );
1213 return $slotDiffRenderer->getDiff( $old, $new ) . $this->getDebugString();
1217 * Generate a diff, no caching
1219 * @param string $otext Old text, must be already segmented
1220 * @param string $ntext New text, must be already segmented
1222 * @throws Exception If content handling for text content is configured in a way
1223 * that makes maintaining B/C hard.
1224 * @return bool|string
1226 * @deprecated since 1.32, use a TextSlotDiffRenderer instead.
1228 public function generateTextDiffBody( $otext, $ntext ) {
1229 $slotDiffRenderer = ContentHandler
::getForModelID( CONTENT_MODEL_TEXT
)
1230 ->getSlotDiffRenderer( $this->getContext() );
1231 if ( !( $slotDiffRenderer instanceof TextSlotDiffRenderer
) ) {
1232 // Someone used the GetSlotDiffRenderer hook to replace the renderer.
1233 // This is too unlikely to happen to bother handling properly.
1234 throw new Exception( 'The slot diff renderer for text content should be a '
1235 . 'TextSlotDiffRenderer subclass' );
1237 return $slotDiffRenderer->getTextDiff( $otext, $ntext ) . $this->getDebugString();
1241 * Process $wgExternalDiffEngine and get a sane, usable engine
1243 * @return bool|string 'wikidiff2', path to an executable, or false
1244 * @internal For use by this class and TextSlotDiffRenderer only.
1246 public static function getEngine() {
1247 global $wgExternalDiffEngine;
1248 // We use the global here instead of Config because we write to the value,
1249 // and Config is not mutable.
1250 if ( $wgExternalDiffEngine == 'wikidiff' ||
$wgExternalDiffEngine == 'wikidiff3' ) {
1251 wfDeprecated( "\$wgExternalDiffEngine = '{$wgExternalDiffEngine}'", '1.27' );
1252 $wgExternalDiffEngine = false;
1253 } elseif ( $wgExternalDiffEngine == 'wikidiff2' ) {
1254 wfDeprecated( "\$wgExternalDiffEngine = '{$wgExternalDiffEngine}'", '1.32' );
1255 $wgExternalDiffEngine = false;
1256 } elseif ( !is_string( $wgExternalDiffEngine ) && $wgExternalDiffEngine !== false ) {
1257 // And prevent people from shooting themselves in the foot...
1258 wfWarn( '$wgExternalDiffEngine is set to a non-string value, forcing it to false' );
1259 $wgExternalDiffEngine = false;
1262 if ( is_string( $wgExternalDiffEngine ) && is_executable( $wgExternalDiffEngine ) ) {
1263 return $wgExternalDiffEngine;
1264 } elseif ( $wgExternalDiffEngine === false && function_exists( 'wikidiff2_do_diff' ) ) {
1273 * Generates diff, to be wrapped internally in a logging/instrumentation
1275 * @param string $otext Old text, must be already segmented
1276 * @param string $ntext New text, must be already segmented
1278 * @throws Exception If content handling for text content is configured in a way
1279 * that makes maintaining B/C hard.
1280 * @return bool|string
1282 * @deprecated since 1.32, use a TextSlotDiffRenderer instead.
1284 protected function textDiff( $otext, $ntext ) {
1285 $slotDiffRenderer = ContentHandler
::getForModelID( CONTENT_MODEL_TEXT
)
1286 ->getSlotDiffRenderer( $this->getContext() );
1287 if ( !( $slotDiffRenderer instanceof TextSlotDiffRenderer
) ) {
1288 // Someone used the GetSlotDiffRenderer hook to replace the renderer.
1289 // This is too unlikely to happen to bother handling properly.
1290 throw new Exception( 'The slot diff renderer for text content should be a '
1291 . 'TextSlotDiffRenderer subclass' );
1293 return $slotDiffRenderer->getTextDiff( $otext, $ntext ) . $this->getDebugString();
1297 * Generate a debug comment indicating diff generating time,
1298 * server node, and generator backend.
1300 * @param string $generator : What diff engine was used
1304 protected function debug( $generator = "internal" ) {
1305 global $wgShowHostnames;
1306 if ( !$this->enableDebugComment
) {
1309 $data = [ $generator ];
1310 if ( $wgShowHostnames ) {
1311 $data[] = wfHostname();
1313 $data[] = wfTimestamp( TS_DB
);
1315 return "<!-- diff generator: " .
1316 implode( " ", array_map( "htmlspecialchars", $data ) ) .
1320 private function getDebugString() {
1321 $engine = self
::getEngine();
1322 if ( $engine === 'wikidiff2' ) {
1323 return $this->debug( 'wikidiff2' );
1324 } elseif ( $engine === false ) {
1325 return $this->debug( 'native PHP' );
1327 return $this->debug( "external $engine" );
1332 * Localise diff output
1334 * @param string $text
1337 private function localiseDiff( $text ) {
1338 $text = $this->localiseLineNumbers( $text );
1339 if ( $this->getEngine() === 'wikidiff2' &&
1340 version_compare( phpversion( 'wikidiff2' ), '1.5.1', '>=' )
1342 $text = $this->addLocalisedTitleTooltips( $text );
1348 * Replace line numbers with the text in the user's language
1350 * @param string $text
1354 public function localiseLineNumbers( $text ) {
1355 return preg_replace_callback(
1356 '/<!--LINE (\d+)-->/',
1357 [ $this, 'localiseLineNumbersCb' ],
1362 public function localiseLineNumbersCb( $matches ) {
1363 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) {
1367 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
1371 * Add title attributes for tooltips on moved paragraph indicators
1373 * @param string $text
1376 private function addLocalisedTitleTooltips( $text ) {
1377 return preg_replace_callback(
1378 '/class="mw-diff-movedpara-(left|right)"/',
1379 [ $this, 'addLocalisedTitleTooltipsCb' ],
1385 * @param array $matches
1388 private function addLocalisedTitleTooltipsCb( array $matches ) {
1389 $key = $matches[1] === 'right' ?
1390 'diff-paragraph-moved-toold' :
1391 'diff-paragraph-moved-tonew';
1392 return $matches[0] . ' title="' . $this->msg( $key )->escaped() . '"';
1396 * If there are revisions between the ones being compared, return a note saying so.
1400 public function getMultiNotice() {
1401 // The notice only make sense if we are diffing two saved revisions of the same page.
1403 !$this->mOldRev ||
!$this->mNewRev
1404 ||
!$this->mOldPage ||
!$this->mNewPage
1405 ||
!$this->mOldPage
->equals( $this->mNewPage
)
1410 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
1411 $oldRev = $this->mNewRev
; // flip
1412 $newRev = $this->mOldRev
; // flip
1413 } else { // normal case
1414 $oldRev = $this->mOldRev
;
1415 $newRev = $this->mNewRev
;
1418 // Sanity: don't show the notice if too many rows must be scanned
1419 // @todo show some special message for that case
1420 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev, 1000 );
1421 if ( $nEdits > 0 && $nEdits <= 1000 ) {
1422 $limit = 100; // use diff-multi-manyusers if too many users
1423 $users = $this->mNewPage
->getAuthorsBetween( $oldRev, $newRev, $limit );
1424 $numUsers = count( $users );
1426 if ( $numUsers == 1 && $users[0] == $newRev->getUserText( Revision
::RAW
) ) {
1427 $numUsers = 0; // special case to say "by the same user" instead of "by one other user"
1430 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
1433 return ''; // nothing
1437 * Get a notice about how many intermediate edits and users there are
1439 * @param int $numEdits
1440 * @param int $numUsers
1445 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
1446 if ( $numUsers === 0 ) {
1447 $msg = 'diff-multi-sameuser';
1448 } elseif ( $numUsers > $limit ) {
1449 $msg = 'diff-multi-manyusers';
1452 $msg = 'diff-multi-otherusers';
1455 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
1459 * Get a header for a specified revision.
1461 * @param Revision $rev
1462 * @param string $complete 'complete' to get the header wrapped depending
1463 * the visibility of the revision and a link to edit the page.
1465 * @return string HTML fragment
1467 public function getRevisionHeader( Revision
$rev, $complete = '' ) {
1468 $lang = $this->getLanguage();
1469 $user = $this->getUser();
1470 $revtimestamp = $rev->getTimestamp();
1471 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
1472 $dateofrev = $lang->userDate( $revtimestamp, $user );
1473 $timeofrev = $lang->userTime( $revtimestamp, $user );
1475 $header = $this->msg(
1476 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
1482 if ( $complete !== 'complete' ) {
1486 $title = $rev->getTitle();
1488 $header = Linker
::linkKnown( $title, $header, [],
1489 [ 'oldid' => $rev->getId() ] );
1491 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
1492 $editQuery = [ 'action' => 'edit' ];
1493 if ( !$rev->isCurrent() ) {
1494 $editQuery['oldid'] = $rev->getId();
1497 $key = $title->quickUserCan( 'edit', $user ) ?
'editold' : 'viewsourceold';
1498 $msg = $this->msg( $key )->escaped();
1499 $editLink = $this->msg( 'parentheses' )->rawParams(
1500 Linker
::linkKnown( $title, $msg, [], $editQuery ) )->escaped();
1501 $header .= ' ' . Html
::rawElement(
1503 [ 'class' => 'mw-diff-edit' ],
1506 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
1507 $header = Html
::rawElement(
1509 [ 'class' => 'history-deleted' ],
1514 $header = Html
::rawElement( 'span', [ 'class' => 'history-deleted' ], $header );
1521 * Add the header to a diff body
1523 * @param string $diff Diff body
1524 * @param string $otitle Old revision header
1525 * @param string $ntitle New revision header
1526 * @param string $multi Notice telling user that there are intermediate
1527 * revisions between the ones being compared
1528 * @param string $notice Other notices, e.g. that user is viewing deleted content
1532 public function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
1533 // shared.css sets diff in interface language/dir, but the actual content
1534 // is often in a different language, mostly the page content language/dir
1535 $header = Html
::openElement( 'table', [
1536 'class' => [ 'diff', 'diff-contentalign-' . $this->getDiffLang()->alignStart() ],
1537 'data-mw' => 'interface',
1539 $userLang = htmlspecialchars( $this->getLanguage()->getHtmlCode() );
1541 if ( !$diff && !$otitle ) {
1543 <tr class=\"diff-title\" lang=\"{$userLang}\">
1544 <td class=\"diff-ntitle\">{$ntitle}</td>
1548 if ( $diff ) { // Safari/Chrome show broken output if cols not used
1550 <col class=\"diff-marker\" />
1551 <col class=\"diff-content\" />
1552 <col class=\"diff-marker\" />
1553 <col class=\"diff-content\" />";
1560 if ( $otitle ||
$ntitle ) {
1562 <tr class=\"diff-title\" lang=\"{$userLang}\">
1563 <td colspan=\"$colspan\" class=\"diff-otitle\">{$otitle}</td>
1564 <td colspan=\"$colspan\" class=\"diff-ntitle\">{$ntitle}</td>
1569 if ( $multi != '' ) {
1570 $header .= "<tr><td colspan=\"{$multiColspan}\" " .
1571 "class=\"diff-multi\" lang=\"{$userLang}\">{$multi}</td></tr>";
1573 if ( $notice != '' ) {
1574 $header .= "<tr><td colspan=\"{$multiColspan}\" " .
1575 "class=\"diff-notice\" lang=\"{$userLang}\">{$notice}</td></tr>";
1578 return $header . $diff . "</table>";
1582 * Use specified text instead of loading from the database
1583 * @param Content $oldContent
1584 * @param Content $newContent
1586 * @deprecated since 1.32, use setRevisions or ContentHandler::getSlotDiffRenderer.
1588 public function setContent( Content
$oldContent, Content
$newContent ) {
1589 $this->mOldContent
= $oldContent;
1590 $this->mNewContent
= $newContent;
1592 $this->mTextLoaded
= 2;
1593 $this->mRevisionsLoaded
= true;
1594 $this->isContentOverridden
= true;
1595 $this->slotDiffRenderers
= null;
1599 * Use specified text instead of loading from the database.
1600 * @param RevisionRecord|null $oldRevision
1601 * @param RevisionRecord $newRevision
1603 public function setRevisions(
1604 RevisionRecord
$oldRevision = null, RevisionRecord
$newRevision
1606 if ( $oldRevision ) {
1607 $this->mOldRev
= new Revision( $oldRevision );
1608 $this->mOldid
= $oldRevision->getId();
1609 $this->mOldPage
= Title
::newFromLinkTarget( $oldRevision->getPageAsLinkTarget() );
1610 // This method is meant for edit diffs and such so there is no reason to provide a
1611 // revision that's not readable to the user, but check it just in case.
1612 $this->mOldContent
= $oldRevision ?
$oldRevision->getContent( 'main',
1613 RevisionRecord
::FOR_THIS_USER
, $this->getUser() ) : null;
1615 $this->mOldPage
= null;
1616 $this->mOldRev
= $this->mOldid
= false;
1618 $this->mNewRev
= new Revision( $newRevision );
1619 $this->mNewid
= $newRevision->getId();
1620 $this->mNewPage
= Title
::newFromLinkTarget( $newRevision->getPageAsLinkTarget() );
1621 $this->mNewContent
= $newRevision->getContent( 'main',
1622 RevisionRecord
::FOR_THIS_USER
, $this->getUser() );
1624 $this->mRevisionsIdsLoaded
= $this->mRevisionsLoaded
= true;
1625 $this->mTextLoaded
= !!$oldRevision +
1;
1626 $this->isContentOverridden
= false;
1627 $this->slotDiffRenderers
= null;
1631 * Set the language in which the diff text is written
1633 * @param Language $lang
1636 public function setTextLanguage( $lang ) {
1637 if ( !$lang instanceof Language
) {
1638 wfDeprecated( __METHOD__
. ' with other type than Language for $lang', '1.32' );
1640 $this->mDiffLang
= wfGetLangObj( $lang );
1644 * Maps a revision pair definition as accepted by DifferenceEngine constructor
1645 * to a pair of actual integers representing revision ids.
1647 * @param int $old Revision id, e.g. from URL parameter 'oldid'
1648 * @param int|string $new Revision id or strings 'next' or 'prev', e.g. from URL parameter 'diff'
1650 * @return array List of two revision ids, older first, later second.
1651 * Zero signifies invalid argument passed.
1652 * false signifies that there is no previous/next revision ($old is the oldest/newest one).
1654 public function mapDiffPrevNext( $old, $new ) {
1655 if ( $new === 'prev' ) {
1656 // Show diff between revision $old and the previous one. Get previous one from DB.
1657 $newid = intval( $old );
1658 $oldid = $this->getTitle()->getPreviousRevisionID( $newid );
1659 } elseif ( $new === 'next' ) {
1660 // Show diff between revision $old and the next one. Get next one from DB.
1661 $oldid = intval( $old );
1662 $newid = $this->getTitle()->getNextRevisionID( $oldid );
1664 $oldid = intval( $old );
1665 $newid = intval( $new );
1668 return [ $oldid, $newid ];
1674 private function loadRevisionIds() {
1675 if ( $this->mRevisionsIdsLoaded
) {
1679 $this->mRevisionsIdsLoaded
= true;
1681 $old = $this->mOldid
;
1682 $new = $this->mNewid
;
1684 list( $this->mOldid
, $this->mNewid
) = self
::mapDiffPrevNext( $old, $new );
1685 if ( $new === 'next' && $this->mNewid
=== false ) {
1686 # if no result, NewId points to the newest old revision. The only newer
1687 # revision is cur, which is "0".
1692 'NewDifferenceEngine',
1693 [ $this->getTitle(), &$this->mOldid
, &$this->mNewid
, $old, $new ]
1698 * Load revision metadata for the specified revisions. If newid is 0, then compare
1699 * the old revision in oldid to the current revision of the current page (as defined
1700 * by the request context); if oldid is 0, then compare the revision in newid to the
1701 * immediately previous one.
1703 * If oldid is false, leave the corresponding revision object set
1704 * to false. This can happen with 'diff=prev' pointing to a non-existent revision,
1705 * and is also used directly by the API.
1707 * @return bool Whether both revisions were loaded successfully. Setting mOldRev
1708 * to false counts as successful loading.
1710 public function loadRevisionData() {
1711 if ( $this->mRevisionsLoaded
) {
1712 return $this->isContentOverridden ||
$this->mNewRev
&& !is_null( $this->mOldRev
);
1715 // Whether it succeeds or fails, we don't want to try again
1716 $this->mRevisionsLoaded
= true;
1718 $this->loadRevisionIds();
1720 // Load the new revision object
1721 if ( $this->mNewid
) {
1722 $this->mNewRev
= Revision
::newFromId( $this->mNewid
);
1724 $this->mNewRev
= Revision
::newFromTitle(
1727 Revision
::READ_NORMAL
1731 if ( !$this->mNewRev
instanceof Revision
) {
1735 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1736 $this->mNewid
= $this->mNewRev
->getId();
1737 if ( $this->mNewid
) {
1738 $this->mNewPage
= $this->mNewRev
->getTitle();
1740 $this->mNewPage
= null;
1743 // Load the old revision object
1744 $this->mOldRev
= false;
1745 if ( $this->mOldid
) {
1746 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1747 } elseif ( $this->mOldid
=== 0 ) {
1748 $rev = $this->mNewRev
->getPrevious();
1750 $this->mOldid
= $rev->getId();
1751 $this->mOldRev
= $rev;
1753 // No previous revision; mark to show as first-version only.
1754 $this->mOldid
= false;
1755 $this->mOldRev
= false;
1757 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1759 if ( is_null( $this->mOldRev
) ) {
1763 if ( $this->mOldRev
&& $this->mOldRev
->getId() ) {
1764 $this->mOldPage
= $this->mOldRev
->getTitle();
1766 $this->mOldPage
= null;
1769 // Load tags information for both revisions
1770 $dbr = wfGetDB( DB_REPLICA
);
1771 if ( $this->mOldid
!== false ) {
1772 $this->mOldTags
= $dbr->selectField(
1775 [ 'ts_rev_id' => $this->mOldid
],
1779 $this->mOldTags
= false;
1781 $this->mNewTags
= $dbr->selectField(
1784 [ 'ts_rev_id' => $this->mNewid
],
1792 * Load the text of the revisions, as well as revision data.
1793 * When the old revision is missing (mOldRev is false), loading mOldContent is not attempted.
1795 * @return bool Whether the content of both revisions could be loaded successfully.
1796 * (When mOldRev is false, that still counts as a success.)
1799 public function loadText() {
1800 if ( $this->mTextLoaded
== 2 ) {
1801 return $this->loadRevisionData() && ( $this->mOldRev
=== false ||
$this->mOldContent
)
1802 && $this->mNewContent
;
1805 // Whether it succeeds or fails, we don't want to try again
1806 $this->mTextLoaded
= 2;
1808 if ( !$this->loadRevisionData() ) {
1812 if ( $this->mOldRev
) {
1813 $this->mOldContent
= $this->mOldRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1814 if ( $this->mOldContent
=== null ) {
1819 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1820 Hooks
::run( 'DifferenceEngineLoadTextAfterNewContentIsLoaded', [ $this ] );
1821 if ( $this->mNewContent
=== null ) {
1829 * Load the text of the new revision, not the old one
1831 * @return bool Whether the content of the new revision could be loaded successfully.
1833 public function loadNewText() {
1834 if ( $this->mTextLoaded
>= 1 ) {
1835 return $this->loadRevisionData();
1838 $this->mTextLoaded
= 1;
1840 if ( !$this->loadRevisionData() ) {
1844 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1846 Hooks
::run( 'DifferenceEngineAfterLoadNewText', [ $this ] );