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