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;
283 * Set reduced line numbers mode.
284 * When set, line X is not displayed when X is 1, for example to increase readability and
285 * conserve space with many small diffs.
288 public function setReducedLineNumbers( $value = true ) {
289 $this->mReducedLineNumbers
= $value;
293 * Get the language of the difference engine, defaults to page content language
297 public function getDiffLang() {
298 if ( $this->mDiffLang
=== null ) {
299 # Default language in which the diff text is written.
300 $this->mDiffLang
= $this->getTitle()->getPageLanguage();
303 return $this->mDiffLang
;
309 public function wasCacheHit() {
310 return $this->mCacheHit
;
316 public function getOldid() {
317 $this->loadRevisionIds();
319 return $this->mOldid
;
325 public function getNewid() {
326 $this->loadRevisionIds();
328 return $this->mNewid
;
332 * Get the left side of the diff.
333 * Could be null when the first revision of the page is diffed to 'prev' (or in the case of
335 * @return RevisionRecord|null
337 public function getOldRevision() {
338 return $this->mOldRev ?
$this->mOldRev
->getRevisionRecord() : null;
342 * Get the right side of the diff.
343 * Should not be null but can still happen in the case of load failure.
344 * @return RevisionRecord|null
346 public function getNewRevision() {
347 return $this->mNewRev ?
$this->mNewRev
->getRevisionRecord() : null;
351 * Look up a special:Undelete link to the given deleted revision id,
352 * as a workaround for being unable to load deleted diffs in currently.
354 * @param int $id Revision ID
356 * @return string|bool Link HTML or false
358 public function deletedLink( $id ) {
359 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
360 $dbr = wfGetDB( DB_REPLICA
);
361 $arQuery = Revision
::getArchiveQueryInfo();
362 $row = $dbr->selectRow(
364 array_merge( $arQuery['fields'], [ 'ar_namespace', 'ar_title' ] ),
365 [ 'ar_rev_id' => $id ],
371 $rev = Revision
::newFromArchiveRow( $row );
372 $title = Title
::makeTitleSafe( $row->ar_namespace
, $row->ar_title
);
374 return SpecialPage
::getTitleFor( 'Undelete' )->getFullURL( [
375 'target' => $title->getPrefixedText(),
376 'timestamp' => $rev->getTimestamp()
385 * Build a wikitext link toward a deleted revision, if viewable.
387 * @param int $id Revision ID
389 * @return string Wikitext fragment
391 public function deletedIdMarker( $id ) {
392 $link = $this->deletedLink( $id );
394 return "[$link $id]";
400 private function showMissingRevision() {
401 $out = $this->getOutput();
404 if ( $this->mOldRev
=== null ||
405 ( $this->mOldRev
&& $this->mOldContent
=== null )
407 $missing[] = $this->deletedIdMarker( $this->mOldid
);
409 if ( $this->mNewRev
=== null ||
410 ( $this->mNewRev
&& $this->mNewContent
=== null )
412 $missing[] = $this->deletedIdMarker( $this->mNewid
);
415 $out->setPageTitle( $this->msg( 'errorpagetitle' ) );
416 $msg = $this->msg( 'difference-missing-revision' )
417 ->params( $this->getLanguage()->listToText( $missing ) )
418 ->numParams( count( $missing ) )
420 $out->addHTML( $msg );
423 public function showDiffPage( $diffOnly = false ) {
424 # Allow frames except in certain special cases
425 $out = $this->getOutput();
426 $out->allowClickjacking();
427 $out->setRobotPolicy( 'noindex,nofollow' );
429 // Allow extensions to add any extra output here
430 Hooks
::run( 'DifferenceEngineShowDiffPage', [ $out ] );
432 if ( !$this->loadRevisionData() ) {
433 if ( Hooks
::run( 'DifferenceEngineShowDiffPageMaybeShowMissingRevision', [ $this ] ) ) {
434 $this->showMissingRevision();
439 $user = $this->getUser();
441 if ( $this->mNewPage
) {
442 $permErrors = $this->mNewPage
->getUserPermissionsErrors( 'read', $user );
444 if ( $this->mOldPage
) {
445 $permErrors = wfMergeErrorArrays( $permErrors,
446 $this->mOldPage
->getUserPermissionsErrors( 'read', $user ) );
448 if ( count( $permErrors ) ) {
449 throw new PermissionsError( 'read', $permErrors );
455 # Carry over 'diffonly' param via navigation links
456 if ( $diffOnly != $user->getBoolOption( 'diffonly' ) ) {
457 $query['diffonly'] = $diffOnly;
459 # Cascade unhide param in links for easy deletion browsing
460 if ( $this->unhide
) {
461 $query['unhide'] = 1;
464 # Check if one of the revisions is deleted/suppressed
465 $deleted = $suppressed = false;
466 $allowed = $this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $user );
470 # mOldRev is false if the difference engine is called with a "vague" query for
471 # a diff between a version V and its previous version V' AND the version V
472 # is the first version of that article. In that case, V' does not exist.
473 if ( $this->mOldRev
=== false ) {
474 if ( $this->mNewPage
) {
475 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
479 // Allow extensions to change the $oldHeader variable
480 Hooks
::run( 'DifferenceEngineOldHeaderNoOldRev', [ &$oldHeader ] );
482 Hooks
::run( 'DiffViewHeader', [ $this, $this->mOldRev
, $this->mNewRev
] );
484 if ( !$this->mOldPage ||
!$this->mNewPage
) {
485 // XXX say something to the user?
487 } elseif ( $this->mNewPage
->equals( $this->mOldPage
) ) {
488 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
491 $out->setPageTitle( $this->msg( 'difference-title-multipage',
492 $this->mOldPage
->getPrefixedText(), $this->mNewPage
->getPrefixedText() ) );
493 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
497 if ( $samePage && $this->mNewPage
&& $this->mNewPage
->quickUserCan( 'edit', $user ) ) {
498 if ( $this->mNewRev
->isCurrent() && $this->mNewPage
->userCan( 'rollback', $user ) ) {
499 $rollbackLink = Linker
::generateRollback( $this->mNewRev
, $this->getContext() );
500 if ( $rollbackLink ) {
501 $out->preventClickjacking();
502 $rollback = "\u{00A0}\u{00A0}\u{00A0}" . $rollbackLink;
506 if ( !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) &&
507 !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
)
509 $undoLink = Html
::element( 'a', [
510 'href' => $this->mNewPage
->getLocalURL( [
512 'undoafter' => $this->mOldid
,
513 'undo' => $this->mNewid
515 'title' => Linker
::titleAttrib( 'undo' ),
517 $this->msg( 'editundo' )->text()
519 $revisionTools['mw-diff-undo'] = $undoLink;
523 # Make "previous revision link"
524 if ( $samePage && $this->mOldPage
&& $this->mOldRev
->getPrevious() ) {
525 $prevlink = Linker
::linkKnown(
527 $this->msg( 'previousdiff' )->escaped(),
528 [ 'id' => 'differences-prevlink' ],
529 [ 'diff' => 'prev', 'oldid' => $this->mOldid
] +
$query
532 $prevlink = "\u{00A0}";
535 if ( $this->mOldRev
->isMinor() ) {
536 $oldminor = ChangesList
::flag( 'minor' );
541 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
542 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev
, 'complete' );
543 $oldChangeTags = ChangeTags
::formatSummaryRow( $this->mOldTags
, 'diff', $this->getContext() );
545 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
546 '<div id="mw-diff-otitle2">' .
547 Linker
::revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
548 '<div id="mw-diff-otitle3">' . $oldminor .
549 Linker
::revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
550 '<div id="mw-diff-otitle5">' . $oldChangeTags[0] . '</div>' .
551 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
553 // Allow extensions to change the $oldHeader variable
554 Hooks
::run( 'DifferenceEngineOldHeader', [ $this, &$oldHeader, $prevlink, $oldminor,
555 $diffOnly, $ldel, $this->unhide
] );
557 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
558 $deleted = true; // old revisions text is hidden
559 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
560 $suppressed = true; // also suppressed
564 # Check if this user can see the revisions
565 if ( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $user ) ) {
570 $out->addJsConfigVars( [
571 'wgDiffOldId' => $this->mOldid
,
572 'wgDiffNewId' => $this->mNewid
,
575 # Make "next revision link"
576 # Skip next link on the top revision
577 if ( $samePage && $this->mNewPage
&& !$this->mNewRev
->isCurrent() ) {
578 $nextlink = Linker
::linkKnown(
580 $this->msg( 'nextdiff' )->escaped(),
581 [ 'id' => 'differences-nextlink' ],
582 [ 'diff' => 'next', 'oldid' => $this->mNewid
] +
$query
585 $nextlink = "\u{00A0}";
588 if ( $this->mNewRev
->isMinor() ) {
589 $newminor = ChangesList
::flag( 'minor' );
594 # Handle RevisionDelete links...
595 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
597 # Allow extensions to define their own revision tools
598 Hooks
::run( 'DiffRevisionTools',
599 [ $this->mNewRev
, &$revisionTools, $this->mOldRev
, $user ] );
600 $formattedRevisionTools = [];
601 // Put each one in parentheses (poor man's button)
602 foreach ( $revisionTools as $key => $tool ) {
603 $toolClass = is_string( $key ) ?
$key : 'mw-diff-tool';
604 $element = Html
::rawElement(
606 [ 'class' => $toolClass ],
607 $this->msg( 'parentheses' )->rawParams( $tool )->escaped()
609 $formattedRevisionTools[] = $element;
611 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev
, 'complete' ) .
612 ' ' . implode( ' ', $formattedRevisionTools );
613 $newChangeTags = ChangeTags
::formatSummaryRow( $this->mNewTags
, 'diff', $this->getContext() );
615 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
616 '<div id="mw-diff-ntitle2">' . Linker
::revUserTools( $this->mNewRev
, !$this->unhide
) .
618 '<div id="mw-diff-ntitle3">' . $newminor .
619 Linker
::revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
620 '<div id="mw-diff-ntitle5">' . $newChangeTags[0] . '</div>' .
621 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
623 // Allow extensions to change the $newHeader variable
624 Hooks
::run( 'DifferenceEngineNewHeader', [ $this, &$newHeader, $formattedRevisionTools,
625 $nextlink, $rollback, $newminor, $diffOnly, $rdel, $this->unhide
] );
627 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
628 $deleted = true; // new revisions text is hidden
629 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
630 $suppressed = true; // also suppressed
634 # If the diff cannot be shown due to a deleted revision, then output
635 # the diff header and links to unhide (if available)...
636 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
637 $this->showDiffStyle();
638 $multi = $this->getMultiNotice();
639 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
641 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
642 # Give explanation for why revision is not visible
643 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
646 # Give explanation and add a link to view the diff...
647 $query = $this->getRequest()->appendQueryValue( 'unhide', '1' );
648 $link = $this->getTitle()->getFullURL( $query );
649 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
651 "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
655 # Otherwise, output a regular diff...
657 # Add deletion notice if the user is viewing deleted content
660 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
661 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" .
662 $this->msg( $msg )->parse() .
665 $this->showDiff( $oldHeader, $newHeader, $notice );
667 $this->renderNewRevision();
673 * Build a link to mark a change as patrolled.
675 * Returns empty string if there's either no revision to patrol or the user is not allowed to.
676 * Side effect: When the patrol link is build, this method will call
677 * OutputPage::preventClickjacking() and load mediawiki.page.patrol.ajax.
679 * @return string HTML or empty string
681 public function markPatrolledLink() {
682 if ( $this->mMarkPatrolledLink
=== null ) {
683 $linkInfo = $this->getMarkPatrolledLinkInfo();
684 // If false, there is no patrol link needed/allowed
685 if ( !$linkInfo ||
!$this->mNewPage
) {
686 $this->mMarkPatrolledLink
= '';
688 $this->mMarkPatrolledLink
= ' <span class="patrollink" data-mw="interface">[' .
691 $this->msg( 'markaspatrolleddiff' )->escaped(),
694 'action' => 'markpatrolled',
695 'rcid' => $linkInfo['rcid'],
698 // Allow extensions to change the markpatrolled link
699 Hooks
::run( 'DifferenceEngineMarkPatrolledLink', [ $this,
700 &$this->mMarkPatrolledLink
, $linkInfo['rcid'] ] );
703 return $this->mMarkPatrolledLink
;
707 * Returns an array of meta data needed to build a "mark as patrolled" link and
708 * adds the mediawiki.page.patrol.ajax to the output.
710 * @return array|false An array of meta data for a patrol link (rcid only)
711 * or false if no link is needed
713 protected function getMarkPatrolledLinkInfo() {
714 global $wgUseRCPatrol;
716 $user = $this->getUser();
718 // Prepare a change patrol link, if applicable
720 // Is patrolling enabled and the user allowed to?
721 $wgUseRCPatrol && $this->mNewPage
&& $this->mNewPage
->quickUserCan( 'patrol', $user ) &&
722 // Only do this if the revision isn't more than 6 hours older
723 // than the Max RC age (6h because the RC might not be cleaned out regularly)
724 RecentChange
::isInRCLifespan( $this->mNewRev
->getTimestamp(), 21600 )
726 // Look for an unpatrolled change corresponding to this diff
727 $db = wfGetDB( DB_REPLICA
);
728 $change = RecentChange
::newFromConds(
730 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
731 'rc_this_oldid' => $this->mNewid
,
732 'rc_patrolled' => RecentChange
::PRC_UNPATROLLED
737 if ( $change && !$change->getPerformer()->equals( $user ) ) {
738 $rcid = $change->getAttribute( 'rc_id' );
740 // None found or the page has been created by the current user.
741 // If the user could patrol this it already would be patrolled
745 // Allow extensions to possibly change the rcid here
746 // For example the rcid might be set to zero due to the user
747 // being the same as the performer of the change but an extension
748 // might still want to show it under certain conditions
749 Hooks
::run( 'DifferenceEngineMarkPatrolledRCID', [ &$rcid, $this, $change, $user ] );
753 $this->getOutput()->preventClickjacking();
754 if ( $user->isAllowed( 'writeapi' ) ) {
755 $this->getOutput()->addModules( 'mediawiki.page.patrol.ajax' );
764 // No mark as patrolled link applicable
769 * @param Revision $rev
773 protected function revisionDeleteLink( $rev ) {
774 $link = Linker
::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
775 if ( $link !== '' ) {
776 $link = "\u{00A0}\u{00A0}\u{00A0}" . $link . ' ';
783 * Show the new revision of the page.
785 public function renderNewRevision() {
786 $out = $this->getOutput();
787 $revHeader = $this->getRevisionHeader( $this->mNewRev
);
788 # Add "current version as of X" title
789 $out->addHTML( "<hr class='diff-hr' id='mw-oldid' />
790 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
791 # Page content may be handled by a hooked call instead...
792 if ( Hooks
::run( 'ArticleContentOnDiff', [ $this, $out ] ) ) {
793 $this->loadNewText();
794 if ( !$this->mNewPage
) {
795 // New revision is unsaved; bail out.
796 // TODO in theory rendering the new revision is a meaningful thing to do
797 // even if it's unsaved, but a lot of untangling is required to do it safely.
800 $out->setRevisionId( $this->mNewid
);
801 $out->setRevisionTimestamp( $this->mNewRev
->getTimestamp() );
802 $out->setArticleFlag( true );
804 if ( !Hooks
::run( 'ArticleContentViewCustom',
805 [ $this->mNewContent
, $this->mNewPage
, $out ] )
807 // Handled by extension
810 if ( $this->getTitle()->equals( $this->mNewPage
) ) {
811 // If the Title stored in the context is the same as the one
812 // of the new revision, we can use its associated WikiPage
814 $wikiPage = $this->getWikiPage();
816 // Otherwise we need to create our own WikiPage object
817 $wikiPage = WikiPage
::factory( $this->mNewPage
);
820 $parserOutput = $this->getParserOutput( $wikiPage, $this->mNewRev
);
822 # WikiPage::getParserOutput() should not return false, but just in case
823 if ( $parserOutput ) {
824 // Allow extensions to change parser output here
825 if ( Hooks
::run( 'DifferenceEngineRenderRevisionAddParserOutput',
826 [ $this, $out, $parserOutput, $wikiPage ] )
828 $out->addParserOutput( $parserOutput, [
829 'enableSectionEditLinks' => $this->mNewRev
->isCurrent()
830 && $this->mNewRev
->getTitle()->quickUserCan( 'edit', $this->getUser() ),
837 // Allow extensions to optionally not show the final patrolled link
838 if ( Hooks
::run( 'DifferenceEngineRenderRevisionShowFinalPatrolLink' ) ) {
839 # Add redundant patrol link on bottom...
840 $out->addHTML( $this->markPatrolledLink() );
845 * @param WikiPage $page
846 * @param Revision $rev
848 * @return ParserOutput|bool False if the revision was not found
850 protected function getParserOutput( WikiPage
$page, Revision
$rev ) {
851 $parserOptions = $page->makeParserOptions( $this->getContext() );
852 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
854 return $parserOutput;
858 * Get the diff text, send it to the OutputPage object
859 * Returns false if the diff could not be generated, otherwise returns true
861 * @param string|bool $otitle Header for old text or false
862 * @param string|bool $ntitle Header for new text or false
863 * @param string $notice HTML between diff header and body
867 public function showDiff( $otitle, $ntitle, $notice = '' ) {
868 // Allow extensions to affect the output here
869 Hooks
::run( 'DifferenceEngineShowDiff', [ $this ] );
871 $diff = $this->getDiff( $otitle, $ntitle, $notice );
872 if ( $diff === false ) {
873 $this->showMissingRevision();
877 $this->showDiffStyle();
878 $this->getOutput()->addHTML( $diff );
885 * Add style sheets for diff display.
887 public function showDiffStyle() {
888 if ( !$this->isSlotDiffRenderer
) {
889 $this->getOutput()->addModuleStyles( 'mediawiki.diff.styles' );
890 foreach ( $this->getSlotDiffRenderers() as $slotDiffRenderer ) {
891 $slotDiffRenderer->addModules( $this->getOutput() );
897 * Get complete diff table, including header
899 * @param string|bool $otitle Header for old text or false
900 * @param string|bool $ntitle Header for new text or false
901 * @param string $notice HTML between diff header and body
905 public function getDiff( $otitle, $ntitle, $notice = '' ) {
906 $body = $this->getDiffBody();
907 if ( $body === false ) {
911 $multi = $this->getMultiNotice();
912 // Display a message when the diff is empty
913 if ( $body === '' ) {
914 $notice .= '<div class="mw-diff-empty">' .
915 $this->msg( 'diff-empty' )->parse() .
919 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
923 * Get the diff table body, without header
925 * @return mixed (string/false)
927 public function getDiffBody() {
928 $this->mCacheHit
= true;
929 // Check if the diff should be hidden from this user
930 if ( !$this->isContentOverridden
) {
931 if ( !$this->loadRevisionData() ) {
933 } elseif ( $this->mOldRev
&&
934 !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
937 } elseif ( $this->mNewRev
&&
938 !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
943 if ( $this->mOldRev
=== false ||
( $this->mOldRev
&& $this->mNewRev
&&
944 $this->mOldRev
->getId() && $this->mOldRev
->getId() == $this->mNewRev
->getId() )
946 if ( Hooks
::run( 'DifferenceEngineShowEmptyOldContent', [ $this ] ) ) {
954 $cache = ObjectCache
::getMainWANInstance();
955 if ( $this->mOldid
&& $this->mNewid
) {
956 // Check if subclass is still using the old way
957 // for backwards-compatibility
958 $key = $this->getDiffBodyCacheKey();
959 if ( $key === null ) {
960 $key = $cache->makeKey( ...$this->getDiffBodyCacheKeyParams() );
964 if ( !$this->mRefreshCache
) {
965 $difftext = $cache->get( $key );
967 wfIncrStats( 'diff_cache.hit' );
968 $difftext = $this->localiseDiff( $difftext );
969 $difftext .= "\n<!-- diff cache key $key -->\n";
973 } // don't try to load but save the result
975 $this->mCacheHit
= false;
977 // Loadtext is permission safe, this just clears out the diff
978 if ( !$this->loadText() ) {
983 // We've checked for revdelete at the beginning of this method; it's OK to ignore
984 // read permissions here.
985 $slotContents = $this->getSlotContents();
986 foreach ( $this->getSlotDiffRenderers() as $role => $slotDiffRenderer ) {
987 $slotDiff = $slotDiffRenderer->getDiff( $slotContents[$role]['old'],
988 $slotContents[$role]['new'] );
989 if ( $slotDiff && $role !== 'main' ) {
990 // TODO use human-readable role name at least
992 $difftext .= $this->getSlotHeader( $slotTitle );
994 $difftext .= $slotDiff;
997 // Avoid PHP 7.1 warning from passing $this by reference
1000 // Save to cache for 7 days
1001 if ( !Hooks
::run( 'AbortDiffCache', [ &$diffEngine ] ) ) {
1002 wfIncrStats( 'diff_cache.uncacheable' );
1003 } elseif ( $key !== false && $difftext !== false ) {
1004 wfIncrStats( 'diff_cache.miss' );
1005 $cache->set( $key, $difftext, 7 * 86400 );
1007 wfIncrStats( 'diff_cache.uncacheable' );
1009 // localise line numbers and title attribute text
1010 if ( $difftext !== false ) {
1011 $difftext = $this->localiseDiff( $difftext );
1018 * Get a slot header for inclusion in a diff body (as a table row).
1020 * @param string $headerText The text of the header
1024 protected function getSlotHeader( $headerText ) {
1025 // The old revision is missing on oldid=<first>&diff=prev; only 2 columns in that case.
1026 $columnCount = $this->mOldRev ?
4 : 2;
1027 $userLang = $this->getLanguage()->getHtmlCode();
1028 return Html
::rawElement( 'tr', [ 'class' => 'mw-diff-slot-header', 'lang' => $userLang ],
1029 Html
::element( 'th', [ 'colspan' => $columnCount ], $headerText ) );
1033 * Returns the cache key for diff body text or content.
1035 * @deprecated since 1.31, use getDiffBodyCacheKeyParams() instead
1038 * @throws MWException
1039 * @return string|null
1041 protected function getDiffBodyCacheKey() {
1046 * Get the cache key parameters
1048 * Subclasses can replace the first element in the array to something
1049 * more specific to the type of diff (e.g. "inline-diff"), or append
1050 * if the cache should vary on more things. Overriding entirely should
1056 * @throws MWException
1058 protected function getDiffBodyCacheKeyParams() {
1059 if ( !$this->mOldid ||
!$this->mNewid
) {
1060 throw new MWException( 'mOldid and mNewid must be set to get diff cache key.' );
1063 $engine = $this->getEngine();
1068 "old-{$this->mOldid}",
1069 "rev-{$this->mNewid}"
1072 if ( $engine === 'wikidiff2' ) {
1073 $params[] = phpversion( 'wikidiff2' );
1074 $params[] = $this->getConfig()->get( 'WikiDiff2MovedParagraphDetectionCutoff' );
1077 if ( !$this->isSlotDiffRenderer
) {
1078 foreach ( $this->getSlotDiffRenderers() as $slotDiffRenderer ) {
1079 $params = array_merge( $params, $slotDiffRenderer->getExtraCacheKeys() );
1087 * Implements DifferenceEngineSlotDiffRenderer::getExtraCacheKeys(). Only used when
1088 * DifferenceEngine is wrapped in DifferenceEngineSlotDiffRenderer.
1090 * @internal for use by DifferenceEngineSlotDiffRenderer only
1093 public function getExtraCacheKeys() {
1094 // This method is called when the DifferenceEngine is used for a slot diff. We only care
1095 // about special things, not the revision IDs, which are added to the cache key by the
1096 // page-level DifferenceEngine, and which might not have a valid value for this object.
1097 $this->mOldid
= 123456789;
1098 $this->mNewid
= 987654321;
1100 // This will repeat a bunch of unnecessary key fields for each slot. Not nice but harmless.
1101 $cacheString = $this->getDiffBodyCacheKey();
1102 if ( $cacheString ) {
1103 return [ $cacheString ];
1106 $params = $this->getDiffBodyCacheKeyParams();
1108 // Try to get rid of the standard keys to keep the cache key human-readable:
1109 // call the getDiffBodyCacheKeyParams implementation of the base class, and if
1110 // the child class includes the same keys, drop them.
1111 // Uses an obscure PHP feature where static calls to non-static methods are allowed
1112 // as long as we are already in a non-static method of the same class, and the call context
1113 // ($this) will be inherited.
1114 // phpcs:ignore Squiz.Classes.SelfMemberReference.NotUsed
1115 $standardParams = DifferenceEngine
::getDiffBodyCacheKeyParams();
1116 if ( array_slice( $params, 0, count( $standardParams ) ) === $standardParams ) {
1117 $params = array_slice( $params, count( $standardParams ) );
1124 * Generate a diff, no caching.
1128 * @param Content $old Old content
1129 * @param Content $new New content
1131 * @throws Exception If old or new content is not an instance of TextContent.
1132 * @return bool|string
1134 * @deprecated since 1.32, use a SlotDiffRenderer instead.
1136 public function generateContentDiffBody( Content
$old, Content
$new ) {
1137 $slotDiffRenderer = $new->getContentHandler()->getSlotDiffRenderer( $this->getContext() );
1139 $slotDiffRenderer instanceof DifferenceEngineSlotDiffRenderer
1140 && $this->isSlotDiffRenderer
1142 // Oops, we are just about to enter an infinite loop (the slot-level DifferenceEngine
1143 // called a DifferenceEngineSlotDiffRenderer that wraps the same DifferenceEngine class).
1144 // This will happen when a content model has no custom slot diff renderer, it does have
1145 // a custom difference engine, but that does not override this method.
1146 throw new Exception( get_class( $this ) . ': could not maintain backwards compatibility. '
1147 . 'Please use a SlotDiffRenderer.' );
1149 return $slotDiffRenderer->getDiff( $old, $new ) . $this->getDebugString();
1153 * Generate a diff, no caching
1155 * @param string $otext Old text, must be already segmented
1156 * @param string $ntext New text, must be already segmented
1158 * @throws Exception If content handling for text content is configured in a way
1159 * that makes maintaining B/C hard.
1160 * @return bool|string
1162 * @deprecated since 1.32, use a TextSlotDiffRenderer instead.
1164 public function generateTextDiffBody( $otext, $ntext ) {
1165 $slotDiffRenderer = ContentHandler
::getForModelID( CONTENT_MODEL_TEXT
)
1166 ->getSlotDiffRenderer( $this->getContext() );
1167 if ( !( $slotDiffRenderer instanceof TextSlotDiffRenderer
) ) {
1168 // Someone used the GetSlotDiffRenderer hook to replace the renderer.
1169 // This is too unlikely to happen to bother handling properly.
1170 throw new Exception( 'The slot diff renderer for text content should be a '
1171 . 'TextSlotDiffRenderer subclass' );
1173 return $slotDiffRenderer->getTextDiff( $otext, $ntext ) . $this->getDebugString();
1177 * Process $wgExternalDiffEngine and get a sane, usable engine
1179 * @return bool|string 'wikidiff2', path to an executable, or false
1180 * @internal For use by this class and TextSlotDiffRenderer only.
1182 public static function getEngine() {
1183 global $wgExternalDiffEngine;
1184 // We use the global here instead of Config because we write to the value,
1185 // and Config is not mutable.
1186 if ( $wgExternalDiffEngine == 'wikidiff' ||
$wgExternalDiffEngine == 'wikidiff3' ) {
1187 wfDeprecated( "\$wgExternalDiffEngine = '{$wgExternalDiffEngine}'", '1.27' );
1188 $wgExternalDiffEngine = false;
1189 } elseif ( $wgExternalDiffEngine == 'wikidiff2' ) {
1190 wfDeprecated( "\$wgExternalDiffEngine = '{$wgExternalDiffEngine}'", '1.32' );
1191 $wgExternalDiffEngine = false;
1192 } elseif ( !is_string( $wgExternalDiffEngine ) && $wgExternalDiffEngine !== false ) {
1193 // And prevent people from shooting themselves in the foot...
1194 wfWarn( '$wgExternalDiffEngine is set to a non-string value, forcing it to false' );
1195 $wgExternalDiffEngine = false;
1198 if ( is_string( $wgExternalDiffEngine ) && is_executable( $wgExternalDiffEngine ) ) {
1199 return $wgExternalDiffEngine;
1200 } elseif ( $wgExternalDiffEngine === false && function_exists( 'wikidiff2_do_diff' ) ) {
1209 * Generates diff, to be wrapped internally in a logging/instrumentation
1211 * @param string $otext Old text, must be already segmented
1212 * @param string $ntext New text, must be already segmented
1214 * @throws Exception If content handling for text content is configured in a way
1215 * that makes maintaining B/C hard.
1216 * @return bool|string
1218 * @deprecated since 1.32, use a TextSlotDiffRenderer instead.
1220 protected function textDiff( $otext, $ntext ) {
1221 $slotDiffRenderer = ContentHandler
::getForModelID( CONTENT_MODEL_TEXT
)
1222 ->getSlotDiffRenderer( $this->getContext() );
1223 if ( !( $slotDiffRenderer instanceof TextSlotDiffRenderer
) ) {
1224 // Someone used the GetSlotDiffRenderer hook to replace the renderer.
1225 // This is too unlikely to happen to bother handling properly.
1226 throw new Exception( 'The slot diff renderer for text content should be a '
1227 . 'TextSlotDiffRenderer subclass' );
1229 return $slotDiffRenderer->getTextDiff( $otext, $ntext ) . $this->getDebugString();
1233 * Generate a debug comment indicating diff generating time,
1234 * server node, and generator backend.
1236 * @param string $generator : What diff engine was used
1240 protected function debug( $generator = "internal" ) {
1241 global $wgShowHostnames;
1242 if ( !$this->enableDebugComment
) {
1245 $data = [ $generator ];
1246 if ( $wgShowHostnames ) {
1247 $data[] = wfHostname();
1249 $data[] = wfTimestamp( TS_DB
);
1251 return "<!-- diff generator: " .
1252 implode( " ", array_map( "htmlspecialchars", $data ) ) .
1256 private function getDebugString() {
1257 $engine = self
::getEngine();
1258 if ( $engine === 'wikidiff2' ) {
1259 return $this->debug( 'wikidiff2' );
1260 } elseif ( $engine === false ) {
1261 return $this->debug( 'native PHP' );
1263 return $this->debug( "external $engine" );
1268 * Localise diff output
1270 * @param string $text
1273 private function localiseDiff( $text ) {
1274 $text = $this->localiseLineNumbers( $text );
1275 if ( $this->getEngine() === 'wikidiff2' &&
1276 version_compare( phpversion( 'wikidiff2' ), '1.5.1', '>=' )
1278 $text = $this->addLocalisedTitleTooltips( $text );
1284 * Replace line numbers with the text in the user's language
1286 * @param string $text
1290 public function localiseLineNumbers( $text ) {
1291 return preg_replace_callback(
1292 '/<!--LINE (\d+)-->/',
1293 [ $this, 'localiseLineNumbersCb' ],
1298 public function localiseLineNumbersCb( $matches ) {
1299 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) {
1303 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
1307 * Add title attributes for tooltips on moved paragraph indicators
1309 * @param string $text
1312 private function addLocalisedTitleTooltips( $text ) {
1313 return preg_replace_callback(
1314 '/class="mw-diff-movedpara-(left|right)"/',
1315 [ $this, 'addLocalisedTitleTooltipsCb' ],
1321 * @param array $matches
1324 private function addLocalisedTitleTooltipsCb( array $matches ) {
1325 $key = $matches[1] === 'right' ?
1326 'diff-paragraph-moved-toold' :
1327 'diff-paragraph-moved-tonew';
1328 return $matches[0] . ' title="' . $this->msg( $key )->escaped() . '"';
1332 * If there are revisions between the ones being compared, return a note saying so.
1336 public function getMultiNotice() {
1337 // The notice only make sense if we are diffing two saved revisions of the same page.
1339 !$this->mOldRev ||
!$this->mNewRev
1340 ||
!$this->mOldPage ||
!$this->mNewPage
1341 ||
!$this->mOldPage
->equals( $this->mNewPage
)
1346 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
1347 $oldRev = $this->mNewRev
; // flip
1348 $newRev = $this->mOldRev
; // flip
1349 } else { // normal case
1350 $oldRev = $this->mOldRev
;
1351 $newRev = $this->mNewRev
;
1354 // Sanity: don't show the notice if too many rows must be scanned
1355 // @todo show some special message for that case
1356 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev, 1000 );
1357 if ( $nEdits > 0 && $nEdits <= 1000 ) {
1358 $limit = 100; // use diff-multi-manyusers if too many users
1359 $users = $this->mNewPage
->getAuthorsBetween( $oldRev, $newRev, $limit );
1360 $numUsers = count( $users );
1362 if ( $numUsers == 1 && $users[0] == $newRev->getUserText( Revision
::RAW
) ) {
1363 $numUsers = 0; // special case to say "by the same user" instead of "by one other user"
1366 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
1369 return ''; // nothing
1373 * Get a notice about how many intermediate edits and users there are
1375 * @param int $numEdits
1376 * @param int $numUsers
1381 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
1382 if ( $numUsers === 0 ) {
1383 $msg = 'diff-multi-sameuser';
1384 } elseif ( $numUsers > $limit ) {
1385 $msg = 'diff-multi-manyusers';
1388 $msg = 'diff-multi-otherusers';
1391 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
1395 * Get a header for a specified revision.
1397 * @param Revision $rev
1398 * @param string $complete 'complete' to get the header wrapped depending
1399 * the visibility of the revision and a link to edit the page.
1401 * @return string HTML fragment
1403 public function getRevisionHeader( Revision
$rev, $complete = '' ) {
1404 $lang = $this->getLanguage();
1405 $user = $this->getUser();
1406 $revtimestamp = $rev->getTimestamp();
1407 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
1408 $dateofrev = $lang->userDate( $revtimestamp, $user );
1409 $timeofrev = $lang->userTime( $revtimestamp, $user );
1411 $header = $this->msg(
1412 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
1418 if ( $complete !== 'complete' ) {
1422 $title = $rev->getTitle();
1424 $header = Linker
::linkKnown( $title, $header, [],
1425 [ 'oldid' => $rev->getId() ] );
1427 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
1428 $editQuery = [ 'action' => 'edit' ];
1429 if ( !$rev->isCurrent() ) {
1430 $editQuery['oldid'] = $rev->getId();
1433 $key = $title->quickUserCan( 'edit', $user ) ?
'editold' : 'viewsourceold';
1434 $msg = $this->msg( $key )->escaped();
1435 $editLink = $this->msg( 'parentheses' )->rawParams(
1436 Linker
::linkKnown( $title, $msg, [], $editQuery ) )->escaped();
1437 $header .= ' ' . Html
::rawElement(
1439 [ 'class' => 'mw-diff-edit' ],
1442 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
1443 $header = Html
::rawElement(
1445 [ 'class' => 'history-deleted' ],
1450 $header = Html
::rawElement( 'span', [ 'class' => 'history-deleted' ], $header );
1457 * Add the header to a diff body
1459 * @param string $diff Diff body
1460 * @param string $otitle Old revision header
1461 * @param string $ntitle New revision header
1462 * @param string $multi Notice telling user that there are intermediate
1463 * revisions between the ones being compared
1464 * @param string $notice Other notices, e.g. that user is viewing deleted content
1468 public function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
1469 // shared.css sets diff in interface language/dir, but the actual content
1470 // is often in a different language, mostly the page content language/dir
1471 $header = Html
::openElement( 'table', [
1472 'class' => [ 'diff', 'diff-contentalign-' . $this->getDiffLang()->alignStart() ],
1473 'data-mw' => 'interface',
1475 $userLang = htmlspecialchars( $this->getLanguage()->getHtmlCode() );
1477 if ( !$diff && !$otitle ) {
1479 <tr class=\"diff-title\" lang=\"{$userLang}\">
1480 <td class=\"diff-ntitle\">{$ntitle}</td>
1484 if ( $diff ) { // Safari/Chrome show broken output if cols not used
1486 <col class=\"diff-marker\" />
1487 <col class=\"diff-content\" />
1488 <col class=\"diff-marker\" />
1489 <col class=\"diff-content\" />";
1496 if ( $otitle ||
$ntitle ) {
1498 <tr class=\"diff-title\" lang=\"{$userLang}\">
1499 <td colspan=\"$colspan\" class=\"diff-otitle\">{$otitle}</td>
1500 <td colspan=\"$colspan\" class=\"diff-ntitle\">{$ntitle}</td>
1505 if ( $multi != '' ) {
1506 $header .= "<tr><td colspan=\"{$multiColspan}\" " .
1507 "class=\"diff-multi\" lang=\"{$userLang}\">{$multi}</td></tr>";
1509 if ( $notice != '' ) {
1510 $header .= "<tr><td colspan=\"{$multiColspan}\" " .
1511 "class=\"diff-notice\" lang=\"{$userLang}\">{$notice}</td></tr>";
1514 return $header . $diff . "</table>";
1518 * Use specified text instead of loading from the database
1519 * @param Content $oldContent
1520 * @param Content $newContent
1522 * @deprecated since 1.32, use setRevisions or ContentHandler::getSlotDiffRenderer.
1524 public function setContent( Content
$oldContent, Content
$newContent ) {
1525 $this->mOldContent
= $oldContent;
1526 $this->mNewContent
= $newContent;
1528 $this->mTextLoaded
= 2;
1529 $this->mRevisionsLoaded
= true;
1530 $this->isContentOverridden
= true;
1531 $this->slotDiffRenderers
= null;
1535 * Use specified text instead of loading from the database.
1536 * @param RevisionRecord|null $oldRevision
1537 * @param RevisionRecord $newRevision
1539 public function setRevisions(
1540 RevisionRecord
$oldRevision = null, RevisionRecord
$newRevision
1542 if ( $oldRevision ) {
1543 $this->mOldRev
= new Revision( $oldRevision );
1544 $this->mOldid
= $oldRevision->getId();
1545 $this->mOldPage
= Title
::newFromLinkTarget( $oldRevision->getPageAsLinkTarget() );
1546 // This method is meant for edit diffs and such so there is no reason to provide a
1547 // revision that's not readable to the user, but check it just in case.
1548 $this->mOldContent
= $oldRevision ?
$oldRevision->getContent( 'main',
1549 RevisionRecord
::FOR_THIS_USER
, $this->getUser() ) : null;
1551 $this->mOldRev
= $this->mOldid
= $this->mOldPage
= null;
1553 $this->mNewRev
= new Revision( $newRevision );
1554 $this->mNewid
= $newRevision->getId();
1555 $this->mNewPage
= Title
::newFromLinkTarget( $newRevision->getPageAsLinkTarget() );
1556 $this->mNewContent
= $newRevision->getContent( 'main',
1557 RevisionRecord
::FOR_THIS_USER
, $this->getUser() );
1559 $this->mRevisionsIdsLoaded
= $this->mRevisionsLoaded
= true;
1560 $this->mTextLoaded
= !!$oldRevision +
1;
1561 $this->isContentOverridden
= false;
1562 $this->slotDiffRenderers
= null;
1566 * Set the language in which the diff text is written
1568 * @param Language $lang
1571 public function setTextLanguage( $lang ) {
1572 if ( !$lang instanceof Language
) {
1573 wfDeprecated( __METHOD__
. ' with other type than Language for $lang', '1.32' );
1575 $this->mDiffLang
= wfGetLangObj( $lang );
1579 * Maps a revision pair definition as accepted by DifferenceEngine constructor
1580 * to a pair of actual integers representing revision ids.
1582 * @param int $old Revision id, e.g. from URL parameter 'oldid'
1583 * @param int|string $new Revision id or strings 'next' or 'prev', e.g. from URL parameter 'diff'
1585 * @return int[] List of two revision ids, older first, later second.
1586 * Zero signifies invalid argument passed.
1587 * false signifies that there is no previous/next revision ($old is the oldest/newest one).
1589 public function mapDiffPrevNext( $old, $new ) {
1590 if ( $new === 'prev' ) {
1591 // Show diff between revision $old and the previous one. Get previous one from DB.
1592 $newid = intval( $old );
1593 $oldid = $this->getTitle()->getPreviousRevisionID( $newid );
1594 } elseif ( $new === 'next' ) {
1595 // Show diff between revision $old and the next one. Get next one from DB.
1596 $oldid = intval( $old );
1597 $newid = $this->getTitle()->getNextRevisionID( $oldid );
1599 $oldid = intval( $old );
1600 $newid = intval( $new );
1603 return [ $oldid, $newid ];
1609 private function loadRevisionIds() {
1610 if ( $this->mRevisionsIdsLoaded
) {
1614 $this->mRevisionsIdsLoaded
= true;
1616 $old = $this->mOldid
;
1617 $new = $this->mNewid
;
1619 list( $this->mOldid
, $this->mNewid
) = self
::mapDiffPrevNext( $old, $new );
1620 if ( $new === 'next' && $this->mNewid
=== false ) {
1621 # if no result, NewId points to the newest old revision. The only newer
1622 # revision is cur, which is "0".
1627 'NewDifferenceEngine',
1628 [ $this->getTitle(), &$this->mOldid
, &$this->mNewid
, $old, $new ]
1633 * Load revision metadata for the specified articles. If newid is 0, then compare
1634 * the old article in oldid to the current article; if oldid is 0, then
1635 * compare the current article to the immediately previous one (ignoring the
1638 * If oldid is false, leave the corresponding revision object set
1639 * to false. This is impossible via ordinary user input, and is provided for
1642 * @return bool Whether both revisions were loaded successfully.
1644 public function loadRevisionData() {
1645 if ( $this->mRevisionsLoaded
) {
1646 return $this->isContentOverridden ||
$this->mNewRev
&& $this->mOldRev
;
1649 // Whether it succeeds or fails, we don't want to try again
1650 $this->mRevisionsLoaded
= true;
1652 $this->loadRevisionIds();
1654 // Load the new revision object
1655 if ( $this->mNewid
) {
1656 $this->mNewRev
= Revision
::newFromId( $this->mNewid
);
1658 $this->mNewRev
= Revision
::newFromTitle(
1661 Revision
::READ_NORMAL
1665 if ( !$this->mNewRev
instanceof Revision
) {
1669 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1670 $this->mNewid
= $this->mNewRev
->getId();
1671 if ( $this->mNewid
) {
1672 $this->mNewPage
= $this->mNewRev
->getTitle();
1674 $this->mNewPage
= null;
1677 // Load the old revision object
1678 $this->mOldRev
= false;
1679 if ( $this->mOldid
) {
1680 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1681 } elseif ( $this->mOldid
=== 0 ) {
1682 $rev = $this->mNewRev
->getPrevious();
1684 $this->mOldid
= $rev->getId();
1685 $this->mOldRev
= $rev;
1687 // No previous revision; mark to show as first-version only.
1688 $this->mOldid
= false;
1689 $this->mOldRev
= false;
1691 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1693 if ( is_null( $this->mOldRev
) ) {
1697 if ( $this->mOldRev
&& $this->mOldRev
->getId() ) {
1698 $this->mOldPage
= $this->mOldRev
->getTitle();
1700 $this->mOldPage
= null;
1703 // Load tags information for both revisions
1704 $dbr = wfGetDB( DB_REPLICA
);
1705 if ( $this->mOldid
!== false ) {
1706 $this->mOldTags
= $dbr->selectField(
1709 [ 'ts_rev_id' => $this->mOldid
],
1713 $this->mOldTags
= false;
1715 $this->mNewTags
= $dbr->selectField(
1718 [ 'ts_rev_id' => $this->mNewid
],
1726 * Load the text of the revisions, as well as revision data.
1728 * @return bool Whether the content of both revisions could be loaded successfully.
1730 public function loadText() {
1731 if ( $this->mTextLoaded
== 2 ) {
1732 return $this->loadRevisionData() && $this->mOldContent
&& $this->mNewContent
;
1735 // Whether it succeeds or fails, we don't want to try again
1736 $this->mTextLoaded
= 2;
1738 if ( !$this->loadRevisionData() ) {
1742 if ( $this->mOldRev
) {
1743 $this->mOldContent
= $this->mOldRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1744 if ( $this->mOldContent
=== null ) {
1749 if ( $this->mNewRev
) {
1750 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1751 Hooks
::run( 'DifferenceEngineLoadTextAfterNewContentIsLoaded', [ $this ] );
1752 if ( $this->mNewContent
=== null ) {
1761 * Load the text of the new revision, not the old one
1763 * @return bool Whether the content of the new revision could be loaded successfully.
1765 public function loadNewText() {
1766 if ( $this->mTextLoaded
>= 1 ) {
1767 return $this->loadRevisionData();
1770 $this->mTextLoaded
= 1;
1772 if ( !$this->loadRevisionData() ) {
1776 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1778 Hooks
::run( 'DifferenceEngineAfterLoadNewText', [ $this ] );