Debian Codegraph @

includes/diff/DifferenceEngine.php

raw symbols SCIP
1 <?php
2 /**
3 * User interface for the difference engine.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup DifferenceEngine
22 */
23
24 use MediaWiki\CommentFormatter\CommentFormatter;
25 use MediaWiki\Content\Content;
26 use MediaWiki\Content\IContentHandlerFactory;
27 use MediaWiki\Context\ContextSource;
28 use MediaWiki\Context\IContextSource;
29 use MediaWiki\Debug\DeprecationHelper;
30 use MediaWiki\Diff\TextDiffer\ManifoldTextDiffer;
31 use MediaWiki\HookContainer\HookRunner;
32 use MediaWiki\Html\Html;
33 use MediaWiki\Language\Language;
34 use MediaWiki\Linker\Linker;
35 use MediaWiki\Linker\LinkRenderer;
36 use MediaWiki\MainConfigNames;
37 use MediaWiki\MediaWikiServices;
38 use MediaWiki\Message\Message;
39 use MediaWiki\Page\ParserOutputAccess;
40 use MediaWiki\Page\WikiPageFactory;
41 use MediaWiki\Permissions\Authority;
42 use MediaWiki\Permissions\PermissionStatus;
43 use MediaWiki\Revision\ArchivedRevisionLookup;
44 use MediaWiki\Revision\BadRevisionException;
45 use MediaWiki\Revision\RevisionRecord;
46 use MediaWiki\Revision\RevisionStore;
47 use MediaWiki\Revision\SlotRecord;
48 use MediaWiki\SpecialPage\SpecialPage;
49 use MediaWiki\Storage\NameTableAccessException;
50 use MediaWiki\Title\Title;
51 use MediaWiki\User\Options\UserOptionsLookup;
52 use MediaWiki\User\UserEditTracker;
53 use MediaWiki\User\UserGroupManager;
54 use MediaWiki\User\UserGroupMembership;
55 use MediaWiki\User\UserIdentity;
56 use MediaWiki\User\UserIdentityUtils;
57 use Wikimedia\Rdbms\IConnectionProvider;
58
59 /**
60 * DifferenceEngine is responsible for rendering the difference between two revisions as HTML.
61 * This includes interpreting URL parameters, retrieving revision data, checking access permissions,
62 * selecting and invoking the diff generator class for the individual slots, doing post-processing
63 * on the generated diff, adding the rest of the HTML (such as headers) and writing the whole thing
64 * to OutputPage.
65 *
66 * DifferenceEngine can be subclassed by extensions, by customizing
67 * ContentHandler::createDifferenceEngine; the content handler will be selected based on the
68 * content model of the main slot (of the new revision, when the two are different).
69 * That might change after PageTypeHandler gets introduced.
70 *
71 * In the past, the class was also used for slot-level diff generation, and extensions might still
72 * subclass it and add such functionality. When that is the case (specifically, when a
73 * ContentHandler returns a standard SlotDiffRenderer but a nonstandard DifferenceEngine)
74 * DifferenceEngineSlotDiffRenderer will be used to convert the old behavior into the new one.
75 *
76 * @ingroup DifferenceEngine
77 *
78 * @todo This class is huge and poorly defined. It should be split into a controller responsible
79 * for interpreting query parameters, retrieving data and checking permissions; and a HTML renderer.
80 */
81 class DifferenceEngine extends ContextSource {
82
83 use DeprecationHelper;
84
85 /**
86 * Constant to indicate diff cache compatibility.
87 * Bump this when changing the diff formatting in a way that
88 * fixes important bugs or such to force cached diff views to
89 * clear.
90 */
91 private const DIFF_VERSION = '1.41';
92
93 /**
94 * Revision ID for the old revision. 0 for the revision previous to $mNewid, false
95 * if the diff does not have an old revision (e.g. 'oldid=<first revision of page>&diff=prev'),
96 * or the revision does not exist, null if the revision is unsaved.
97 * @var int|false|null
98 */
99 protected $mOldid;
100
101 /**
102 * Revision ID for the new revision. 0 for the last revision of the current page
103 * (as defined by the request context), false if the revision does not exist, null
104 * if it is unsaved, or an alias such as 'next'.
105 * @var int|string|false|null
106 */
107 protected $mNewid;
108
109 /**
110 * Old revision (left pane).
111 * Allowed to be an unsaved revision, unlikely that's ever needed though.
112 * False when the old revision does not exist; this can happen when using
113 * diff=prev on the first revision. Null when the revision should exist but
114 * doesn't (e.g. load failure); loadRevisionData() will return false in that
115 * case. Also null until lazy-loaded. Ignored completely when isContentOverridden
116 * is set.
117 * @var RevisionRecord|null|false
118 */
119 private $mOldRevisionRecord;
120
121 /**
122 * New revision (right pane).
123 * Note that this might be an unsaved revision (e.g. for edit preview).
124 * Null in case of load failure; diff methods will just return an error message in that case,
125 * and loadRevisionData() will return false. Also null until lazy-loaded. Ignored completely
126 * when isContentOverridden is set.
127 * @var RevisionRecord|null
128 */
129 private $mNewRevisionRecord;
130
131 /**
132 * Title of old revision or null if the old revision does not exist or does not belong to a page.
133 * @var Title|null
134 */
135 protected $mOldPage;
136
137 /**
138 * Title of new revision or null if the new revision does not exist or does not belong to a page.
139 * @var Title|null
140 */
141 protected $mNewPage;
142
143 /**
144 * Change tags of old revision or null if it does not exist / is not saved.
145 * @var string|false|null
146 */
147 private $mOldTags;
148
149 /**
150 * Change tags of new revision or null if it does not exist / is not saved.
151 * @var string|null
152 */
153 private $mNewTags;
154
155 /**
156 * @var Content|null
157 * @deprecated since 1.32, content slots are now handled by the corresponding SlotDiffRenderer.
158 * This property is set to the content of the main slot, but not actually used for the main diff.
159 */
160 private $mOldContent;
161
162 /**
163 * @var Content|null
164 * @deprecated since 1.32, content slots are now handled by the corresponding SlotDiffRenderer.
165 * This property is set to the content of the main slot, but not actually used for the main diff.
166 */
167 private $mNewContent;
168
169 /** @var Language */
170 protected $mDiffLang;
171
172 /** @var bool Have the revisions IDs been loaded */
173 private $mRevisionsIdsLoaded = false;
174
175 /** @var bool Have the revisions been loaded */
176 protected $mRevisionsLoaded = false;
177
178 /** @var int How many text blobs have been loaded, 0, 1 or 2? */
179 protected $mTextLoaded = 0;
180
181 /**
182 * Was the content overridden via setContent()?
183 * If the content was overridden, most internal state (e.g. mOldid or mOldRev) should be ignored
184 * and only mOldContent and mNewContent is reliable.
185 * (Note that setRevisions() does not set this flag as in that case all properties are
186 * overridden and remain consistent with each other, so no special handling is needed.)
187 * @var bool
188 */
189 protected $isContentOverridden = false;
190
191 /** @var bool Was the diff fetched from cache? */
192 protected $mCacheHit = false;
193
194 /** @var string|null Cache key if the diff was fetched from cache */
195 private $cacheHitKey = null;
196
197 /**
198 * Set this to true to add debug info to the HTML output.
199 * Warning: this may cause RSS readers to spuriously mark articles as "new"
200 * (T22601)
201 * @var bool
202 */
203 public $enableDebugComment = false;
204
205 /** @var bool If true, line X is not displayed when X is 1, for example
206 * to increase readability and conserve space with many small diffs.
207 */
208 protected $mReducedLineNumbers = false;
209
210 /** @var string Link to action=markpatrolled */
211 protected $mMarkPatrolledLink = null;
212
213 /** @var bool Show rev_deleted content if allowed */
214 protected $unhide = false;
215
216 /** @var bool Refresh the diff cache */
217 protected $mRefreshCache = false;
218
219 /** @var SlotDiffRenderer[]|null DifferenceEngine classes for the slots, keyed by role name. */
220 protected $slotDiffRenderers = null;
221
222 /**
223 * Temporary hack for B/C while slot diff related methods of DifferenceEngine are being
224 * deprecated. When true, we are inside a DifferenceEngineSlotDiffRenderer and
225 * $slotDiffRenderers should not be used.
226 * @var bool
227 */
228 protected $isSlotDiffRenderer = false;
229
230 /**
231 * A set of options that will be passed to the SlotDiffRenderer upon creation
232 * @var array
233 */
234 private $slotDiffOptions = [];
235
236 /**
237 * Extra query parameters to be appended to diff page links
238 * @var array
239 */
240 private $extraQueryParams = [];
241
242 /** @var ManifoldTextDiffer|null */
243 private $textDiffer;
244
245 protected LinkRenderer $linkRenderer;
246 private IContentHandlerFactory $contentHandlerFactory;
247 private RevisionStore $revisionStore;
248 private ArchivedRevisionLookup $archivedRevisionLookup;
249 private HookRunner $hookRunner;
250 private WikiPageFactory $wikiPageFactory;
251 private UserOptionsLookup $userOptionsLookup;
252 private CommentFormatter $commentFormatter;
253 private IConnectionProvider $dbProvider;
254 private UserGroupManager $userGroupManager;
255 private UserEditTracker $userEditTracker;
256 private UserIdentityUtils $userIdentityUtils;
257
258 /** @var Message[] */
259 private $revisionLoadErrors = [];
260
261 /**
262 * @param IContextSource|null $context Context to use, anything else will be ignored
263 * @param int $old Old ID we want to show and diff with.
264 * @param string|int $new Either revision ID or 'prev' or 'next'. Default: 0.
265 * @param int $rcid Deprecated, no longer used!
266 * @param bool $refreshCache If set, refreshes the diff cache
267 * @param bool $unhide If set, allow viewing deleted revs
268 */
269 public function __construct( $context = null, $old = 0, $new = 0, $rcid = 0,
270 $refreshCache = false, $unhide = false
271 ) {
272 if ( $context instanceof IContextSource ) {
273 $this->setContext( $context );
274 }
275
276 wfDebug( "DifferenceEngine old '$old' new '$new' rcid '$rcid'" );
277
278 $this->mOldid = $old;
279 $this->mNewid = $new;
280 $this->mRefreshCache = $refreshCache;
281 $this->unhide = $unhide;
282
283 $services = MediaWikiServices::getInstance();
284 $this->linkRenderer = $services->getLinkRenderer();
285 $this->contentHandlerFactory = $services->getContentHandlerFactory();
286 $this->revisionStore = $services->getRevisionStore();
287 $this->archivedRevisionLookup = $services->getArchivedRevisionLookup();
288 $this->hookRunner = new HookRunner( $services->getHookContainer() );
289 $this->wikiPageFactory = $services->getWikiPageFactory();
290 $this->userOptionsLookup = $services->getUserOptionsLookup();
291 $this->commentFormatter = $services->getCommentFormatter();
292 $this->dbProvider = $services->getConnectionProvider();
293 $this->userGroupManager = $services->getUserGroupManager();
294 $this->userEditTracker = $services->getUserEditTracker();
295 $this->userIdentityUtils = $services->getUserIdentityUtils();
296 }
297
298 /**
299 * @return SlotDiffRenderer[] Diff renderers for each slot, keyed by role name.
300 * Includes slots only present in one of the revisions. Does not include slots
301 * for which content is identical in the two revisions.
302 */
303 protected function getSlotDiffRenderers() {
304 if ( $this->isSlotDiffRenderer ) {
305 throw new LogicException( __METHOD__ . ' called in slot diff renderer mode' );
306 }
307
308 if ( $this->slotDiffRenderers === null ) {
309 if ( !$this->loadRevisionData() ) {
310 return [];
311 }
312
313 $slotContents = $this->getSlotContents();
314 $this->slotDiffRenderers = [];
315 foreach ( $slotContents as $role => $contents ) {
316 if ( $contents['new'] && $contents['old']
317 && $contents['new']->equals( $contents['old'] )
318 ) {
319 // Do not produce a diff of identical content
320 continue;
321 }
322 if ( !$contents['new'] && !$contents['old'] ) {
323 // Nothing to diff (i.e both revisions are corrupted), just ignore
324 continue;
325 }
326 $handler = ( $contents['new'] ?: $contents['old'] )->getContentHandler();
327 $this->slotDiffRenderers[$role] = $handler->getSlotDiffRenderer(
328 $this->getContext(),
329 $this->slotDiffOptions + [
330 'contentLanguage' => $this->getDiffLang()->getCode(),
331 'textDiffer' => $this->getTextDiffer()
332 ]
333 );
334 }
335 }
336
337 return $this->slotDiffRenderers;
338 }
339
340 /**
341 * Mark this DifferenceEngine as a slot renderer (as opposed to a page renderer).
342 * This is used in legacy mode when the DifferenceEngine is wrapped in a
343 * DifferenceEngineSlotDiffRenderer.
344 * @internal For use by DifferenceEngineSlotDiffRenderer only.
345 */
346 public function markAsSlotDiffRenderer() {
347 $this->isSlotDiffRenderer = true;
348 }
349
350 /**
351 * Get the old and new content objects for all slots.
352 * This method does not do any permission checks.
353 * @return (Content|null)[][] [ role => [ 'old' => Content|null, 'new' => Content|null ], ... ]
354 */
355 protected function getSlotContents() {
356 if ( $this->isContentOverridden ) {
357 return [
358 SlotRecord::MAIN => [ 'old' => $this->mOldContent, 'new' => $this->mNewContent ]
359 ];
360 } elseif ( !$this->loadRevisionData() ) {
361 return [];
362 }
363
364 $newSlots = $this->mNewRevisionRecord->getPrimarySlots()->getSlots();
365 $oldSlots = $this->mOldRevisionRecord ?
366 $this->mOldRevisionRecord->getPrimarySlots()->getSlots() :
367 [];
368 // The order here will determine the visual order of the diff. The current logic is
369 // slots of the new revision first in natural order, then deleted ones. This is ad hoc
370 // and should not be relied on - in the future we may want the ordering to depend
371 // on the page type.
372 $roles = array_keys( array_merge( $newSlots, $oldSlots ) );
373
374 $slots = [];
375 foreach ( $roles as $role ) {
376 $slots[$role] = [
377 'old' => $this->loadSingleSlot(
378 $oldSlots[$role] ?? null,
379 'old'
380 ),
381 'new' => $this->loadSingleSlot(
382 $newSlots[$role] ?? null,
383 'new'
384 )
385 ];
386 }
387 // move main slot to front
388 if ( isset( $slots[SlotRecord::MAIN] ) ) {
389 $slots = [ SlotRecord::MAIN => $slots[SlotRecord::MAIN] ] + $slots;
390 }
391 return $slots;
392 }
393
394 /**
395 * Load the content of a single slot record
396 *
397 * @param SlotRecord|null $slot
398 * @param string $which "new" or "old"
399 * @return Content|null
400 */
401 private function loadSingleSlot( ?SlotRecord $slot, string $which ) {
402 if ( !$slot ) {
403 return null;
404 }
405 try {
406 return $slot->getContent();
407 } catch ( BadRevisionException $e ) {
408 $this->addRevisionLoadError( $which );
409 return null;
410 }
411 }
412
413 /**
414 * Set a message to show as a notice at the top of the page
415 *
416 * @param string $which "new" or "old"
417 */
418 private function addRevisionLoadError( $which ) {
419 $this->revisionLoadErrors[] = $this->msg( $which === 'new'
420 ? 'difference-bad-new-revision' : 'difference-bad-old-revision'
421 );
422 }
423
424 /**
425 * If errors were encountered while loading the revision contents, this
426 * will return an array of Messages describing the errors.
427 *
428 * @return Message[]
429 */
430 public function getRevisionLoadErrors() {
431 return $this->revisionLoadErrors;
432 }
433
434 /**
435 * Determine whether there was an error loading the new revision
436 * @return bool
437 */
438 private function hasNewRevisionLoadError() {
439 foreach ( $this->revisionLoadErrors as $error ) {
440 if ( $error->getKey() === 'difference-bad-new-revision' ) {
441 return true;
442 }
443 }
444 return false;
445 }
446
447 /** @inheritDoc */
448 public function getTitle() {
449 // T202454 avoid errors when there is no title
450 return parent::getTitle() ?: Title::makeTitle( NS_SPECIAL, 'BadTitle/DifferenceEngine' );
451 }
452
453 /**
454 * Set reduced line numbers mode.
455 * When set, line X is not displayed when X is 1, for example to increase readability and
456 * conserve space with many small diffs.
457 * @param bool $value
458 */
459 public function setReducedLineNumbers( $value = true ) {
460 $this->mReducedLineNumbers = $value;
461 }
462
463 /**
464 * Get the language in which the diff text is written
465 *
466 * @return Language
467 */
468 public function getDiffLang() {
469 # Default language in which the diff text is written.
470 $this->mDiffLang ??= $this->getDefaultLanguage();
471 return $this->mDiffLang;
472 }
473
474 /**
475 * Get the language to use if none has been set by setTextLanguage().
476 * Wikibase overrides this to use the user language.
477 *
478 * @return Language
479 */
480 protected function getDefaultLanguage() {
481 return $this->getTitle()->getPageLanguage();
482 }
483
484 /**
485 * @return bool
486 */
487 public function wasCacheHit() {
488 return $this->mCacheHit;
489 }
490
491 /**
492 * Get the ID of old revision (left pane) of the diff. 0 for the revision
493 * previous to getNewid(), false if the old revision does not exist, null
494 * if it's unsaved.
495 * To get a real revision ID instead of 0, call loadRevisionData() first.
496 * @return int|false|null
497 */
498 public function getOldid() {
499 $this->loadRevisionIds();
500
501 return $this->mOldid;
502 }
503
504 /**
505 * Get the ID of new revision (right pane) of the diff. 0 for the current revision,
506 * false if the new revision does not exist, null if it's unsaved.
507 * To get a real revision ID instead of 0, call loadRevisionData() first.
508 * @return int|false|null
509 */
510 public function getNewid() {
511 $this->loadRevisionIds();
512
513 return $this->mNewid;
514 }
515
516 /**
517 * Get the left side of the diff.
518 * Could be null when the first revision of the page is diffed to 'prev' (or in the case of
519 * load failure).
520 * @return RevisionRecord|null
521 */
522 public function getOldRevision() {
523 return $this->mOldRevisionRecord ?: null;
524 }
525
526 /**
527 * Get the right side of the diff.
528 * Should not be null but can still happen in the case of load failure.
529 * @return RevisionRecord|null
530 */
531 public function getNewRevision() {
532 return $this->mNewRevisionRecord;
533 }
534
535 /**
536 * Look up a special:Undelete link to the given deleted revision id,
537 * as a workaround for being unable to load deleted diffs in currently.
538 *
539 * @param int $id Revision ID
540 *
541 * @return string|bool Link HTML or false
542 */
543 public function deletedLink( $id ) {
544 if ( $this->getAuthority()->isAllowed( 'deletedhistory' ) ) {
545 $revRecord = $this->archivedRevisionLookup->getArchivedRevisionRecord( null, $id );
546 if ( $revRecord ) {
547 $title = Title::newFromPageIdentity( $revRecord->getPage() );
548
549 return SpecialPage::getTitleFor( 'Undelete' )->getFullURL( [
550 'target' => $title->getPrefixedText(),
551 'timestamp' => $revRecord->getTimestamp()
552 ] );
553 }
554 }
555
556 return false;
557 }
558
559 /**
560 * Build a wikitext link toward a deleted revision, if viewable.
561 *
562 * @param int $id Revision ID
563 *
564 * @return string Wikitext fragment
565 */
566 public function deletedIdMarker( $id ) {
567 $link = $this->deletedLink( $id );
568 if ( $link ) {
569 return "[$link $id]";
570 } else {
571 return (string)$id;
572 }
573 }
574
575 private function showMissingRevision() {
576 $out = $this->getOutput();
577
578 $missing = [];
579 if ( $this->mOldid && ( !$this->mOldRevisionRecord || !$this->mOldContent ) ) {
580 $missing[] = $this->deletedIdMarker( $this->mOldid );
581 }
582 if ( !$this->mNewRevisionRecord || !$this->mNewContent ) {
583 $missing[] = $this->deletedIdMarker( $this->mNewid );
584 }
585
586 $out->setPageTitleMsg( $this->msg( 'errorpagetitle' ) );
587 $msg = $this->msg( 'difference-missing-revision' )
588 ->params( $this->getLanguage()->listToText( $missing ) )
589 ->numParams( count( $missing ) )
590 ->parseAsBlock();
591 $out->addHTML( $msg );
592 }
593
594 /**
595 * Checks whether one of the given Revisions was deleted
596 *
597 * @return bool
598 */
599 public function hasDeletedRevision() {
600 $this->loadRevisionData();
601 return (
602 $this->mNewRevisionRecord &&
603 $this->mNewRevisionRecord->isDeleted( RevisionRecord::DELETED_TEXT )
604 ) ||
605 (
606 $this->mOldRevisionRecord &&
607 $this->mOldRevisionRecord->isDeleted( RevisionRecord::DELETED_TEXT )
608 );
609 }
610
611 /**
612 * Get the permission errors associated with the revisions for the current diff.
613 *
614 * @param Authority $performer
615 * @return array[] Array of arrays of the arguments to wfMessage to explain permissions problems.
616 */
617 public function getPermissionErrors( Authority $performer ) {
618 $this->loadRevisionData();
619 $permStatus = PermissionStatus::newEmpty();
620 if ( $this->mNewPage ) {
621 $performer->authorizeRead( 'read', $this->mNewPage, $permStatus );
622 }
623 if ( $this->mOldPage ) {
624 $performer->authorizeRead( 'read', $this->mOldPage, $permStatus );
625 }
626 return $permStatus->toLegacyErrorArray();
627 }
628
629 /**
630 * Checks whether one of the given Revisions was suppressed
631 *
632 * @return bool
633 */
634 public function hasSuppressedRevision() {
635 return $this->hasDeletedRevision() && (
636 ( $this->mOldRevisionRecord &&
637 $this->mOldRevisionRecord->isDeleted( RevisionRecord::DELETED_RESTRICTED ) ) ||
638 ( $this->mNewRevisionRecord &&
639 $this->mNewRevisionRecord->isDeleted( RevisionRecord::DELETED_RESTRICTED ) )
640 );
641 }
642
643 /**
644 * Renders user associated edit count
645 *
646 * @param UserIdentity $user
647 * @return string
648 */
649 private function getUserEditCount( $user ): string {
650 $editCount = $this->userEditTracker->getUserEditCount( $user );
651 if ( $editCount === null ) {
652 return '';
653 }
654
655 return Html::rawElement( 'div', [
656 'class' => 'mw-diff-usereditcount',
657 ],
658 $this->msg(
659 'diff-user-edits',
660 $this->getLanguage()->formatNum( $editCount )
661 )->parse()
662 );
663 }
664
665 /**
666 * Renders user roles
667 *
668 * @param UserIdentity $user
669 * @return string
670 */
671 private function getUserRoles( UserIdentity $user ) {
672 if ( !$this->userIdentityUtils->isNamed( $user ) ) {
673 return '';
674 }
675 $userGroups = $this->userGroupManager->getUserGroups( $user );
676 $userGroupLinks = [];
677 foreach ( $userGroups as $group ) {
678 $userGroupLinks[] = UserGroupMembership::getLinkHTML( $group, $this->getContext() );
679 }
680 return Html::rawElement( 'div', [
681 'class' => 'mw-diff-userroles',
682 ], $this->getLanguage()->commaList( $userGroupLinks ) );
683 }
684
685 /**
686 * Renders user associated meta data
687 *
688 * @param UserIdentity|null $user
689 * @return string
690 */
691 private function getUserMetaData( ?UserIdentity $user ) {
692 if ( !$user ) {
693 return '';
694 }
695 return Html::rawElement( 'div', [
696 'class' => 'mw-diff-usermetadata',
697 ], $this->getUserRoles( $user ) . $this->getUserEditCount( $user ) );
698 }
699
700 /**
701 * Checks whether the current user has permission for accessing the revisions of the diff.
702 * Note that this does not check whether the user has permission to view the page, it only
703 * checks revdelete permissions.
704 *
705 * It is the caller's responsibility to call
706 * $this->getUserPermissionErrors or similar checks.
707 *
708 * @param Authority $performer
709 * @return bool
710 */
711 public function isUserAllowedToSeeRevisions( Authority $performer ) {
712 $this->loadRevisionData();
713
714 if ( $this->mOldRevisionRecord && !$this->mOldRevisionRecord->userCan(
715 RevisionRecord::DELETED_TEXT,
716 $performer
717 ) ) {
718 return false;
719 }
720
721 // $this->mNewRev will only be falsy if a loading error occurred
722 // (in which case the user is allowed to see).
723 return !$this->mNewRevisionRecord || $this->mNewRevisionRecord->userCan(
724 RevisionRecord::DELETED_TEXT,
725 $performer
726 );
727 }
728
729 /**
730 * Checks whether the diff should be hidden from the current user
731 * This is based on whether the user is allowed to see it and has specifically asked to see it.
732 *
733 * @param Authority $performer
734 * @return bool
735 */
736 public function shouldBeHiddenFromUser( Authority $performer ) {
737 return $this->hasDeletedRevision() && ( !$this->unhide ||
738 !$this->isUserAllowedToSeeRevisions( $performer ) );
739 }
740
741 /**
742 * @param bool $diffOnly
743 */
744 public function showDiffPage( $diffOnly = false ) {
745 # Allow frames except in certain special cases
746 $out = $this->getOutput();
747 $out->getMetadata()->setPreventClickjacking( false );
748 $out->setRobotPolicy( 'noindex,nofollow' );
749
750 // Allow extensions to add any extra output here
751 $this->hookRunner->onDifferenceEngineShowDiffPage( $out );
752
753 if ( !$this->loadRevisionData() ) {
754 if ( $this->hookRunner->onDifferenceEngineShowDiffPageMaybeShowMissingRevision( $this ) ) {
755 $this->showMissingRevision();
756 }
757 return;
758 }
759
760 $user = $this->getUser();
761 $permErrors = $this->getPermissionErrors( $this->getAuthority() );
762 if ( $permErrors ) {
763 throw new PermissionsError( 'read', $permErrors );
764 }
765
766 $rollback = '';
767
768 $query = $this->extraQueryParams;
769 # Carry over 'diffonly' param via navigation links
770 if ( $diffOnly != MediaWikiServices::getInstance()
771 ->getUserOptionsLookup()->getBoolOption( $user, 'diffonly' )
772 ) {
773 $query['diffonly'] = $diffOnly;
774 }
775 # Cascade unhide param in links for easy deletion browsing
776 if ( $this->unhide ) {
777 $query['unhide'] = 1;
778 }
779
780 # Check if one of the revisions is deleted/suppressed
781 $deleted = $this->hasDeletedRevision();
782 $suppressed = $this->hasSuppressedRevision();
783 $allowed = $this->isUserAllowedToSeeRevisions( $this->getAuthority() );
784
785 $revisionTools = [];
786 $breadCrumbs = '';
787
788 # mOldRevisionRecord is false if the difference engine is called with a "vague" query for
789 # a diff between a version V and its previous version V' AND the version V
790 # is the first version of that article. In that case, V' does not exist.
791 if ( $this->mOldRevisionRecord === false ) {
792 if ( $this->mNewPage ) {
793 $out->setPageTitleMsg(
794 $this->msg( 'difference-title' )->plaintextParams( $this->mNewPage->getPrefixedText() )
795 );
796 }
797 $samePage = true;
798 $oldHeader = '';
799 // Allow extensions to change the $oldHeader variable
800 $this->hookRunner->onDifferenceEngineOldHeaderNoOldRev( $oldHeader );
801 } else {
802 $this->hookRunner->onDifferenceEngineViewHeader( $this );
803
804 if ( !$this->mOldPage || !$this->mNewPage ) {
805 // XXX say something to the user?
806 $samePage = false;
807 } elseif ( $this->mNewPage->equals( $this->mOldPage ) ) {
808 $out->setPageTitleMsg(
809 $this->msg( 'difference-title' )->plaintextParams( $this->mNewPage->getPrefixedText() )
810 );
811 $samePage = true;
812 } else {
813 $out->setPageTitleMsg( $this->msg( 'difference-title-multipage' )->plaintextParams(
814 $this->mOldPage->getPrefixedText(), $this->mNewPage->getPrefixedText() ) );
815 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
816 $samePage = false;
817 }
818
819 if ( $samePage && $this->mNewPage &&
820 $this->getAuthority()->probablyCan( 'edit', $this->mNewPage )
821 ) {
822 if ( $this->mNewRevisionRecord->isCurrent() &&
823 $this->getAuthority()->probablyCan( 'rollback', $this->mNewPage )
824 ) {
825 $rollbackLink = Linker::generateRollback(
826 $this->mNewRevisionRecord,
827 $this->getContext(),
828 [ 'noBrackets' ]
829 );
830 if ( $rollbackLink ) {
831 $out->getMetadata()->setPreventClickjacking( true );
832 $rollback = "\u{00A0}\u{00A0}\u{00A0}" . $rollbackLink;
833 }
834 }
835
836 if ( $this->userCanEdit( $this->mOldRevisionRecord ) &&
837 $this->userCanEdit( $this->mNewRevisionRecord )
838 ) {
839 $undoLink = $this->linkRenderer->makeKnownLink(
840 $this->mNewPage,
841 $this->msg( 'editundo' )->text(),
842 [ 'title' => Linker::titleAttrib( 'undo' ) ],
843 [
844 'action' => 'edit',
845 'undoafter' => $this->mOldid,
846 'undo' => $this->mNewid
847 ]
848 );
849 $revisionTools['mw-diff-undo'] = $undoLink;
850 }
851 }
852 # Make "previous revision link"
853 $hasPrevious = $samePage && $this->mOldPage &&
854 $this->revisionStore->getPreviousRevision( $this->mOldRevisionRecord );
855 if ( $hasPrevious ) {
856 $prevlinkQuery = [ 'diff' => 'prev', 'oldid' => $this->mOldid ] + $query;
857 $prevlink = $this->linkRenderer->makeKnownLink(
858 $this->mOldPage,
859 $this->msg( 'previousdiff' )->text(),
860 [ 'id' => 'differences-prevlink' ],
861 $prevlinkQuery
862 );
863 $breadCrumbs .= $this->linkRenderer->makeKnownLink(
864 $this->mOldPage,
865 $this->msg( 'previousdiff' )->text(),
866 [
867 'class' => 'mw-diff-revision-history-link-previous'
868 ],
869 $prevlinkQuery
870 );
871 } else {
872 $prevlink = "\u{00A0}";
873 }
874
875 if ( $this->mOldRevisionRecord->isMinor() ) {
876 $oldminor = ChangesList::flag( 'minor' );
877 } else {
878 $oldminor = '';
879 }
880
881 $oldRevRecord = $this->mOldRevisionRecord;
882
883 $ldel = $this->revisionDeleteLink( $oldRevRecord );
884 $oldRevisionHeader = $this->getRevisionHeader( $oldRevRecord, 'complete' );
885 $oldChangeTags = ChangeTags::formatSummaryRow( $this->mOldTags, 'diff', $this->getContext() );
886 $oldRevComment = $this->commentFormatter
887 ->formatRevision(
888 $oldRevRecord, $user, !$diffOnly, !$this->unhide, /** disable parentheseses */ false
889 );
890
891 if ( $oldRevComment === '' ) {
892 $defaultComment = $this->msg( 'changeslist-nocomment' )->escaped();
893 $oldRevComment = "<span class=\"comment mw-comment-none\">$defaultComment</span>";
894 }
895
896 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
897 '<div id="mw-diff-otitle2">' .
898 Linker::revUserTools( $oldRevRecord, !$this->unhide ) .
899 $this->getUserMetaData( $oldRevRecord->getUser() ) .
900 '</div>' .
901 '<div id="mw-diff-otitle3">' . $oldminor . $oldRevComment . $ldel . '</div>' .
902 '<div id="mw-diff-otitle5">' . $oldChangeTags[0] . '</div>' .
903 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
904
905 // Allow extensions to change the $oldHeader variable
906 $this->hookRunner->onDifferenceEngineOldHeader(
907 $this, $oldHeader, $prevlink, $oldminor, $diffOnly, $ldel, $this->unhide );
908 }
909
910 $out->addJsConfigVars( [
911 'wgDiffOldId' => $this->mOldid,
912 'wgDiffNewId' => $this->mNewid,
913 ] );
914
915 # Make "next revision link"
916 # Skip next link on the top revision
917 if ( $samePage && $this->mNewPage && !$this->mNewRevisionRecord->isCurrent() ) {
918 $nextlinkQuery = [ 'diff' => 'next', 'oldid' => $this->mNewid ] + $query;
919 $nextlink = $this->linkRenderer->makeKnownLink(
920 $this->mNewPage,
921 $this->msg( 'nextdiff' )->text(),
922 [ 'id' => 'differences-nextlink' ],
923 $nextlinkQuery
924 );
925 $breadCrumbs .= $this->linkRenderer->makeKnownLink(
926 $this->mNewPage,
927 $this->msg( 'nextdiff' )->text(),
928 [
929 'class' => 'mw-diff-revision-history-link-next'
930 ],
931 $nextlinkQuery
932 );
933 } else {
934 $nextlink = "\u{00A0}";
935 }
936
937 if ( $this->mNewRevisionRecord->isMinor() ) {
938 $newminor = ChangesList::flag( 'minor' );
939 } else {
940 $newminor = '';
941 }
942
943 # Handle RevisionDelete links...
944 $rdel = $this->revisionDeleteLink( $this->mNewRevisionRecord );
945
946 # Allow extensions to define their own revision tools
947 $this->hookRunner->onDiffTools(
948 $this->mNewRevisionRecord,
949 $revisionTools,
950 $this->mOldRevisionRecord ?: null,
951 $user
952 );
953
954 $formattedRevisionTools = [];
955 // Put each one in parentheses (poor man's button)
956 foreach ( $revisionTools as $key => $tool ) {
957 $toolClass = is_string( $key ) ? $key : 'mw-diff-tool';
958 $element = Html::rawElement(
959 'span',
960 [ 'class' => $toolClass ],
961 $tool
962 );
963 $formattedRevisionTools[] = $element;
964 }
965
966 $newRevRecord = $this->mNewRevisionRecord;
967
968 $newRevisionHeader = $this->getRevisionHeader( $newRevRecord, 'complete' ) .
969 ' ' . implode( ' ', $formattedRevisionTools );
970 $newChangeTags = ChangeTags::formatSummaryRow( $this->mNewTags, 'diff', $this->getContext() );
971 $newRevComment = $this->commentFormatter->formatRevision(
972 $newRevRecord, $user, !$diffOnly, !$this->unhide, /** disable parentheseses */ false
973 );
974
975 if ( $newRevComment === '' ) {
976 $defaultComment = $this->msg( 'changeslist-nocomment' )->escaped();
977 $newRevComment = "<span class=\"comment mw-comment-none\">$defaultComment</span>";
978 }
979
980 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
981 '<div id="mw-diff-ntitle2">' . Linker::revUserTools( $newRevRecord, !$this->unhide ) .
982 $rollback .
983 $this->getUserMetaData( $newRevRecord->getUser() ) .
984 '</div>' .
985 '<div id="mw-diff-ntitle3">' . $newminor . $newRevComment . $rdel . '</div>' .
986 '<div id="mw-diff-ntitle5">' . $newChangeTags[0] . '</div>' .
987 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
988
989 // Allow extensions to change the $newHeader variable
990 $this->hookRunner->onDifferenceEngineNewHeader( $this, $newHeader,
991 $formattedRevisionTools, $nextlink, $rollback, $newminor, $diffOnly,
992 $rdel, $this->unhide );
993
994 $out->addHTML(
995 Html::rawElement( 'div', [
996 'class' => 'mw-diff-revision-history-links'
997 ], $breadCrumbs )
998 );
999 # If the diff cannot be shown due to a deleted revision, then output
1000 # the diff header and links to unhide (if available)...
1001 if ( $this->shouldBeHiddenFromUser( $this->getAuthority() ) ) {
1002 $this->showDiffStyle();
1003 $multi = $this->getMultiNotice();
1004 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
1005 if ( !$allowed ) {
1006 # Give explanation for why revision is not visible
1007 $msg = [ $suppressed ? 'rev-suppressed-no-diff' : 'rev-deleted-no-diff' ];
1008 } else {
1009 # Give explanation and add a link to view the diff...
1010 $query = $this->getRequest()->appendQueryValue( 'unhide', '1' );
1011 $msg = [
1012 $suppressed ? 'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff',
1013 $this->getTitle()->getFullURL( $query )
1014 ];
1015 }
1016 $out->addHTML( Html::warningBox( $this->msg( ...$msg )->parse(), 'plainlinks' ) );
1017 # Otherwise, output a regular diff...
1018 } else {
1019 # Add deletion notice if the user is viewing deleted content
1020 $notice = '';
1021 if ( $deleted ) {
1022 $msg = $suppressed ? 'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
1023 $notice = Html::warningBox( $this->msg( $msg )->parse(), 'plainlinks' );
1024 }
1025
1026 # Add an error if the content can't be loaded
1027 $this->getSlotContents();
1028 foreach ( $this->getRevisionLoadErrors() as $msg ) {
1029 $notice .= Html::warningBox( $msg->parse() );
1030 }
1031
1032 // Check if inline switcher will be needed
1033 if ( $this->getTextDiffer()->hasFormat( 'inline' ) ) {
1034 $out->enableOOUI();
1035 }
1036
1037 $this->showTablePrefixes();
1038 $this->showDiff( $oldHeader, $newHeader, $notice );
1039 if ( !$diffOnly ) {
1040 $this->renderNewRevision();
1041 }
1042
1043 // Allow extensions to optionally not show the final patrolled link
1044 if ( $this->hookRunner->onDifferenceEngineRenderRevisionShowFinalPatrolLink() ) {
1045 # Add redundant patrol link on bottom...
1046 $out->addHTML( $this->markPatrolledLink() );
1047 }
1048 }
1049 }
1050
1051 /**
1052 * Add table prefixes
1053 */
1054 private function showTablePrefixes() {
1055 $parts = [];
1056 foreach ( $this->getSlotDiffRenderers() as $slotDiffRenderer ) {
1057 $parts += $slotDiffRenderer->getTablePrefix( $this->getContext(), $this->mNewPage );
1058 }
1059 ksort( $parts );
1060 if ( count( array_filter( $parts ) ) > 0 ) {
1061 $language = $this->getLanguage();
1062 $attrs = [
1063 'class' => 'mw-diff-table-prefix',
1064 'dir' => $language->getDir(),
1065 'lang' => $language->getCode(),
1066 ];
1067 $this->getOutput()->addHTML(
1068 Html::rawElement( 'div', $attrs, implode( '', $parts ) ) );
1069 }
1070 }
1071
1072 /**
1073 * Build a link to mark a change as patrolled.
1074 *
1075 * Returns empty string if there's either no revision to patrol or the user is not allowed to.
1076 *
1077 * Side effect: When the patrol link is build, this method will call
1078 * OutputPage::getMetadata()->setPreventClickjacking(true) and load a
1079 * JS module.
1080 *
1081 * @return string HTML or empty string
1082 */
1083 public function markPatrolledLink() {
1084 if ( $this->mMarkPatrolledLink === null ) {
1085 $linkInfo = $this->getMarkPatrolledLinkInfo();
1086 // If false, there is no patrol link needed/allowed
1087 if ( !$linkInfo || !$this->mNewPage ) {
1088 $this->mMarkPatrolledLink = '';
1089 } else {
1090 $patrolLinkClass = 'patrollink';
1091 $this->mMarkPatrolledLink = ' <span class="' . $patrolLinkClass . '" data-mw="interface">[' .
1092 $this->linkRenderer->makeKnownLink(
1093 $this->mNewPage,
1094 $this->msg( 'markaspatrolleddiff' )->text(),
1095 [],
1096 [
1097 'action' => 'markpatrolled',
1098 'rcid' => $linkInfo['rcid'],
1099 ]
1100 ) . ']</span>';
1101 // Allow extensions to change the markpatrolled link
1102 $this->hookRunner->onDifferenceEngineMarkPatrolledLink( $this,
1103 $this->mMarkPatrolledLink, $linkInfo['rcid'] );
1104 }
1105 }
1106 return $this->mMarkPatrolledLink;
1107 }
1108
1109 /**
1110 * Returns an array of meta data needed to build a "mark as patrolled" link and
1111 * adds a JS module to the output.
1112 *
1113 * @return array|false An array of meta data for a patrol link (rcid only)
1114 * or false if no link is needed
1115 */
1116 protected function getMarkPatrolledLinkInfo() {
1117 $user = $this->getUser();
1118 $config = $this->getConfig();
1119
1120 // Prepare a change patrol link, if applicable
1121 if (
1122 // Is patrolling enabled and the user allowed to?
1123 $config->get( MainConfigNames::UseRCPatrol ) &&
1124 $this->mNewPage &&
1125 $this->getAuthority()->probablyCan( 'patrol', $this->mNewPage ) &&
1126 // Only do this if the revision isn't more than 6 hours older
1127 // than the Max RC age (6h because the RC might not be cleaned out regularly)
1128 RecentChange::isInRCLifespan( $this->mNewRevisionRecord->getTimestamp(), 21600 )
1129 ) {
1130 // Look for an unpatrolled change corresponding to this diff
1131 $change = RecentChange::newFromConds(
1132 [
1133 'rc_this_oldid' => $this->mNewid,
1134 'rc_patrolled' => RecentChange::PRC_UNPATROLLED
1135 ],
1136 __METHOD__
1137 );
1138
1139 if ( $change && !$change->getPerformerIdentity()->equals( $user ) ) {
1140 $rcid = $change->getAttribute( 'rc_id' );
1141 } else {
1142 // None found or the page has been created by the current user.
1143 // If the user could patrol this it already would be patrolled
1144 $rcid = 0;
1145 }
1146
1147 // Allow extensions to possibly change the rcid here
1148 // For example the rcid might be set to zero due to the user
1149 // being the same as the performer of the change but an extension
1150 // might still want to show it under certain conditions
1151 $this->hookRunner->onDifferenceEngineMarkPatrolledRCID( $rcid, $this, $change, $user );
1152
1153 // Build the link
1154 if ( $rcid ) {
1155 $this->getOutput()->getMetadata()->setPreventClickjacking( true );
1156 $this->getOutput()->addModules( 'mediawiki.misc-authed-curate' );
1157
1158 return [ 'rcid' => $rcid ];
1159 }
1160 }
1161
1162 // No mark as patrolled link applicable
1163 return false;
1164 }
1165
1166 /**
1167 * @param RevisionRecord $revRecord
1168 *
1169 * @return string
1170 */
1171 private function revisionDeleteLink( RevisionRecord $revRecord ) {
1172 $link = Linker::getRevDeleteLink(
1173 $this->getAuthority(),
1174 $revRecord,
1175 $revRecord->getPageAsLinkTarget()
1176 );
1177 if ( $link !== '' ) {
1178 $link = "\u{00A0}\u{00A0}\u{00A0}" . $link . ' ';
1179 }
1180
1181 return $link;
1182 }
1183
1184 /**
1185 * Show the new revision of the page.
1186 *
1187 * @note Not supported after calling setContent().
1188 */
1189 public function renderNewRevision() {
1190 if ( $this->isContentOverridden ) {
1191 // The code below only works with a RevisionRecord object. We could construct a
1192 // fake RevisionRecord (here or in setContent), but since this does not seem
1193 // needed at the moment, we'll just fail for now.
1194 throw new LogicException(
1195 __METHOD__
1196 . ' is not supported after calling setContent(). Use setRevisions() instead.'
1197 );
1198 }
1199
1200 $out = $this->getOutput();
1201 $revHeader = $this->getRevisionHeader( $this->mNewRevisionRecord );
1202 # Add "current version as of X" title
1203 $out->addHTML( "<hr class='diff-hr' id='mw-oldid' />
1204 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
1205 # Page content may be handled by a hooked call instead...
1206 if ( $this->hookRunner->onArticleContentOnDiff( $this, $out ) ) {
1207 $this->loadNewText();
1208 if ( !$this->mNewPage ) {
1209 // New revision is unsaved; bail out.
1210 // TODO in theory rendering the new revision is a meaningful thing to do
1211 // even if it's unsaved, but a lot of untangling is required to do it safely.
1212 return;
1213 }
1214 if ( $this->hasNewRevisionLoadError() ) {
1215 // There was an error loading the new revision
1216 return;
1217 }
1218
1219 $out->setRevisionId( $this->mNewid );
1220 $out->setRevisionIsCurrent( $this->mNewRevisionRecord->isCurrent() );
1221 $out->setRevisionTimestamp( $this->mNewRevisionRecord->getTimestamp() );
1222 $out->setArticleFlag( true );
1223
1224 if ( !$this->hookRunner->onArticleRevisionViewCustom(
1225 $this->mNewRevisionRecord, $this->mNewPage, $this->mOldid, $out )
1226 ) {
1227 // Handled by extension
1228 // NOTE: sync with hooks called in Article::view()
1229 } else {
1230 // Normal page
1231 if ( $this->getTitle()->equals( $this->mNewPage ) ) {
1232 // If the Title stored in the context is the same as the one
1233 // of the new revision, we can use its associated WikiPage
1234 // object.
1235 $wikiPage = $this->getWikiPage();
1236 } else {
1237 // Otherwise we need to create our own WikiPage object
1238 $wikiPage = $this->wikiPageFactory->newFromTitle( $this->mNewPage );
1239 }
1240
1241 $parserOptions = $wikiPage->makeParserOptions( $this->getContext() );
1242 $parserOptions->setRenderReason( 'diff-page' );
1243
1244 $parserOutputAccess = MediaWikiServices::getInstance()->getParserOutputAccess();
1245 $status = $parserOutputAccess->getParserOutput(
1246 $wikiPage,
1247 $parserOptions,
1248 $this->mNewRevisionRecord,
1249 // we already checked
1250 ParserOutputAccess::OPT_NO_AUDIENCE_CHECK |
1251 // Update cascading protection
1252 ParserOutputAccess::OPT_LINKS_UPDATE
1253 );
1254 if ( $status->isOK() ) {
1255 $parserOutput = $status->getValue();
1256 // Allow extensions to change parser output here
1257 if ( $this->hookRunner->onDifferenceEngineRenderRevisionAddParserOutput(
1258 $this, $out, $parserOutput, $wikiPage )
1259 ) {
1260 $out->addParserOutput( $parserOutput, [
1261 'enableSectionEditLinks' => $this->mNewRevisionRecord->isCurrent()
1262 && $this->getAuthority()->probablyCan(
1263 'edit',
1264 $this->mNewRevisionRecord->getPage()
1265 ),
1266 'absoluteURLs' => $this->slotDiffOptions['expand-url'] ?? false
1267 ] );
1268 }
1269 } else {
1270 $out->addHTML(
1271 Html::errorBox(
1272 $out->parseAsInterface(
1273 $status->getWikiText( false, false, $this->getLanguage() )
1274 )
1275 )
1276 );
1277 }
1278 }
1279 }
1280 }
1281
1282 /**
1283 * Get the diff text, send it to the OutputPage object
1284 * Returns false if the diff could not be generated, otherwise returns true
1285 *
1286 * @param string|false $otitle Header for old text or false
1287 * @param string|false $ntitle Header for new text or false
1288 * @param string $notice HTML between diff header and body
1289 *
1290 * @return bool
1291 */
1292 public function showDiff( $otitle, $ntitle, $notice = '' ) {
1293 // Allow extensions to affect the output here
1294 $this->hookRunner->onDifferenceEngineShowDiff( $this );
1295
1296 $diff = $this->getDiff( $otitle, $ntitle, $notice );
1297 if ( $diff === false ) {
1298 $this->showMissingRevision();
1299 return false;
1300 }
1301
1302 $this->showDiffStyle();
1303 if ( $this->slotDiffOptions['expand-url'] ?? false ) {
1304 $diff = Linker::expandLocalLinks( $diff );
1305 }
1306 $this->getOutput()->addHTML( $diff );
1307 return true;
1308 }
1309
1310 /**
1311 * Add style sheets for diff display.
1312 */
1313 public function showDiffStyle() {
1314 if ( !$this->isSlotDiffRenderer ) {
1315 $this->getOutput()->addModules( 'mediawiki.diff' );
1316 $this->getOutput()->addModuleStyles( [
1317 'mediawiki.interface.helpers.styles',
1318 'mediawiki.diff.styles'
1319 ] );
1320 foreach ( $this->getSlotDiffRenderers() as $slotDiffRenderer ) {
1321 $slotDiffRenderer->addModules( $this->getOutput() );
1322 }
1323 }
1324 }
1325
1326 /**
1327 * Get complete diff table, including header
1328 *
1329 * @param string|false $otitle Header for old text or false
1330 * @param string|false $ntitle Header for new text or false
1331 * @param string $notice HTML between diff header and body
1332 *
1333 * @return string|false
1334 */
1335 public function getDiff( $otitle, $ntitle, $notice = '' ) {
1336 $body = $this->getDiffBody();
1337 if ( $body === false ) {
1338 return false;
1339 }
1340
1341 $multi = $this->getMultiNotice();
1342 // Display a message when the diff is empty
1343 if ( $body === '' ) {
1344 $notice .= '<div class="mw-diff-empty">' .
1345 $this->msg( 'diff-empty' )->parse() .
1346 "</div>\n";
1347 }
1348
1349 if ( $this->cacheHitKey !== null ) {
1350 $body .= "\n<!-- diff cache key " . htmlspecialchars( $this->cacheHitKey ) . " -->\n";
1351 }
1352
1353 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
1354 }
1355
1356 private function incrementStats( string $cacheStatus ): void {
1357 $stats = MediaWikiServices::getInstance()->getStatsFactory();
1358 $stats->getCounter( 'diff_cache_total' )
1359 ->setLabel( 'status', $cacheStatus )
1360 ->copyToStatsdAt( 'diff_cache.' . $cacheStatus )
1361 ->increment();
1362 }
1363
1364 /**
1365 * Get the diff table body, without header
1366 *
1367 * @return string|false
1368 */
1369 public function getDiffBody() {
1370 $this->mCacheHit = true;
1371 // Check if the diff should be hidden from this user
1372 if ( !$this->isContentOverridden ) {
1373 if ( !$this->loadRevisionData() ) {
1374 return false;
1375 } elseif ( $this->mOldRevisionRecord &&
1376 !$this->mOldRevisionRecord->userCan(
1377 RevisionRecord::DELETED_TEXT,
1378 $this->getAuthority()
1379 )
1380 ) {
1381 return false;
1382 } elseif ( $this->mNewRevisionRecord &&
1383 !$this->mNewRevisionRecord->userCan(
1384 RevisionRecord::DELETED_TEXT,
1385 $this->getAuthority()
1386 ) ) {
1387 return false;
1388 }
1389 // Short-circuit
1390 if ( $this->mOldRevisionRecord === false || (
1391 $this->mOldRevisionRecord &&
1392 $this->mNewRevisionRecord &&
1393 $this->mOldRevisionRecord->getId() &&
1394 $this->mOldRevisionRecord->getId() == $this->mNewRevisionRecord->getId()
1395 ) ) {
1396 if ( $this->hookRunner->onDifferenceEngineShowEmptyOldContent( $this ) ) {
1397 return '';
1398 }
1399 }
1400 }
1401
1402 // Cacheable?
1403 $key = false;
1404 $services = MediaWikiServices::getInstance();
1405 $cache = $services->getMainWANObjectCache();
1406 $stats = $services->getStatsdDataFactory();
1407 if ( $this->mOldid && $this->mNewid ) {
1408 $key = $cache->makeKey( ...$this->getDiffBodyCacheKeyParams() );
1409
1410 // Try cache
1411 if ( !$this->mRefreshCache ) {
1412 $difftext = $cache->get( $key );
1413 if ( is_string( $difftext ) ) {
1414 $this->incrementStats( 'hit' );
1415 $difftext = $this->localiseDiff( $difftext );
1416 $this->cacheHitKey = $key;
1417 return $difftext;
1418 }
1419 } // don't try to load but save the result
1420 }
1421 $this->mCacheHit = false;
1422 $this->cacheHitKey = null;
1423
1424 // Loadtext is permission safe, this just clears out the diff
1425 if ( !$this->loadText() ) {
1426 return false;
1427 }
1428
1429 $difftext = '';
1430 // We've checked for revdelete at the beginning of this method; it's OK to ignore
1431 // read permissions here.
1432 $slotContents = $this->getSlotContents();
1433 foreach ( $this->getSlotDiffRenderers() as $role => $slotDiffRenderer ) {
1434 try {
1435 $slotDiff = $slotDiffRenderer->getDiff( $slotContents[$role]['old'],
1436 $slotContents[$role]['new'] );
1437 } catch ( IncompatibleDiffTypesException $e ) {
1438 $slotDiff = $this->getSlotError( $e->getMessageObject()->parse() );
1439 }
1440 if ( $slotDiff && $role !== SlotRecord::MAIN ) {
1441 // FIXME: ask SlotRoleHandler::getSlotNameMessage
1442 $slotTitle = $role;
1443 $difftext .= $this->getSlotHeader( $slotTitle );
1444 }
1445 $difftext .= $slotDiff;
1446 }
1447
1448 // Save to cache for 7 days
1449 if ( !$this->hookRunner->onAbortDiffCache( $this ) ) {
1450 $this->incrementStats( 'uncacheable' );
1451 } elseif ( $key !== false ) {
1452 $this->incrementStats( 'miss' );
1453 $cache->set( $key, $difftext, 7 * 86400 );
1454 } else {
1455 $this->incrementStats( 'uncacheable' );
1456 }
1457 // localise line numbers and title attribute text
1458 $difftext = $this->localiseDiff( $difftext );
1459
1460 return $difftext;
1461 }
1462
1463 /**
1464 * Get the diff table body for one slot, without header
1465 *
1466 * @param string $role
1467 * @return string|false
1468 */
1469 public function getDiffBodyForRole( $role ) {
1470 $diffRenderers = $this->getSlotDiffRenderers();
1471 if ( !isset( $diffRenderers[$role] ) ) {
1472 return false;
1473 }
1474
1475 $slotContents = $this->getSlotContents();
1476 try {
1477 $slotDiff = $diffRenderers[$role]->getDiff( $slotContents[$role]['old'],
1478 $slotContents[$role]['new'] );
1479 } catch ( IncompatibleDiffTypesException $e ) {
1480 $slotDiff = $this->getSlotError( $e->getMessageObject()->parse() );
1481 }
1482 if ( $slotDiff === '' ) {
1483 return false;
1484 }
1485
1486 if ( $role !== SlotRecord::MAIN ) {
1487 // TODO use human-readable role name at least
1488 $slotTitle = $role;
1489 $slotDiff = $this->getSlotHeader( $slotTitle ) . $slotDiff;
1490 }
1491
1492 return $this->localiseDiff( $slotDiff );
1493 }
1494
1495 /**
1496 * Get a slot header for inclusion in a diff body (as a table row).
1497 *
1498 * @param string $headerText The text of the header
1499 * @return string
1500 *
1501 */
1502 protected function getSlotHeader( $headerText ) {
1503 // The old revision is missing on oldid=<first>&diff=prev; only 2 columns in that case.
1504 $columnCount = $this->mOldRevisionRecord ? 4 : 2;
1505 $userLang = $this->getLanguage()->getHtmlCode();
1506 return Html::rawElement( 'tr', [ 'class' => 'mw-diff-slot-header', 'lang' => $userLang ],
1507 Html::element( 'th', [ 'colspan' => $columnCount ], $headerText ) );
1508 }
1509
1510 /**
1511 * Get an error message for inclusion in a diff body (as a table row).
1512 *
1513 * @param string $errorText The HTML of the error
1514 * @return string
1515 */
1516 protected function getSlotError( $errorText ) {
1517 // The old revision is missing on oldid=<first>&diff=prev; only 2 columns in that case.
1518 $columnCount = $this->mOldRevisionRecord ? 4 : 2;
1519 $userLang = $this->getLanguage()->getHtmlCode();
1520 return Html::rawElement( 'tr', [ 'class' => 'mw-diff-slot-error', 'lang' => $userLang ],
1521 Html::rawElement( 'td', [ 'colspan' => $columnCount ], $errorText ) );
1522 }
1523
1524 /**
1525 * Get the cache key parameters
1526 *
1527 * Subclasses can replace the first element in the array to something
1528 * more specific to the type of diff (e.g. "inline-diff"), or append
1529 * if the cache should vary on more things. Overriding entirely should
1530 * be avoided.
1531 *
1532 * @since 1.31
1533 *
1534 * @return string[]
1535 * @phan-return non-empty-array<string>
1536 */
1537 protected function getDiffBodyCacheKeyParams() {
1538 if ( !$this->mOldid || !$this->mNewid ) {
1539 throw new BadMethodCallException( 'mOldid and mNewid must be set to get diff cache key.' );
1540 }
1541
1542 $params = [
1543 'diff',
1544 self::DIFF_VERSION,
1545 "old-{$this->mOldid}",
1546 "rev-{$this->mNewid}"
1547 ];
1548
1549 $extraKeys = [];
1550 if ( !$this->isSlotDiffRenderer ) {
1551 foreach ( $this->getSlotDiffRenderers() as $slotDiffRenderer ) {
1552 $extraKeys = array_merge( $extraKeys, $slotDiffRenderer->getExtraCacheKeys() );
1553 }
1554 }
1555 ksort( $extraKeys );
1556 return array_merge( $params, array_values( $extraKeys ) );
1557 }
1558
1559 /**
1560 * Implements DifferenceEngineSlotDiffRenderer::getExtraCacheKeys(). Only used when
1561 * DifferenceEngine is wrapped in DifferenceEngineSlotDiffRenderer.
1562 * @return string[]
1563 * @internal for use by DifferenceEngineSlotDiffRenderer only
1564 * @deprecated
1565 */
1566 public function getExtraCacheKeys() {
1567 // This method is called when the DifferenceEngine is used for a slot diff. We only care
1568 // about special things, not the revision IDs, which are added to the cache key by the
1569 // page-level DifferenceEngine, and which might not have a valid value for this object.
1570 $this->mOldid = 123456789;
1571 $this->mNewid = 987654321;
1572
1573 // This will repeat a bunch of unnecessary key fields for each slot. Not nice but harmless.
1574 $params = $this->getDiffBodyCacheKeyParams();
1575
1576 // Try to get rid of the standard keys to keep the cache key human-readable:
1577 // call the getDiffBodyCacheKeyParams implementation of the base class, and if
1578 // the child class includes the same keys, drop them.
1579 // Uses an obscure PHP feature where static calls to non-static methods are allowed
1580 // as long as we are already in a non-static method of the same class, and the call context
1581 // ($this) will be inherited.
1582 // phpcs:ignore Squiz.Classes.SelfMemberReference.NotUsed
1583 $standardParams = DifferenceEngine::getDiffBodyCacheKeyParams();
1584 if ( array_slice( $params, 0, count( $standardParams ) ) === $standardParams ) {
1585 $params = array_slice( $params, count( $standardParams ) );
1586 }
1587
1588 return $params;
1589 }
1590
1591 /**
1592 * @param array $options for the difference engine. Available options:
1593 * - diff-type: The text diff format, e.g. "table" or "inline". If the
1594 * specified format is not supported, the option will be ignored, so
1595 * the site default format (table) will be used.
1596 * - expand-url: If true, put full URLs in href attributes (for action=render)
1597 * FIXME: expand-url is not a slot diff option, it is a DifferenceEngine option.
1598 * - inline-toggle: If true, and the inline format is supported
1599 * a format selector toggle switch will be shown.
1600 */
1601 public function setSlotDiffOptions( $options ) {
1602 $validatedOptions = [];
1603 if ( isset( $options['diff-type'] )
1604 && $this->getTextDiffer()->hasFormat( $options['diff-type'] )
1605 ) {
1606 $validatedOptions['diff-type'] = $options['diff-type'];
1607 }
1608 if ( !empty( $options['expand-url'] ) ) {
1609 $validatedOptions['expand-url'] = true;
1610 }
1611 if ( !empty( $options['inline-toggle'] ) ) {
1612 $validatedOptions['inline-toggle'] = true;
1613 }
1614 $this->slotDiffOptions = $validatedOptions;
1615 }
1616
1617 /**
1618 * Set query parameters to append to diff page links
1619 *
1620 * @since 1.41
1621 *
1622 * @param array $params
1623 */
1624 public function setExtraQueryParams( $params ) {
1625 $this->extraQueryParams = $params;
1626 }
1627
1628 /**
1629 * Generate a diff, no caching.
1630 *
1631 * @since 1.21
1632 *
1633 * @param Content $old Old content
1634 * @param Content $new New content
1635 *
1636 * @throws Exception If old or new content is not an instance of TextContent.
1637 * @return bool|string
1638 *
1639 * @deprecated since 1.32, use a SlotDiffRenderer instead.
1640 */
1641 public function generateContentDiffBody( Content $old, Content $new ) {
1642 $slotDiffRenderer = $new->getContentHandler()->getSlotDiffRenderer( $this->getContext() );
1643 if (
1644 $slotDiffRenderer instanceof DifferenceEngineSlotDiffRenderer
1645 && $this->isSlotDiffRenderer
1646 ) {
1647 // Oops, we are just about to enter an infinite loop (the slot-level DifferenceEngine
1648 // called a DifferenceEngineSlotDiffRenderer that wraps the same DifferenceEngine class).
1649 // This will happen when a content model has no custom slot diff renderer, it does have
1650 // a custom difference engine, but that does not override this method.
1651 throw new LogicException( get_class( $this ) . ': could not maintain backwards compatibility. '
1652 . 'Please use a SlotDiffRenderer.' );
1653 }
1654 return $slotDiffRenderer->getDiff( $old, $new ) . $this->getDebugString();
1655 }
1656
1657 /**
1658 * Generate a diff, no caching
1659 *
1660 * @param string $otext Old text, must be already segmented
1661 * @param string $ntext New text, must be already segmented
1662 *
1663 * @throws LogicException If content handling for text content is configured in a way
1664 * that makes maintaining B/C hard.
1665 * @return bool|string
1666 *
1667 * @deprecated since 1.32, use a TextSlotDiffRenderer instead.
1668 */
1669 public function generateTextDiffBody( $otext, $ntext ) {
1670 $slotDiffRenderer = $this->contentHandlerFactory
1671 ->getContentHandler( CONTENT_MODEL_TEXT )
1672 ->getSlotDiffRenderer( $this->getContext() );
1673 if ( !( $slotDiffRenderer instanceof TextSlotDiffRenderer ) ) {
1674 // Someone used the GetSlotDiffRenderer hook to replace the renderer.
1675 // This is too unlikely to happen to bother handling properly.
1676 throw new LogicException( 'The slot diff renderer for text content should be a '
1677 . 'TextSlotDiffRenderer subclass' );
1678 }
1679 return $slotDiffRenderer->getTextDiff( $otext, $ntext ) . $this->getDebugString();
1680 }
1681
1682 /**
1683 * Process DiffEngine config and get a sensible, usable engine
1684 *
1685 * @return string 'wikidiff2', 'php', or path to an executable
1686 * @internal For use by this class and within Core only.
1687 */
1688 public static function getEngine() {
1689 $differenceEngine = new self;
1690 $engine = $differenceEngine->getTextDiffer()->getEngineForFormat( 'table' );
1691 if ( $engine === 'external' ) {
1692 return MediaWikiServices::getInstance()->getMainConfig()
1693 ->get( MainConfigNames::ExternalDiffEngine );
1694 } else {
1695 return $engine;
1696 }
1697 }
1698
1699 /**
1700 * Generate a debug comment indicating diff generating time,
1701 * server node, and generator backend.
1702 *
1703 * @param string $generator What diff engine was used
1704 *
1705 * @return string
1706 */
1707 protected function debug( $generator = "internal" ) {
1708 if ( !$this->enableDebugComment ) {
1709 return '';
1710 }
1711 $data = [ $generator ];
1712 if ( $this->getConfig()->get( MainConfigNames::ShowHostnames ) ) {
1713 $data[] = wfHostname();
1714 }
1715 $data[] = wfTimestamp( TS_DB );
1716
1717 return "<!-- diff generator: " .
1718 implode( " ", array_map( "htmlspecialchars", $data ) ) .
1719 " -->\n";
1720 }
1721
1722 /**
1723 * @return string
1724 */
1725 private function getDebugString() {
1726 $engine = self::getEngine();
1727 if ( $engine === 'wikidiff2' ) {
1728 return $this->debug( 'wikidiff2' );
1729 } elseif ( $engine === 'php' ) {
1730 return $this->debug( 'native PHP' );
1731 } else {
1732 return $this->debug( "external $engine" );
1733 }
1734 }
1735
1736 /**
1737 * Localise diff output
1738 *
1739 * @param string $text
1740 * @return string
1741 */
1742 private function localiseDiff( $text ) {
1743 return $this->getTextDiffer()->localize( $this->getTextDiffFormat(), $text );
1744 }
1745
1746 /**
1747 * Replace a common convention for language-independent line numbers with
1748 * the text in the user's language.
1749 *
1750 * @deprecated since 1.41, use BaseTextDiffer::localizeLineNumbers()
1751 * @param string $text
1752 * @return string
1753 */
1754 public function localiseLineNumbers( $text ) {
1755 return preg_replace_callback( '/<!--LINE (\d+)-->/',
1756 function ( array $matches ) {
1757 if ( $matches[1] === '1' && $this->mReducedLineNumbers ) {
1758 return '';
1759 }
1760 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
1761 }, $text );
1762 }
1763
1764 /**
1765 * If there are revisions between the ones being compared, return a note saying so.
1766 *
1767 * @return string
1768 */
1769 public function getMultiNotice() {
1770 // The notice only make sense if we are diffing two saved revisions of the same page.
1771 if (
1772 !$this->mOldRevisionRecord || !$this->mNewRevisionRecord
1773 || !$this->mOldPage || !$this->mNewPage
1774 || !$this->mOldPage->equals( $this->mNewPage )
1775 || $this->mOldRevisionRecord->getId() === null
1776 || $this->mNewRevisionRecord->getId() === null
1777 // (T237709) Deleted revs might have different page IDs
1778 || $this->mNewPage->getArticleID() !== $this->mOldRevisionRecord->getPageId()
1779 || $this->mNewPage->getArticleID() !== $this->mNewRevisionRecord->getPageId()
1780 ) {
1781 return '';
1782 }
1783
1784 if ( $this->mOldRevisionRecord->getTimestamp() > $this->mNewRevisionRecord->getTimestamp() ) {
1785 $oldRevRecord = $this->mNewRevisionRecord; // flip
1786 $newRevRecord = $this->mOldRevisionRecord; // flip
1787 } else { // normal case
1788 $oldRevRecord = $this->mOldRevisionRecord;
1789 $newRevRecord = $this->mNewRevisionRecord;
1790 }
1791
1792 // Don't show the notice if too many rows must be scanned
1793 // @todo show some special message for that case
1794 $nEdits = 0;
1795 $revisionIdList = $this->revisionStore->getRevisionIdsBetween(
1796 $this->mNewPage->getArticleID(),
1797 $oldRevRecord,
1798 $newRevRecord,
1799 1000
1800 );
1801 // only count revisions that are visible
1802 if ( count( $revisionIdList ) > 0 ) {
1803 foreach ( $revisionIdList as $revisionId ) {
1804 $revision = $this->revisionStore->getRevisionById( $revisionId );
1805 if ( $revision->getUser( RevisionRecord::FOR_THIS_USER, $this->getAuthority() ) ) {
1806 $nEdits++;
1807 }
1808 }
1809 }
1810 if ( $nEdits > 0 && $nEdits <= 1000 ) {
1811 // Use an invalid username to get the wiki's default gender (as fallback)
1812 $newRevUserForGender = '[HIDDEN]';
1813 $limit = 100; // use diff-multi-manyusers if too many users
1814 try {
1815 $users = $this->revisionStore->getAuthorsBetween(
1816 $this->mNewPage->getArticleID(),
1817 $oldRevRecord,
1818 $newRevRecord,
1819 null,
1820 $limit
1821 );
1822 $numUsers = count( $users );
1823
1824 $newRevUser = $newRevRecord->getUser( RevisionRecord::RAW );
1825 $newRevUserText = $newRevUser ? $newRevUser->getName() : '';
1826 $newRevUserSafe = $newRevRecord->getUser(
1827 RevisionRecord::FOR_THIS_USER,
1828 $this->getAuthority()
1829 );
1830 $newRevUserForGender = $newRevUserSafe ? $newRevUserSafe->getName() : '[HIDDEN]';
1831 if ( $numUsers == 1 && $users[0]->getName() == $newRevUserText ) {
1832 $numUsers = 0; // special case to say "by the same user" instead of "by one other user"
1833 }
1834 } catch ( InvalidArgumentException $e ) {
1835 $numUsers = 0;
1836 }
1837
1838 return self::intermediateEditsMsg( $nEdits, $numUsers, $limit, $newRevUserForGender );
1839 }
1840
1841 return '';
1842 }
1843
1844 /**
1845 * Get a notice about how many intermediate edits and users there are
1846 *
1847 * @param int $numEdits
1848 * @param int $numUsers
1849 * @param int $limit
1850 * @param string $lastUser
1851 *
1852 * @return string
1853 */
1854 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit, $lastUser = '[HIDDEN]' ) {
1855 if ( $numUsers === 0 ) {
1856 $msg = 'diff-multi-sameuser';
1857 return wfMessage( $msg )
1858 ->numParams( $numEdits, $numUsers )
1859 ->params( $lastUser )
1860 ->parse();
1861 } elseif ( $numUsers > $limit ) {
1862 $msg = 'diff-multi-manyusers';
1863 $numUsers = $limit;
1864 } else {
1865 $msg = 'diff-multi-otherusers';
1866 }
1867
1868 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
1869 }
1870
1871 /**
1872 * @param RevisionRecord $revRecord
1873 * @return bool whether the user can see and edit the revision.
1874 */
1875 private function userCanEdit( RevisionRecord $revRecord ) {
1876 if ( !$revRecord->userCan( RevisionRecord::DELETED_TEXT, $this->getAuthority() ) ) {
1877 return false;
1878 }
1879
1880 return true;
1881 }
1882
1883 /**
1884 * Get a header for a specified revision.
1885 *
1886 * @param RevisionRecord $rev
1887 * @param string $complete 'complete' to get the header wrapped depending
1888 * the visibility of the revision and a link to edit the page.
1889 *
1890 * @return string HTML fragment
1891 */
1892 public function getRevisionHeader( RevisionRecord $rev, $complete = '' ) {
1893 $lang = $this->getLanguage();
1894 $user = $this->getUser();
1895 $revtimestamp = $rev->getTimestamp();
1896 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
1897 $dateofrev = $lang->userDate( $revtimestamp, $user );
1898 $timeofrev = $lang->userTime( $revtimestamp, $user );
1899
1900 $header = $this->msg(
1901 $rev->isCurrent() ? 'currentrev-asof' : 'revisionasof',
1902 $timestamp,
1903 $dateofrev,
1904 $timeofrev
1905 );
1906
1907 if ( $complete !== 'complete' ) {
1908 return $header->escaped();
1909 }
1910
1911 $title = $rev->getPageAsLinkTarget();
1912
1913 if ( $this->userCanEdit( $rev ) ) {
1914 $header = $this->linkRenderer->makeKnownLink(
1915 $title,
1916 $header->text(),
1917 [],
1918 [ 'oldid' => $rev->getId() ]
1919 );
1920 $editQuery = [ 'action' => 'edit' ];
1921 if ( !$rev->isCurrent() ) {
1922 $editQuery['oldid'] = $rev->getId();
1923 }
1924
1925 $key = $this->getAuthority()->probablyCan( 'edit', $rev->getPage() ) ? 'editold' : 'viewsourceold';
1926 $msg = $this->msg( $key )->text();
1927 $editLink = $this->linkRenderer->makeKnownLink( $title, $msg, [], $editQuery );
1928 $header .= ' ' . Html::rawElement(
1929 'span',
1930 [ 'class' => 'mw-diff-edit' ],
1931 $editLink
1932 );
1933 } else {
1934 $header = $header->escaped();
1935 }
1936
1937 // Machine readable information
1938 $header .= Html::element( 'span',
1939 [
1940 'class' => 'mw-diff-timestamp',
1941 'data-timestamp' => wfTimestamp( TS_ISO_8601, $revtimestamp ),
1942 ], ''
1943 );
1944
1945 if ( $rev->isDeleted( RevisionRecord::DELETED_TEXT ) ) {
1946 return Html::rawElement(
1947 'span',
1948 [ 'class' => Linker::getRevisionDeletedClass( $rev ) ],
1949 $header
1950 );
1951 }
1952
1953 return $header;
1954 }
1955
1956 /**
1957 * Add the header to a diff body
1958 *
1959 * @param string $diff Diff body
1960 * @param string $otitle Old revision header
1961 * @param string $ntitle New revision header
1962 * @param string $multi Notice telling user that there are intermediate
1963 * revisions between the ones being compared
1964 * @param string $notice Other notices, e.g. that user is viewing deleted content
1965 *
1966 * @return string
1967 */
1968 public function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
1969 // shared.css sets diff in interface language/dir, but the actual content
1970 // is often in a different language, mostly the page content language/dir
1971 $header = Html::openElement( 'table', [
1972 'class' => [
1973 'diff',
1974 // The following classes are used here:
1975 // * diff-type-table
1976 // * diff-type-inline
1977 'diff-type-' . $this->getTextDiffFormat(),
1978 // The following classes are used here:
1979 // * diff-contentalign-left
1980 // * diff-contentalign-right
1981 'diff-contentalign-' . $this->getDiffLang()->alignStart(),
1982 // The following classes are used here:
1983 // * diff-editfont-monospace
1984 // * diff-editfont-sans-serif
1985 // * diff-editfont-serif
1986 'diff-editfont-' . $this->userOptionsLookup->getOption(
1987 $this->getUser(),
1988 'editfont'
1989 )
1990 ],
1991 'data-mw' => 'interface',
1992 ] );
1993 $userLang = htmlspecialchars( $this->getLanguage()->getHtmlCode() );
1994
1995 if ( !$diff && !$otitle ) {
1996 $header .= "
1997 <tr class=\"diff-title\" lang=\"{$userLang}\">
1998 <td class=\"diff-ntitle\">{$ntitle}</td>
1999 </tr>";
2000 $multiColspan = 1;
2001 } else {
2002 if ( $diff ) { // Safari/Chrome show broken output if cols not used
2003 $header .= "
2004 <col class=\"diff-marker\" />
2005 <col class=\"diff-content\" />
2006 <col class=\"diff-marker\" />
2007 <col class=\"diff-content\" />";
2008 $colspan = 2;
2009 $multiColspan = 4;
2010 } else {
2011 $colspan = 1;
2012 $multiColspan = 2;
2013 }
2014 if ( $otitle || $ntitle ) {
2015 // FIXME Hardcoding values from TableDiffFormatter.
2016 $deletedClass = 'diff-side-deleted';
2017 $addedClass = 'diff-side-added';
2018 $header .= "
2019 <tr class=\"diff-title\" lang=\"{$userLang}\">
2020 <td colspan=\"$colspan\" class=\"diff-otitle {$deletedClass}\">{$otitle}</td>
2021 <td colspan=\"$colspan\" class=\"diff-ntitle {$addedClass}\">{$ntitle}</td>
2022 </tr>";
2023 }
2024 }
2025
2026 if ( $multi != '' ) {
2027 $header .= "<tr><td colspan=\"{$multiColspan}\" " .
2028 "class=\"diff-multi\" lang=\"{$userLang}\">{$multi}</td></tr>";
2029 }
2030 if ( $notice != '' ) {
2031 $header .= "<tr><td colspan=\"{$multiColspan}\" " .
2032 "class=\"diff-notice\" lang=\"{$userLang}\">{$notice}</td></tr>";
2033 }
2034
2035 return $header . $diff . "</table>";
2036 }
2037
2038 /**
2039 * Use specified text instead of loading from the database
2040 * @param Content $oldContent
2041 * @param Content $newContent
2042 * @since 1.21
2043 * @deprecated since 1.32, use setRevisions or ContentHandler::getSlotDiffRenderer.
2044 */
2045 public function setContent( Content $oldContent, Content $newContent ) {
2046 $this->mOldContent = $oldContent;
2047 $this->mNewContent = $newContent;
2048
2049 $this->mTextLoaded = 2;
2050 $this->mRevisionsLoaded = true;
2051 $this->isContentOverridden = true;
2052 $this->slotDiffRenderers = null;
2053 }
2054
2055 /**
2056 * Use specified text instead of loading from the database.
2057 * @param RevisionRecord|null $oldRevision
2058 * @param RevisionRecord $newRevision
2059 */
2060 public function setRevisions(
2061 ?RevisionRecord $oldRevision, RevisionRecord $newRevision
2062 ) {
2063 if ( $oldRevision ) {
2064 $this->mOldRevisionRecord = $oldRevision;
2065 $this->mOldid = $oldRevision->getId();
2066 $this->mOldPage = Title::newFromLinkTarget( $oldRevision->getPageAsLinkTarget() );
2067 // This method is meant for edit diffs and such so there is no reason to provide a
2068 // revision that's not readable to the user, but check it just in case.
2069 $this->mOldContent = $oldRevision->getContent( SlotRecord::MAIN,
2070 RevisionRecord::FOR_THIS_USER, $this->getAuthority() );
2071 if ( !$this->mOldContent ) {
2072 $this->addRevisionLoadError( 'old' );
2073 }
2074 } else {
2075 $this->mOldPage = null;
2076 $this->mOldRevisionRecord = $this->mOldid = false;
2077 }
2078 $this->mNewRevisionRecord = $newRevision;
2079 $this->mNewid = $newRevision->getId();
2080 $this->mNewPage = Title::newFromLinkTarget( $newRevision->getPageAsLinkTarget() );
2081 $this->mNewContent = $newRevision->getContent( SlotRecord::MAIN,
2082 RevisionRecord::FOR_THIS_USER, $this->getAuthority() );
2083 if ( !$this->mNewContent ) {
2084 $this->addRevisionLoadError( 'new' );
2085 }
2086
2087 $this->mRevisionsIdsLoaded = $this->mRevisionsLoaded = true;
2088 $this->mTextLoaded = $oldRevision ? 2 : 1;
2089 $this->isContentOverridden = false;
2090 $this->slotDiffRenderers = null;
2091 }
2092
2093 /**
2094 * Set the language in which the diff text is written
2095 *
2096 * @param Language $lang
2097 * @since 1.19
2098 */
2099 public function setTextLanguage( Language $lang ) {
2100 $this->mDiffLang = $lang;
2101 }
2102
2103 /**
2104 * Maps a revision pair definition as accepted by DifferenceEngine constructor
2105 * to a pair of actual integers representing revision ids.
2106 *
2107 * @param int $old Revision id, e.g. from URL parameter 'oldid'
2108 * @param int|string $new Revision id or strings 'next' or 'prev', e.g. from URL parameter 'diff'
2109 *
2110 * @return array List of two revision ids, older first, later second.
2111 * Zero signifies invalid argument passed.
2112 * false signifies that there is no previous/next revision ($old is the oldest/newest one).
2113 * @phan-return (int|false)[]
2114 */
2115 public function mapDiffPrevNext( $old, $new ) {
2116 if ( $new === 'prev' ) {
2117 // Show diff between revision $old and the previous one. Get previous one from DB.
2118 $newid = intval( $old );
2119 $oldid = false;
2120 $newRev = $this->revisionStore->getRevisionById( $newid );
2121 if ( $newRev ) {
2122 $oldRev = $this->revisionStore->getPreviousRevision( $newRev );
2123 if ( $oldRev ) {
2124 $oldid = $oldRev->getId();
2125 }
2126 }
2127 } elseif ( $new === 'next' ) {
2128 // Show diff between revision $old and the next one. Get next one from DB.
2129 $oldid = intval( $old );
2130 $newid = false;
2131 $oldRev = $this->revisionStore->getRevisionById( $oldid );
2132 if ( $oldRev ) {
2133 $newRev = $this->revisionStore->getNextRevision( $oldRev );
2134 if ( $newRev ) {
2135 $newid = $newRev->getId();
2136 }
2137 }
2138 } else {
2139 $oldid = intval( $old );
2140 $newid = intval( $new );
2141 }
2142
2143 // @phan-suppress-next-line PhanTypeMismatchReturn getId does not return null here
2144 return [ $oldid, $newid ];
2145 }
2146
2147 private function loadRevisionIds() {
2148 if ( $this->mRevisionsIdsLoaded ) {
2149 return;
2150 }
2151
2152 $this->mRevisionsIdsLoaded = true;
2153
2154 $old = $this->mOldid;
2155 $new = $this->mNewid;
2156
2157 [ $this->mOldid, $this->mNewid ] = self::mapDiffPrevNext( $old, $new );
2158 if ( $new === 'next' && $this->mNewid === false ) {
2159 # if no result, NewId points to the newest old revision. The only newer
2160 # revision is cur, which is "0".
2161 $this->mNewid = 0;
2162 }
2163
2164 $this->hookRunner->onNewDifferenceEngine(
2165 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable False positive
2166 $this->getTitle(), $this->mOldid, $this->mNewid, $old, $new );
2167 }
2168
2169 /**
2170 * Load revision metadata for the specified revisions. If newid is 0, then compare
2171 * the old revision in oldid to the current revision of the current page (as defined
2172 * by the request context); if oldid is 0, then compare the revision in newid to the
2173 * immediately previous one.
2174 *
2175 * If oldid is false, leave the corresponding RevisionRecord object set to false. This can
2176 * happen with 'diff=prev' pointing to a non-existent revision, and is also used directly
2177 * by the API.
2178 *
2179 * @return bool Whether both revisions were loaded successfully. Setting mOldRevisionRecord
2180 * to false counts as successful loading.
2181 */
2182 public function loadRevisionData() {
2183 if ( $this->mRevisionsLoaded ) {
2184 return $this->isContentOverridden ||
2185 ( $this->mOldRevisionRecord !== null && $this->mNewRevisionRecord !== null );
2186 }
2187
2188 // Whether it succeeds or fails, we don't want to try again
2189 $this->mRevisionsLoaded = true;
2190
2191 $this->loadRevisionIds();
2192
2193 // Load the new RevisionRecord object
2194 if ( $this->mNewid ) {
2195 $this->mNewRevisionRecord = $this->revisionStore->getRevisionById( $this->mNewid );
2196 } else {
2197 $this->mNewRevisionRecord = $this->revisionStore->getRevisionByTitle( $this->getTitle() );
2198 }
2199
2200 if ( !$this->mNewRevisionRecord instanceof RevisionRecord ) {
2201 return false;
2202 }
2203
2204 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
2205 $this->mNewid = $this->mNewRevisionRecord->getId();
2206 $this->mNewPage = $this->mNewid ?
2207 Title::newFromLinkTarget( $this->mNewRevisionRecord->getPageAsLinkTarget() ) :
2208 null;
2209
2210 // Load the old RevisionRecord object
2211 $this->mOldRevisionRecord = false;
2212 if ( $this->mOldid ) {
2213 $this->mOldRevisionRecord = $this->revisionStore->getRevisionById( $this->mOldid );
2214 } elseif ( $this->mOldid === 0 ) {
2215 $revRecord = $this->revisionStore->getPreviousRevision( $this->mNewRevisionRecord );
2216 // No previous revision; mark to show as first-version only.
2217 $this->mOldid = $revRecord ? $revRecord->getId() : false;
2218 $this->mOldRevisionRecord = $revRecord ?? false;
2219 } /* elseif ( $this->mOldid === false ) leave mOldRevisionRecord false; */
2220
2221 if ( $this->mOldRevisionRecord === null ) {
2222 return false;
2223 }
2224
2225 if ( $this->mOldRevisionRecord && $this->mOldRevisionRecord->getId() ) {
2226 $this->mOldPage = Title::newFromLinkTarget(
2227 $this->mOldRevisionRecord->getPageAsLinkTarget()
2228 );
2229 } else {
2230 $this->mOldPage = null;
2231 }
2232
2233 // Load tags information for both revisions
2234 $dbr = $this->dbProvider->getReplicaDatabase();
2235 $changeTagDefStore = MediaWikiServices::getInstance()->getChangeTagDefStore();
2236 if ( $this->mOldid !== false ) {
2237 $tagIds = $dbr->newSelectQueryBuilder()
2238 ->select( 'ct_tag_id' )
2239 ->from( 'change_tag' )
2240 ->where( [ 'ct_rev_id' => $this->mOldid ] )
2241 ->caller( __METHOD__ )->fetchFieldValues();
2242 $tags = [];
2243 foreach ( $tagIds as $tagId ) {
2244 try {
2245 $tags[] = $changeTagDefStore->getName( (int)$tagId );
2246 } catch ( NameTableAccessException $exception ) {
2247 continue;
2248 }
2249 }
2250 $this->mOldTags = implode( ',', $tags );
2251 } else {
2252 $this->mOldTags = false;
2253 }
2254
2255 $tagIds = $dbr->newSelectQueryBuilder()
2256 ->select( 'ct_tag_id' )
2257 ->from( 'change_tag' )
2258 ->where( [ 'ct_rev_id' => $this->mNewid ] )
2259 ->caller( __METHOD__ )->fetchFieldValues();
2260 $tags = [];
2261 foreach ( $tagIds as $tagId ) {
2262 try {
2263 $tags[] = $changeTagDefStore->getName( (int)$tagId );
2264 } catch ( NameTableAccessException $exception ) {
2265 continue;
2266 }
2267 }
2268 $this->mNewTags = implode( ',', $tags );
2269
2270 return true;
2271 }
2272
2273 /**
2274 * Load the text of the revisions, as well as revision data.
2275 * When the old revision is missing (mOldRev is false), loading mOldContent is not attempted.
2276 *
2277 * @return bool Whether the content of both revisions could be loaded successfully.
2278 * (When mOldRev is false, that still counts as a success.)
2279 *
2280 */
2281 public function loadText() {
2282 if ( $this->mTextLoaded == 2 ) {
2283 return $this->loadRevisionData() &&
2284 ( $this->mOldRevisionRecord === false || $this->mOldContent )
2285 && $this->mNewContent;
2286 }
2287
2288 // Whether it succeeds or fails, we don't want to try again
2289 $this->mTextLoaded = 2;
2290
2291 if ( !$this->loadRevisionData() ) {
2292 return false;
2293 }
2294
2295 if ( $this->mOldRevisionRecord ) {
2296 $this->mOldContent = $this->mOldRevisionRecord->getContent(
2297 SlotRecord::MAIN,
2298 RevisionRecord::FOR_THIS_USER,
2299 $this->getAuthority()
2300 );
2301 if ( $this->mOldContent === null ) {
2302 return false;
2303 }
2304 }
2305
2306 $this->mNewContent = $this->mNewRevisionRecord->getContent(
2307 SlotRecord::MAIN,
2308 RevisionRecord::FOR_THIS_USER,
2309 $this->getAuthority()
2310 );
2311 $this->hookRunner->onDifferenceEngineLoadTextAfterNewContentIsLoaded( $this );
2312 if ( $this->mNewContent === null ) {
2313 return false;
2314 }
2315
2316 return true;
2317 }
2318
2319 /**
2320 * Load the text of the new revision, not the old one
2321 *
2322 * @return bool Whether the content of the new revision could be loaded successfully.
2323 */
2324 public function loadNewText() {
2325 if ( $this->mTextLoaded >= 1 ) {
2326 return $this->loadRevisionData();
2327 }
2328
2329 $this->mTextLoaded = 1;
2330
2331 if ( !$this->loadRevisionData() ) {
2332 return false;
2333 }
2334
2335 $this->mNewContent = $this->mNewRevisionRecord->getContent(
2336 SlotRecord::MAIN,
2337 RevisionRecord::FOR_THIS_USER,
2338 $this->getAuthority()
2339 );
2340
2341 $this->hookRunner->onDifferenceEngineAfterLoadNewText( $this );
2342
2343 return true;
2344 }
2345
2346 /**
2347 * Get the TextDiffer which will be used for rendering text
2348 *
2349 * @return ManifoldTextDiffer
2350 */
2351 protected function getTextDiffer() {
2352 if ( $this->textDiffer === null ) {
2353 $this->textDiffer = new ManifoldTextDiffer(
2354 $this->getContext(),
2355 $this->getDiffLang(),
2356 $this->getConfig()->get( MainConfigNames::DiffEngine ),
2357 $this->getConfig()->get( MainConfigNames::ExternalDiffEngine ),
2358 $this->getConfig()->get( MainConfigNames::Wikidiff2Options )
2359 );
2360 }
2361 return $this->textDiffer;
2362 }
2363
2364 /**
2365 * Get the list of supported text diff formats
2366 *
2367 * @since 1.41
2368 * @return array|string[]
2369 */
2370 public function getSupportedFormats() {
2371 return $this->getTextDiffer()->getFormats();
2372 }
2373
2374 /**
2375 * Get the selected text diff format
2376 *
2377 * @since 1.41
2378 * @return string
2379 */
2380 public function getTextDiffFormat() {
2381 return $this->slotDiffOptions['diff-type'] ?? 'table';
2382 }
2383
2384 }