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