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';
60 /** @var int Revision ID or 0 for current */
63 /** @var int|string Revision ID or null for current or an alias such as 'next' */
70 * Old revision (left pane).
71 * Allowed to be an unsaved revision, unlikely that's ever needed though.
72 * Null when the old revision does not exist; this can happen when using
73 * diff=prev on the first revision.
74 * Since 1.32 public access is deprecated.
80 * New revision (right pane).
81 * Note that this might be an unsaved revision (e.g. for edit preview).
82 * Null only in case of load failure; diff methods will just return an error message in that case.
83 * Since 1.32 public access is deprecated.
89 * Title of $mOldRev or null if the old revision does not exist or does not belong to a page.
90 * Since 1.32 public access is deprecated and the property can be null.
96 * Title of $mNewRev or null if the new revision does not exist or does not belong to a page.
97 * Since 1.32 public access is deprecated and the property can be null.
104 * @deprecated since 1.32, content slots are now handled by the corresponding SlotDiffRenderer.
105 * This property is set to the content of the main slot, but not actually used for the main diff.
107 private $mOldContent;
111 * @deprecated since 1.32, content slots are now handled by the corresponding SlotDiffRenderer.
112 * This property is set to the content of the main slot, but not actually used for the main diff.
114 private $mNewContent;
117 protected $mDiffLang;
119 /** @var bool Have the revisions IDs been loaded */
120 private $mRevisionsIdsLoaded = false;
122 /** @var bool Have the revisions been loaded */
123 protected $mRevisionsLoaded = false;
125 /** @var int How many text blobs have been loaded, 0, 1 or 2? */
126 protected $mTextLoaded = 0;
129 * Was the content overridden via setContent()?
130 * If the content was overridden, most internal state (e.g. mOldid or mOldRev) should be ignored
131 * and only mOldContent and mNewContent is reliable.
132 * (Note that setRevisions() does not set this flag as in that case all properties are
133 * overriden and remain consistent with each other, so no special handling is needed.)
136 protected $isContentOverridden = false;
138 /** @var bool Was the diff fetched from cache? */
139 protected $mCacheHit = false;
142 * Set this to true to add debug info to the HTML output.
143 * Warning: this may cause RSS readers to spuriously mark articles as "new"
146 public $enableDebugComment = false;
148 /** @var bool If true, line X is not displayed when X is 1, for example
149 * to increase readability and conserve space with many small diffs.
151 protected $mReducedLineNumbers = false;
153 /** @var string Link to action=markpatrolled */
154 protected $mMarkPatrolledLink = null;
156 /** @var bool Show rev_deleted content if allowed */
157 protected $unhide = false;
159 /** @var bool Refresh the diff cache */
160 protected $mRefreshCache = false;
162 /** @var SlotDiffRenderer[] DifferenceEngine classes for the slots, keyed by role name. */
163 protected $slotDiffRenderers = null;
166 * Temporary hack for B/C while slot diff related methods of DifferenceEngine are being
167 * deprecated. When true, we are inside a DifferenceEngineSlotDiffRenderer and
168 * $slotDiffRenderers should not be used.
171 protected $isSlotDiffRenderer = false;
176 * @param IContextSource|null $context Context to use, anything else will be ignored
177 * @param int $old Old ID we want to show and diff with.
178 * @param string|int $new Either revision ID or 'prev' or 'next'. Default: 0.
179 * @param int $rcid Deprecated, no longer used!
180 * @param bool $refreshCache If set, refreshes the diff cache
181 * @param bool $unhide If set, allow viewing deleted revs
183 public function __construct( $context = null, $old = 0, $new = 0, $rcid = 0,
184 $refreshCache = false, $unhide = false
186 $this->deprecatePublicProperty( 'mOldid', '1.32', __CLASS__
);
187 $this->deprecatePublicProperty( 'mNewid', '1.32', __CLASS__
);
188 $this->deprecatePublicProperty( 'mOldRev', '1.32', __CLASS__
);
189 $this->deprecatePublicProperty( 'mNewRev', '1.32', __CLASS__
);
190 $this->deprecatePublicProperty( 'mOldPage', '1.32', __CLASS__
);
191 $this->deprecatePublicProperty( 'mNewPage', '1.32', __CLASS__
);
192 $this->deprecatePublicProperty( 'mOldContent', '1.32', __CLASS__
);
193 $this->deprecatePublicProperty( 'mNewContent', '1.32', __CLASS__
);
194 $this->deprecatePublicProperty( 'mRevisionsLoaded', '1.32', __CLASS__
);
195 $this->deprecatePublicProperty( 'mTextLoaded', '1.32', __CLASS__
);
196 $this->deprecatePublicProperty( 'mCacheHit', '1.32', __CLASS__
);
198 if ( $context instanceof IContextSource
) {
199 $this->setContext( $context );
202 wfDebug( "DifferenceEngine old '$old' new '$new' rcid '$rcid'\n" );
204 $this->mOldid
= $old;
205 $this->mNewid
= $new;
206 $this->mRefreshCache
= $refreshCache;
207 $this->unhide
= $unhide;
211 * @return SlotDiffRenderer[] Diff renderers for each slot, keyed by role name.
212 * Includes slots only present in one of the revisions.
214 protected function getSlotDiffRenderers() {
215 if ( $this->isSlotDiffRenderer
) {
216 throw new LogicException( __METHOD__
. ' called in slot diff renderer mode' );
219 if ( $this->slotDiffRenderers
=== null ) {
220 if ( !$this->loadRevisionData() ) {
224 $slotContents = $this->getSlotContents();
225 $this->slotDiffRenderers
= array_map( function ( $contents ) {
226 /** @var $content Content */
227 $content = $contents['new'] ?
: $contents['old'];
228 return $content->getContentHandler()->getSlotDiffRenderer( $this->getContext() );
231 return $this->slotDiffRenderers
;
235 * Mark this DifferenceEngine as a slot renderer (as opposed to a page renderer).
236 * This is used in legacy mode when the DifferenceEngine is wrapped in a
237 * DifferenceEngineSlotDiffRenderer.
238 * @internal For use by DifferenceEngineSlotDiffRenderer only.
240 public function markAsSlotDiffRenderer() {
241 $this->isSlotDiffRenderer
= true;
245 * Get the old and new content objects for all slots.
246 * This method does not do any permission checks.
247 * @return array [ role => [ 'old' => SlotRecord, 'new' => SlotRecord ], ... ]
249 protected function getSlotContents() {
250 if ( $this->isContentOverridden
) {
253 'old' => $this->mOldContent
,
254 'new' => $this->mNewContent
,
259 $oldRev = $this->mOldRev
->getRevisionRecord();
260 $newRev = $this->mNewRev
->getRevisionRecord();
261 // The order here will determine the visual order of the diff. The current logic is
262 // changed first, then added, then deleted. This is ad hoc and should not be relied on
263 // - in the future we may want the ordering to depend on the page type.
264 $roles = array_merge( $newRev->getSlotRoles(), $oldRev->getSlotRoles() );
265 $oldSlots = $oldRev->getSlots()->getSlots();
266 $newSlots = $newRev->getSlots()->getSlots();
269 foreach ( $roles as $role ) {
271 'old' => isset( $oldSlots[$role] ) ?
$oldSlots[$role]->getContent() : null,
272 'new' => isset( $newSlots[$role] ) ?
$newSlots[$role]->getContent() : null,
275 // move main slot to front
276 if ( isset( $slots['main'] ) ) {
277 $slots = [ 'main' => $slots['main'] ] +
$slots;
282 public function getTitle() {
283 // T202454 avoid errors when there is no title
284 return parent
::getTitle() ?
: Title
::makeTitle( NS_SPECIAL
, 'BadTitle/DifferenceEngine' );
288 * Set reduced line numbers mode.
289 * When set, line X is not displayed when X is 1, for example to increase readability and
290 * conserve space with many small diffs.
293 public function setReducedLineNumbers( $value = true ) {
294 $this->mReducedLineNumbers
= $value;
298 * Get the language of the difference engine, defaults to page content language
302 public function getDiffLang() {
303 if ( $this->mDiffLang
=== null ) {
304 # Default language in which the diff text is written.
305 $this->mDiffLang
= $this->getTitle()->getPageLanguage();
308 return $this->mDiffLang
;
314 public function wasCacheHit() {
315 return $this->mCacheHit
;
321 public function getOldid() {
322 $this->loadRevisionIds();
324 return $this->mOldid
;
330 public function getNewid() {
331 $this->loadRevisionIds();
333 return $this->mNewid
;
337 * Get the left side of the diff.
338 * Could be null when the first revision of the page is diffed to 'prev' (or in the case of
340 * @return RevisionRecord|null
342 public function getOldRevision() {
343 return $this->mOldRev ?
$this->mOldRev
->getRevisionRecord() : null;
347 * Get the right side of the diff.
348 * Should not be null but can still happen in the case of load failure.
349 * @return RevisionRecord|null
351 public function getNewRevision() {
352 return $this->mNewRev ?
$this->mNewRev
->getRevisionRecord() : null;
356 * Look up a special:Undelete link to the given deleted revision id,
357 * as a workaround for being unable to load deleted diffs in currently.
359 * @param int $id Revision ID
361 * @return string|bool Link HTML or false
363 public function deletedLink( $id ) {
364 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
365 $dbr = wfGetDB( DB_REPLICA
);
366 $arQuery = Revision
::getArchiveQueryInfo();
367 $row = $dbr->selectRow(
369 array_merge( $arQuery['fields'], [ 'ar_namespace', 'ar_title' ] ),
370 [ 'ar_rev_id' => $id ],
376 $rev = Revision
::newFromArchiveRow( $row );
377 $title = Title
::makeTitleSafe( $row->ar_namespace
, $row->ar_title
);
379 return SpecialPage
::getTitleFor( 'Undelete' )->getFullURL( [
380 'target' => $title->getPrefixedText(),
381 'timestamp' => $rev->getTimestamp()
390 * Build a wikitext link toward a deleted revision, if viewable.
392 * @param int $id Revision ID
394 * @return string Wikitext fragment
396 public function deletedIdMarker( $id ) {
397 $link = $this->deletedLink( $id );
399 return "[$link $id]";
405 private function showMissingRevision() {
406 $out = $this->getOutput();
409 if ( $this->mOldRev
=== null ||
410 ( $this->mOldRev
&& $this->mOldContent
=== null )
412 $missing[] = $this->deletedIdMarker( $this->mOldid
);
414 if ( $this->mNewRev
=== null ||
415 ( $this->mNewRev
&& $this->mNewContent
=== null )
417 $missing[] = $this->deletedIdMarker( $this->mNewid
);
420 $out->setPageTitle( $this->msg( 'errorpagetitle' ) );
421 $msg = $this->msg( 'difference-missing-revision' )
422 ->params( $this->getLanguage()->listToText( $missing ) )
423 ->numParams( count( $missing ) )
425 $out->addHTML( $msg );
428 public function showDiffPage( $diffOnly = false ) {
429 # Allow frames except in certain special cases
430 $out = $this->getOutput();
431 $out->allowClickjacking();
432 $out->setRobotPolicy( 'noindex,nofollow' );
434 // Allow extensions to add any extra output here
435 Hooks
::run( 'DifferenceEngineShowDiffPage', [ $out ] );
437 if ( !$this->loadRevisionData() ) {
438 if ( Hooks
::run( 'DifferenceEngineShowDiffPageMaybeShowMissingRevision', [ $this ] ) ) {
439 $this->showMissingRevision();
444 $user = $this->getUser();
446 if ( $this->mNewPage
) {
447 $permErrors = $this->mNewPage
->getUserPermissionsErrors( 'read', $user );
449 if ( $this->mOldPage
) {
450 $permErrors = wfMergeErrorArrays( $permErrors,
451 $this->mOldPage
->getUserPermissionsErrors( 'read', $user ) );
453 if ( count( $permErrors ) ) {
454 throw new PermissionsError( 'read', $permErrors );
460 # Carry over 'diffonly' param via navigation links
461 if ( $diffOnly != $user->getBoolOption( 'diffonly' ) ) {
462 $query['diffonly'] = $diffOnly;
464 # Cascade unhide param in links for easy deletion browsing
465 if ( $this->unhide
) {
466 $query['unhide'] = 1;
469 # Check if one of the revisions is deleted/suppressed
470 $deleted = $suppressed = false;
471 $allowed = $this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $user );
475 # mOldRev is false if the difference engine is called with a "vague" query for
476 # a diff between a version V and its previous version V' AND the version V
477 # is the first version of that article. In that case, V' does not exist.
478 if ( $this->mOldRev
=== false ) {
479 if ( $this->mNewPage
) {
480 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
484 // Allow extensions to change the $oldHeader variable
485 Hooks
::run( 'DifferenceEngineOldHeaderNoOldRev', [ &$oldHeader ] );
487 Hooks
::run( 'DiffViewHeader', [ $this, $this->mOldRev
, $this->mNewRev
] );
489 if ( !$this->mOldPage ||
!$this->mNewPage
) {
490 // XXX say something to the user?
492 } elseif ( $this->mNewPage
->equals( $this->mOldPage
) ) {
493 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
496 $out->setPageTitle( $this->msg( 'difference-title-multipage',
497 $this->mOldPage
->getPrefixedText(), $this->mNewPage
->getPrefixedText() ) );
498 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
502 if ( $samePage && $this->mNewPage
&& $this->mNewPage
->quickUserCan( 'edit', $user ) ) {
503 if ( $this->mNewRev
->isCurrent() && $this->mNewPage
->userCan( 'rollback', $user ) ) {
504 $rollbackLink = Linker
::generateRollback( $this->mNewRev
, $this->getContext() );
505 if ( $rollbackLink ) {
506 $out->preventClickjacking();
507 $rollback = "\u{00A0}\u{00A0}\u{00A0}" . $rollbackLink;
511 if ( !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) &&
512 !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
)
514 $undoLink = Html
::element( 'a', [
515 'href' => $this->mNewPage
->getLocalURL( [
517 'undoafter' => $this->mOldid
,
518 'undo' => $this->mNewid
520 'title' => Linker
::titleAttrib( 'undo' ),
522 $this->msg( 'editundo' )->text()
524 $revisionTools['mw-diff-undo'] = $undoLink;
528 # Make "previous revision link"
529 if ( $samePage && $this->mOldPage
&& $this->mOldRev
->getPrevious() ) {
530 $prevlink = Linker
::linkKnown(
532 $this->msg( 'previousdiff' )->escaped(),
533 [ 'id' => 'differences-prevlink' ],
534 [ 'diff' => 'prev', 'oldid' => $this->mOldid
] +
$query
537 $prevlink = "\u{00A0}";
540 if ( $this->mOldRev
->isMinor() ) {
541 $oldminor = ChangesList
::flag( 'minor' );
546 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
547 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev
, 'complete' );
548 $oldChangeTags = ChangeTags
::formatSummaryRow( $this->mOldTags
, 'diff', $this->getContext() );
550 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
551 '<div id="mw-diff-otitle2">' .
552 Linker
::revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
553 '<div id="mw-diff-otitle3">' . $oldminor .
554 Linker
::revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
555 '<div id="mw-diff-otitle5">' . $oldChangeTags[0] . '</div>' .
556 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
558 // Allow extensions to change the $oldHeader variable
559 Hooks
::run( 'DifferenceEngineOldHeader', [ $this, &$oldHeader, $prevlink, $oldminor,
560 $diffOnly, $ldel, $this->unhide
] );
562 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
563 $deleted = true; // old revisions text is hidden
564 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
565 $suppressed = true; // also suppressed
569 # Check if this user can see the revisions
570 if ( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $user ) ) {
575 $out->addJsConfigVars( [
576 'wgDiffOldId' => $this->mOldid
,
577 'wgDiffNewId' => $this->mNewid
,
580 # Make "next revision link"
581 # Skip next link on the top revision
582 if ( $samePage && $this->mNewPage
&& !$this->mNewRev
->isCurrent() ) {
583 $nextlink = Linker
::linkKnown(
585 $this->msg( 'nextdiff' )->escaped(),
586 [ 'id' => 'differences-nextlink' ],
587 [ 'diff' => 'next', 'oldid' => $this->mNewid
] +
$query
590 $nextlink = "\u{00A0}";
593 if ( $this->mNewRev
->isMinor() ) {
594 $newminor = ChangesList
::flag( 'minor' );
599 # Handle RevisionDelete links...
600 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
602 # Allow extensions to define their own revision tools
603 Hooks
::run( 'DiffRevisionTools',
604 [ $this->mNewRev
, &$revisionTools, $this->mOldRev
, $user ] );
605 $formattedRevisionTools = [];
606 // Put each one in parentheses (poor man's button)
607 foreach ( $revisionTools as $key => $tool ) {
608 $toolClass = is_string( $key ) ?
$key : 'mw-diff-tool';
609 $element = Html
::rawElement(
611 [ 'class' => $toolClass ],
612 $this->msg( 'parentheses' )->rawParams( $tool )->escaped()
614 $formattedRevisionTools[] = $element;
616 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev
, 'complete' ) .
617 ' ' . implode( ' ', $formattedRevisionTools );
618 $newChangeTags = ChangeTags
::formatSummaryRow( $this->mNewTags
, 'diff', $this->getContext() );
620 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
621 '<div id="mw-diff-ntitle2">' . Linker
::revUserTools( $this->mNewRev
, !$this->unhide
) .
623 '<div id="mw-diff-ntitle3">' . $newminor .
624 Linker
::revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
625 '<div id="mw-diff-ntitle5">' . $newChangeTags[0] . '</div>' .
626 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
628 // Allow extensions to change the $newHeader variable
629 Hooks
::run( 'DifferenceEngineNewHeader', [ $this, &$newHeader, $formattedRevisionTools,
630 $nextlink, $rollback, $newminor, $diffOnly, $rdel, $this->unhide
] );
632 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
633 $deleted = true; // new revisions text is hidden
634 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
635 $suppressed = true; // also suppressed
639 # If the diff cannot be shown due to a deleted revision, then output
640 # the diff header and links to unhide (if available)...
641 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
642 $this->showDiffStyle();
643 $multi = $this->getMultiNotice();
644 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
646 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
647 # Give explanation for why revision is not visible
648 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
651 # Give explanation and add a link to view the diff...
652 $query = $this->getRequest()->appendQueryValue( 'unhide', '1' );
653 $link = $this->getTitle()->getFullURL( $query );
654 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
656 "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
660 # Otherwise, output a regular diff...
662 # Add deletion notice if the user is viewing deleted content
665 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
666 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" .
667 $this->msg( $msg )->parse() .
670 $this->showDiff( $oldHeader, $newHeader, $notice );
672 $this->renderNewRevision();
678 * Build a link to mark a change as patrolled.
680 * Returns empty string if there's either no revision to patrol or the user is not allowed to.
681 * Side effect: When the patrol link is build, this method will call
682 * OutputPage::preventClickjacking() and load mediawiki.page.patrol.ajax.
684 * @return string HTML or empty string
686 public function markPatrolledLink() {
687 if ( $this->mMarkPatrolledLink
=== null ) {
688 $linkInfo = $this->getMarkPatrolledLinkInfo();
689 // If false, there is no patrol link needed/allowed
690 if ( !$linkInfo ||
!$this->mNewPage
) {
691 $this->mMarkPatrolledLink
= '';
693 $this->mMarkPatrolledLink
= ' <span class="patrollink" data-mw="interface">[' .
696 $this->msg( 'markaspatrolleddiff' )->escaped(),
699 'action' => 'markpatrolled',
700 'rcid' => $linkInfo['rcid'],
703 // Allow extensions to change the markpatrolled link
704 Hooks
::run( 'DifferenceEngineMarkPatrolledLink', [ $this,
705 &$this->mMarkPatrolledLink
, $linkInfo['rcid'] ] );
708 return $this->mMarkPatrolledLink
;
712 * Returns an array of meta data needed to build a "mark as patrolled" link and
713 * adds the mediawiki.page.patrol.ajax to the output.
715 * @return array|false An array of meta data for a patrol link (rcid only)
716 * or false if no link is needed
718 protected function getMarkPatrolledLinkInfo() {
719 global $wgUseRCPatrol;
721 $user = $this->getUser();
723 // Prepare a change patrol link, if applicable
725 // Is patrolling enabled and the user allowed to?
726 $wgUseRCPatrol && $this->mNewPage
&& $this->mNewPage
->quickUserCan( 'patrol', $user ) &&
727 // Only do this if the revision isn't more than 6 hours older
728 // than the Max RC age (6h because the RC might not be cleaned out regularly)
729 RecentChange
::isInRCLifespan( $this->mNewRev
->getTimestamp(), 21600 )
731 // Look for an unpatrolled change corresponding to this diff
732 $db = wfGetDB( DB_REPLICA
);
733 $change = RecentChange
::newFromConds(
735 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
736 'rc_this_oldid' => $this->mNewid
,
737 'rc_patrolled' => RecentChange
::PRC_UNPATROLLED
742 if ( $change && !$change->getPerformer()->equals( $user ) ) {
743 $rcid = $change->getAttribute( 'rc_id' );
745 // None found or the page has been created by the current user.
746 // If the user could patrol this it already would be patrolled
750 // Allow extensions to possibly change the rcid here
751 // For example the rcid might be set to zero due to the user
752 // being the same as the performer of the change but an extension
753 // might still want to show it under certain conditions
754 Hooks
::run( 'DifferenceEngineMarkPatrolledRCID', [ &$rcid, $this, $change, $user ] );
758 $this->getOutput()->preventClickjacking();
759 if ( $user->isAllowed( 'writeapi' ) ) {
760 $this->getOutput()->addModules( 'mediawiki.page.patrol.ajax' );
769 // No mark as patrolled link applicable
774 * @param Revision $rev
778 protected function revisionDeleteLink( $rev ) {
779 $link = Linker
::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
780 if ( $link !== '' ) {
781 $link = "\u{00A0}\u{00A0}\u{00A0}" . $link . ' ';
788 * Show the new revision of the page.
790 public function renderNewRevision() {
791 $out = $this->getOutput();
792 $revHeader = $this->getRevisionHeader( $this->mNewRev
);
793 # Add "current version as of X" title
794 $out->addHTML( "<hr class='diff-hr' id='mw-oldid' />
795 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
796 # Page content may be handled by a hooked call instead...
797 if ( Hooks
::run( 'ArticleContentOnDiff', [ $this, $out ] ) ) {
798 $this->loadNewText();
799 if ( !$this->mNewPage
) {
800 // New revision is unsaved; bail out.
801 // TODO in theory rendering the new revision is a meaningful thing to do
802 // even if it's unsaved, but a lot of untangling is required to do it safely.
805 $out->setRevisionId( $this->mNewid
);
806 $out->setRevisionTimestamp( $this->mNewRev
->getTimestamp() );
807 $out->setArticleFlag( true );
809 if ( !Hooks
::run( 'ArticleContentViewCustom',
810 [ $this->mNewContent
, $this->mNewPage
, $out ] )
812 // Handled by extension
815 if ( $this->getTitle()->equals( $this->mNewPage
) ) {
816 // If the Title stored in the context is the same as the one
817 // of the new revision, we can use its associated WikiPage
819 $wikiPage = $this->getWikiPage();
821 // Otherwise we need to create our own WikiPage object
822 $wikiPage = WikiPage
::factory( $this->mNewPage
);
825 $parserOutput = $this->getParserOutput( $wikiPage, $this->mNewRev
);
827 # WikiPage::getParserOutput() should not return false, but just in case
828 if ( $parserOutput ) {
829 // Allow extensions to change parser output here
830 if ( Hooks
::run( 'DifferenceEngineRenderRevisionAddParserOutput',
831 [ $this, $out, $parserOutput, $wikiPage ] )
833 $out->addParserOutput( $parserOutput, [
834 'enableSectionEditLinks' => $this->mNewRev
->isCurrent()
835 && $this->mNewRev
->getTitle()->quickUserCan( 'edit', $this->getUser() ),
842 // Allow extensions to optionally not show the final patrolled link
843 if ( Hooks
::run( 'DifferenceEngineRenderRevisionShowFinalPatrolLink' ) ) {
844 # Add redundant patrol link on bottom...
845 $out->addHTML( $this->markPatrolledLink() );
850 * @param WikiPage $page
851 * @param Revision $rev
853 * @return ParserOutput|bool False if the revision was not found
855 protected function getParserOutput( WikiPage
$page, Revision
$rev ) {
856 $parserOptions = $page->makeParserOptions( $this->getContext() );
857 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
859 return $parserOutput;
863 * Get the diff text, send it to the OutputPage object
864 * Returns false if the diff could not be generated, otherwise returns true
866 * @param string|bool $otitle Header for old text or false
867 * @param string|bool $ntitle Header for new text or false
868 * @param string $notice HTML between diff header and body
872 public function showDiff( $otitle, $ntitle, $notice = '' ) {
873 // Allow extensions to affect the output here
874 Hooks
::run( 'DifferenceEngineShowDiff', [ $this ] );
876 $diff = $this->getDiff( $otitle, $ntitle, $notice );
877 if ( $diff === false ) {
878 $this->showMissingRevision();
882 $this->showDiffStyle();
883 $this->getOutput()->addHTML( $diff );
890 * Add style sheets for diff display.
892 public function showDiffStyle() {
893 if ( !$this->isSlotDiffRenderer
) {
894 $this->getOutput()->addModuleStyles( 'mediawiki.diff.styles' );
895 foreach ( $this->getSlotDiffRenderers() as $slotDiffRenderer ) {
896 $slotDiffRenderer->addModules( $this->getOutput() );
902 * Get complete diff table, including header
904 * @param string|bool $otitle Header for old text or false
905 * @param string|bool $ntitle Header for new text or false
906 * @param string $notice HTML between diff header and body
910 public function getDiff( $otitle, $ntitle, $notice = '' ) {
911 $body = $this->getDiffBody();
912 if ( $body === false ) {
916 $multi = $this->getMultiNotice();
917 // Display a message when the diff is empty
918 if ( $body === '' ) {
919 $notice .= '<div class="mw-diff-empty">' .
920 $this->msg( 'diff-empty' )->parse() .
924 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
928 * Get the diff table body, without header
930 * @return mixed (string/false)
932 public function getDiffBody() {
933 $this->mCacheHit
= true;
934 // Check if the diff should be hidden from this user
935 if ( !$this->isContentOverridden
) {
936 if ( !$this->loadRevisionData() ) {
938 } elseif ( $this->mOldRev
&&
939 !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
942 } elseif ( $this->mNewRev
&&
943 !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
948 if ( $this->mOldRev
=== false ||
( $this->mOldRev
&& $this->mNewRev
&&
949 $this->mOldRev
->getId() && $this->mOldRev
->getId() == $this->mNewRev
->getId() )
951 if ( Hooks
::run( 'DifferenceEngineShowEmptyOldContent', [ $this ] ) ) {
959 $cache = ObjectCache
::getMainWANInstance();
960 if ( $this->mOldid
&& $this->mNewid
) {
961 // Check if subclass is still using the old way
962 // for backwards-compatibility
963 $key = $this->getDiffBodyCacheKey();
964 if ( $key === null ) {
965 $key = $cache->makeKey( ...$this->getDiffBodyCacheKeyParams() );
969 if ( !$this->mRefreshCache
) {
970 $difftext = $cache->get( $key );
972 wfIncrStats( 'diff_cache.hit' );
973 $difftext = $this->localiseDiff( $difftext );
974 $difftext .= "\n<!-- diff cache key $key -->\n";
978 } // don't try to load but save the result
980 $this->mCacheHit
= false;
982 // Loadtext is permission safe, this just clears out the diff
983 if ( !$this->loadText() ) {
988 // We've checked for revdelete at the beginning of this method; it's OK to ignore
989 // read permissions here.
990 $slotContents = $this->getSlotContents();
991 foreach ( $this->getSlotDiffRenderers() as $role => $slotDiffRenderer ) {
992 $slotDiff = $slotDiffRenderer->getDiff( $slotContents[$role]['old'],
993 $slotContents[$role]['new'] );
994 if ( $slotDiff && $role !== 'main' ) {
995 // TODO use human-readable role name at least
997 $difftext .= $this->getSlotHeader( $slotTitle );
999 $difftext .= $slotDiff;
1002 // Avoid PHP 7.1 warning from passing $this by reference
1003 $diffEngine = $this;
1005 // Save to cache for 7 days
1006 if ( !Hooks
::run( 'AbortDiffCache', [ &$diffEngine ] ) ) {
1007 wfIncrStats( 'diff_cache.uncacheable' );
1008 } elseif ( $key !== false && $difftext !== false ) {
1009 wfIncrStats( 'diff_cache.miss' );
1010 $cache->set( $key, $difftext, 7 * 86400 );
1012 wfIncrStats( 'diff_cache.uncacheable' );
1014 // localise line numbers and title attribute text
1015 if ( $difftext !== false ) {
1016 $difftext = $this->localiseDiff( $difftext );
1023 * Get a slot header for inclusion in a diff body (as a table row).
1025 * @param string $headerText The text of the header
1029 protected function getSlotHeader( $headerText ) {
1030 // The old revision is missing on oldid=<first>&diff=prev; only 2 columns in that case.
1031 $columnCount = $this->mOldRev ?
4 : 2;
1032 $userLang = $this->getLanguage()->getHtmlCode();
1033 return Html
::rawElement( 'tr', [ 'class' => 'mw-diff-slot-header', 'lang' => $userLang ],
1034 Html
::element( 'th', [ 'colspan' => $columnCount ], $headerText ) );
1038 * Returns the cache key for diff body text or content.
1040 * @deprecated since 1.31, use getDiffBodyCacheKeyParams() instead
1043 * @throws MWException
1044 * @return string|null
1046 protected function getDiffBodyCacheKey() {
1051 * Get the cache key parameters
1053 * Subclasses can replace the first element in the array to something
1054 * more specific to the type of diff (e.g. "inline-diff"), or append
1055 * if the cache should vary on more things. Overriding entirely should
1061 * @throws MWException
1063 protected function getDiffBodyCacheKeyParams() {
1064 if ( !$this->mOldid ||
!$this->mNewid
) {
1065 throw new MWException( 'mOldid and mNewid must be set to get diff cache key.' );
1068 $engine = $this->getEngine();
1073 "old-{$this->mOldid}",
1074 "rev-{$this->mNewid}"
1077 if ( $engine === 'wikidiff2' ) {
1078 $params[] = phpversion( 'wikidiff2' );
1079 $params[] = $this->getConfig()->get( 'WikiDiff2MovedParagraphDetectionCutoff' );
1082 if ( !$this->isSlotDiffRenderer
) {
1083 foreach ( $this->getSlotDiffRenderers() as $slotDiffRenderer ) {
1084 $params = array_merge( $params, $slotDiffRenderer->getExtraCacheKeys() );
1092 * Implements DifferenceEngineSlotDiffRenderer::getExtraCacheKeys(). Only used when
1093 * DifferenceEngine is wrapped in DifferenceEngineSlotDiffRenderer.
1095 * @internal for use by DifferenceEngineSlotDiffRenderer only
1098 public function getExtraCacheKeys() {
1099 // This method is called when the DifferenceEngine is used for a slot diff. We only care
1100 // about special things, not the revision IDs, which are added to the cache key by the
1101 // page-level DifferenceEngine, and which might not have a valid value for this object.
1102 $this->mOldid
= 123456789;
1103 $this->mNewid
= 987654321;
1105 // This will repeat a bunch of unnecessary key fields for each slot. Not nice but harmless.
1106 $cacheString = $this->getDiffBodyCacheKey();
1107 if ( $cacheString ) {
1108 return [ $cacheString ];
1111 $params = $this->getDiffBodyCacheKeyParams();
1113 // Try to get rid of the standard keys to keep the cache key human-readable:
1114 // call the getDiffBodyCacheKeyParams implementation of the base class, and if
1115 // the child class includes the same keys, drop them.
1116 // Uses an obscure PHP feature where static calls to non-static methods are allowed
1117 // as long as we are already in a non-static method of the same class, and the call context
1118 // ($this) will be inherited.
1119 // phpcs:ignore Squiz.Classes.SelfMemberReference.NotUsed
1120 $standardParams = DifferenceEngine
::getDiffBodyCacheKeyParams();
1121 if ( array_slice( $params, 0, count( $standardParams ) ) === $standardParams ) {
1122 $params = array_slice( $params, count( $standardParams ) );
1129 * Generate a diff, no caching.
1133 * @param Content $old Old content
1134 * @param Content $new New content
1136 * @throws Exception If old or new content is not an instance of TextContent.
1137 * @return bool|string
1139 * @deprecated since 1.32, use a SlotDiffRenderer instead.
1141 public function generateContentDiffBody( Content
$old, Content
$new ) {
1142 $slotDiffRenderer = $new->getContentHandler()->getSlotDiffRenderer( $this->getContext() );
1144 $slotDiffRenderer instanceof DifferenceEngineSlotDiffRenderer
1145 && $this->isSlotDiffRenderer
1147 // Oops, we are just about to enter an infinite loop (the slot-level DifferenceEngine
1148 // called a DifferenceEngineSlotDiffRenderer that wraps the same DifferenceEngine class).
1149 // This will happen when a content model has no custom slot diff renderer, it does have
1150 // a custom difference engine, but that does not override this method.
1151 throw new Exception( get_class( $this ) . ': could not maintain backwards compatibility. '
1152 . 'Please use a SlotDiffRenderer.' );
1154 return $slotDiffRenderer->getDiff( $old, $new ) . $this->getDebugString();
1158 * Generate a diff, no caching
1160 * @param string $otext Old text, must be already segmented
1161 * @param string $ntext New text, must be already segmented
1163 * @throws Exception If content handling for text content is configured in a way
1164 * that makes maintaining B/C hard.
1165 * @return bool|string
1167 * @deprecated since 1.32, use a TextSlotDiffRenderer instead.
1169 public function generateTextDiffBody( $otext, $ntext ) {
1170 $slotDiffRenderer = ContentHandler
::getForModelID( CONTENT_MODEL_TEXT
)
1171 ->getSlotDiffRenderer( $this->getContext() );
1172 if ( !( $slotDiffRenderer instanceof TextSlotDiffRenderer
) ) {
1173 // Someone used the GetSlotDiffRenderer hook to replace the renderer.
1174 // This is too unlikely to happen to bother handling properly.
1175 throw new Exception( 'The slot diff renderer for text content should be a '
1176 . 'TextSlotDiffRenderer subclass' );
1178 return $slotDiffRenderer->getTextDiff( $otext, $ntext ) . $this->getDebugString();
1182 * Process $wgExternalDiffEngine and get a sane, usable engine
1184 * @return bool|string 'wikidiff2', path to an executable, or false
1185 * @internal For use by this class and TextSlotDiffRenderer only.
1187 public static function getEngine() {
1188 global $wgExternalDiffEngine;
1189 // We use the global here instead of Config because we write to the value,
1190 // and Config is not mutable.
1191 if ( $wgExternalDiffEngine == 'wikidiff' ||
$wgExternalDiffEngine == 'wikidiff3' ) {
1192 wfDeprecated( "\$wgExternalDiffEngine = '{$wgExternalDiffEngine}'", '1.27' );
1193 $wgExternalDiffEngine = false;
1194 } elseif ( $wgExternalDiffEngine == 'wikidiff2' ) {
1195 wfDeprecated( "\$wgExternalDiffEngine = '{$wgExternalDiffEngine}'", '1.32' );
1196 $wgExternalDiffEngine = false;
1197 } elseif ( !is_string( $wgExternalDiffEngine ) && $wgExternalDiffEngine !== false ) {
1198 // And prevent people from shooting themselves in the foot...
1199 wfWarn( '$wgExternalDiffEngine is set to a non-string value, forcing it to false' );
1200 $wgExternalDiffEngine = false;
1203 if ( is_string( $wgExternalDiffEngine ) && is_executable( $wgExternalDiffEngine ) ) {
1204 return $wgExternalDiffEngine;
1205 } elseif ( $wgExternalDiffEngine === false && function_exists( 'wikidiff2_do_diff' ) ) {
1214 * Generates diff, to be wrapped internally in a logging/instrumentation
1216 * @param string $otext Old text, must be already segmented
1217 * @param string $ntext New text, must be already segmented
1219 * @throws Exception If content handling for text content is configured in a way
1220 * that makes maintaining B/C hard.
1221 * @return bool|string
1223 * @deprecated since 1.32, use a TextSlotDiffRenderer instead.
1225 protected function textDiff( $otext, $ntext ) {
1226 $slotDiffRenderer = ContentHandler
::getForModelID( CONTENT_MODEL_TEXT
)
1227 ->getSlotDiffRenderer( $this->getContext() );
1228 if ( !( $slotDiffRenderer instanceof TextSlotDiffRenderer
) ) {
1229 // Someone used the GetSlotDiffRenderer hook to replace the renderer.
1230 // This is too unlikely to happen to bother handling properly.
1231 throw new Exception( 'The slot diff renderer for text content should be a '
1232 . 'TextSlotDiffRenderer subclass' );
1234 return $slotDiffRenderer->getTextDiff( $otext, $ntext ) . $this->getDebugString();
1238 * Generate a debug comment indicating diff generating time,
1239 * server node, and generator backend.
1241 * @param string $generator : What diff engine was used
1245 protected function debug( $generator = "internal" ) {
1246 global $wgShowHostnames;
1247 if ( !$this->enableDebugComment
) {
1250 $data = [ $generator ];
1251 if ( $wgShowHostnames ) {
1252 $data[] = wfHostname();
1254 $data[] = wfTimestamp( TS_DB
);
1256 return "<!-- diff generator: " .
1257 implode( " ", array_map( "htmlspecialchars", $data ) ) .
1261 private function getDebugString() {
1262 $engine = self
::getEngine();
1263 if ( $engine === 'wikidiff2' ) {
1264 return $this->debug( 'wikidiff2' );
1265 } elseif ( $engine === false ) {
1266 return $this->debug( 'native PHP' );
1268 return $this->debug( "external $engine" );
1273 * Localise diff output
1275 * @param string $text
1278 private function localiseDiff( $text ) {
1279 $text = $this->localiseLineNumbers( $text );
1280 if ( $this->getEngine() === 'wikidiff2' &&
1281 version_compare( phpversion( 'wikidiff2' ), '1.5.1', '>=' )
1283 $text = $this->addLocalisedTitleTooltips( $text );
1289 * Replace line numbers with the text in the user's language
1291 * @param string $text
1295 public function localiseLineNumbers( $text ) {
1296 return preg_replace_callback(
1297 '/<!--LINE (\d+)-->/',
1298 [ $this, 'localiseLineNumbersCb' ],
1303 public function localiseLineNumbersCb( $matches ) {
1304 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) {
1308 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
1312 * Add title attributes for tooltips on moved paragraph indicators
1314 * @param string $text
1317 private function addLocalisedTitleTooltips( $text ) {
1318 return preg_replace_callback(
1319 '/class="mw-diff-movedpara-(left|right)"/',
1320 [ $this, 'addLocalisedTitleTooltipsCb' ],
1326 * @param array $matches
1329 private function addLocalisedTitleTooltipsCb( array $matches ) {
1330 $key = $matches[1] === 'right' ?
1331 'diff-paragraph-moved-toold' :
1332 'diff-paragraph-moved-tonew';
1333 return $matches[0] . ' title="' . $this->msg( $key )->escaped() . '"';
1337 * If there are revisions between the ones being compared, return a note saying so.
1341 public function getMultiNotice() {
1342 // The notice only make sense if we are diffing two saved revisions of the same page.
1344 !$this->mOldRev ||
!$this->mNewRev
1345 ||
!$this->mOldPage ||
!$this->mNewPage
1346 ||
!$this->mOldPage
->equals( $this->mNewPage
)
1351 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
1352 $oldRev = $this->mNewRev
; // flip
1353 $newRev = $this->mOldRev
; // flip
1354 } else { // normal case
1355 $oldRev = $this->mOldRev
;
1356 $newRev = $this->mNewRev
;
1359 // Sanity: don't show the notice if too many rows must be scanned
1360 // @todo show some special message for that case
1361 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev, 1000 );
1362 if ( $nEdits > 0 && $nEdits <= 1000 ) {
1363 $limit = 100; // use diff-multi-manyusers if too many users
1364 $users = $this->mNewPage
->getAuthorsBetween( $oldRev, $newRev, $limit );
1365 $numUsers = count( $users );
1367 if ( $numUsers == 1 && $users[0] == $newRev->getUserText( Revision
::RAW
) ) {
1368 $numUsers = 0; // special case to say "by the same user" instead of "by one other user"
1371 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
1374 return ''; // nothing
1378 * Get a notice about how many intermediate edits and users there are
1380 * @param int $numEdits
1381 * @param int $numUsers
1386 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
1387 if ( $numUsers === 0 ) {
1388 $msg = 'diff-multi-sameuser';
1389 } elseif ( $numUsers > $limit ) {
1390 $msg = 'diff-multi-manyusers';
1393 $msg = 'diff-multi-otherusers';
1396 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
1400 * Get a header for a specified revision.
1402 * @param Revision $rev
1403 * @param string $complete 'complete' to get the header wrapped depending
1404 * the visibility of the revision and a link to edit the page.
1406 * @return string HTML fragment
1408 public function getRevisionHeader( Revision
$rev, $complete = '' ) {
1409 $lang = $this->getLanguage();
1410 $user = $this->getUser();
1411 $revtimestamp = $rev->getTimestamp();
1412 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
1413 $dateofrev = $lang->userDate( $revtimestamp, $user );
1414 $timeofrev = $lang->userTime( $revtimestamp, $user );
1416 $header = $this->msg(
1417 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
1423 if ( $complete !== 'complete' ) {
1427 $title = $rev->getTitle();
1429 $header = Linker
::linkKnown( $title, $header, [],
1430 [ 'oldid' => $rev->getId() ] );
1432 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
1433 $editQuery = [ 'action' => 'edit' ];
1434 if ( !$rev->isCurrent() ) {
1435 $editQuery['oldid'] = $rev->getId();
1438 $key = $title->quickUserCan( 'edit', $user ) ?
'editold' : 'viewsourceold';
1439 $msg = $this->msg( $key )->escaped();
1440 $editLink = $this->msg( 'parentheses' )->rawParams(
1441 Linker
::linkKnown( $title, $msg, [], $editQuery ) )->escaped();
1442 $header .= ' ' . Html
::rawElement(
1444 [ 'class' => 'mw-diff-edit' ],
1447 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
1448 $header = Html
::rawElement(
1450 [ 'class' => 'history-deleted' ],
1455 $header = Html
::rawElement( 'span', [ 'class' => 'history-deleted' ], $header );
1462 * Add the header to a diff body
1464 * @param string $diff Diff body
1465 * @param string $otitle Old revision header
1466 * @param string $ntitle New revision header
1467 * @param string $multi Notice telling user that there are intermediate
1468 * revisions between the ones being compared
1469 * @param string $notice Other notices, e.g. that user is viewing deleted content
1473 public function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
1474 // shared.css sets diff in interface language/dir, but the actual content
1475 // is often in a different language, mostly the page content language/dir
1476 $header = Html
::openElement( 'table', [
1477 'class' => [ 'diff', 'diff-contentalign-' . $this->getDiffLang()->alignStart() ],
1478 'data-mw' => 'interface',
1480 $userLang = htmlspecialchars( $this->getLanguage()->getHtmlCode() );
1482 if ( !$diff && !$otitle ) {
1484 <tr class=\"diff-title\" lang=\"{$userLang}\">
1485 <td class=\"diff-ntitle\">{$ntitle}</td>
1489 if ( $diff ) { // Safari/Chrome show broken output if cols not used
1491 <col class=\"diff-marker\" />
1492 <col class=\"diff-content\" />
1493 <col class=\"diff-marker\" />
1494 <col class=\"diff-content\" />";
1501 if ( $otitle ||
$ntitle ) {
1503 <tr class=\"diff-title\" lang=\"{$userLang}\">
1504 <td colspan=\"$colspan\" class=\"diff-otitle\">{$otitle}</td>
1505 <td colspan=\"$colspan\" class=\"diff-ntitle\">{$ntitle}</td>
1510 if ( $multi != '' ) {
1511 $header .= "<tr><td colspan=\"{$multiColspan}\" " .
1512 "class=\"diff-multi\" lang=\"{$userLang}\">{$multi}</td></tr>";
1514 if ( $notice != '' ) {
1515 $header .= "<tr><td colspan=\"{$multiColspan}\" " .
1516 "class=\"diff-notice\" lang=\"{$userLang}\">{$notice}</td></tr>";
1519 return $header . $diff . "</table>";
1523 * Use specified text instead of loading from the database
1524 * @param Content $oldContent
1525 * @param Content $newContent
1527 * @deprecated since 1.32, use setRevisions or ContentHandler::getSlotDiffRenderer.
1529 public function setContent( Content
$oldContent, Content
$newContent ) {
1530 $this->mOldContent
= $oldContent;
1531 $this->mNewContent
= $newContent;
1533 $this->mTextLoaded
= 2;
1534 $this->mRevisionsLoaded
= true;
1535 $this->isContentOverridden
= true;
1536 $this->slotDiffRenderers
= null;
1540 * Use specified text instead of loading from the database.
1541 * @param RevisionRecord|null $oldRevision
1542 * @param RevisionRecord $newRevision
1544 public function setRevisions(
1545 RevisionRecord
$oldRevision = null, RevisionRecord
$newRevision
1547 if ( $oldRevision ) {
1548 $this->mOldRev
= new Revision( $oldRevision );
1549 $this->mOldid
= $oldRevision->getId();
1550 $this->mOldPage
= Title
::newFromLinkTarget( $oldRevision->getPageAsLinkTarget() );
1551 // This method is meant for edit diffs and such so there is no reason to provide a
1552 // revision that's not readable to the user, but check it just in case.
1553 $this->mOldContent
= $oldRevision ?
$oldRevision->getContent( 'main',
1554 RevisionRecord
::FOR_THIS_USER
, $this->getUser() ) : null;
1556 $this->mOldRev
= $this->mOldid
= $this->mOldPage
= null;
1558 $this->mNewRev
= new Revision( $newRevision );
1559 $this->mNewid
= $newRevision->getId();
1560 $this->mNewPage
= Title
::newFromLinkTarget( $newRevision->getPageAsLinkTarget() );
1561 $this->mNewContent
= $newRevision->getContent( 'main',
1562 RevisionRecord
::FOR_THIS_USER
, $this->getUser() );
1564 $this->mRevisionsIdsLoaded
= $this->mRevisionsLoaded
= true;
1565 $this->mTextLoaded
= !!$oldRevision +
1;
1566 $this->isContentOverridden
= false;
1567 $this->slotDiffRenderers
= null;
1571 * Set the language in which the diff text is written
1573 * @param Language $lang
1576 public function setTextLanguage( $lang ) {
1577 if ( !$lang instanceof Language
) {
1578 wfDeprecated( __METHOD__
. ' with other type than Language for $lang', '1.32' );
1580 $this->mDiffLang
= wfGetLangObj( $lang );
1584 * Maps a revision pair definition as accepted by DifferenceEngine constructor
1585 * to a pair of actual integers representing revision ids.
1587 * @param int $old Revision id, e.g. from URL parameter 'oldid'
1588 * @param int|string $new Revision id or strings 'next' or 'prev', e.g. from URL parameter 'diff'
1590 * @return int[] List of two revision ids, older first, later second.
1591 * Zero signifies invalid argument passed.
1592 * false signifies that there is no previous/next revision ($old is the oldest/newest one).
1594 public function mapDiffPrevNext( $old, $new ) {
1595 if ( $new === 'prev' ) {
1596 // Show diff between revision $old and the previous one. Get previous one from DB.
1597 $newid = intval( $old );
1598 $oldid = $this->getTitle()->getPreviousRevisionID( $newid );
1599 } elseif ( $new === 'next' ) {
1600 // Show diff between revision $old and the next one. Get next one from DB.
1601 $oldid = intval( $old );
1602 $newid = $this->getTitle()->getNextRevisionID( $oldid );
1604 $oldid = intval( $old );
1605 $newid = intval( $new );
1608 return [ $oldid, $newid ];
1614 private function loadRevisionIds() {
1615 if ( $this->mRevisionsIdsLoaded
) {
1619 $this->mRevisionsIdsLoaded
= true;
1621 $old = $this->mOldid
;
1622 $new = $this->mNewid
;
1624 list( $this->mOldid
, $this->mNewid
) = self
::mapDiffPrevNext( $old, $new );
1625 if ( $new === 'next' && $this->mNewid
=== false ) {
1626 # if no result, NewId points to the newest old revision. The only newer
1627 # revision is cur, which is "0".
1632 'NewDifferenceEngine',
1633 [ $this->getTitle(), &$this->mOldid
, &$this->mNewid
, $old, $new ]
1638 * Load revision metadata for the specified articles. If newid is 0, then compare
1639 * the old article in oldid to the current article; if oldid is 0, then
1640 * compare the current article to the immediately previous one (ignoring the
1643 * If oldid is false, leave the corresponding revision object set
1644 * to false. This is impossible via ordinary user input, and is provided for
1647 * @return bool Whether both revisions were loaded successfully.
1649 public function loadRevisionData() {
1650 if ( $this->mRevisionsLoaded
) {
1651 return $this->isContentOverridden ||
$this->mNewRev
&& $this->mOldRev
;
1654 // Whether it succeeds or fails, we don't want to try again
1655 $this->mRevisionsLoaded
= true;
1657 $this->loadRevisionIds();
1659 // Load the new revision object
1660 if ( $this->mNewid
) {
1661 $this->mNewRev
= Revision
::newFromId( $this->mNewid
);
1663 $this->mNewRev
= Revision
::newFromTitle(
1666 Revision
::READ_NORMAL
1670 if ( !$this->mNewRev
instanceof Revision
) {
1674 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1675 $this->mNewid
= $this->mNewRev
->getId();
1676 if ( $this->mNewid
) {
1677 $this->mNewPage
= $this->mNewRev
->getTitle();
1679 $this->mNewPage
= null;
1682 // Load the old revision object
1683 $this->mOldRev
= false;
1684 if ( $this->mOldid
) {
1685 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1686 } elseif ( $this->mOldid
=== 0 ) {
1687 $rev = $this->mNewRev
->getPrevious();
1689 $this->mOldid
= $rev->getId();
1690 $this->mOldRev
= $rev;
1692 // No previous revision; mark to show as first-version only.
1693 $this->mOldid
= false;
1694 $this->mOldRev
= false;
1696 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1698 if ( is_null( $this->mOldRev
) ) {
1702 if ( $this->mOldRev
&& $this->mOldRev
->getId() ) {
1703 $this->mOldPage
= $this->mOldRev
->getTitle();
1705 $this->mOldPage
= null;
1708 // Load tags information for both revisions
1709 $dbr = wfGetDB( DB_REPLICA
);
1710 if ( $this->mOldid
!== false ) {
1711 $this->mOldTags
= $dbr->selectField(
1714 [ 'ts_rev_id' => $this->mOldid
],
1718 $this->mOldTags
= false;
1720 $this->mNewTags
= $dbr->selectField(
1723 [ 'ts_rev_id' => $this->mNewid
],
1731 * Load the text of the revisions, as well as revision data.
1733 * @return bool Whether the content of both revisions could be loaded successfully.
1735 public function loadText() {
1736 if ( $this->mTextLoaded
== 2 ) {
1737 return $this->loadRevisionData() && $this->mOldContent
&& $this->mNewContent
;
1740 // Whether it succeeds or fails, we don't want to try again
1741 $this->mTextLoaded
= 2;
1743 if ( !$this->loadRevisionData() ) {
1747 if ( $this->mOldRev
) {
1748 $this->mOldContent
= $this->mOldRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1749 if ( $this->mOldContent
=== null ) {
1754 if ( $this->mNewRev
) {
1755 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1756 Hooks
::run( 'DifferenceEngineLoadTextAfterNewContentIsLoaded', [ $this ] );
1757 if ( $this->mNewContent
=== null ) {
1766 * Load the text of the new revision, not the old one
1768 * @return bool Whether the content of the new revision could be loaded successfully.
1770 public function loadNewText() {
1771 if ( $this->mTextLoaded
>= 1 ) {
1772 return $this->loadRevisionData();
1775 $this->mTextLoaded
= 1;
1777 if ( !$this->loadRevisionData() ) {
1781 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1783 Hooks
::run( 'DifferenceEngineAfterLoadNewText', [ $this ] );