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