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