f7658fc54dbfe207077a2e82db3471fe67bf51b7
[lhc/web/wiklou.git] / includes / diff / DifferenceEngine.php
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\MediaWikiServices;
25 use MediaWiki\Revision\RevisionRecord;
26 use MediaWiki\Revision\SlotRecord;
27 use MediaWiki\Storage\NameTableAccessException;
28
29 /**
30 * DifferenceEngine is responsible for rendering the difference between two revisions as HTML.
31 * This includes interpreting URL parameters, retrieving revision data, checking access permissions,
32 * selecting and invoking the diff generator class for the individual slots, doing post-processing
33 * on the generated diff, adding the rest of the HTML (such as headers) and writing the whole thing
34 * to OutputPage.
35 *
36 * DifferenceEngine can be subclassed by extensions, by customizing
37 * ContentHandler::createDifferenceEngine; the content handler will be selected based on the
38 * content model of the main slot (of the new revision, when the two are different).
39 * That might change after PageTypeHandler gets introduced.
40 *
41 * In the past, the class was also used for slot-level diff generation, and extensions might still
42 * subclass it and add such functionality. When that is the case (sepcifically, when a
43 * ContentHandler returns a standard SlotDiffRenderer but a nonstandard DifferenceEngine)
44 * DifferenceEngineSlotDiffRenderer will be used to convert the old behavior into the new one.
45 *
46 * @ingroup DifferenceEngine
47 *
48 * @todo This class is huge and poorly defined. It should be split into a controller responsible
49 * for interpreting query parameters, retrieving data and checking permissions; and a HTML renderer.
50 */
51 class DifferenceEngine extends ContextSource {
52
53 use DeprecationHelper;
54
55 /**
56 * Constant to indicate diff cache compatibility.
57 * Bump this when changing the diff formatting in a way that
58 * fixes important bugs or such to force cached diff views to
59 * clear.
60 */
61 const DIFF_VERSION = '1.12';
62
63 /**
64 * Revision ID for the old revision. 0 for the revision previous to $mNewid, false
65 * if the diff does not have an old revision (e.g. 'oldid=<first revision of page>&diff=prev'),
66 * or the revision does not exist, null if the revision is unsaved.
67 * @var int|false|null
68 */
69 protected $mOldid;
70
71 /**
72 * Revision ID for the new revision. 0 for the last revision of the current page
73 * (as defined by the request context), false if the revision does not exist, null
74 * if it is unsaved, or an alias such as 'next'.
75 * @var int|string|false|null
76 */
77 protected $mNewid;
78
79 /**
80 * Old revision (left pane).
81 * Allowed to be an unsaved revision, unlikely that's ever needed though.
82 * False when the old revision does not exist; this can happen when using
83 * diff=prev on the first revision. Null when the revision should exist but
84 * doesn't (e.g. load failure); loadRevisionData() will return false in that
85 * case. Also null until lazy-loaded. Ignored completely when isContentOverridden
86 * is set.
87 * Since 1.32 public access is deprecated.
88 * @var Revision|null|false
89 */
90 protected $mOldRev;
91
92 /**
93 * New revision (right pane).
94 * Note that this might be an unsaved revision (e.g. for edit preview).
95 * Null in case of load failure; diff methods will just return an error message in that case,
96 * and loadRevisionData() will return false. Also null until lazy-loaded. Ignored completely
97 * when isContentOverridden is set.
98 * Since 1.32 public access is deprecated.
99 * @var Revision|null
100 */
101 protected $mNewRev;
102
103 /**
104 * Title of $mOldRev or null if the old revision does not exist or does not belong to a page.
105 * Since 1.32 public access is deprecated and the property can be null.
106 * @var Title|null
107 */
108 protected $mOldPage;
109
110 /**
111 * Title of $mNewRev or null if the new revision does not exist or does not belong to a page.
112 * Since 1.32 public access is deprecated and the property can be null.
113 * @var Title|null
114 */
115 protected $mNewPage;
116
117 /**
118 * Change tags of $mOldRev or null if it does not exist / is not saved.
119 * @var string[]|null
120 */
121 private $mOldTags;
122
123 /**
124 * Change tags of $mNewRev or null if it does not exist / is not saved.
125 * @var string[]|null
126 */
127 private $mNewTags;
128
129 /**
130 * @var Content|null
131 * @deprecated since 1.32, content slots are now handled by the corresponding SlotDiffRenderer.
132 * This property is set to the content of the main slot, but not actually used for the main diff.
133 */
134 private $mOldContent;
135
136 /**
137 * @var Content|null
138 * @deprecated since 1.32, content slots are now handled by the corresponding SlotDiffRenderer.
139 * This property is set to the content of the main slot, but not actually used for the main diff.
140 */
141 private $mNewContent;
142
143 /** @var Language */
144 protected $mDiffLang;
145
146 /** @var bool Have the revisions IDs been loaded */
147 private $mRevisionsIdsLoaded = false;
148
149 /** @var bool Have the revisions been loaded */
150 protected $mRevisionsLoaded = false;
151
152 /** @var int How many text blobs have been loaded, 0, 1 or 2? */
153 protected $mTextLoaded = 0;
154
155 /**
156 * Was the content overridden via setContent()?
157 * If the content was overridden, most internal state (e.g. mOldid or mOldRev) should be ignored
158 * and only mOldContent and mNewContent is reliable.
159 * (Note that setRevisions() does not set this flag as in that case all properties are
160 * overriden and remain consistent with each other, so no special handling is needed.)
161 * @var bool
162 */
163 protected $isContentOverridden = false;
164
165 /** @var bool Was the diff fetched from cache? */
166 protected $mCacheHit = false;
167
168 /**
169 * Set this to true to add debug info to the HTML output.
170 * Warning: this may cause RSS readers to spuriously mark articles as "new"
171 * (T22601)
172 */
173 public $enableDebugComment = false;
174
175 /** @var bool If true, line X is not displayed when X is 1, for example
176 * to increase readability and conserve space with many small diffs.
177 */
178 protected $mReducedLineNumbers = false;
179
180 /** @var string Link to action=markpatrolled */
181 protected $mMarkPatrolledLink = null;
182
183 /** @var bool Show rev_deleted content if allowed */
184 protected $unhide = false;
185
186 /** @var bool Refresh the diff cache */
187 protected $mRefreshCache = false;
188
189 /** @var SlotDiffRenderer[] DifferenceEngine classes for the slots, keyed by role name. */
190 protected $slotDiffRenderers = null;
191
192 /**
193 * Temporary hack for B/C while slot diff related methods of DifferenceEngine are being
194 * deprecated. When true, we are inside a DifferenceEngineSlotDiffRenderer and
195 * $slotDiffRenderers should not be used.
196 * @var bool
197 */
198 protected $isSlotDiffRenderer = false;
199
200 /**#@-*/
201
202 /**
203 * @param IContextSource|null $context Context to use, anything else will be ignored
204 * @param int $old Old ID we want to show and diff with.
205 * @param string|int $new Either revision ID or 'prev' or 'next'. Default: 0.
206 * @param int $rcid Deprecated, no longer used!
207 * @param bool $refreshCache If set, refreshes the diff cache
208 * @param bool $unhide If set, allow viewing deleted revs
209 */
210 public function __construct( $context = null, $old = 0, $new = 0, $rcid = 0,
211 $refreshCache = false, $unhide = false
212 ) {
213 $this->deprecatePublicProperty( 'mOldid', '1.32', __CLASS__ );
214 $this->deprecatePublicProperty( 'mNewid', '1.32', __CLASS__ );
215 $this->deprecatePublicProperty( 'mOldRev', '1.32', __CLASS__ );
216 $this->deprecatePublicProperty( 'mNewRev', '1.32', __CLASS__ );
217 $this->deprecatePublicProperty( 'mOldPage', '1.32', __CLASS__ );
218 $this->deprecatePublicProperty( 'mNewPage', '1.32', __CLASS__ );
219 $this->deprecatePublicProperty( 'mOldContent', '1.32', __CLASS__ );
220 $this->deprecatePublicProperty( 'mNewContent', '1.32', __CLASS__ );
221 $this->deprecatePublicProperty( 'mRevisionsLoaded', '1.32', __CLASS__ );
222 $this->deprecatePublicProperty( 'mTextLoaded', '1.32', __CLASS__ );
223 $this->deprecatePublicProperty( 'mCacheHit', '1.32', __CLASS__ );
224
225 if ( $context instanceof IContextSource ) {
226 $this->setContext( $context );
227 }
228
229 wfDebug( "DifferenceEngine old '$old' new '$new' rcid '$rcid'\n" );
230
231 $this->mOldid = $old;
232 $this->mNewid = $new;
233 $this->mRefreshCache = $refreshCache;
234 $this->unhide = $unhide;
235 }
236
237 /**
238 * @return SlotDiffRenderer[] Diff renderers for each slot, keyed by role name.
239 * Includes slots only present in one of the revisions.
240 */
241 protected function getSlotDiffRenderers() {
242 if ( $this->isSlotDiffRenderer ) {
243 throw new LogicException( __METHOD__ . ' called in slot diff renderer mode' );
244 }
245
246 if ( $this->slotDiffRenderers === null ) {
247 if ( !$this->loadRevisionData() ) {
248 return [];
249 }
250
251 $slotContents = $this->getSlotContents();
252 $this->slotDiffRenderers = array_map( function ( $contents ) {
253 /** @var Content $content */
254 $content = $contents['new'] ?: $contents['old'];
255 return $content->getContentHandler()->getSlotDiffRenderer( $this->getContext() );
256 }, $slotContents );
257 }
258 return $this->slotDiffRenderers;
259 }
260
261 /**
262 * Mark this DifferenceEngine as a slot renderer (as opposed to a page renderer).
263 * This is used in legacy mode when the DifferenceEngine is wrapped in a
264 * DifferenceEngineSlotDiffRenderer.
265 * @internal For use by DifferenceEngineSlotDiffRenderer only.
266 */
267 public function markAsSlotDiffRenderer() {
268 $this->isSlotDiffRenderer = true;
269 }
270
271 /**
272 * Get the old and new content objects for all slots.
273 * This method does not do any permission checks.
274 * @return array [ role => [ 'old' => SlotRecord|null, 'new' => SlotRecord|null ], ... ]
275 */
276 protected function getSlotContents() {
277 if ( $this->isContentOverridden ) {
278 return [
279 SlotRecord::MAIN => [
280 'old' => $this->mOldContent,
281 'new' => $this->mNewContent,
282 ]
283 ];
284 } elseif ( !$this->loadRevisionData() ) {
285 return [];
286 }
287
288 $newSlots = $this->mNewRev->getRevisionRecord()->getSlots()->getSlots();
289 if ( $this->mOldRev ) {
290 $oldSlots = $this->mOldRev->getRevisionRecord()->getSlots()->getSlots();
291 } else {
292 $oldSlots = [];
293 }
294 // The order here will determine the visual order of the diff. The current logic is
295 // slots of the new revision first in natural order, then deleted ones. This is ad hoc
296 // and should not be relied on - in the future we may want the ordering to depend
297 // on the page type.
298 $roles = array_merge( array_keys( $newSlots ), array_keys( $oldSlots ) );
299
300 $slots = [];
301 foreach ( $roles as $role ) {
302 $slots[$role] = [
303 'old' => isset( $oldSlots[$role] ) ? $oldSlots[$role]->getContent() : null,
304 'new' => isset( $newSlots[$role] ) ? $newSlots[$role]->getContent() : null,
305 ];
306 }
307 // move main slot to front
308 if ( isset( $slots[SlotRecord::MAIN] ) ) {
309 $slots = [ SlotRecord::MAIN => $slots[SlotRecord::MAIN] ] + $slots;
310 }
311 return $slots;
312 }
313
314 public function getTitle() {
315 // T202454 avoid errors when there is no title
316 return parent::getTitle() ?: Title::makeTitle( NS_SPECIAL, 'BadTitle/DifferenceEngine' );
317 }
318
319 /**
320 * Set reduced line numbers mode.
321 * When set, line X is not displayed when X is 1, for example to increase readability and
322 * conserve space with many small diffs.
323 * @param bool $value
324 */
325 public function setReducedLineNumbers( $value = true ) {
326 $this->mReducedLineNumbers = $value;
327 }
328
329 /**
330 * Get the language of the difference engine, defaults to page content language
331 *
332 * @return Language
333 */
334 public function getDiffLang() {
335 if ( $this->mDiffLang === null ) {
336 # Default language in which the diff text is written.
337 $this->mDiffLang = $this->getTitle()->getPageLanguage();
338 }
339
340 return $this->mDiffLang;
341 }
342
343 /**
344 * @return bool
345 */
346 public function wasCacheHit() {
347 return $this->mCacheHit;
348 }
349
350 /**
351 * Get the ID of old revision (left pane) of the diff. 0 for the revision
352 * previous to getNewid(), false if the old revision does not exist, null
353 * if it's unsaved.
354 * To get a real revision ID instead of 0, call loadRevisionData() first.
355 * @return int|false|null
356 */
357 public function getOldid() {
358 $this->loadRevisionIds();
359
360 return $this->mOldid;
361 }
362
363 /**
364 * Get the ID of new revision (right pane) of the diff. 0 for the current revision,
365 * false if the new revision does not exist, null if it's unsaved.
366 * To get a real revision ID instead of 0, call loadRevisionData() first.
367 * @return int|false|null
368 */
369 public function getNewid() {
370 $this->loadRevisionIds();
371
372 return $this->mNewid;
373 }
374
375 /**
376 * Get the left side of the diff.
377 * Could be null when the first revision of the page is diffed to 'prev' (or in the case of
378 * load failure).
379 * @return RevisionRecord|null
380 */
381 public function getOldRevision() {
382 return $this->mOldRev ? $this->mOldRev->getRevisionRecord() : null;
383 }
384
385 /**
386 * Get the right side of the diff.
387 * Should not be null but can still happen in the case of load failure.
388 * @return RevisionRecord|null
389 */
390 public function getNewRevision() {
391 return $this->mNewRev ? $this->mNewRev->getRevisionRecord() : null;
392 }
393
394 /**
395 * Look up a special:Undelete link to the given deleted revision id,
396 * as a workaround for being unable to load deleted diffs in currently.
397 *
398 * @param int $id Revision ID
399 *
400 * @return string|bool Link HTML or false
401 */
402 public function deletedLink( $id ) {
403 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
404 $dbr = wfGetDB( DB_REPLICA );
405 $arQuery = Revision::getArchiveQueryInfo();
406 $row = $dbr->selectRow(
407 $arQuery['tables'],
408 array_merge( $arQuery['fields'], [ 'ar_namespace', 'ar_title' ] ),
409 [ 'ar_rev_id' => $id ],
410 __METHOD__,
411 [],
412 $arQuery['joins']
413 );
414 if ( $row ) {
415 $rev = Revision::newFromArchiveRow( $row );
416 $title = Title::makeTitleSafe( $row->ar_namespace, $row->ar_title );
417
418 return SpecialPage::getTitleFor( 'Undelete' )->getFullURL( [
419 'target' => $title->getPrefixedText(),
420 'timestamp' => $rev->getTimestamp()
421 ] );
422 }
423 }
424
425 return false;
426 }
427
428 /**
429 * Build a wikitext link toward a deleted revision, if viewable.
430 *
431 * @param int $id Revision ID
432 *
433 * @return string Wikitext fragment
434 */
435 public function deletedIdMarker( $id ) {
436 $link = $this->deletedLink( $id );
437 if ( $link ) {
438 return "[$link $id]";
439 } else {
440 return (string)$id;
441 }
442 }
443
444 private function showMissingRevision() {
445 $out = $this->getOutput();
446
447 $missing = [];
448 if ( $this->mOldRev === null ||
449 ( $this->mOldRev && $this->mOldContent === null )
450 ) {
451 $missing[] = $this->deletedIdMarker( $this->mOldid );
452 }
453 if ( $this->mNewRev === null ||
454 ( $this->mNewRev && $this->mNewContent === null )
455 ) {
456 $missing[] = $this->deletedIdMarker( $this->mNewid );
457 }
458
459 $out->setPageTitle( $this->msg( 'errorpagetitle' ) );
460 $msg = $this->msg( 'difference-missing-revision' )
461 ->params( $this->getLanguage()->listToText( $missing ) )
462 ->numParams( count( $missing ) )
463 ->parseAsBlock();
464 $out->addHTML( $msg );
465 }
466
467 public function showDiffPage( $diffOnly = false ) {
468 # Allow frames except in certain special cases
469 $out = $this->getOutput();
470 $out->allowClickjacking();
471 $out->setRobotPolicy( 'noindex,nofollow' );
472
473 // Allow extensions to add any extra output here
474 Hooks::run( 'DifferenceEngineShowDiffPage', [ $out ] );
475
476 if ( !$this->loadRevisionData() ) {
477 if ( Hooks::run( 'DifferenceEngineShowDiffPageMaybeShowMissingRevision', [ $this ] ) ) {
478 $this->showMissingRevision();
479 }
480 return;
481 }
482
483 $user = $this->getUser();
484 $permErrors = [];
485 if ( $this->mNewPage ) {
486 $permErrors = $this->mNewPage->getUserPermissionsErrors( 'read', $user );
487 }
488 if ( $this->mOldPage ) {
489 $permErrors = wfMergeErrorArrays( $permErrors,
490 $this->mOldPage->getUserPermissionsErrors( 'read', $user ) );
491 }
492 if ( count( $permErrors ) ) {
493 throw new PermissionsError( 'read', $permErrors );
494 }
495
496 $rollback = '';
497
498 $query = [];
499 # Carry over 'diffonly' param via navigation links
500 if ( $diffOnly != $user->getBoolOption( 'diffonly' ) ) {
501 $query['diffonly'] = $diffOnly;
502 }
503 # Cascade unhide param in links for easy deletion browsing
504 if ( $this->unhide ) {
505 $query['unhide'] = 1;
506 }
507
508 # Check if one of the revisions is deleted/suppressed
509 $deleted = $suppressed = false;
510 $allowed = $this->mNewRev->userCan( Revision::DELETED_TEXT, $user );
511
512 $revisionTools = [];
513
514 # mOldRev is false if the difference engine is called with a "vague" query for
515 # a diff between a version V and its previous version V' AND the version V
516 # is the first version of that article. In that case, V' does not exist.
517 if ( $this->mOldRev === false ) {
518 if ( $this->mNewPage ) {
519 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage->getPrefixedText() ) );
520 }
521 $samePage = true;
522 $oldHeader = '';
523 // Allow extensions to change the $oldHeader variable
524 Hooks::run( 'DifferenceEngineOldHeaderNoOldRev', [ &$oldHeader ] );
525 } else {
526 Hooks::run( 'DiffViewHeader', [ $this, $this->mOldRev, $this->mNewRev ] );
527
528 if ( !$this->mOldPage || !$this->mNewPage ) {
529 // XXX say something to the user?
530 $samePage = false;
531 } elseif ( $this->mNewPage->equals( $this->mOldPage ) ) {
532 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage->getPrefixedText() ) );
533 $samePage = true;
534 } else {
535 $out->setPageTitle( $this->msg( 'difference-title-multipage',
536 $this->mOldPage->getPrefixedText(), $this->mNewPage->getPrefixedText() ) );
537 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
538 $samePage = false;
539 }
540
541 if ( $samePage && $this->mNewPage && $this->mNewPage->quickUserCan( 'edit', $user ) ) {
542 if ( $this->mNewRev->isCurrent() && $this->mNewPage->userCan( 'rollback', $user ) ) {
543 $rollbackLink = Linker::generateRollback( $this->mNewRev, $this->getContext() );
544 if ( $rollbackLink ) {
545 $out->preventClickjacking();
546 $rollback = "\u{00A0}\u{00A0}\u{00A0}" . $rollbackLink;
547 }
548 }
549
550 if ( !$this->mOldRev->isDeleted( Revision::DELETED_TEXT ) &&
551 !$this->mNewRev->isDeleted( Revision::DELETED_TEXT )
552 ) {
553 $undoLink = Html::element( 'a', [
554 'href' => $this->mNewPage->getLocalURL( [
555 'action' => 'edit',
556 'undoafter' => $this->mOldid,
557 'undo' => $this->mNewid
558 ] ),
559 'title' => Linker::titleAttrib( 'undo' ),
560 ],
561 $this->msg( 'editundo' )->text()
562 );
563 $revisionTools['mw-diff-undo'] = $undoLink;
564 }
565 }
566
567 # Make "previous revision link"
568 if ( $samePage && $this->mOldPage && $this->mOldRev->getPrevious() ) {
569 $prevlink = Linker::linkKnown(
570 $this->mOldPage,
571 $this->msg( 'previousdiff' )->escaped(),
572 [ 'id' => 'differences-prevlink' ],
573 [ 'diff' => 'prev', 'oldid' => $this->mOldid ] + $query
574 );
575 } else {
576 $prevlink = "\u{00A0}";
577 }
578
579 if ( $this->mOldRev->isMinor() ) {
580 $oldminor = ChangesList::flag( 'minor' );
581 } else {
582 $oldminor = '';
583 }
584
585 $ldel = $this->revisionDeleteLink( $this->mOldRev );
586 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev, 'complete' );
587 $oldChangeTags = ChangeTags::formatSummaryRow( $this->mOldTags, 'diff', $this->getContext() );
588
589 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
590 '<div id="mw-diff-otitle2">' .
591 Linker::revUserTools( $this->mOldRev, !$this->unhide ) . '</div>' .
592 '<div id="mw-diff-otitle3">' . $oldminor .
593 Linker::revComment( $this->mOldRev, !$diffOnly, !$this->unhide ) . $ldel . '</div>' .
594 '<div id="mw-diff-otitle5">' . $oldChangeTags[0] . '</div>' .
595 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
596
597 // Allow extensions to change the $oldHeader variable
598 Hooks::run( 'DifferenceEngineOldHeader', [ $this, &$oldHeader, $prevlink, $oldminor,
599 $diffOnly, $ldel, $this->unhide ] );
600
601 if ( $this->mOldRev->isDeleted( Revision::DELETED_TEXT ) ) {
602 $deleted = true; // old revisions text is hidden
603 if ( $this->mOldRev->isDeleted( Revision::DELETED_RESTRICTED ) ) {
604 $suppressed = true; // also suppressed
605 }
606 }
607
608 # Check if this user can see the revisions
609 if ( !$this->mOldRev->userCan( Revision::DELETED_TEXT, $user ) ) {
610 $allowed = false;
611 }
612 }
613
614 $out->addJsConfigVars( [
615 'wgDiffOldId' => $this->mOldid,
616 'wgDiffNewId' => $this->mNewid,
617 ] );
618
619 # Make "next revision link"
620 # Skip next link on the top revision
621 if ( $samePage && $this->mNewPage && !$this->mNewRev->isCurrent() ) {
622 $nextlink = Linker::linkKnown(
623 $this->mNewPage,
624 $this->msg( 'nextdiff' )->escaped(),
625 [ 'id' => 'differences-nextlink' ],
626 [ 'diff' => 'next', 'oldid' => $this->mNewid ] + $query
627 );
628 } else {
629 $nextlink = "\u{00A0}";
630 }
631
632 if ( $this->mNewRev->isMinor() ) {
633 $newminor = ChangesList::flag( 'minor' );
634 } else {
635 $newminor = '';
636 }
637
638 # Handle RevisionDelete links...
639 $rdel = $this->revisionDeleteLink( $this->mNewRev );
640
641 # Allow extensions to define their own revision tools
642 Hooks::run( 'DiffRevisionTools',
643 [ $this->mNewRev, &$revisionTools, $this->mOldRev, $user ] );
644 $formattedRevisionTools = [];
645 // Put each one in parentheses (poor man's button)
646 foreach ( $revisionTools as $key => $tool ) {
647 $toolClass = is_string( $key ) ? $key : 'mw-diff-tool';
648 $element = Html::rawElement(
649 'span',
650 [ 'class' => $toolClass ],
651 $this->msg( 'parentheses' )->rawParams( $tool )->escaped()
652 );
653 $formattedRevisionTools[] = $element;
654 }
655 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev, 'complete' ) .
656 ' ' . implode( ' ', $formattedRevisionTools );
657 $newChangeTags = ChangeTags::formatSummaryRow( $this->mNewTags, 'diff', $this->getContext() );
658
659 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
660 '<div id="mw-diff-ntitle2">' . Linker::revUserTools( $this->mNewRev, !$this->unhide ) .
661 " $rollback</div>" .
662 '<div id="mw-diff-ntitle3">' . $newminor .
663 Linker::revComment( $this->mNewRev, !$diffOnly, !$this->unhide ) . $rdel . '</div>' .
664 '<div id="mw-diff-ntitle5">' . $newChangeTags[0] . '</div>' .
665 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
666
667 // Allow extensions to change the $newHeader variable
668 Hooks::run( 'DifferenceEngineNewHeader', [ $this, &$newHeader, $formattedRevisionTools,
669 $nextlink, $rollback, $newminor, $diffOnly, $rdel, $this->unhide ] );
670
671 if ( $this->mNewRev->isDeleted( Revision::DELETED_TEXT ) ) {
672 $deleted = true; // new revisions text is hidden
673 if ( $this->mNewRev->isDeleted( Revision::DELETED_RESTRICTED ) ) {
674 $suppressed = true; // also suppressed
675 }
676 }
677
678 # If the diff cannot be shown due to a deleted revision, then output
679 # the diff header and links to unhide (if available)...
680 if ( $deleted && ( !$this->unhide || !$allowed ) ) {
681 $this->showDiffStyle();
682 $multi = $this->getMultiNotice();
683 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
684 if ( !$allowed ) {
685 $msg = $suppressed ? 'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
686 # Give explanation for why revision is not visible
687 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
688 [ $msg ] );
689 } else {
690 # Give explanation and add a link to view the diff...
691 $query = $this->getRequest()->appendQueryValue( 'unhide', '1' );
692 $link = $this->getTitle()->getFullURL( $query );
693 $msg = $suppressed ? 'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
694 $out->wrapWikiMsg(
695 "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
696 [ $msg, $link ]
697 );
698 }
699 # Otherwise, output a regular diff...
700 } else {
701 # Add deletion notice if the user is viewing deleted content
702 $notice = '';
703 if ( $deleted ) {
704 $msg = $suppressed ? 'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
705 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" .
706 $this->msg( $msg )->parse() .
707 "</div>\n";
708 }
709 $this->showDiff( $oldHeader, $newHeader, $notice );
710 if ( !$diffOnly ) {
711 $this->renderNewRevision();
712 }
713 }
714 }
715
716 /**
717 * Build a link to mark a change as patrolled.
718 *
719 * Returns empty string if there's either no revision to patrol or the user is not allowed to.
720 * Side effect: When the patrol link is build, this method will call
721 * OutputPage::preventClickjacking() and load mediawiki.page.patrol.ajax.
722 *
723 * @return string HTML or empty string
724 */
725 public function markPatrolledLink() {
726 if ( $this->mMarkPatrolledLink === null ) {
727 $linkInfo = $this->getMarkPatrolledLinkInfo();
728 // If false, there is no patrol link needed/allowed
729 if ( !$linkInfo || !$this->mNewPage ) {
730 $this->mMarkPatrolledLink = '';
731 } else {
732 $this->mMarkPatrolledLink = ' <span class="patrollink" data-mw="interface">[' .
733 Linker::linkKnown(
734 $this->mNewPage,
735 $this->msg( 'markaspatrolleddiff' )->escaped(),
736 [],
737 [
738 'action' => 'markpatrolled',
739 'rcid' => $linkInfo['rcid'],
740 ]
741 ) . ']</span>';
742 // Allow extensions to change the markpatrolled link
743 Hooks::run( 'DifferenceEngineMarkPatrolledLink', [ $this,
744 &$this->mMarkPatrolledLink, $linkInfo['rcid'] ] );
745 }
746 }
747 return $this->mMarkPatrolledLink;
748 }
749
750 /**
751 * Returns an array of meta data needed to build a "mark as patrolled" link and
752 * adds the mediawiki.page.patrol.ajax to the output.
753 *
754 * @return array|false An array of meta data for a patrol link (rcid only)
755 * or false if no link is needed
756 */
757 protected function getMarkPatrolledLinkInfo() {
758 $user = $this->getUser();
759 $config = $this->getConfig();
760
761 // Prepare a change patrol link, if applicable
762 if (
763 // Is patrolling enabled and the user allowed to?
764 $config->get( 'UseRCPatrol' ) &&
765 $this->mNewPage && $this->mNewPage->quickUserCan( 'patrol', $user ) &&
766 // Only do this if the revision isn't more than 6 hours older
767 // than the Max RC age (6h because the RC might not be cleaned out regularly)
768 RecentChange::isInRCLifespan( $this->mNewRev->getTimestamp(), 21600 )
769 ) {
770 // Look for an unpatrolled change corresponding to this diff
771 $db = wfGetDB( DB_REPLICA );
772 $change = RecentChange::newFromConds(
773 [
774 'rc_timestamp' => $db->timestamp( $this->mNewRev->getTimestamp() ),
775 'rc_this_oldid' => $this->mNewid,
776 'rc_patrolled' => RecentChange::PRC_UNPATROLLED
777 ],
778 __METHOD__
779 );
780
781 if ( $change && !$change->getPerformer()->equals( $user ) ) {
782 $rcid = $change->getAttribute( 'rc_id' );
783 } else {
784 // None found or the page has been created by the current user.
785 // If the user could patrol this it already would be patrolled
786 $rcid = 0;
787 }
788
789 // Allow extensions to possibly change the rcid here
790 // For example the rcid might be set to zero due to the user
791 // being the same as the performer of the change but an extension
792 // might still want to show it under certain conditions
793 Hooks::run( 'DifferenceEngineMarkPatrolledRCID', [ &$rcid, $this, $change, $user ] );
794
795 // Build the link
796 if ( $rcid ) {
797 $this->getOutput()->preventClickjacking();
798 if ( $user->isAllowed( 'writeapi' ) ) {
799 $this->getOutput()->addModules( 'mediawiki.page.patrol.ajax' );
800 }
801
802 return [
803 'rcid' => $rcid,
804 ];
805 }
806 }
807
808 // No mark as patrolled link applicable
809 return false;
810 }
811
812 /**
813 * @param Revision $rev
814 *
815 * @return string
816 */
817 protected function revisionDeleteLink( $rev ) {
818 $link = Linker::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
819 if ( $link !== '' ) {
820 $link = "\u{00A0}\u{00A0}\u{00A0}" . $link . ' ';
821 }
822
823 return $link;
824 }
825
826 /**
827 * Show the new revision of the page.
828 *
829 * @note Not supported after calling setContent().
830 */
831 public function renderNewRevision() {
832 if ( $this->isContentOverridden ) {
833 // The code below only works with a Revision object. We could construct a fake revision
834 // (here or in setContent), but since this does not seem needed at the moment,
835 // we'll just fail for now.
836 throw new LogicException(
837 __METHOD__
838 . ' is not supported after calling setContent(). Use setRevisions() instead.'
839 );
840 }
841
842 $out = $this->getOutput();
843 $revHeader = $this->getRevisionHeader( $this->mNewRev );
844 # Add "current version as of X" title
845 $out->addHTML( "<hr class='diff-hr' id='mw-oldid' />
846 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
847 # Page content may be handled by a hooked call instead...
848 if ( Hooks::run( 'ArticleContentOnDiff', [ $this, $out ] ) ) {
849 $this->loadNewText();
850 if ( !$this->mNewPage ) {
851 // New revision is unsaved; bail out.
852 // TODO in theory rendering the new revision is a meaningful thing to do
853 // even if it's unsaved, but a lot of untangling is required to do it safely.
854 return;
855 }
856
857 $out->setRevisionId( $this->mNewid );
858 $out->setRevisionTimestamp( $this->mNewRev->getTimestamp() );
859 $out->setArticleFlag( true );
860
861 if ( !Hooks::run( 'ArticleRevisionViewCustom',
862 [ $this->mNewRev->getRevisionRecord(), $this->mNewPage, $out ] )
863 ) {
864 // Handled by extension
865 // NOTE: sync with hooks called in Article::view()
866 } elseif ( !Hooks::run( 'ArticleContentViewCustom',
867 [ $this->mNewContent, $this->mNewPage, $out ], '1.32' )
868 ) {
869 // Handled by extension
870 // NOTE: sync with hooks called in Article::view()
871 } else {
872 // Normal page
873 if ( $this->getTitle()->equals( $this->mNewPage ) ) {
874 // If the Title stored in the context is the same as the one
875 // of the new revision, we can use its associated WikiPage
876 // object.
877 $wikiPage = $this->getWikiPage();
878 } else {
879 // Otherwise we need to create our own WikiPage object
880 $wikiPage = WikiPage::factory( $this->mNewPage );
881 }
882
883 $parserOutput = $this->getParserOutput( $wikiPage, $this->mNewRev );
884
885 # WikiPage::getParserOutput() should not return false, but just in case
886 if ( $parserOutput ) {
887 // Allow extensions to change parser output here
888 if ( Hooks::run( 'DifferenceEngineRenderRevisionAddParserOutput',
889 [ $this, $out, $parserOutput, $wikiPage ] )
890 ) {
891 $out->addParserOutput( $parserOutput, [
892 'enableSectionEditLinks' => $this->mNewRev->isCurrent()
893 && $this->mNewRev->getTitle()->quickUserCan( 'edit', $this->getUser() ),
894 ] );
895 }
896 }
897 }
898 }
899
900 // Allow extensions to optionally not show the final patrolled link
901 if ( Hooks::run( 'DifferenceEngineRenderRevisionShowFinalPatrolLink' ) ) {
902 # Add redundant patrol link on bottom...
903 $out->addHTML( $this->markPatrolledLink() );
904 }
905 }
906
907 /**
908 * @param WikiPage $page
909 * @param Revision $rev
910 *
911 * @return ParserOutput|bool False if the revision was not found
912 */
913 protected function getParserOutput( WikiPage $page, Revision $rev ) {
914 if ( !$rev->getId() ) {
915 // WikiPage::getParserOutput wants a revision ID. Passing 0 will incorrectly show
916 // the current revision, so fail instead. If need be, WikiPage::getParserOutput
917 // could be made to accept a Revision or RevisionRecord instead of the id.
918 return false;
919 }
920
921 $parserOptions = $page->makeParserOptions( $this->getContext() );
922 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
923
924 return $parserOutput;
925 }
926
927 /**
928 * Get the diff text, send it to the OutputPage object
929 * Returns false if the diff could not be generated, otherwise returns true
930 *
931 * @param string|bool $otitle Header for old text or false
932 * @param string|bool $ntitle Header for new text or false
933 * @param string $notice HTML between diff header and body
934 *
935 * @return bool
936 */
937 public function showDiff( $otitle, $ntitle, $notice = '' ) {
938 // Allow extensions to affect the output here
939 Hooks::run( 'DifferenceEngineShowDiff', [ $this ] );
940
941 $diff = $this->getDiff( $otitle, $ntitle, $notice );
942 if ( $diff === false ) {
943 $this->showMissingRevision();
944
945 return false;
946 } else {
947 $this->showDiffStyle();
948 $this->getOutput()->addHTML( $diff );
949
950 return true;
951 }
952 }
953
954 /**
955 * Add style sheets for diff display.
956 */
957 public function showDiffStyle() {
958 if ( !$this->isSlotDiffRenderer ) {
959 $this->getOutput()->addModuleStyles( [
960 'mediawiki.interface.helpers.styles',
961 'mediawiki.diff.styles'
962 ] );
963 foreach ( $this->getSlotDiffRenderers() as $slotDiffRenderer ) {
964 $slotDiffRenderer->addModules( $this->getOutput() );
965 }
966 }
967 }
968
969 /**
970 * Get complete diff table, including header
971 *
972 * @param string|bool $otitle Header for old text or false
973 * @param string|bool $ntitle Header for new text or false
974 * @param string $notice HTML between diff header and body
975 *
976 * @return mixed
977 */
978 public function getDiff( $otitle, $ntitle, $notice = '' ) {
979 $body = $this->getDiffBody();
980 if ( $body === false ) {
981 return false;
982 }
983
984 $multi = $this->getMultiNotice();
985 // Display a message when the diff is empty
986 if ( $body === '' ) {
987 $notice .= '<div class="mw-diff-empty">' .
988 $this->msg( 'diff-empty' )->parse() .
989 "</div>\n";
990 }
991
992 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
993 }
994
995 /**
996 * Get the diff table body, without header
997 *
998 * @return mixed (string/false)
999 */
1000 public function getDiffBody() {
1001 $this->mCacheHit = true;
1002 // Check if the diff should be hidden from this user
1003 if ( !$this->isContentOverridden ) {
1004 if ( !$this->loadRevisionData() ) {
1005 return false;
1006 } elseif ( $this->mOldRev &&
1007 !$this->mOldRev->userCan( Revision::DELETED_TEXT, $this->getUser() )
1008 ) {
1009 return false;
1010 } elseif ( $this->mNewRev &&
1011 !$this->mNewRev->userCan( Revision::DELETED_TEXT, $this->getUser() )
1012 ) {
1013 return false;
1014 }
1015 // Short-circuit
1016 if ( $this->mOldRev === false || ( $this->mOldRev && $this->mNewRev &&
1017 $this->mOldRev->getId() && $this->mOldRev->getId() == $this->mNewRev->getId() )
1018 ) {
1019 if ( Hooks::run( 'DifferenceEngineShowEmptyOldContent', [ $this ] ) ) {
1020 return '';
1021 }
1022 }
1023 }
1024
1025 // Cacheable?
1026 $key = false;
1027 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1028 if ( $this->mOldid && $this->mNewid ) {
1029 // Check if subclass is still using the old way
1030 // for backwards-compatibility
1031 $key = $this->getDiffBodyCacheKey();
1032 if ( $key === null ) {
1033 $key = $cache->makeKey( ...$this->getDiffBodyCacheKeyParams() );
1034 }
1035
1036 // Try cache
1037 if ( !$this->mRefreshCache ) {
1038 $difftext = $cache->get( $key );
1039 if ( is_string( $difftext ) ) {
1040 wfIncrStats( 'diff_cache.hit' );
1041 $difftext = $this->localiseDiff( $difftext );
1042 $difftext .= "\n<!-- diff cache key $key -->\n";
1043
1044 return $difftext;
1045 }
1046 } // don't try to load but save the result
1047 }
1048 $this->mCacheHit = false;
1049
1050 // Loadtext is permission safe, this just clears out the diff
1051 if ( !$this->loadText() ) {
1052 return false;
1053 }
1054
1055 $difftext = '';
1056 // We've checked for revdelete at the beginning of this method; it's OK to ignore
1057 // read permissions here.
1058 $slotContents = $this->getSlotContents();
1059 foreach ( $this->getSlotDiffRenderers() as $role => $slotDiffRenderer ) {
1060 $slotDiff = $slotDiffRenderer->getDiff( $slotContents[$role]['old'],
1061 $slotContents[$role]['new'] );
1062 if ( $slotDiff && $role !== SlotRecord::MAIN ) {
1063 // FIXME: ask SlotRoleHandler::getSlotNameMessage
1064 $slotTitle = $role;
1065 $difftext .= $this->getSlotHeader( $slotTitle );
1066 }
1067 $difftext .= $slotDiff;
1068 }
1069
1070 // Avoid PHP 7.1 warning from passing $this by reference
1071 $diffEngine = $this;
1072
1073 // Save to cache for 7 days
1074 if ( !Hooks::run( 'AbortDiffCache', [ &$diffEngine ] ) ) {
1075 wfIncrStats( 'diff_cache.uncacheable' );
1076 } elseif ( $key !== false && $difftext !== false ) {
1077 wfIncrStats( 'diff_cache.miss' );
1078 $cache->set( $key, $difftext, 7 * 86400 );
1079 } else {
1080 wfIncrStats( 'diff_cache.uncacheable' );
1081 }
1082 // localise line numbers and title attribute text
1083 if ( $difftext !== false ) {
1084 $difftext = $this->localiseDiff( $difftext );
1085 }
1086
1087 return $difftext;
1088 }
1089
1090 /**
1091 * Get the diff table body for one slot, without header
1092 *
1093 * @param string $role
1094 * @return string|false
1095 */
1096 public function getDiffBodyForRole( $role ) {
1097 $diffRenderers = $this->getSlotDiffRenderers();
1098 if ( !isset( $diffRenderers[$role] ) ) {
1099 return false;
1100 }
1101
1102 $slotContents = $this->getSlotContents();
1103 $slotDiff = $diffRenderers[$role]->getDiff( $slotContents[$role]['old'],
1104 $slotContents[$role]['new'] );
1105 if ( !$slotDiff ) {
1106 return false;
1107 }
1108
1109 if ( $role !== SlotRecord::MAIN ) {
1110 // TODO use human-readable role name at least
1111 $slotTitle = $role;
1112 $slotDiff = $this->getSlotHeader( $slotTitle ) . $slotDiff;
1113 }
1114
1115 return $this->localiseDiff( $slotDiff );
1116 }
1117
1118 /**
1119 * Get a slot header for inclusion in a diff body (as a table row).
1120 *
1121 * @param string $headerText The text of the header
1122 * @return string
1123 *
1124 */
1125 protected function getSlotHeader( $headerText ) {
1126 // The old revision is missing on oldid=<first>&diff=prev; only 2 columns in that case.
1127 $columnCount = $this->mOldRev ? 4 : 2;
1128 $userLang = $this->getLanguage()->getHtmlCode();
1129 return Html::rawElement( 'tr', [ 'class' => 'mw-diff-slot-header', 'lang' => $userLang ],
1130 Html::element( 'th', [ 'colspan' => $columnCount ], $headerText ) );
1131 }
1132
1133 /**
1134 * Returns the cache key for diff body text or content.
1135 *
1136 * @deprecated since 1.31, use getDiffBodyCacheKeyParams() instead
1137 * @since 1.23
1138 *
1139 * @throws MWException
1140 * @return string|null
1141 */
1142 protected function getDiffBodyCacheKey() {
1143 return null;
1144 }
1145
1146 /**
1147 * Get the cache key parameters
1148 *
1149 * Subclasses can replace the first element in the array to something
1150 * more specific to the type of diff (e.g. "inline-diff"), or append
1151 * if the cache should vary on more things. Overriding entirely should
1152 * be avoided.
1153 *
1154 * @since 1.31
1155 *
1156 * @return array
1157 * @throws MWException
1158 */
1159 protected function getDiffBodyCacheKeyParams() {
1160 if ( !$this->mOldid || !$this->mNewid ) {
1161 throw new MWException( 'mOldid and mNewid must be set to get diff cache key.' );
1162 }
1163
1164 $engine = $this->getEngine();
1165 $params = [
1166 'diff',
1167 $engine,
1168 self::DIFF_VERSION,
1169 "old-{$this->mOldid}",
1170 "rev-{$this->mNewid}"
1171 ];
1172
1173 if ( $engine === 'wikidiff2' ) {
1174 $params[] = phpversion( 'wikidiff2' );
1175 }
1176
1177 if ( !$this->isSlotDiffRenderer ) {
1178 foreach ( $this->getSlotDiffRenderers() as $slotDiffRenderer ) {
1179 $params = array_merge( $params, $slotDiffRenderer->getExtraCacheKeys() );
1180 }
1181 }
1182
1183 return $params;
1184 }
1185
1186 /**
1187 * Implements DifferenceEngineSlotDiffRenderer::getExtraCacheKeys(). Only used when
1188 * DifferenceEngine is wrapped in DifferenceEngineSlotDiffRenderer.
1189 * @return array
1190 * @internal for use by DifferenceEngineSlotDiffRenderer only
1191 * @deprecated
1192 */
1193 public function getExtraCacheKeys() {
1194 // This method is called when the DifferenceEngine is used for a slot diff. We only care
1195 // about special things, not the revision IDs, which are added to the cache key by the
1196 // page-level DifferenceEngine, and which might not have a valid value for this object.
1197 $this->mOldid = 123456789;
1198 $this->mNewid = 987654321;
1199
1200 // This will repeat a bunch of unnecessary key fields for each slot. Not nice but harmless.
1201 $cacheString = $this->getDiffBodyCacheKey();
1202 if ( $cacheString ) {
1203 return [ $cacheString ];
1204 }
1205
1206 $params = $this->getDiffBodyCacheKeyParams();
1207
1208 // Try to get rid of the standard keys to keep the cache key human-readable:
1209 // call the getDiffBodyCacheKeyParams implementation of the base class, and if
1210 // the child class includes the same keys, drop them.
1211 // Uses an obscure PHP feature where static calls to non-static methods are allowed
1212 // as long as we are already in a non-static method of the same class, and the call context
1213 // ($this) will be inherited.
1214 // phpcs:ignore Squiz.Classes.SelfMemberReference.NotUsed
1215 $standardParams = DifferenceEngine::getDiffBodyCacheKeyParams();
1216 if ( array_slice( $params, 0, count( $standardParams ) ) === $standardParams ) {
1217 $params = array_slice( $params, count( $standardParams ) );
1218 }
1219
1220 return $params;
1221 }
1222
1223 /**
1224 * Generate a diff, no caching.
1225 *
1226 * @since 1.21
1227 *
1228 * @param Content $old Old content
1229 * @param Content $new New content
1230 *
1231 * @throws Exception If old or new content is not an instance of TextContent.
1232 * @return bool|string
1233 *
1234 * @deprecated since 1.32, use a SlotDiffRenderer instead.
1235 */
1236 public function generateContentDiffBody( Content $old, Content $new ) {
1237 $slotDiffRenderer = $new->getContentHandler()->getSlotDiffRenderer( $this->getContext() );
1238 if (
1239 $slotDiffRenderer instanceof DifferenceEngineSlotDiffRenderer
1240 && $this->isSlotDiffRenderer
1241 ) {
1242 // Oops, we are just about to enter an infinite loop (the slot-level DifferenceEngine
1243 // called a DifferenceEngineSlotDiffRenderer that wraps the same DifferenceEngine class).
1244 // This will happen when a content model has no custom slot diff renderer, it does have
1245 // a custom difference engine, but that does not override this method.
1246 throw new Exception( get_class( $this ) . ': could not maintain backwards compatibility. '
1247 . 'Please use a SlotDiffRenderer.' );
1248 }
1249 return $slotDiffRenderer->getDiff( $old, $new ) . $this->getDebugString();
1250 }
1251
1252 /**
1253 * Generate a diff, no caching
1254 *
1255 * @param string $otext Old text, must be already segmented
1256 * @param string $ntext New text, must be already segmented
1257 *
1258 * @throws Exception If content handling for text content is configured in a way
1259 * that makes maintaining B/C hard.
1260 * @return bool|string
1261 *
1262 * @deprecated since 1.32, use a TextSlotDiffRenderer instead.
1263 */
1264 public function generateTextDiffBody( $otext, $ntext ) {
1265 $slotDiffRenderer = ContentHandler::getForModelID( CONTENT_MODEL_TEXT )
1266 ->getSlotDiffRenderer( $this->getContext() );
1267 if ( !( $slotDiffRenderer instanceof TextSlotDiffRenderer ) ) {
1268 // Someone used the GetSlotDiffRenderer hook to replace the renderer.
1269 // This is too unlikely to happen to bother handling properly.
1270 throw new Exception( 'The slot diff renderer for text content should be a '
1271 . 'TextSlotDiffRenderer subclass' );
1272 }
1273 return $slotDiffRenderer->getTextDiff( $otext, $ntext ) . $this->getDebugString();
1274 }
1275
1276 /**
1277 * Process $wgExternalDiffEngine and get a sane, usable engine
1278 *
1279 * @return bool|string 'wikidiff2', path to an executable, or false
1280 * @internal For use by this class and TextSlotDiffRenderer only.
1281 */
1282 public static function getEngine() {
1283 global $wgExternalDiffEngine;
1284 // We use the global here instead of Config because we write to the value,
1285 // and Config is not mutable.
1286 if ( $wgExternalDiffEngine == 'wikidiff' || $wgExternalDiffEngine == 'wikidiff3' ) {
1287 wfDeprecated( "\$wgExternalDiffEngine = '{$wgExternalDiffEngine}'", '1.27' );
1288 $wgExternalDiffEngine = false;
1289 } elseif ( $wgExternalDiffEngine == 'wikidiff2' ) {
1290 wfDeprecated( "\$wgExternalDiffEngine = '{$wgExternalDiffEngine}'", '1.32' );
1291 $wgExternalDiffEngine = false;
1292 } elseif ( !is_string( $wgExternalDiffEngine ) && $wgExternalDiffEngine !== false ) {
1293 // And prevent people from shooting themselves in the foot...
1294 wfWarn( '$wgExternalDiffEngine is set to a non-string value, forcing it to false' );
1295 $wgExternalDiffEngine = false;
1296 }
1297
1298 if ( is_string( $wgExternalDiffEngine ) && is_executable( $wgExternalDiffEngine ) ) {
1299 return $wgExternalDiffEngine;
1300 } elseif ( $wgExternalDiffEngine === false && function_exists( 'wikidiff2_do_diff' ) ) {
1301 return 'wikidiff2';
1302 } else {
1303 // Native PHP
1304 return false;
1305 }
1306 }
1307
1308 /**
1309 * Generates diff, to be wrapped internally in a logging/instrumentation
1310 *
1311 * @param string $otext Old text, must be already segmented
1312 * @param string $ntext New text, must be already segmented
1313 *
1314 * @throws Exception If content handling for text content is configured in a way
1315 * that makes maintaining B/C hard.
1316 * @return bool|string
1317 *
1318 * @deprecated since 1.32, use a TextSlotDiffRenderer instead.
1319 */
1320 protected function textDiff( $otext, $ntext ) {
1321 $slotDiffRenderer = ContentHandler::getForModelID( CONTENT_MODEL_TEXT )
1322 ->getSlotDiffRenderer( $this->getContext() );
1323 if ( !( $slotDiffRenderer instanceof TextSlotDiffRenderer ) ) {
1324 // Someone used the GetSlotDiffRenderer hook to replace the renderer.
1325 // This is too unlikely to happen to bother handling properly.
1326 throw new Exception( 'The slot diff renderer for text content should be a '
1327 . 'TextSlotDiffRenderer subclass' );
1328 }
1329 return $slotDiffRenderer->getTextDiff( $otext, $ntext ) . $this->getDebugString();
1330 }
1331
1332 /**
1333 * Generate a debug comment indicating diff generating time,
1334 * server node, and generator backend.
1335 *
1336 * @param string $generator : What diff engine was used
1337 *
1338 * @return string
1339 */
1340 protected function debug( $generator = "internal" ) {
1341 if ( !$this->enableDebugComment ) {
1342 return '';
1343 }
1344 $data = [ $generator ];
1345 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1346 $data[] = wfHostname();
1347 }
1348 $data[] = wfTimestamp( TS_DB );
1349
1350 return "<!-- diff generator: " .
1351 implode( " ", array_map( "htmlspecialchars", $data ) ) .
1352 " -->\n";
1353 }
1354
1355 private function getDebugString() {
1356 $engine = self::getEngine();
1357 if ( $engine === 'wikidiff2' ) {
1358 return $this->debug( 'wikidiff2' );
1359 } elseif ( $engine === false ) {
1360 return $this->debug( 'native PHP' );
1361 } else {
1362 return $this->debug( "external $engine" );
1363 }
1364 }
1365
1366 /**
1367 * Localise diff output
1368 *
1369 * @param string $text
1370 * @return string
1371 */
1372 private function localiseDiff( $text ) {
1373 $text = $this->localiseLineNumbers( $text );
1374 if ( $this->getEngine() === 'wikidiff2' &&
1375 version_compare( phpversion( 'wikidiff2' ), '1.5.1', '>=' )
1376 ) {
1377 $text = $this->addLocalisedTitleTooltips( $text );
1378 }
1379 return $text;
1380 }
1381
1382 /**
1383 * Replace line numbers with the text in the user's language
1384 *
1385 * @param string $text
1386 *
1387 * @return mixed
1388 */
1389 public function localiseLineNumbers( $text ) {
1390 return preg_replace_callback(
1391 '/<!--LINE (\d+)-->/',
1392 [ $this, 'localiseLineNumbersCb' ],
1393 $text
1394 );
1395 }
1396
1397 public function localiseLineNumbersCb( $matches ) {
1398 if ( $matches[1] === '1' && $this->mReducedLineNumbers ) {
1399 return '';
1400 }
1401
1402 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
1403 }
1404
1405 /**
1406 * Add title attributes for tooltips on moved paragraph indicators
1407 *
1408 * @param string $text
1409 * @return string
1410 */
1411 private function addLocalisedTitleTooltips( $text ) {
1412 return preg_replace_callback(
1413 '/class="mw-diff-movedpara-(left|right)"/',
1414 [ $this, 'addLocalisedTitleTooltipsCb' ],
1415 $text
1416 );
1417 }
1418
1419 /**
1420 * @param array $matches
1421 * @return string
1422 */
1423 private function addLocalisedTitleTooltipsCb( array $matches ) {
1424 $key = $matches[1] === 'right' ?
1425 'diff-paragraph-moved-toold' :
1426 'diff-paragraph-moved-tonew';
1427 return $matches[0] . ' title="' . $this->msg( $key )->escaped() . '"';
1428 }
1429
1430 /**
1431 * If there are revisions between the ones being compared, return a note saying so.
1432 *
1433 * @return string
1434 */
1435 public function getMultiNotice() {
1436 // The notice only make sense if we are diffing two saved revisions of the same page.
1437 if (
1438 !$this->mOldRev || !$this->mNewRev
1439 || !$this->mOldPage || !$this->mNewPage
1440 || !$this->mOldPage->equals( $this->mNewPage )
1441 ) {
1442 return '';
1443 }
1444
1445 if ( $this->mOldRev->getTimestamp() > $this->mNewRev->getTimestamp() ) {
1446 $oldRev = $this->mNewRev; // flip
1447 $newRev = $this->mOldRev; // flip
1448 } else { // normal case
1449 $oldRev = $this->mOldRev;
1450 $newRev = $this->mNewRev;
1451 }
1452
1453 // Sanity: don't show the notice if too many rows must be scanned
1454 // @todo show some special message for that case
1455 $nEdits = $this->mNewPage->countRevisionsBetween( $oldRev, $newRev, 1000 );
1456 if ( $nEdits > 0 && $nEdits <= 1000 ) {
1457 $limit = 100; // use diff-multi-manyusers if too many users
1458 $users = $this->mNewPage->getAuthorsBetween( $oldRev, $newRev, $limit );
1459 $numUsers = count( $users );
1460
1461 if ( $numUsers == 1 && $users[0] == $newRev->getUserText( Revision::RAW ) ) {
1462 $numUsers = 0; // special case to say "by the same user" instead of "by one other user"
1463 }
1464
1465 return self::intermediateEditsMsg( $nEdits, $numUsers, $limit );
1466 }
1467
1468 return '';
1469 }
1470
1471 /**
1472 * Get a notice about how many intermediate edits and users there are
1473 *
1474 * @param int $numEdits
1475 * @param int $numUsers
1476 * @param int $limit
1477 *
1478 * @return string
1479 */
1480 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
1481 if ( $numUsers === 0 ) {
1482 $msg = 'diff-multi-sameuser';
1483 } elseif ( $numUsers > $limit ) {
1484 $msg = 'diff-multi-manyusers';
1485 $numUsers = $limit;
1486 } else {
1487 $msg = 'diff-multi-otherusers';
1488 }
1489
1490 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
1491 }
1492
1493 /**
1494 * Get a header for a specified revision.
1495 *
1496 * @param Revision $rev
1497 * @param string $complete 'complete' to get the header wrapped depending
1498 * the visibility of the revision and a link to edit the page.
1499 *
1500 * @return string HTML fragment
1501 */
1502 public function getRevisionHeader( Revision $rev, $complete = '' ) {
1503 $lang = $this->getLanguage();
1504 $user = $this->getUser();
1505 $revtimestamp = $rev->getTimestamp();
1506 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
1507 $dateofrev = $lang->userDate( $revtimestamp, $user );
1508 $timeofrev = $lang->userTime( $revtimestamp, $user );
1509
1510 $header = $this->msg(
1511 $rev->isCurrent() ? 'currentrev-asof' : 'revisionasof',
1512 $timestamp,
1513 $dateofrev,
1514 $timeofrev
1515 )->escaped();
1516
1517 if ( $complete !== 'complete' ) {
1518 return $header;
1519 }
1520
1521 $title = $rev->getTitle();
1522
1523 $header = Linker::linkKnown( $title, $header, [],
1524 [ 'oldid' => $rev->getId() ] );
1525
1526 if ( $rev->userCan( Revision::DELETED_TEXT, $user ) ) {
1527 $editQuery = [ 'action' => 'edit' ];
1528 if ( !$rev->isCurrent() ) {
1529 $editQuery['oldid'] = $rev->getId();
1530 }
1531
1532 $key = $title->quickUserCan( 'edit', $user ) ? 'editold' : 'viewsourceold';
1533 $msg = $this->msg( $key )->escaped();
1534 $editLink = $this->msg( 'parentheses' )->rawParams(
1535 Linker::linkKnown( $title, $msg, [], $editQuery ) )->escaped();
1536 $header .= ' ' . Html::rawElement(
1537 'span',
1538 [ 'class' => 'mw-diff-edit' ],
1539 $editLink
1540 );
1541 if ( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
1542 $header = Html::rawElement(
1543 'span',
1544 [ 'class' => 'history-deleted' ],
1545 $header
1546 );
1547 }
1548 } else {
1549 $header = Html::rawElement( 'span', [ 'class' => 'history-deleted' ], $header );
1550 }
1551
1552 return $header;
1553 }
1554
1555 /**
1556 * Add the header to a diff body
1557 *
1558 * @param string $diff Diff body
1559 * @param string $otitle Old revision header
1560 * @param string $ntitle New revision header
1561 * @param string $multi Notice telling user that there are intermediate
1562 * revisions between the ones being compared
1563 * @param string $notice Other notices, e.g. that user is viewing deleted content
1564 *
1565 * @return string
1566 */
1567 public function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
1568 // shared.css sets diff in interface language/dir, but the actual content
1569 // is often in a different language, mostly the page content language/dir
1570 $header = Html::openElement( 'table', [
1571 'class' => [ 'diff', 'diff-contentalign-' . $this->getDiffLang()->alignStart() ],
1572 'data-mw' => 'interface',
1573 ] );
1574 $userLang = htmlspecialchars( $this->getLanguage()->getHtmlCode() );
1575
1576 if ( !$diff && !$otitle ) {
1577 $header .= "
1578 <tr class=\"diff-title\" lang=\"{$userLang}\">
1579 <td class=\"diff-ntitle\">{$ntitle}</td>
1580 </tr>";
1581 $multiColspan = 1;
1582 } else {
1583 if ( $diff ) { // Safari/Chrome show broken output if cols not used
1584 $header .= "
1585 <col class=\"diff-marker\" />
1586 <col class=\"diff-content\" />
1587 <col class=\"diff-marker\" />
1588 <col class=\"diff-content\" />";
1589 $colspan = 2;
1590 $multiColspan = 4;
1591 } else {
1592 $colspan = 1;
1593 $multiColspan = 2;
1594 }
1595 if ( $otitle || $ntitle ) {
1596 $header .= "
1597 <tr class=\"diff-title\" lang=\"{$userLang}\">
1598 <td colspan=\"$colspan\" class=\"diff-otitle\">{$otitle}</td>
1599 <td colspan=\"$colspan\" class=\"diff-ntitle\">{$ntitle}</td>
1600 </tr>";
1601 }
1602 }
1603
1604 if ( $multi != '' ) {
1605 $header .= "<tr><td colspan=\"{$multiColspan}\" " .
1606 "class=\"diff-multi\" lang=\"{$userLang}\">{$multi}</td></tr>";
1607 }
1608 if ( $notice != '' ) {
1609 $header .= "<tr><td colspan=\"{$multiColspan}\" " .
1610 "class=\"diff-notice\" lang=\"{$userLang}\">{$notice}</td></tr>";
1611 }
1612
1613 return $header . $diff . "</table>";
1614 }
1615
1616 /**
1617 * Use specified text instead of loading from the database
1618 * @param Content $oldContent
1619 * @param Content $newContent
1620 * @since 1.21
1621 * @deprecated since 1.32, use setRevisions or ContentHandler::getSlotDiffRenderer.
1622 */
1623 public function setContent( Content $oldContent, Content $newContent ) {
1624 $this->mOldContent = $oldContent;
1625 $this->mNewContent = $newContent;
1626
1627 $this->mTextLoaded = 2;
1628 $this->mRevisionsLoaded = true;
1629 $this->isContentOverridden = true;
1630 $this->slotDiffRenderers = null;
1631 }
1632
1633 /**
1634 * Use specified text instead of loading from the database.
1635 * @param RevisionRecord|null $oldRevision
1636 * @param RevisionRecord $newRevision
1637 */
1638 public function setRevisions(
1639 RevisionRecord $oldRevision = null, RevisionRecord $newRevision
1640 ) {
1641 if ( $oldRevision ) {
1642 $this->mOldRev = new Revision( $oldRevision );
1643 $this->mOldid = $oldRevision->getId();
1644 $this->mOldPage = Title::newFromLinkTarget( $oldRevision->getPageAsLinkTarget() );
1645 // This method is meant for edit diffs and such so there is no reason to provide a
1646 // revision that's not readable to the user, but check it just in case.
1647 $this->mOldContent = $oldRevision->getContent( SlotRecord::MAIN,
1648 RevisionRecord::FOR_THIS_USER, $this->getUser() );
1649 } else {
1650 $this->mOldPage = null;
1651 $this->mOldRev = $this->mOldid = false;
1652 }
1653 $this->mNewRev = new Revision( $newRevision );
1654 $this->mNewid = $newRevision->getId();
1655 $this->mNewPage = Title::newFromLinkTarget( $newRevision->getPageAsLinkTarget() );
1656 $this->mNewContent = $newRevision->getContent( SlotRecord::MAIN,
1657 RevisionRecord::FOR_THIS_USER, $this->getUser() );
1658
1659 $this->mRevisionsIdsLoaded = $this->mRevisionsLoaded = true;
1660 $this->mTextLoaded = $oldRevision ? 2 : 1;
1661 $this->isContentOverridden = false;
1662 $this->slotDiffRenderers = null;
1663 }
1664
1665 /**
1666 * Set the language in which the diff text is written
1667 *
1668 * @param Language $lang
1669 * @since 1.19
1670 */
1671 public function setTextLanguage( Language $lang ) {
1672 $this->mDiffLang = $lang;
1673 }
1674
1675 /**
1676 * Maps a revision pair definition as accepted by DifferenceEngine constructor
1677 * to a pair of actual integers representing revision ids.
1678 *
1679 * @param int $old Revision id, e.g. from URL parameter 'oldid'
1680 * @param int|string $new Revision id or strings 'next' or 'prev', e.g. from URL parameter 'diff'
1681 *
1682 * @return array List of two revision ids, older first, later second.
1683 * Zero signifies invalid argument passed.
1684 * false signifies that there is no previous/next revision ($old is the oldest/newest one).
1685 */
1686 public function mapDiffPrevNext( $old, $new ) {
1687 if ( $new === 'prev' ) {
1688 // Show diff between revision $old and the previous one. Get previous one from DB.
1689 $newid = intval( $old );
1690 $oldid = $this->getTitle()->getPreviousRevisionID( $newid );
1691 } elseif ( $new === 'next' ) {
1692 // Show diff between revision $old and the next one. Get next one from DB.
1693 $oldid = intval( $old );
1694 $newid = $this->getTitle()->getNextRevisionID( $oldid );
1695 } else {
1696 $oldid = intval( $old );
1697 $newid = intval( $new );
1698 }
1699
1700 return [ $oldid, $newid ];
1701 }
1702
1703 /**
1704 * Load revision IDs
1705 */
1706 private function loadRevisionIds() {
1707 if ( $this->mRevisionsIdsLoaded ) {
1708 return;
1709 }
1710
1711 $this->mRevisionsIdsLoaded = true;
1712
1713 $old = $this->mOldid;
1714 $new = $this->mNewid;
1715
1716 list( $this->mOldid, $this->mNewid ) = self::mapDiffPrevNext( $old, $new );
1717 if ( $new === 'next' && $this->mNewid === false ) {
1718 # if no result, NewId points to the newest old revision. The only newer
1719 # revision is cur, which is "0".
1720 $this->mNewid = 0;
1721 }
1722
1723 Hooks::run(
1724 'NewDifferenceEngine',
1725 [ $this->getTitle(), &$this->mOldid, &$this->mNewid, $old, $new ]
1726 );
1727 }
1728
1729 /**
1730 * Load revision metadata for the specified revisions. If newid is 0, then compare
1731 * the old revision in oldid to the current revision of the current page (as defined
1732 * by the request context); if oldid is 0, then compare the revision in newid to the
1733 * immediately previous one.
1734 *
1735 * If oldid is false, leave the corresponding revision object set to false. This can
1736 * happen with 'diff=prev' pointing to a non-existent revision, and is also used directly
1737 * by the API.
1738 *
1739 * @return bool Whether both revisions were loaded successfully. Setting mOldRev
1740 * to false counts as successful loading.
1741 */
1742 public function loadRevisionData() {
1743 if ( $this->mRevisionsLoaded ) {
1744 return $this->isContentOverridden || ( $this->mOldRev !== null && $this->mNewRev !== null );
1745 }
1746
1747 // Whether it succeeds or fails, we don't want to try again
1748 $this->mRevisionsLoaded = true;
1749
1750 $this->loadRevisionIds();
1751
1752 // Load the new revision object
1753 if ( $this->mNewid ) {
1754 $this->mNewRev = Revision::newFromId( $this->mNewid );
1755 } else {
1756 $this->mNewRev = Revision::newFromTitle(
1757 $this->getTitle(),
1758 false,
1759 Revision::READ_NORMAL
1760 );
1761 }
1762
1763 if ( !$this->mNewRev instanceof Revision ) {
1764 return false;
1765 }
1766
1767 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1768 $this->mNewid = $this->mNewRev->getId();
1769 if ( $this->mNewid ) {
1770 $this->mNewPage = $this->mNewRev->getTitle();
1771 } else {
1772 $this->mNewPage = null;
1773 }
1774
1775 // Load the old revision object
1776 $this->mOldRev = false;
1777 if ( $this->mOldid ) {
1778 $this->mOldRev = Revision::newFromId( $this->mOldid );
1779 } elseif ( $this->mOldid === 0 ) {
1780 $rev = $this->mNewRev->getPrevious();
1781 if ( $rev ) {
1782 $this->mOldid = $rev->getId();
1783 $this->mOldRev = $rev;
1784 } else {
1785 // No previous revision; mark to show as first-version only.
1786 $this->mOldid = false;
1787 $this->mOldRev = false;
1788 }
1789 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1790
1791 if ( is_null( $this->mOldRev ) ) {
1792 return false;
1793 }
1794
1795 if ( $this->mOldRev && $this->mOldRev->getId() ) {
1796 $this->mOldPage = $this->mOldRev->getTitle();
1797 } else {
1798 $this->mOldPage = null;
1799 }
1800
1801 // Load tags information for both revisions
1802 $dbr = wfGetDB( DB_REPLICA );
1803 $changeTagDefStore = MediaWikiServices::getInstance()->getChangeTagDefStore();
1804 if ( $this->mOldid !== false ) {
1805 $tagIds = $dbr->selectFieldValues(
1806 'change_tag',
1807 'ct_tag_id',
1808 [ 'ct_rev_id' => $this->mOldid ],
1809 __METHOD__
1810 );
1811 $tags = [];
1812 foreach ( $tagIds as $tagId ) {
1813 try {
1814 $tags[] = $changeTagDefStore->getName( (int)$tagId );
1815 } catch ( NameTableAccessException $exception ) {
1816 continue;
1817 }
1818 }
1819 $this->mOldTags = implode( ',', $tags );
1820 } else {
1821 $this->mOldTags = false;
1822 }
1823
1824 $tagIds = $dbr->selectFieldValues(
1825 'change_tag',
1826 'ct_tag_id',
1827 [ 'ct_rev_id' => $this->mNewid ],
1828 __METHOD__
1829 );
1830 $tags = [];
1831 foreach ( $tagIds as $tagId ) {
1832 try {
1833 $tags[] = $changeTagDefStore->getName( (int)$tagId );
1834 } catch ( NameTableAccessException $exception ) {
1835 continue;
1836 }
1837 }
1838 $this->mNewTags = implode( ',', $tags );
1839
1840 return true;
1841 }
1842
1843 /**
1844 * Load the text of the revisions, as well as revision data.
1845 * When the old revision is missing (mOldRev is false), loading mOldContent is not attempted.
1846 *
1847 * @return bool Whether the content of both revisions could be loaded successfully.
1848 * (When mOldRev is false, that still counts as a success.)
1849 *
1850 */
1851 public function loadText() {
1852 if ( $this->mTextLoaded == 2 ) {
1853 return $this->loadRevisionData() && ( $this->mOldRev === false || $this->mOldContent )
1854 && $this->mNewContent;
1855 }
1856
1857 // Whether it succeeds or fails, we don't want to try again
1858 $this->mTextLoaded = 2;
1859
1860 if ( !$this->loadRevisionData() ) {
1861 return false;
1862 }
1863
1864 if ( $this->mOldRev ) {
1865 $this->mOldContent = $this->mOldRev->getContent( Revision::FOR_THIS_USER, $this->getUser() );
1866 if ( $this->mOldContent === null ) {
1867 return false;
1868 }
1869 }
1870
1871 $this->mNewContent = $this->mNewRev->getContent( Revision::FOR_THIS_USER, $this->getUser() );
1872 Hooks::run( 'DifferenceEngineLoadTextAfterNewContentIsLoaded', [ $this ] );
1873 if ( $this->mNewContent === null ) {
1874 return false;
1875 }
1876
1877 return true;
1878 }
1879
1880 /**
1881 * Load the text of the new revision, not the old one
1882 *
1883 * @return bool Whether the content of the new revision could be loaded successfully.
1884 */
1885 public function loadNewText() {
1886 if ( $this->mTextLoaded >= 1 ) {
1887 return $this->loadRevisionData();
1888 }
1889
1890 $this->mTextLoaded = 1;
1891
1892 if ( !$this->loadRevisionData() ) {
1893 return false;
1894 }
1895
1896 $this->mNewContent = $this->mNewRev->getContent( Revision::FOR_THIS_USER, $this->getUser() );
1897
1898 Hooks::run( 'DifferenceEngineAfterLoadNewText', [ $this ] );
1899
1900 return true;
1901 }
1902
1903 }