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\Revision\RevisionRecord
;
25 use MediaWiki\Revision\SlotRecord
;
28 * DifferenceEngine is responsible for rendering the difference between two revisions as HTML.
29 * This includes interpreting URL parameters, retrieving revision data, checking access permissions,
30 * selecting and invoking the diff generator class for the individual slots, doing post-processing
31 * on the generated diff, adding the rest of the HTML (such as headers) and writing the whole thing
34 * DifferenceEngine can be subclassed by extensions, by customizing
35 * ContentHandler::createDifferenceEngine; the content handler will be selected based on the
36 * content model of the main slot (of the new revision, when the two are different).
37 * That might change after PageTypeHandler gets introduced.
39 * In the past, the class was also used for slot-level diff generation, and extensions might still
40 * subclass it and add such functionality. When that is the case (sepcifically, when a
41 * ContentHandler returns a standard SlotDiffRenderer but a nonstandard DifferenceEngine)
42 * DifferenceEngineSlotDiffRenderer will be used to convert the old behavior into the new one.
44 * @ingroup DifferenceEngine
46 * @todo This class is huge and poorly defined. It should be split into a controller responsible
47 * for interpreting query parameters, retrieving data and checking permissions; and a HTML renderer.
49 class DifferenceEngine
extends ContextSource
{
51 use DeprecationHelper
;
54 * Constant to indicate diff cache compatibility.
55 * Bump this when changing the diff formatting in a way that
56 * fixes important bugs or such to force cached diff views to
59 const DIFF_VERSION
= '1.12';
62 * Revision ID for the old revision. 0 for the revision previous to $mNewid, false
63 * if the diff does not have an old revision (e.g. 'oldid=<first revision of page>&diff=prev'),
64 * or the revision does not exist, null if the revision is unsaved.
70 * Revision ID for the new revision. 0 for the last revision of the current page
71 * (as defined by the request context), false if the revision does not exist, null
72 * if it is unsaved, or an alias such as 'next'.
73 * @var int|string|false|null
78 * Old revision (left pane).
79 * Allowed to be an unsaved revision, unlikely that's ever needed though.
80 * False when the old revision does not exist; this can happen when using
81 * diff=prev on the first revision. Null when the revision should exist but
82 * doesn't (e.g. load failure); loadRevisionData() will return false in that
83 * case. Also null until lazy-loaded. Ignored completely when isContentOverridden
85 * Since 1.32 public access is deprecated.
86 * @var Revision|null|false
91 * New revision (right pane).
92 * Note that this might be an unsaved revision (e.g. for edit preview).
93 * Null in case of load failure; diff methods will just return an error message in that case,
94 * and loadRevisionData() will return false. Also null until lazy-loaded. Ignored completely
95 * when isContentOverridden is set.
96 * Since 1.32 public access is deprecated.
102 * Title of $mOldRev or null if the old revision does not exist or does not belong to a page.
103 * Since 1.32 public access is deprecated and the property can be null.
109 * Title of $mNewRev or null if the new revision does not exist or does not belong to a page.
110 * Since 1.32 public access is deprecated and the property can be null.
116 * Change tags of $mOldRev or null if it does not exist / is not saved.
122 * Change tags of $mNewRev or null if it does not exist / is not saved.
129 * @deprecated since 1.32, content slots are now handled by the corresponding SlotDiffRenderer.
130 * This property is set to the content of the main slot, but not actually used for the main diff.
132 private $mOldContent;
136 * @deprecated since 1.32, content slots are now handled by the corresponding SlotDiffRenderer.
137 * This property is set to the content of the main slot, but not actually used for the main diff.
139 private $mNewContent;
142 protected $mDiffLang;
144 /** @var bool Have the revisions IDs been loaded */
145 private $mRevisionsIdsLoaded = false;
147 /** @var bool Have the revisions been loaded */
148 protected $mRevisionsLoaded = false;
150 /** @var int How many text blobs have been loaded, 0, 1 or 2? */
151 protected $mTextLoaded = 0;
154 * Was the content overridden via setContent()?
155 * If the content was overridden, most internal state (e.g. mOldid or mOldRev) should be ignored
156 * and only mOldContent and mNewContent is reliable.
157 * (Note that setRevisions() does not set this flag as in that case all properties are
158 * overriden and remain consistent with each other, so no special handling is needed.)
161 protected $isContentOverridden = false;
163 /** @var bool Was the diff fetched from cache? */
164 protected $mCacheHit = false;
167 * Set this to true to add debug info to the HTML output.
168 * Warning: this may cause RSS readers to spuriously mark articles as "new"
171 public $enableDebugComment = false;
173 /** @var bool If true, line X is not displayed when X is 1, for example
174 * to increase readability and conserve space with many small diffs.
176 protected $mReducedLineNumbers = false;
178 /** @var string Link to action=markpatrolled */
179 protected $mMarkPatrolledLink = null;
181 /** @var bool Show rev_deleted content if allowed */
182 protected $unhide = false;
184 /** @var bool Refresh the diff cache */
185 protected $mRefreshCache = false;
187 /** @var SlotDiffRenderer[] DifferenceEngine classes for the slots, keyed by role name. */
188 protected $slotDiffRenderers = null;
191 * Temporary hack for B/C while slot diff related methods of DifferenceEngine are being
192 * deprecated. When true, we are inside a DifferenceEngineSlotDiffRenderer and
193 * $slotDiffRenderers should not be used.
196 protected $isSlotDiffRenderer = false;
201 * @param IContextSource|null $context Context to use, anything else will be ignored
202 * @param int $old Old ID we want to show and diff with.
203 * @param string|int $new Either revision ID or 'prev' or 'next'. Default: 0.
204 * @param int $rcid Deprecated, no longer used!
205 * @param bool $refreshCache If set, refreshes the diff cache
206 * @param bool $unhide If set, allow viewing deleted revs
208 public function __construct( $context = null, $old = 0, $new = 0, $rcid = 0,
209 $refreshCache = false, $unhide = false
211 $this->deprecatePublicProperty( 'mOldid', '1.32', __CLASS__
);
212 $this->deprecatePublicProperty( 'mNewid', '1.32', __CLASS__
);
213 $this->deprecatePublicProperty( 'mOldRev', '1.32', __CLASS__
);
214 $this->deprecatePublicProperty( 'mNewRev', '1.32', __CLASS__
);
215 $this->deprecatePublicProperty( 'mOldPage', '1.32', __CLASS__
);
216 $this->deprecatePublicProperty( 'mNewPage', '1.32', __CLASS__
);
217 $this->deprecatePublicProperty( 'mOldContent', '1.32', __CLASS__
);
218 $this->deprecatePublicProperty( 'mNewContent', '1.32', __CLASS__
);
219 $this->deprecatePublicProperty( 'mRevisionsLoaded', '1.32', __CLASS__
);
220 $this->deprecatePublicProperty( 'mTextLoaded', '1.32', __CLASS__
);
221 $this->deprecatePublicProperty( 'mCacheHit', '1.32', __CLASS__
);
223 if ( $context instanceof IContextSource
) {
224 $this->setContext( $context );
227 wfDebug( "DifferenceEngine old '$old' new '$new' rcid '$rcid'\n" );
229 $this->mOldid
= $old;
230 $this->mNewid
= $new;
231 $this->mRefreshCache
= $refreshCache;
232 $this->unhide
= $unhide;
236 * @return SlotDiffRenderer[] Diff renderers for each slot, keyed by role name.
237 * Includes slots only present in one of the revisions.
239 protected function getSlotDiffRenderers() {
240 if ( $this->isSlotDiffRenderer
) {
241 throw new LogicException( __METHOD__
. ' called in slot diff renderer mode' );
244 if ( $this->slotDiffRenderers
=== null ) {
245 if ( !$this->loadRevisionData() ) {
249 $slotContents = $this->getSlotContents();
250 $this->slotDiffRenderers
= array_map( function ( $contents ) {
251 /** @var $content Content */
252 $content = $contents['new'] ?
: $contents['old'];
253 return $content->getContentHandler()->getSlotDiffRenderer( $this->getContext() );
256 return $this->slotDiffRenderers
;
260 * Mark this DifferenceEngine as a slot renderer (as opposed to a page renderer).
261 * This is used in legacy mode when the DifferenceEngine is wrapped in a
262 * DifferenceEngineSlotDiffRenderer.
263 * @internal For use by DifferenceEngineSlotDiffRenderer only.
265 public function markAsSlotDiffRenderer() {
266 $this->isSlotDiffRenderer
= true;
270 * Get the old and new content objects for all slots.
271 * This method does not do any permission checks.
272 * @return array [ role => [ 'old' => SlotRecord|null, 'new' => SlotRecord|null ], ... ]
274 protected function getSlotContents() {
275 if ( $this->isContentOverridden
) {
277 SlotRecord
::MAIN
=> [
278 'old' => $this->mOldContent
,
279 'new' => $this->mNewContent
,
282 } elseif ( !$this->loadRevisionData() ) {
286 $newSlots = $this->mNewRev
->getRevisionRecord()->getSlots()->getSlots();
287 if ( $this->mOldRev
) {
288 $oldSlots = $this->mOldRev
->getRevisionRecord()->getSlots()->getSlots();
292 // The order here will determine the visual order of the diff. The current logic is
293 // slots of the new revision first in natural order, then deleted ones. This is ad hoc
294 // and should not be relied on - in the future we may want the ordering to depend
296 $roles = array_merge( array_keys( $newSlots ), array_keys( $oldSlots ) );
299 foreach ( $roles as $role ) {
301 'old' => isset( $oldSlots[$role] ) ?
$oldSlots[$role]->getContent() : null,
302 'new' => isset( $newSlots[$role] ) ?
$newSlots[$role]->getContent() : null,
305 // move main slot to front
306 if ( isset( $slots[SlotRecord
::MAIN
] ) ) {
307 $slots = [ SlotRecord
::MAIN
=> $slots[SlotRecord
::MAIN
] ] +
$slots;
312 public function getTitle() {
313 // T202454 avoid errors when there is no title
314 return parent
::getTitle() ?
: Title
::makeTitle( NS_SPECIAL
, 'BadTitle/DifferenceEngine' );
318 * Set reduced line numbers mode.
319 * When set, line X is not displayed when X is 1, for example to increase readability and
320 * conserve space with many small diffs.
323 public function setReducedLineNumbers( $value = true ) {
324 $this->mReducedLineNumbers
= $value;
328 * Get the language of the difference engine, defaults to page content language
332 public function getDiffLang() {
333 if ( $this->mDiffLang
=== null ) {
334 # Default language in which the diff text is written.
335 $this->mDiffLang
= $this->getTitle()->getPageLanguage();
338 return $this->mDiffLang
;
344 public function wasCacheHit() {
345 return $this->mCacheHit
;
349 * Get the ID of old revision (left pane) of the diff. 0 for the revision
350 * previous to getNewid(), false if the old revision does not exist, null
352 * To get a real revision ID instead of 0, call loadRevisionData() first.
353 * @return int|false|null
355 public function getOldid() {
356 $this->loadRevisionIds();
358 return $this->mOldid
;
362 * Get the ID of new revision (right pane) of the diff. 0 for the current revision,
363 * false if the new revision does not exist, null if it's unsaved.
364 * To get a real revision ID instead of 0, call loadRevisionData() first.
365 * @return int|false|null
367 public function getNewid() {
368 $this->loadRevisionIds();
370 return $this->mNewid
;
374 * Get the left side of the diff.
375 * Could be null when the first revision of the page is diffed to 'prev' (or in the case of
377 * @return RevisionRecord|null
379 public function getOldRevision() {
380 return $this->mOldRev ?
$this->mOldRev
->getRevisionRecord() : null;
384 * Get the right side of the diff.
385 * Should not be null but can still happen in the case of load failure.
386 * @return RevisionRecord|null
388 public function getNewRevision() {
389 return $this->mNewRev ?
$this->mNewRev
->getRevisionRecord() : null;
393 * Look up a special:Undelete link to the given deleted revision id,
394 * as a workaround for being unable to load deleted diffs in currently.
396 * @param int $id Revision ID
398 * @return string|bool Link HTML or false
400 public function deletedLink( $id ) {
401 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
402 $dbr = wfGetDB( DB_REPLICA
);
403 $arQuery = Revision
::getArchiveQueryInfo();
404 $row = $dbr->selectRow(
406 array_merge( $arQuery['fields'], [ 'ar_namespace', 'ar_title' ] ),
407 [ 'ar_rev_id' => $id ],
413 $rev = Revision
::newFromArchiveRow( $row );
414 $title = Title
::makeTitleSafe( $row->ar_namespace
, $row->ar_title
);
416 return SpecialPage
::getTitleFor( 'Undelete' )->getFullURL( [
417 'target' => $title->getPrefixedText(),
418 'timestamp' => $rev->getTimestamp()
427 * Build a wikitext link toward a deleted revision, if viewable.
429 * @param int $id Revision ID
431 * @return string Wikitext fragment
433 public function deletedIdMarker( $id ) {
434 $link = $this->deletedLink( $id );
436 return "[$link $id]";
442 private function showMissingRevision() {
443 $out = $this->getOutput();
446 if ( $this->mOldRev
=== null ||
447 ( $this->mOldRev
&& $this->mOldContent
=== null )
449 $missing[] = $this->deletedIdMarker( $this->mOldid
);
451 if ( $this->mNewRev
=== null ||
452 ( $this->mNewRev
&& $this->mNewContent
=== null )
454 $missing[] = $this->deletedIdMarker( $this->mNewid
);
457 $out->setPageTitle( $this->msg( 'errorpagetitle' ) );
458 $msg = $this->msg( 'difference-missing-revision' )
459 ->params( $this->getLanguage()->listToText( $missing ) )
460 ->numParams( count( $missing ) )
462 $out->addHTML( $msg );
465 public function showDiffPage( $diffOnly = false ) {
466 # Allow frames except in certain special cases
467 $out = $this->getOutput();
468 $out->allowClickjacking();
469 $out->setRobotPolicy( 'noindex,nofollow' );
471 // Allow extensions to add any extra output here
472 Hooks
::run( 'DifferenceEngineShowDiffPage', [ $out ] );
474 if ( !$this->loadRevisionData() ) {
475 if ( Hooks
::run( 'DifferenceEngineShowDiffPageMaybeShowMissingRevision', [ $this ] ) ) {
476 $this->showMissingRevision();
481 $user = $this->getUser();
483 if ( $this->mNewPage
) {
484 $permErrors = $this->mNewPage
->getUserPermissionsErrors( 'read', $user );
486 if ( $this->mOldPage
) {
487 $permErrors = wfMergeErrorArrays( $permErrors,
488 $this->mOldPage
->getUserPermissionsErrors( 'read', $user ) );
490 if ( count( $permErrors ) ) {
491 throw new PermissionsError( 'read', $permErrors );
497 # Carry over 'diffonly' param via navigation links
498 if ( $diffOnly != $user->getBoolOption( 'diffonly' ) ) {
499 $query['diffonly'] = $diffOnly;
501 # Cascade unhide param in links for easy deletion browsing
502 if ( $this->unhide
) {
503 $query['unhide'] = 1;
506 # Check if one of the revisions is deleted/suppressed
507 $deleted = $suppressed = false;
508 $allowed = $this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $user );
512 # mOldRev is false if the difference engine is called with a "vague" query for
513 # a diff between a version V and its previous version V' AND the version V
514 # is the first version of that article. In that case, V' does not exist.
515 if ( $this->mOldRev
=== false ) {
516 if ( $this->mNewPage
) {
517 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
521 // Allow extensions to change the $oldHeader variable
522 Hooks
::run( 'DifferenceEngineOldHeaderNoOldRev', [ &$oldHeader ] );
524 Hooks
::run( 'DiffViewHeader', [ $this, $this->mOldRev
, $this->mNewRev
] );
526 if ( !$this->mOldPage ||
!$this->mNewPage
) {
527 // XXX say something to the user?
529 } elseif ( $this->mNewPage
->equals( $this->mOldPage
) ) {
530 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
533 $out->setPageTitle( $this->msg( 'difference-title-multipage',
534 $this->mOldPage
->getPrefixedText(), $this->mNewPage
->getPrefixedText() ) );
535 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
539 if ( $samePage && $this->mNewPage
&& $this->mNewPage
->quickUserCan( 'edit', $user ) ) {
540 if ( $this->mNewRev
->isCurrent() && $this->mNewPage
->userCan( 'rollback', $user ) ) {
541 $rollbackLink = Linker
::generateRollback( $this->mNewRev
, $this->getContext() );
542 if ( $rollbackLink ) {
543 $out->preventClickjacking();
544 $rollback = "\u{00A0}\u{00A0}\u{00A0}" . $rollbackLink;
548 if ( !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) &&
549 !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
)
551 $undoLink = Html
::element( 'a', [
552 'href' => $this->mNewPage
->getLocalURL( [
554 'undoafter' => $this->mOldid
,
555 'undo' => $this->mNewid
557 'title' => Linker
::titleAttrib( 'undo' ),
559 $this->msg( 'editundo' )->text()
561 $revisionTools['mw-diff-undo'] = $undoLink;
565 # Make "previous revision link"
566 if ( $samePage && $this->mOldPage
&& $this->mOldRev
->getPrevious() ) {
567 $prevlink = Linker
::linkKnown(
569 $this->msg( 'previousdiff' )->escaped(),
570 [ 'id' => 'differences-prevlink' ],
571 [ 'diff' => 'prev', 'oldid' => $this->mOldid
] +
$query
574 $prevlink = "\u{00A0}";
577 if ( $this->mOldRev
->isMinor() ) {
578 $oldminor = ChangesList
::flag( 'minor' );
583 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
584 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev
, 'complete' );
585 $oldChangeTags = ChangeTags
::formatSummaryRow( $this->mOldTags
, 'diff', $this->getContext() );
587 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
588 '<div id="mw-diff-otitle2">' .
589 Linker
::revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
590 '<div id="mw-diff-otitle3">' . $oldminor .
591 Linker
::revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
592 '<div id="mw-diff-otitle5">' . $oldChangeTags[0] . '</div>' .
593 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
595 // Allow extensions to change the $oldHeader variable
596 Hooks
::run( 'DifferenceEngineOldHeader', [ $this, &$oldHeader, $prevlink, $oldminor,
597 $diffOnly, $ldel, $this->unhide
] );
599 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
600 $deleted = true; // old revisions text is hidden
601 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
602 $suppressed = true; // also suppressed
606 # Check if this user can see the revisions
607 if ( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $user ) ) {
612 $out->addJsConfigVars( [
613 'wgDiffOldId' => $this->mOldid
,
614 'wgDiffNewId' => $this->mNewid
,
617 # Make "next revision link"
618 # Skip next link on the top revision
619 if ( $samePage && $this->mNewPage
&& !$this->mNewRev
->isCurrent() ) {
620 $nextlink = Linker
::linkKnown(
622 $this->msg( 'nextdiff' )->escaped(),
623 [ 'id' => 'differences-nextlink' ],
624 [ 'diff' => 'next', 'oldid' => $this->mNewid
] +
$query
627 $nextlink = "\u{00A0}";
630 if ( $this->mNewRev
->isMinor() ) {
631 $newminor = ChangesList
::flag( 'minor' );
636 # Handle RevisionDelete links...
637 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
639 # Allow extensions to define their own revision tools
640 Hooks
::run( 'DiffRevisionTools',
641 [ $this->mNewRev
, &$revisionTools, $this->mOldRev
, $user ] );
642 $formattedRevisionTools = [];
643 // Put each one in parentheses (poor man's button)
644 foreach ( $revisionTools as $key => $tool ) {
645 $toolClass = is_string( $key ) ?
$key : 'mw-diff-tool';
646 $element = Html
::rawElement(
648 [ 'class' => $toolClass ],
649 $this->msg( 'parentheses' )->rawParams( $tool )->escaped()
651 $formattedRevisionTools[] = $element;
653 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev
, 'complete' ) .
654 ' ' . implode( ' ', $formattedRevisionTools );
655 $newChangeTags = ChangeTags
::formatSummaryRow( $this->mNewTags
, 'diff', $this->getContext() );
657 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
658 '<div id="mw-diff-ntitle2">' . Linker
::revUserTools( $this->mNewRev
, !$this->unhide
) .
660 '<div id="mw-diff-ntitle3">' . $newminor .
661 Linker
::revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
662 '<div id="mw-diff-ntitle5">' . $newChangeTags[0] . '</div>' .
663 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
665 // Allow extensions to change the $newHeader variable
666 Hooks
::run( 'DifferenceEngineNewHeader', [ $this, &$newHeader, $formattedRevisionTools,
667 $nextlink, $rollback, $newminor, $diffOnly, $rdel, $this->unhide
] );
669 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
670 $deleted = true; // new revisions text is hidden
671 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
672 $suppressed = true; // also suppressed
676 # If the diff cannot be shown due to a deleted revision, then output
677 # the diff header and links to unhide (if available)...
678 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
679 $this->showDiffStyle();
680 $multi = $this->getMultiNotice();
681 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
683 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
684 # Give explanation for why revision is not visible
685 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
688 # Give explanation and add a link to view the diff...
689 $query = $this->getRequest()->appendQueryValue( 'unhide', '1' );
690 $link = $this->getTitle()->getFullURL( $query );
691 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
693 "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
697 # Otherwise, output a regular diff...
699 # Add deletion notice if the user is viewing deleted content
702 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
703 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" .
704 $this->msg( $msg )->parse() .
707 $this->showDiff( $oldHeader, $newHeader, $notice );
709 $this->renderNewRevision();
715 * Build a link to mark a change as patrolled.
717 * Returns empty string if there's either no revision to patrol or the user is not allowed to.
718 * Side effect: When the patrol link is build, this method will call
719 * OutputPage::preventClickjacking() and load mediawiki.page.patrol.ajax.
721 * @return string HTML or empty string
723 public function markPatrolledLink() {
724 if ( $this->mMarkPatrolledLink
=== null ) {
725 $linkInfo = $this->getMarkPatrolledLinkInfo();
726 // If false, there is no patrol link needed/allowed
727 if ( !$linkInfo ||
!$this->mNewPage
) {
728 $this->mMarkPatrolledLink
= '';
730 $this->mMarkPatrolledLink
= ' <span class="patrollink" data-mw="interface">[' .
733 $this->msg( 'markaspatrolleddiff' )->escaped(),
736 'action' => 'markpatrolled',
737 'rcid' => $linkInfo['rcid'],
740 // Allow extensions to change the markpatrolled link
741 Hooks
::run( 'DifferenceEngineMarkPatrolledLink', [ $this,
742 &$this->mMarkPatrolledLink
, $linkInfo['rcid'] ] );
745 return $this->mMarkPatrolledLink
;
749 * Returns an array of meta data needed to build a "mark as patrolled" link and
750 * adds the mediawiki.page.patrol.ajax to the output.
752 * @return array|false An array of meta data for a patrol link (rcid only)
753 * or false if no link is needed
755 protected function getMarkPatrolledLinkInfo() {
756 global $wgUseRCPatrol;
758 $user = $this->getUser();
760 // Prepare a change patrol link, if applicable
762 // Is patrolling enabled and the user allowed to?
763 $wgUseRCPatrol && $this->mNewPage
&& $this->mNewPage
->quickUserCan( 'patrol', $user ) &&
764 // Only do this if the revision isn't more than 6 hours older
765 // than the Max RC age (6h because the RC might not be cleaned out regularly)
766 RecentChange
::isInRCLifespan( $this->mNewRev
->getTimestamp(), 21600 )
768 // Look for an unpatrolled change corresponding to this diff
769 $db = wfGetDB( DB_REPLICA
);
770 $change = RecentChange
::newFromConds(
772 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
773 'rc_this_oldid' => $this->mNewid
,
774 'rc_patrolled' => RecentChange
::PRC_UNPATROLLED
779 if ( $change && !$change->getPerformer()->equals( $user ) ) {
780 $rcid = $change->getAttribute( 'rc_id' );
782 // None found or the page has been created by the current user.
783 // If the user could patrol this it already would be patrolled
787 // Allow extensions to possibly change the rcid here
788 // For example the rcid might be set to zero due to the user
789 // being the same as the performer of the change but an extension
790 // might still want to show it under certain conditions
791 Hooks
::run( 'DifferenceEngineMarkPatrolledRCID', [ &$rcid, $this, $change, $user ] );
795 $this->getOutput()->preventClickjacking();
796 if ( $user->isAllowed( 'writeapi' ) ) {
797 $this->getOutput()->addModules( 'mediawiki.page.patrol.ajax' );
806 // No mark as patrolled link applicable
811 * @param Revision $rev
815 protected function revisionDeleteLink( $rev ) {
816 $link = Linker
::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
817 if ( $link !== '' ) {
818 $link = "\u{00A0}\u{00A0}\u{00A0}" . $link . ' ';
825 * Show the new revision of the page.
827 * @note Not supported after calling setContent().
829 public function renderNewRevision() {
830 if ( $this->isContentOverridden
) {
831 // The code below only works with a Revision object. We could construct a fake revision
832 // (here or in setContent), but since this does not seem needed at the moment,
833 // we'll just fail for now.
834 throw new LogicException(
836 . ' is not supported after calling setContent(). Use setRevisions() instead.'
840 $out = $this->getOutput();
841 $revHeader = $this->getRevisionHeader( $this->mNewRev
);
842 # Add "current version as of X" title
843 $out->addHTML( "<hr class='diff-hr' id='mw-oldid' />
844 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
845 # Page content may be handled by a hooked call instead...
846 if ( Hooks
::run( 'ArticleContentOnDiff', [ $this, $out ] ) ) {
847 $this->loadNewText();
848 if ( !$this->mNewPage
) {
849 // New revision is unsaved; bail out.
850 // TODO in theory rendering the new revision is a meaningful thing to do
851 // even if it's unsaved, but a lot of untangling is required to do it safely.
855 $out->setRevisionId( $this->mNewid
);
856 $out->setRevisionTimestamp( $this->mNewRev
->getTimestamp() );
857 $out->setArticleFlag( true );
859 if ( !Hooks
::run( 'ArticleRevisionViewCustom',
860 [ $this->mNewRev
->getRevisionRecord(), $this->mNewPage
, $out ] )
862 // Handled by extension
863 // NOTE: sync with hooks called in Article::view()
864 } elseif ( !Hooks
::run( 'ArticleContentViewCustom',
865 [ $this->mNewContent
, $this->mNewPage
, $out ], '1.32' )
867 // Handled by extension
868 // NOTE: sync with hooks called in Article::view()
871 if ( $this->getTitle()->equals( $this->mNewPage
) ) {
872 // If the Title stored in the context is the same as the one
873 // of the new revision, we can use its associated WikiPage
875 $wikiPage = $this->getWikiPage();
877 // Otherwise we need to create our own WikiPage object
878 $wikiPage = WikiPage
::factory( $this->mNewPage
);
881 $parserOutput = $this->getParserOutput( $wikiPage, $this->mNewRev
);
883 # WikiPage::getParserOutput() should not return false, but just in case
884 if ( $parserOutput ) {
885 // Allow extensions to change parser output here
886 if ( Hooks
::run( 'DifferenceEngineRenderRevisionAddParserOutput',
887 [ $this, $out, $parserOutput, $wikiPage ] )
889 $out->addParserOutput( $parserOutput, [
890 'enableSectionEditLinks' => $this->mNewRev
->isCurrent()
891 && $this->mNewRev
->getTitle()->quickUserCan( 'edit', $this->getUser() ),
898 // Allow extensions to optionally not show the final patrolled link
899 if ( Hooks
::run( 'DifferenceEngineRenderRevisionShowFinalPatrolLink' ) ) {
900 # Add redundant patrol link on bottom...
901 $out->addHTML( $this->markPatrolledLink() );
906 * @param WikiPage $page
907 * @param Revision $rev
909 * @return ParserOutput|bool False if the revision was not found
911 protected function getParserOutput( WikiPage
$page, Revision
$rev ) {
912 if ( !$rev->getId() ) {
913 // WikiPage::getParserOutput wants a revision ID. Passing 0 will incorrectly show
914 // the current revision, so fail instead. If need be, WikiPage::getParserOutput
915 // could be made to accept a Revision or RevisionRecord instead of the id.
919 $parserOptions = $page->makeParserOptions( $this->getContext() );
920 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
922 return $parserOutput;
926 * Get the diff text, send it to the OutputPage object
927 * Returns false if the diff could not be generated, otherwise returns true
929 * @param string|bool $otitle Header for old text or false
930 * @param string|bool $ntitle Header for new text or false
931 * @param string $notice HTML between diff header and body
935 public function showDiff( $otitle, $ntitle, $notice = '' ) {
936 // Allow extensions to affect the output here
937 Hooks
::run( 'DifferenceEngineShowDiff', [ $this ] );
939 $diff = $this->getDiff( $otitle, $ntitle, $notice );
940 if ( $diff === false ) {
941 $this->showMissingRevision();
945 $this->showDiffStyle();
946 $this->getOutput()->addHTML( $diff );
953 * Add style sheets for diff display.
955 public function showDiffStyle() {
956 if ( !$this->isSlotDiffRenderer
) {
957 $this->getOutput()->addModuleStyles( 'mediawiki.diff.styles' );
958 foreach ( $this->getSlotDiffRenderers() as $slotDiffRenderer ) {
959 $slotDiffRenderer->addModules( $this->getOutput() );
965 * Get complete diff table, including header
967 * @param string|bool $otitle Header for old text or false
968 * @param string|bool $ntitle Header for new text or false
969 * @param string $notice HTML between diff header and body
973 public function getDiff( $otitle, $ntitle, $notice = '' ) {
974 $body = $this->getDiffBody();
975 if ( $body === false ) {
979 $multi = $this->getMultiNotice();
980 // Display a message when the diff is empty
981 if ( $body === '' ) {
982 $notice .= '<div class="mw-diff-empty">' .
983 $this->msg( 'diff-empty' )->parse() .
987 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
991 * Get the diff table body, without header
993 * @return mixed (string/false)
995 public function getDiffBody() {
996 $this->mCacheHit
= true;
997 // Check if the diff should be hidden from this user
998 if ( !$this->isContentOverridden
) {
999 if ( !$this->loadRevisionData() ) {
1001 } elseif ( $this->mOldRev
&&
1002 !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
1005 } elseif ( $this->mNewRev
&&
1006 !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
1011 if ( $this->mOldRev
=== false ||
( $this->mOldRev
&& $this->mNewRev
&&
1012 $this->mOldRev
->getId() && $this->mOldRev
->getId() == $this->mNewRev
->getId() )
1014 if ( Hooks
::run( 'DifferenceEngineShowEmptyOldContent', [ $this ] ) ) {
1022 $cache = ObjectCache
::getMainWANInstance();
1023 if ( $this->mOldid
&& $this->mNewid
) {
1024 // Check if subclass is still using the old way
1025 // for backwards-compatibility
1026 $key = $this->getDiffBodyCacheKey();
1027 if ( $key === null ) {
1028 $key = $cache->makeKey( ...$this->getDiffBodyCacheKeyParams() );
1032 if ( !$this->mRefreshCache
) {
1033 $difftext = $cache->get( $key );
1035 wfIncrStats( 'diff_cache.hit' );
1036 $difftext = $this->localiseDiff( $difftext );
1037 $difftext .= "\n<!-- diff cache key $key -->\n";
1041 } // don't try to load but save the result
1043 $this->mCacheHit
= false;
1045 // Loadtext is permission safe, this just clears out the diff
1046 if ( !$this->loadText() ) {
1051 // We've checked for revdelete at the beginning of this method; it's OK to ignore
1052 // read permissions here.
1053 $slotContents = $this->getSlotContents();
1054 foreach ( $this->getSlotDiffRenderers() as $role => $slotDiffRenderer ) {
1055 $slotDiff = $slotDiffRenderer->getDiff( $slotContents[$role]['old'],
1056 $slotContents[$role]['new'] );
1057 if ( $slotDiff && $role !== SlotRecord
::MAIN
) {
1058 // FIXME: ask SlotRoleHandler::getSlotNameMessage
1060 $difftext .= $this->getSlotHeader( $slotTitle );
1062 $difftext .= $slotDiff;
1065 // Avoid PHP 7.1 warning from passing $this by reference
1066 $diffEngine = $this;
1068 // Save to cache for 7 days
1069 if ( !Hooks
::run( 'AbortDiffCache', [ &$diffEngine ] ) ) {
1070 wfIncrStats( 'diff_cache.uncacheable' );
1071 } elseif ( $key !== false && $difftext !== false ) {
1072 wfIncrStats( 'diff_cache.miss' );
1073 $cache->set( $key, $difftext, 7 * 86400 );
1075 wfIncrStats( 'diff_cache.uncacheable' );
1077 // localise line numbers and title attribute text
1078 if ( $difftext !== false ) {
1079 $difftext = $this->localiseDiff( $difftext );
1086 * Get the diff table body for one slot, without header
1088 * @param string $role
1089 * @return string|false
1091 public function getDiffBodyForRole( $role ) {
1092 $diffRenderers = $this->getSlotDiffRenderers();
1093 if ( !isset( $diffRenderers[$role] ) ) {
1097 $slotContents = $this->getSlotContents();
1098 $slotDiff = $diffRenderers[$role]->getDiff( $slotContents[$role]['old'],
1099 $slotContents[$role]['new'] );
1104 if ( $role !== SlotRecord
::MAIN
) {
1105 // TODO use human-readable role name at least
1107 $slotDiff = $this->getSlotHeader( $slotTitle ) . $slotDiff;
1110 return $this->localiseDiff( $slotDiff );
1114 * Get a slot header for inclusion in a diff body (as a table row).
1116 * @param string $headerText The text of the header
1120 protected function getSlotHeader( $headerText ) {
1121 // The old revision is missing on oldid=<first>&diff=prev; only 2 columns in that case.
1122 $columnCount = $this->mOldRev ?
4 : 2;
1123 $userLang = $this->getLanguage()->getHtmlCode();
1124 return Html
::rawElement( 'tr', [ 'class' => 'mw-diff-slot-header', 'lang' => $userLang ],
1125 Html
::element( 'th', [ 'colspan' => $columnCount ], $headerText ) );
1129 * Returns the cache key for diff body text or content.
1131 * @deprecated since 1.31, use getDiffBodyCacheKeyParams() instead
1134 * @throws MWException
1135 * @return string|null
1137 protected function getDiffBodyCacheKey() {
1142 * Get the cache key parameters
1144 * Subclasses can replace the first element in the array to something
1145 * more specific to the type of diff (e.g. "inline-diff"), or append
1146 * if the cache should vary on more things. Overriding entirely should
1152 * @throws MWException
1154 protected function getDiffBodyCacheKeyParams() {
1155 if ( !$this->mOldid ||
!$this->mNewid
) {
1156 throw new MWException( 'mOldid and mNewid must be set to get diff cache key.' );
1159 $engine = $this->getEngine();
1164 "old-{$this->mOldid}",
1165 "rev-{$this->mNewid}"
1168 if ( $engine === 'wikidiff2' ) {
1169 $params[] = phpversion( 'wikidiff2' );
1170 $params[] = $this->getConfig()->get( 'WikiDiff2MovedParagraphDetectionCutoff' );
1173 if ( !$this->isSlotDiffRenderer
) {
1174 foreach ( $this->getSlotDiffRenderers() as $slotDiffRenderer ) {
1175 $params = array_merge( $params, $slotDiffRenderer->getExtraCacheKeys() );
1183 * Implements DifferenceEngineSlotDiffRenderer::getExtraCacheKeys(). Only used when
1184 * DifferenceEngine is wrapped in DifferenceEngineSlotDiffRenderer.
1186 * @internal for use by DifferenceEngineSlotDiffRenderer only
1189 public function getExtraCacheKeys() {
1190 // This method is called when the DifferenceEngine is used for a slot diff. We only care
1191 // about special things, not the revision IDs, which are added to the cache key by the
1192 // page-level DifferenceEngine, and which might not have a valid value for this object.
1193 $this->mOldid
= 123456789;
1194 $this->mNewid
= 987654321;
1196 // This will repeat a bunch of unnecessary key fields for each slot. Not nice but harmless.
1197 $cacheString = $this->getDiffBodyCacheKey();
1198 if ( $cacheString ) {
1199 return [ $cacheString ];
1202 $params = $this->getDiffBodyCacheKeyParams();
1204 // Try to get rid of the standard keys to keep the cache key human-readable:
1205 // call the getDiffBodyCacheKeyParams implementation of the base class, and if
1206 // the child class includes the same keys, drop them.
1207 // Uses an obscure PHP feature where static calls to non-static methods are allowed
1208 // as long as we are already in a non-static method of the same class, and the call context
1209 // ($this) will be inherited.
1210 // phpcs:ignore Squiz.Classes.SelfMemberReference.NotUsed
1211 $standardParams = DifferenceEngine
::getDiffBodyCacheKeyParams();
1212 if ( array_slice( $params, 0, count( $standardParams ) ) === $standardParams ) {
1213 $params = array_slice( $params, count( $standardParams ) );
1220 * Generate a diff, no caching.
1224 * @param Content $old Old content
1225 * @param Content $new New content
1227 * @throws Exception If old or new content is not an instance of TextContent.
1228 * @return bool|string
1230 * @deprecated since 1.32, use a SlotDiffRenderer instead.
1232 public function generateContentDiffBody( Content
$old, Content
$new ) {
1233 $slotDiffRenderer = $new->getContentHandler()->getSlotDiffRenderer( $this->getContext() );
1235 $slotDiffRenderer instanceof DifferenceEngineSlotDiffRenderer
1236 && $this->isSlotDiffRenderer
1238 // Oops, we are just about to enter an infinite loop (the slot-level DifferenceEngine
1239 // called a DifferenceEngineSlotDiffRenderer that wraps the same DifferenceEngine class).
1240 // This will happen when a content model has no custom slot diff renderer, it does have
1241 // a custom difference engine, but that does not override this method.
1242 throw new Exception( get_class( $this ) . ': could not maintain backwards compatibility. '
1243 . 'Please use a SlotDiffRenderer.' );
1245 return $slotDiffRenderer->getDiff( $old, $new ) . $this->getDebugString();
1249 * Generate a diff, no caching
1251 * @param string $otext Old text, must be already segmented
1252 * @param string $ntext New text, must be already segmented
1254 * @throws Exception If content handling for text content is configured in a way
1255 * that makes maintaining B/C hard.
1256 * @return bool|string
1258 * @deprecated since 1.32, use a TextSlotDiffRenderer instead.
1260 public function generateTextDiffBody( $otext, $ntext ) {
1261 $slotDiffRenderer = ContentHandler
::getForModelID( CONTENT_MODEL_TEXT
)
1262 ->getSlotDiffRenderer( $this->getContext() );
1263 if ( !( $slotDiffRenderer instanceof TextSlotDiffRenderer
) ) {
1264 // Someone used the GetSlotDiffRenderer hook to replace the renderer.
1265 // This is too unlikely to happen to bother handling properly.
1266 throw new Exception( 'The slot diff renderer for text content should be a '
1267 . 'TextSlotDiffRenderer subclass' );
1269 return $slotDiffRenderer->getTextDiff( $otext, $ntext ) . $this->getDebugString();
1273 * Process $wgExternalDiffEngine and get a sane, usable engine
1275 * @return bool|string 'wikidiff2', path to an executable, or false
1276 * @internal For use by this class and TextSlotDiffRenderer only.
1278 public static function getEngine() {
1279 global $wgExternalDiffEngine;
1280 // We use the global here instead of Config because we write to the value,
1281 // and Config is not mutable.
1282 if ( $wgExternalDiffEngine == 'wikidiff' ||
$wgExternalDiffEngine == 'wikidiff3' ) {
1283 wfDeprecated( "\$wgExternalDiffEngine = '{$wgExternalDiffEngine}'", '1.27' );
1284 $wgExternalDiffEngine = false;
1285 } elseif ( $wgExternalDiffEngine == 'wikidiff2' ) {
1286 wfDeprecated( "\$wgExternalDiffEngine = '{$wgExternalDiffEngine}'", '1.32' );
1287 $wgExternalDiffEngine = false;
1288 } elseif ( !is_string( $wgExternalDiffEngine ) && $wgExternalDiffEngine !== false ) {
1289 // And prevent people from shooting themselves in the foot...
1290 wfWarn( '$wgExternalDiffEngine is set to a non-string value, forcing it to false' );
1291 $wgExternalDiffEngine = false;
1294 if ( is_string( $wgExternalDiffEngine ) && is_executable( $wgExternalDiffEngine ) ) {
1295 return $wgExternalDiffEngine;
1296 } elseif ( $wgExternalDiffEngine === false && function_exists( 'wikidiff2_do_diff' ) ) {
1305 * Generates diff, to be wrapped internally in a logging/instrumentation
1307 * @param string $otext Old text, must be already segmented
1308 * @param string $ntext New text, must be already segmented
1310 * @throws Exception If content handling for text content is configured in a way
1311 * that makes maintaining B/C hard.
1312 * @return bool|string
1314 * @deprecated since 1.32, use a TextSlotDiffRenderer instead.
1316 protected function textDiff( $otext, $ntext ) {
1317 $slotDiffRenderer = ContentHandler
::getForModelID( CONTENT_MODEL_TEXT
)
1318 ->getSlotDiffRenderer( $this->getContext() );
1319 if ( !( $slotDiffRenderer instanceof TextSlotDiffRenderer
) ) {
1320 // Someone used the GetSlotDiffRenderer hook to replace the renderer.
1321 // This is too unlikely to happen to bother handling properly.
1322 throw new Exception( 'The slot diff renderer for text content should be a '
1323 . 'TextSlotDiffRenderer subclass' );
1325 return $slotDiffRenderer->getTextDiff( $otext, $ntext ) . $this->getDebugString();
1329 * Generate a debug comment indicating diff generating time,
1330 * server node, and generator backend.
1332 * @param string $generator : What diff engine was used
1336 protected function debug( $generator = "internal" ) {
1337 global $wgShowHostnames;
1338 if ( !$this->enableDebugComment
) {
1341 $data = [ $generator ];
1342 if ( $wgShowHostnames ) {
1343 $data[] = wfHostname();
1345 $data[] = wfTimestamp( TS_DB
);
1347 return "<!-- diff generator: " .
1348 implode( " ", array_map( "htmlspecialchars", $data ) ) .
1352 private function getDebugString() {
1353 $engine = self
::getEngine();
1354 if ( $engine === 'wikidiff2' ) {
1355 return $this->debug( 'wikidiff2' );
1356 } elseif ( $engine === false ) {
1357 return $this->debug( 'native PHP' );
1359 return $this->debug( "external $engine" );
1364 * Localise diff output
1366 * @param string $text
1369 private function localiseDiff( $text ) {
1370 $text = $this->localiseLineNumbers( $text );
1371 if ( $this->getEngine() === 'wikidiff2' &&
1372 version_compare( phpversion( 'wikidiff2' ), '1.5.1', '>=' )
1374 $text = $this->addLocalisedTitleTooltips( $text );
1380 * Replace line numbers with the text in the user's language
1382 * @param string $text
1386 public function localiseLineNumbers( $text ) {
1387 return preg_replace_callback(
1388 '/<!--LINE (\d+)-->/',
1389 [ $this, 'localiseLineNumbersCb' ],
1394 public function localiseLineNumbersCb( $matches ) {
1395 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) {
1399 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
1403 * Add title attributes for tooltips on moved paragraph indicators
1405 * @param string $text
1408 private function addLocalisedTitleTooltips( $text ) {
1409 return preg_replace_callback(
1410 '/class="mw-diff-movedpara-(left|right)"/',
1411 [ $this, 'addLocalisedTitleTooltipsCb' ],
1417 * @param array $matches
1420 private function addLocalisedTitleTooltipsCb( array $matches ) {
1421 $key = $matches[1] === 'right' ?
1422 'diff-paragraph-moved-toold' :
1423 'diff-paragraph-moved-tonew';
1424 return $matches[0] . ' title="' . $this->msg( $key )->escaped() . '"';
1428 * If there are revisions between the ones being compared, return a note saying so.
1432 public function getMultiNotice() {
1433 // The notice only make sense if we are diffing two saved revisions of the same page.
1435 !$this->mOldRev ||
!$this->mNewRev
1436 ||
!$this->mOldPage ||
!$this->mNewPage
1437 ||
!$this->mOldPage
->equals( $this->mNewPage
)
1442 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
1443 $oldRev = $this->mNewRev
; // flip
1444 $newRev = $this->mOldRev
; // flip
1445 } else { // normal case
1446 $oldRev = $this->mOldRev
;
1447 $newRev = $this->mNewRev
;
1450 // Sanity: don't show the notice if too many rows must be scanned
1451 // @todo show some special message for that case
1452 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev, 1000 );
1453 if ( $nEdits > 0 && $nEdits <= 1000 ) {
1454 $limit = 100; // use diff-multi-manyusers if too many users
1455 $users = $this->mNewPage
->getAuthorsBetween( $oldRev, $newRev, $limit );
1456 $numUsers = count( $users );
1458 if ( $numUsers == 1 && $users[0] == $newRev->getUserText( Revision
::RAW
) ) {
1459 $numUsers = 0; // special case to say "by the same user" instead of "by one other user"
1462 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
1465 return ''; // nothing
1469 * Get a notice about how many intermediate edits and users there are
1471 * @param int $numEdits
1472 * @param int $numUsers
1477 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
1478 if ( $numUsers === 0 ) {
1479 $msg = 'diff-multi-sameuser';
1480 } elseif ( $numUsers > $limit ) {
1481 $msg = 'diff-multi-manyusers';
1484 $msg = 'diff-multi-otherusers';
1487 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
1491 * Get a header for a specified revision.
1493 * @param Revision $rev
1494 * @param string $complete 'complete' to get the header wrapped depending
1495 * the visibility of the revision and a link to edit the page.
1497 * @return string HTML fragment
1499 public function getRevisionHeader( Revision
$rev, $complete = '' ) {
1500 $lang = $this->getLanguage();
1501 $user = $this->getUser();
1502 $revtimestamp = $rev->getTimestamp();
1503 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
1504 $dateofrev = $lang->userDate( $revtimestamp, $user );
1505 $timeofrev = $lang->userTime( $revtimestamp, $user );
1507 $header = $this->msg(
1508 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
1514 if ( $complete !== 'complete' ) {
1518 $title = $rev->getTitle();
1520 $header = Linker
::linkKnown( $title, $header, [],
1521 [ 'oldid' => $rev->getId() ] );
1523 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
1524 $editQuery = [ 'action' => 'edit' ];
1525 if ( !$rev->isCurrent() ) {
1526 $editQuery['oldid'] = $rev->getId();
1529 $key = $title->quickUserCan( 'edit', $user ) ?
'editold' : 'viewsourceold';
1530 $msg = $this->msg( $key )->escaped();
1531 $editLink = $this->msg( 'parentheses' )->rawParams(
1532 Linker
::linkKnown( $title, $msg, [], $editQuery ) )->escaped();
1533 $header .= ' ' . Html
::rawElement(
1535 [ 'class' => 'mw-diff-edit' ],
1538 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
1539 $header = Html
::rawElement(
1541 [ 'class' => 'history-deleted' ],
1546 $header = Html
::rawElement( 'span', [ 'class' => 'history-deleted' ], $header );
1553 * Add the header to a diff body
1555 * @param string $diff Diff body
1556 * @param string $otitle Old revision header
1557 * @param string $ntitle New revision header
1558 * @param string $multi Notice telling user that there are intermediate
1559 * revisions between the ones being compared
1560 * @param string $notice Other notices, e.g. that user is viewing deleted content
1564 public function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
1565 // shared.css sets diff in interface language/dir, but the actual content
1566 // is often in a different language, mostly the page content language/dir
1567 $header = Html
::openElement( 'table', [
1568 'class' => [ 'diff', 'diff-contentalign-' . $this->getDiffLang()->alignStart() ],
1569 'data-mw' => 'interface',
1571 $userLang = htmlspecialchars( $this->getLanguage()->getHtmlCode() );
1573 if ( !$diff && !$otitle ) {
1575 <tr class=\"diff-title\" lang=\"{$userLang}\">
1576 <td class=\"diff-ntitle\">{$ntitle}</td>
1580 if ( $diff ) { // Safari/Chrome show broken output if cols not used
1582 <col class=\"diff-marker\" />
1583 <col class=\"diff-content\" />
1584 <col class=\"diff-marker\" />
1585 <col class=\"diff-content\" />";
1592 if ( $otitle ||
$ntitle ) {
1594 <tr class=\"diff-title\" lang=\"{$userLang}\">
1595 <td colspan=\"$colspan\" class=\"diff-otitle\">{$otitle}</td>
1596 <td colspan=\"$colspan\" class=\"diff-ntitle\">{$ntitle}</td>
1601 if ( $multi != '' ) {
1602 $header .= "<tr><td colspan=\"{$multiColspan}\" " .
1603 "class=\"diff-multi\" lang=\"{$userLang}\">{$multi}</td></tr>";
1605 if ( $notice != '' ) {
1606 $header .= "<tr><td colspan=\"{$multiColspan}\" " .
1607 "class=\"diff-notice\" lang=\"{$userLang}\">{$notice}</td></tr>";
1610 return $header . $diff . "</table>";
1614 * Use specified text instead of loading from the database
1615 * @param Content $oldContent
1616 * @param Content $newContent
1618 * @deprecated since 1.32, use setRevisions or ContentHandler::getSlotDiffRenderer.
1620 public function setContent( Content
$oldContent, Content
$newContent ) {
1621 $this->mOldContent
= $oldContent;
1622 $this->mNewContent
= $newContent;
1624 $this->mTextLoaded
= 2;
1625 $this->mRevisionsLoaded
= true;
1626 $this->isContentOverridden
= true;
1627 $this->slotDiffRenderers
= null;
1631 * Use specified text instead of loading from the database.
1632 * @param RevisionRecord|null $oldRevision
1633 * @param RevisionRecord $newRevision
1635 public function setRevisions(
1636 RevisionRecord
$oldRevision = null, RevisionRecord
$newRevision
1638 if ( $oldRevision ) {
1639 $this->mOldRev
= new Revision( $oldRevision );
1640 $this->mOldid
= $oldRevision->getId();
1641 $this->mOldPage
= Title
::newFromLinkTarget( $oldRevision->getPageAsLinkTarget() );
1642 // This method is meant for edit diffs and such so there is no reason to provide a
1643 // revision that's not readable to the user, but check it just in case.
1644 $this->mOldContent
= $oldRevision ?
$oldRevision->getContent( SlotRecord
::MAIN
,
1645 RevisionRecord
::FOR_THIS_USER
, $this->getUser() ) : null;
1647 $this->mOldPage
= null;
1648 $this->mOldRev
= $this->mOldid
= false;
1650 $this->mNewRev
= new Revision( $newRevision );
1651 $this->mNewid
= $newRevision->getId();
1652 $this->mNewPage
= Title
::newFromLinkTarget( $newRevision->getPageAsLinkTarget() );
1653 $this->mNewContent
= $newRevision->getContent( SlotRecord
::MAIN
,
1654 RevisionRecord
::FOR_THIS_USER
, $this->getUser() );
1656 $this->mRevisionsIdsLoaded
= $this->mRevisionsLoaded
= true;
1657 $this->mTextLoaded
= !!$oldRevision +
1;
1658 $this->isContentOverridden
= false;
1659 $this->slotDiffRenderers
= null;
1663 * Set the language in which the diff text is written
1665 * @param Language $lang
1668 public function setTextLanguage( Language
$lang ) {
1669 $this->mDiffLang
= $lang;
1673 * Maps a revision pair definition as accepted by DifferenceEngine constructor
1674 * to a pair of actual integers representing revision ids.
1676 * @param int $old Revision id, e.g. from URL parameter 'oldid'
1677 * @param int|string $new Revision id or strings 'next' or 'prev', e.g. from URL parameter 'diff'
1679 * @return array List of two revision ids, older first, later second.
1680 * Zero signifies invalid argument passed.
1681 * false signifies that there is no previous/next revision ($old is the oldest/newest one).
1683 public function mapDiffPrevNext( $old, $new ) {
1684 if ( $new === 'prev' ) {
1685 // Show diff between revision $old and the previous one. Get previous one from DB.
1686 $newid = intval( $old );
1687 $oldid = $this->getTitle()->getPreviousRevisionID( $newid );
1688 } elseif ( $new === 'next' ) {
1689 // Show diff between revision $old and the next one. Get next one from DB.
1690 $oldid = intval( $old );
1691 $newid = $this->getTitle()->getNextRevisionID( $oldid );
1693 $oldid = intval( $old );
1694 $newid = intval( $new );
1697 return [ $oldid, $newid ];
1703 private function loadRevisionIds() {
1704 if ( $this->mRevisionsIdsLoaded
) {
1708 $this->mRevisionsIdsLoaded
= true;
1710 $old = $this->mOldid
;
1711 $new = $this->mNewid
;
1713 list( $this->mOldid
, $this->mNewid
) = self
::mapDiffPrevNext( $old, $new );
1714 if ( $new === 'next' && $this->mNewid
=== false ) {
1715 # if no result, NewId points to the newest old revision. The only newer
1716 # revision is cur, which is "0".
1721 'NewDifferenceEngine',
1722 [ $this->getTitle(), &$this->mOldid
, &$this->mNewid
, $old, $new ]
1727 * Load revision metadata for the specified revisions. If newid is 0, then compare
1728 * the old revision in oldid to the current revision of the current page (as defined
1729 * by the request context); if oldid is 0, then compare the revision in newid to the
1730 * immediately previous one.
1732 * If oldid is false, leave the corresponding revision object set
1733 * to false. This can happen with 'diff=prev' pointing to a non-existent revision,
1734 * and is also used directly by the API.
1736 * @return bool Whether both revisions were loaded successfully. Setting mOldRev
1737 * to false counts as successful loading.
1739 public function loadRevisionData() {
1740 if ( $this->mRevisionsLoaded
) {
1741 return $this->isContentOverridden ||
$this->mNewRev
&& !is_null( $this->mOldRev
);
1744 // Whether it succeeds or fails, we don't want to try again
1745 $this->mRevisionsLoaded
= true;
1747 $this->loadRevisionIds();
1749 // Load the new revision object
1750 if ( $this->mNewid
) {
1751 $this->mNewRev
= Revision
::newFromId( $this->mNewid
);
1753 $this->mNewRev
= Revision
::newFromTitle(
1756 Revision
::READ_NORMAL
1760 if ( !$this->mNewRev
instanceof Revision
) {
1764 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1765 $this->mNewid
= $this->mNewRev
->getId();
1766 if ( $this->mNewid
) {
1767 $this->mNewPage
= $this->mNewRev
->getTitle();
1769 $this->mNewPage
= null;
1772 // Load the old revision object
1773 $this->mOldRev
= false;
1774 if ( $this->mOldid
) {
1775 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1776 } elseif ( $this->mOldid
=== 0 ) {
1777 $rev = $this->mNewRev
->getPrevious();
1779 $this->mOldid
= $rev->getId();
1780 $this->mOldRev
= $rev;
1782 // No previous revision; mark to show as first-version only.
1783 $this->mOldid
= false;
1784 $this->mOldRev
= false;
1786 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1788 if ( is_null( $this->mOldRev
) ) {
1792 if ( $this->mOldRev
&& $this->mOldRev
->getId() ) {
1793 $this->mOldPage
= $this->mOldRev
->getTitle();
1795 $this->mOldPage
= null;
1798 // Load tags information for both revisions
1799 $dbr = wfGetDB( DB_REPLICA
);
1800 if ( $this->mOldid
!== false ) {
1801 $this->mOldTags
= $dbr->selectField(
1804 [ 'ts_rev_id' => $this->mOldid
],
1808 $this->mOldTags
= false;
1810 $this->mNewTags
= $dbr->selectField(
1813 [ 'ts_rev_id' => $this->mNewid
],
1821 * Load the text of the revisions, as well as revision data.
1822 * When the old revision is missing (mOldRev is false), loading mOldContent is not attempted.
1824 * @return bool Whether the content of both revisions could be loaded successfully.
1825 * (When mOldRev is false, that still counts as a success.)
1828 public function loadText() {
1829 if ( $this->mTextLoaded
== 2 ) {
1830 return $this->loadRevisionData() && ( $this->mOldRev
=== false ||
$this->mOldContent
)
1831 && $this->mNewContent
;
1834 // Whether it succeeds or fails, we don't want to try again
1835 $this->mTextLoaded
= 2;
1837 if ( !$this->loadRevisionData() ) {
1841 if ( $this->mOldRev
) {
1842 $this->mOldContent
= $this->mOldRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1843 if ( $this->mOldContent
=== null ) {
1848 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1849 Hooks
::run( 'DifferenceEngineLoadTextAfterNewContentIsLoaded', [ $this ] );
1850 if ( $this->mNewContent
=== null ) {
1858 * Load the text of the new revision, not the old one
1860 * @return bool Whether the content of the new revision could be loaded successfully.
1862 public function loadNewText() {
1863 if ( $this->mTextLoaded
>= 1 ) {
1864 return $this->loadRevisionData();
1867 $this->mTextLoaded
= 1;
1869 if ( !$this->loadRevisionData() ) {
1873 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1875 Hooks
::run( 'DifferenceEngineAfterLoadNewText', [ $this ] );