Merge "Change 'editfont' default preference to 'monospace'"
[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 use MediaWiki\MediaWikiServices;
24
25 /** @deprecated use class constant instead */
26 define( 'MW_DIFF_VERSION', '1.11a' );
27
28 /**
29 * @todo document
30 * @ingroup DifferenceEngine
31 */
32 class DifferenceEngine extends ContextSource {
33 /**
34 * Constant to indicate diff cache compatibility.
35 * Bump this when changing the diff formatting in a way that
36 * fixes important bugs or such to force cached diff views to
37 * clear.
38 */
39 const DIFF_VERSION = MW_DIFF_VERSION;
40
41 /** @var int */
42 public $mOldid;
43
44 /** @var int */
45 public $mNewid;
46
47 private $mOldTags;
48 private $mNewTags;
49
50 /** @var Content */
51 public $mOldContent;
52
53 /** @var Content */
54 public $mNewContent;
55
56 /** @var Language */
57 protected $mDiffLang;
58
59 /** @var Title */
60 public $mOldPage;
61
62 /** @var Title */
63 public $mNewPage;
64
65 /** @var Revision */
66 public $mOldRev;
67
68 /** @var Revision */
69 public $mNewRev;
70
71 /** @var bool Have the revisions IDs been loaded */
72 private $mRevisionsIdsLoaded = false;
73
74 /** @var bool Have the revisions been loaded */
75 public $mRevisionsLoaded = false;
76
77 /** @var int How many text blobs have been loaded, 0, 1 or 2? */
78 public $mTextLoaded = 0;
79
80 /** @var bool Was the diff fetched from cache? */
81 public $mCacheHit = false;
82
83 /**
84 * Set this to true to add debug info to the HTML output.
85 * Warning: this may cause RSS readers to spuriously mark articles as "new"
86 * (T22601)
87 */
88 public $enableDebugComment = false;
89
90 /** @var bool If true, line X is not displayed when X is 1, for example
91 * to increase readability and conserve space with many small diffs.
92 */
93 protected $mReducedLineNumbers = false;
94
95 /** @var string Link to action=markpatrolled */
96 protected $mMarkPatrolledLink = null;
97
98 /** @var bool Show rev_deleted content if allowed */
99 protected $unhide = false;
100
101 /** @var bool Refresh the diff cache */
102 protected $mRefreshCache = false;
103
104 /**#@-*/
105
106 /**
107 * @param IContextSource $context Context to use, anything else will be ignored
108 * @param int $old Old ID we want to show and diff with.
109 * @param string|int $new Either revision ID or 'prev' or 'next'. Default: 0.
110 * @param int $rcid Deprecated, no longer used!
111 * @param bool $refreshCache If set, refreshes the diff cache
112 * @param bool $unhide If set, allow viewing deleted revs
113 */
114 public function __construct( $context = null, $old = 0, $new = 0, $rcid = 0,
115 $refreshCache = false, $unhide = false
116 ) {
117 if ( $context instanceof IContextSource ) {
118 $this->setContext( $context );
119 }
120
121 wfDebug( "DifferenceEngine old '$old' new '$new' rcid '$rcid'\n" );
122
123 $this->mOldid = $old;
124 $this->mNewid = $new;
125 $this->mRefreshCache = $refreshCache;
126 $this->unhide = $unhide;
127 }
128
129 /**
130 * @param bool $value
131 */
132 public function setReducedLineNumbers( $value = true ) {
133 $this->mReducedLineNumbers = $value;
134 }
135
136 /**
137 * @return Language
138 */
139 public function getDiffLang() {
140 if ( $this->mDiffLang === null ) {
141 # Default language in which the diff text is written.
142 $this->mDiffLang = $this->getTitle()->getPageLanguage();
143 }
144
145 return $this->mDiffLang;
146 }
147
148 /**
149 * @return bool
150 */
151 public function wasCacheHit() {
152 return $this->mCacheHit;
153 }
154
155 /**
156 * @return int
157 */
158 public function getOldid() {
159 $this->loadRevisionIds();
160
161 return $this->mOldid;
162 }
163
164 /**
165 * @return bool|int
166 */
167 public function getNewid() {
168 $this->loadRevisionIds();
169
170 return $this->mNewid;
171 }
172
173 /**
174 * Look up a special:Undelete link to the given deleted revision id,
175 * as a workaround for being unable to load deleted diffs in currently.
176 *
177 * @param int $id Revision ID
178 *
179 * @return string|bool Link HTML or false
180 */
181 public function deletedLink( $id ) {
182 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
183 $dbr = wfGetDB( DB_REPLICA );
184 $row = $dbr->selectRow( 'archive', '*',
185 [ 'ar_rev_id' => $id ],
186 __METHOD__ );
187 if ( $row ) {
188 $rev = Revision::newFromArchiveRow( $row );
189 $title = Title::makeTitleSafe( $row->ar_namespace, $row->ar_title );
190
191 return SpecialPage::getTitleFor( 'Undelete' )->getFullURL( [
192 'target' => $title->getPrefixedText(),
193 'timestamp' => $rev->getTimestamp()
194 ] );
195 }
196 }
197
198 return false;
199 }
200
201 /**
202 * Build a wikitext link toward a deleted revision, if viewable.
203 *
204 * @param int $id Revision ID
205 *
206 * @return string Wikitext fragment
207 */
208 public function deletedIdMarker( $id ) {
209 $link = $this->deletedLink( $id );
210 if ( $link ) {
211 return "[$link $id]";
212 } else {
213 return (string)$id;
214 }
215 }
216
217 private function showMissingRevision() {
218 $out = $this->getOutput();
219
220 $missing = [];
221 if ( $this->mOldRev === null ||
222 ( $this->mOldRev && $this->mOldContent === null )
223 ) {
224 $missing[] = $this->deletedIdMarker( $this->mOldid );
225 }
226 if ( $this->mNewRev === null ||
227 ( $this->mNewRev && $this->mNewContent === null )
228 ) {
229 $missing[] = $this->deletedIdMarker( $this->mNewid );
230 }
231
232 $out->setPageTitle( $this->msg( 'errorpagetitle' ) );
233 $msg = $this->msg( 'difference-missing-revision' )
234 ->params( $this->getLanguage()->listToText( $missing ) )
235 ->numParams( count( $missing ) )
236 ->parseAsBlock();
237 $out->addHTML( $msg );
238 }
239
240 public function showDiffPage( $diffOnly = false ) {
241 # Allow frames except in certain special cases
242 $out = $this->getOutput();
243 $out->allowClickjacking();
244 $out->setRobotPolicy( 'noindex,nofollow' );
245
246 // Allow extensions to add any extra output here
247 Hooks::run( 'DifferenceEngineShowDiffPage', [ $out ] );
248
249 if ( !$this->loadRevisionData() ) {
250 if ( Hooks::run( 'DifferenceEngineShowDiffPageMaybeShowMissingRevision', [ $this ] ) ) {
251 $this->showMissingRevision();
252 }
253 return;
254 }
255
256 $user = $this->getUser();
257 $permErrors = $this->mNewPage->getUserPermissionsErrors( 'read', $user );
258 if ( $this->mOldPage ) { # mOldPage might not be set, see below.
259 $permErrors = wfMergeErrorArrays( $permErrors,
260 $this->mOldPage->getUserPermissionsErrors( 'read', $user ) );
261 }
262 if ( count( $permErrors ) ) {
263 throw new PermissionsError( 'read', $permErrors );
264 }
265
266 $rollback = '';
267
268 $query = [];
269 # Carry over 'diffonly' param via navigation links
270 if ( $diffOnly != $user->getBoolOption( 'diffonly' ) ) {
271 $query['diffonly'] = $diffOnly;
272 }
273 # Cascade unhide param in links for easy deletion browsing
274 if ( $this->unhide ) {
275 $query['unhide'] = 1;
276 }
277
278 # Check if one of the revisions is deleted/suppressed
279 $deleted = $suppressed = false;
280 $allowed = $this->mNewRev->userCan( Revision::DELETED_TEXT, $user );
281
282 $revisionTools = [];
283
284 # mOldRev is false if the difference engine is called with a "vague" query for
285 # a diff between a version V and its previous version V' AND the version V
286 # is the first version of that article. In that case, V' does not exist.
287 if ( $this->mOldRev === false ) {
288 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage->getPrefixedText() ) );
289 $samePage = true;
290 $oldHeader = '';
291 // Allow extensions to change the $oldHeader variable
292 Hooks::run( 'DifferenceEngineOldHeaderNoOldRev', [ &$oldHeader ] );
293 } else {
294 Hooks::run( 'DiffViewHeader', [ $this, $this->mOldRev, $this->mNewRev ] );
295
296 if ( $this->mNewPage->equals( $this->mOldPage ) ) {
297 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage->getPrefixedText() ) );
298 $samePage = true;
299 } else {
300 $out->setPageTitle( $this->msg( 'difference-title-multipage',
301 $this->mOldPage->getPrefixedText(), $this->mNewPage->getPrefixedText() ) );
302 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
303 $samePage = false;
304 }
305
306 if ( $samePage && $this->mNewPage->quickUserCan( 'edit', $user ) ) {
307 if ( $this->mNewRev->isCurrent() && $this->mNewPage->userCan( 'rollback', $user ) ) {
308 $rollbackLink = Linker::generateRollback( $this->mNewRev, $this->getContext() );
309 if ( $rollbackLink ) {
310 $out->preventClickjacking();
311 $rollback = '&#160;&#160;&#160;' . $rollbackLink;
312 }
313 }
314
315 if ( !$this->mOldRev->isDeleted( Revision::DELETED_TEXT ) &&
316 !$this->mNewRev->isDeleted( Revision::DELETED_TEXT )
317 ) {
318 $undoLink = Html::element( 'a', [
319 'href' => $this->mNewPage->getLocalURL( [
320 'action' => 'edit',
321 'undoafter' => $this->mOldid,
322 'undo' => $this->mNewid
323 ] ),
324 'title' => Linker::titleAttrib( 'undo' ),
325 ],
326 $this->msg( 'editundo' )->text()
327 );
328 $revisionTools['mw-diff-undo'] = $undoLink;
329 }
330 }
331
332 # Make "previous revision link"
333 if ( $samePage && $this->mOldRev->getPrevious() ) {
334 $prevlink = Linker::linkKnown(
335 $this->mOldPage,
336 $this->msg( 'previousdiff' )->escaped(),
337 [ 'id' => 'differences-prevlink' ],
338 [ 'diff' => 'prev', 'oldid' => $this->mOldid ] + $query
339 );
340 } else {
341 $prevlink = '&#160;';
342 }
343
344 if ( $this->mOldRev->isMinor() ) {
345 $oldminor = ChangesList::flag( 'minor' );
346 } else {
347 $oldminor = '';
348 }
349
350 $ldel = $this->revisionDeleteLink( $this->mOldRev );
351 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev, 'complete' );
352 $oldChangeTags = ChangeTags::formatSummaryRow( $this->mOldTags, 'diff', $this->getContext() );
353
354 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
355 '<div id="mw-diff-otitle2">' .
356 Linker::revUserTools( $this->mOldRev, !$this->unhide ) . '</div>' .
357 '<div id="mw-diff-otitle3">' . $oldminor .
358 Linker::revComment( $this->mOldRev, !$diffOnly, !$this->unhide ) . $ldel . '</div>' .
359 '<div id="mw-diff-otitle5">' . $oldChangeTags[0] . '</div>' .
360 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
361
362 // Allow extensions to change the $oldHeader variable
363 Hooks::run( 'DifferenceEngineOldHeader', [ $this, &$oldHeader, $prevlink, $oldminor,
364 $diffOnly, $ldel, $this->unhide ] );
365
366 if ( $this->mOldRev->isDeleted( Revision::DELETED_TEXT ) ) {
367 $deleted = true; // old revisions text is hidden
368 if ( $this->mOldRev->isDeleted( Revision::DELETED_RESTRICTED ) ) {
369 $suppressed = true; // also suppressed
370 }
371 }
372
373 # Check if this user can see the revisions
374 if ( !$this->mOldRev->userCan( Revision::DELETED_TEXT, $user ) ) {
375 $allowed = false;
376 }
377 }
378
379 $out->addJsConfigVars( [
380 'wgDiffOldId' => $this->mOldid,
381 'wgDiffNewId' => $this->mNewid,
382 ] );
383
384 # Make "next revision link"
385 # Skip next link on the top revision
386 if ( $samePage && !$this->mNewRev->isCurrent() ) {
387 $nextlink = Linker::linkKnown(
388 $this->mNewPage,
389 $this->msg( 'nextdiff' )->escaped(),
390 [ 'id' => 'differences-nextlink' ],
391 [ 'diff' => 'next', 'oldid' => $this->mNewid ] + $query
392 );
393 } else {
394 $nextlink = '&#160;';
395 }
396
397 if ( $this->mNewRev->isMinor() ) {
398 $newminor = ChangesList::flag( 'minor' );
399 } else {
400 $newminor = '';
401 }
402
403 # Handle RevisionDelete links...
404 $rdel = $this->revisionDeleteLink( $this->mNewRev );
405
406 # Allow extensions to define their own revision tools
407 Hooks::run( 'DiffRevisionTools',
408 [ $this->mNewRev, &$revisionTools, $this->mOldRev, $user ] );
409 $formattedRevisionTools = [];
410 // Put each one in parentheses (poor man's button)
411 foreach ( $revisionTools as $key => $tool ) {
412 $toolClass = is_string( $key ) ? $key : 'mw-diff-tool';
413 $element = Html::rawElement(
414 'span',
415 [ 'class' => $toolClass ],
416 $this->msg( 'parentheses' )->rawParams( $tool )->escaped()
417 );
418 $formattedRevisionTools[] = $element;
419 }
420 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev, 'complete' ) .
421 ' ' . implode( ' ', $formattedRevisionTools );
422 $newChangeTags = ChangeTags::formatSummaryRow( $this->mNewTags, 'diff', $this->getContext() );
423
424 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
425 '<div id="mw-diff-ntitle2">' . Linker::revUserTools( $this->mNewRev, !$this->unhide ) .
426 " $rollback</div>" .
427 '<div id="mw-diff-ntitle3">' . $newminor .
428 Linker::revComment( $this->mNewRev, !$diffOnly, !$this->unhide ) . $rdel . '</div>' .
429 '<div id="mw-diff-ntitle5">' . $newChangeTags[0] . '</div>' .
430 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
431
432 // Allow extensions to change the $newHeader variable
433 Hooks::run( 'DifferenceEngineNewHeader', [ $this, &$newHeader, $formattedRevisionTools,
434 $nextlink, $rollback, $newminor, $diffOnly, $rdel, $this->unhide ] );
435
436 if ( $this->mNewRev->isDeleted( Revision::DELETED_TEXT ) ) {
437 $deleted = true; // new revisions text is hidden
438 if ( $this->mNewRev->isDeleted( Revision::DELETED_RESTRICTED ) ) {
439 $suppressed = true; // also suppressed
440 }
441 }
442
443 # If the diff cannot be shown due to a deleted revision, then output
444 # the diff header and links to unhide (if available)...
445 if ( $deleted && ( !$this->unhide || !$allowed ) ) {
446 $this->showDiffStyle();
447 $multi = $this->getMultiNotice();
448 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
449 if ( !$allowed ) {
450 $msg = $suppressed ? 'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
451 # Give explanation for why revision is not visible
452 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
453 [ $msg ] );
454 } else {
455 # Give explanation and add a link to view the diff...
456 $query = $this->getRequest()->appendQueryValue( 'unhide', '1' );
457 $link = $this->getTitle()->getFullURL( $query );
458 $msg = $suppressed ? 'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
459 $out->wrapWikiMsg(
460 "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
461 [ $msg, $link ]
462 );
463 }
464 # Otherwise, output a regular diff...
465 } else {
466 # Add deletion notice if the user is viewing deleted content
467 $notice = '';
468 if ( $deleted ) {
469 $msg = $suppressed ? 'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
470 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" .
471 $this->msg( $msg )->parse() .
472 "</div>\n";
473 }
474 $this->showDiff( $oldHeader, $newHeader, $notice );
475 if ( !$diffOnly ) {
476 $this->renderNewRevision();
477 }
478 }
479 }
480
481 /**
482 * Build a link to mark a change as patrolled.
483 *
484 * Returns empty string if there's either no revision to patrol or the user is not allowed to.
485 * Side effect: When the patrol link is build, this method will call
486 * OutputPage::preventClickjacking() and load mediawiki.page.patrol.ajax.
487 *
488 * @return string HTML or empty string
489 */
490 public function markPatrolledLink() {
491 if ( $this->mMarkPatrolledLink === null ) {
492 $linkInfo = $this->getMarkPatrolledLinkInfo();
493 // If false, there is no patrol link needed/allowed
494 if ( !$linkInfo ) {
495 $this->mMarkPatrolledLink = '';
496 } else {
497 $this->mMarkPatrolledLink = ' <span class="patrollink" data-mw="interface">[' .
498 Linker::linkKnown(
499 $this->mNewPage,
500 $this->msg( 'markaspatrolleddiff' )->escaped(),
501 [],
502 [
503 'action' => 'markpatrolled',
504 'rcid' => $linkInfo['rcid'],
505 ]
506 ) . ']</span>';
507 // Allow extensions to change the markpatrolled link
508 Hooks::run( 'DifferenceEngineMarkPatrolledLink', [ $this,
509 &$this->mMarkPatrolledLink, $linkInfo['rcid'] ] );
510 }
511 }
512 return $this->mMarkPatrolledLink;
513 }
514
515 /**
516 * Returns an array of meta data needed to build a "mark as patrolled" link and
517 * adds the mediawiki.page.patrol.ajax to the output.
518 *
519 * @return array|false An array of meta data for a patrol link (rcid only)
520 * or false if no link is needed
521 */
522 protected function getMarkPatrolledLinkInfo() {
523 global $wgUseRCPatrol, $wgEnableAPI, $wgEnableWriteAPI;
524
525 $user = $this->getUser();
526
527 // Prepare a change patrol link, if applicable
528 if (
529 // Is patrolling enabled and the user allowed to?
530 $wgUseRCPatrol && $this->mNewPage->quickUserCan( 'patrol', $user ) &&
531 // Only do this if the revision isn't more than 6 hours older
532 // than the Max RC age (6h because the RC might not be cleaned out regularly)
533 RecentChange::isInRCLifespan( $this->mNewRev->getTimestamp(), 21600 )
534 ) {
535 // Look for an unpatrolled change corresponding to this diff
536 $db = wfGetDB( DB_REPLICA );
537 $change = RecentChange::newFromConds(
538 [
539 'rc_timestamp' => $db->timestamp( $this->mNewRev->getTimestamp() ),
540 'rc_this_oldid' => $this->mNewid,
541 'rc_patrolled' => 0
542 ],
543 __METHOD__
544 );
545
546 if ( $change && !$change->getPerformer()->equals( $user ) ) {
547 $rcid = $change->getAttribute( 'rc_id' );
548 } else {
549 // None found or the page has been created by the current user.
550 // If the user could patrol this it already would be patrolled
551 $rcid = 0;
552 }
553
554 // Allow extensions to possibly change the rcid here
555 // For example the rcid might be set to zero due to the user
556 // being the same as the performer of the change but an extension
557 // might still want to show it under certain conditions
558 Hooks::run( 'DifferenceEngineMarkPatrolledRCID', [ &$rcid, $this, $change, $user ] );
559
560 // Build the link
561 if ( $rcid ) {
562 $this->getOutput()->preventClickjacking();
563 if ( $wgEnableAPI && $wgEnableWriteAPI
564 && $user->isAllowed( 'writeapi' )
565 ) {
566 $this->getOutput()->addModules( 'mediawiki.page.patrol.ajax' );
567 }
568
569 return [
570 'rcid' => $rcid,
571 ];
572 }
573 }
574
575 // No mark as patrolled link applicable
576 return false;
577 }
578
579 /**
580 * @param Revision $rev
581 *
582 * @return string
583 */
584 protected function revisionDeleteLink( $rev ) {
585 $link = Linker::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
586 if ( $link !== '' ) {
587 $link = '&#160;&#160;&#160;' . $link . ' ';
588 }
589
590 return $link;
591 }
592
593 /**
594 * Show the new revision of the page.
595 */
596 public function renderNewRevision() {
597 $out = $this->getOutput();
598 $revHeader = $this->getRevisionHeader( $this->mNewRev );
599 # Add "current version as of X" title
600 $out->addHTML( "<hr class='diff-hr' id='mw-oldid' />
601 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
602 # Page content may be handled by a hooked call instead...
603 # @codingStandardsIgnoreStart Ignoring long lines.
604 if ( Hooks::run( 'ArticleContentOnDiff', [ $this, $out ] ) ) {
605 $this->loadNewText();
606 $out->setRevisionId( $this->mNewid );
607 $out->setRevisionTimestamp( $this->mNewRev->getTimestamp() );
608 $out->setArticleFlag( true );
609
610 if ( !Hooks::run( 'ArticleContentViewCustom', [ $this->mNewContent, $this->mNewPage, $out ] ) ) {
611 // Handled by extension
612 } else {
613 // Normal page
614 if ( $this->getTitle()->equals( $this->mNewPage ) ) {
615 // If the Title stored in the context is the same as the one
616 // of the new revision, we can use its associated WikiPage
617 // object.
618 $wikiPage = $this->getWikiPage();
619 } else {
620 // Otherwise we need to create our own WikiPage object
621 $wikiPage = WikiPage::factory( $this->mNewPage );
622 }
623
624 $parserOutput = $this->getParserOutput( $wikiPage, $this->mNewRev );
625
626 # WikiPage::getParserOutput() should not return false, but just in case
627 if ( $parserOutput ) {
628 // Allow extensions to change parser output here
629 if ( Hooks::run( 'DifferenceEngineRenderRevisionAddParserOutput', [ $this, $out, $parserOutput, $wikiPage ] ) ) {
630 $out->addParserOutput( $parserOutput );
631 }
632 }
633 }
634 }
635 # @codingStandardsIgnoreEnd
636
637 // Allow extensions to optionally not show the final patrolled link
638 if ( Hooks::run( 'DifferenceEngineRenderRevisionShowFinalPatrolLink' ) ) {
639 # Add redundant patrol link on bottom...
640 $out->addHTML( $this->markPatrolledLink() );
641 }
642 }
643
644 protected function getParserOutput( WikiPage $page, Revision $rev ) {
645 $parserOptions = $page->makeParserOptions( $this->getContext() );
646
647 if ( !$rev->isCurrent() || !$rev->getTitle()->quickUserCan( 'edit', $this->getUser() ) ) {
648 $parserOptions->setEditSection( false );
649 }
650
651 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
652
653 return $parserOutput;
654 }
655
656 /**
657 * Get the diff text, send it to the OutputPage object
658 * Returns false if the diff could not be generated, otherwise returns true
659 *
660 * @param string|bool $otitle Header for old text or false
661 * @param string|bool $ntitle Header for new text or false
662 * @param string $notice HTML between diff header and body
663 *
664 * @return bool
665 */
666 public function showDiff( $otitle, $ntitle, $notice = '' ) {
667 // Allow extensions to affect the output here
668 Hooks::run( 'DifferenceEngineShowDiff', [ $this ] );
669
670 $diff = $this->getDiff( $otitle, $ntitle, $notice );
671 if ( $diff === false ) {
672 $this->showMissingRevision();
673
674 return false;
675 } else {
676 $this->showDiffStyle();
677 $this->getOutput()->addHTML( $diff );
678
679 return true;
680 }
681 }
682
683 /**
684 * Add style sheets for diff display.
685 */
686 public function showDiffStyle() {
687 $this->getOutput()->addModuleStyles( 'mediawiki.diff.styles' );
688 }
689
690 /**
691 * Get complete diff table, including header
692 *
693 * @param string|bool $otitle Header for old text or false
694 * @param string|bool $ntitle Header for new text or false
695 * @param string $notice HTML between diff header and body
696 *
697 * @return mixed
698 */
699 public function getDiff( $otitle, $ntitle, $notice = '' ) {
700 $body = $this->getDiffBody();
701 if ( $body === false ) {
702 return false;
703 }
704
705 $multi = $this->getMultiNotice();
706 // Display a message when the diff is empty
707 if ( $body === '' ) {
708 $notice .= '<div class="mw-diff-empty">' .
709 $this->msg( 'diff-empty' )->parse() .
710 "</div>\n";
711 }
712
713 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
714 }
715
716 /**
717 * Get the diff table body, without header
718 *
719 * @return mixed (string/false)
720 */
721 public function getDiffBody() {
722 $this->mCacheHit = true;
723 // Check if the diff should be hidden from this user
724 if ( !$this->loadRevisionData() ) {
725 return false;
726 } elseif ( $this->mOldRev &&
727 !$this->mOldRev->userCan( Revision::DELETED_TEXT, $this->getUser() )
728 ) {
729 return false;
730 } elseif ( $this->mNewRev &&
731 !$this->mNewRev->userCan( Revision::DELETED_TEXT, $this->getUser() )
732 ) {
733 return false;
734 }
735 // Short-circuit
736 if ( $this->mOldRev === false || ( $this->mOldRev && $this->mNewRev
737 && $this->mOldRev->getId() == $this->mNewRev->getId() )
738 ) {
739 if ( Hooks::run( 'DifferenceEngineShowEmptyOldContent', [ $this ] ) ) {
740 return '';
741 }
742 }
743 // Cacheable?
744 $key = false;
745 $cache = ObjectCache::getMainWANInstance();
746 if ( $this->mOldid && $this->mNewid ) {
747 $key = $this->getDiffBodyCacheKey();
748
749 // Try cache
750 if ( !$this->mRefreshCache ) {
751 $difftext = $cache->get( $key );
752 if ( $difftext ) {
753 wfIncrStats( 'diff_cache.hit' );
754 $difftext = $this->localiseLineNumbers( $difftext );
755 $difftext .= "\n<!-- diff cache key $key -->\n";
756
757 return $difftext;
758 }
759 } // don't try to load but save the result
760 }
761 $this->mCacheHit = false;
762
763 // Loadtext is permission safe, this just clears out the diff
764 if ( !$this->loadText() ) {
765 return false;
766 }
767
768 $difftext = $this->generateContentDiffBody( $this->mOldContent, $this->mNewContent );
769
770 // Avoid PHP 7.1 warning from passing $this by reference
771 $diffEngine = $this;
772
773 // Save to cache for 7 days
774 if ( !Hooks::run( 'AbortDiffCache', [ &$diffEngine ] ) ) {
775 wfIncrStats( 'diff_cache.uncacheable' );
776 } elseif ( $key !== false && $difftext !== false ) {
777 wfIncrStats( 'diff_cache.miss' );
778 $cache->set( $key, $difftext, 7 * 86400 );
779 } else {
780 wfIncrStats( 'diff_cache.uncacheable' );
781 }
782 // Replace line numbers with the text in the user's language
783 if ( $difftext !== false ) {
784 $difftext = $this->localiseLineNumbers( $difftext );
785 }
786
787 return $difftext;
788 }
789
790 /**
791 * Returns the cache key for diff body text or content.
792 *
793 * @since 1.23
794 *
795 * @throws MWException
796 * @return string
797 */
798 protected function getDiffBodyCacheKey() {
799 if ( !$this->mOldid || !$this->mNewid ) {
800 throw new MWException( 'mOldid and mNewid must be set to get diff cache key.' );
801 }
802
803 return wfMemcKey( 'diff', 'version', self::DIFF_VERSION,
804 'oldid', $this->mOldid, 'newid', $this->mNewid );
805 }
806
807 /**
808 * Generate a diff, no caching.
809 *
810 * This implementation uses generateTextDiffBody() to generate a diff based on the default
811 * serialization of the given Content objects. This will fail if $old or $new are not
812 * instances of TextContent.
813 *
814 * Subclasses may override this to provide a different rendering for the diff,
815 * perhaps taking advantage of the content's native form. This is required for all content
816 * models that are not text based.
817 *
818 * @since 1.21
819 *
820 * @param Content $old Old content
821 * @param Content $new New content
822 *
823 * @throws MWException If old or new content is not an instance of TextContent.
824 * @return bool|string
825 */
826 public function generateContentDiffBody( Content $old, Content $new ) {
827 if ( !( $old instanceof TextContent ) ) {
828 throw new MWException( "Diff not implemented for " . get_class( $old ) . "; " .
829 "override generateContentDiffBody to fix this." );
830 }
831
832 if ( !( $new instanceof TextContent ) ) {
833 throw new MWException( "Diff not implemented for " . get_class( $new ) . "; "
834 . "override generateContentDiffBody to fix this." );
835 }
836
837 $otext = $old->serialize();
838 $ntext = $new->serialize();
839
840 return $this->generateTextDiffBody( $otext, $ntext );
841 }
842
843 /**
844 * Generate a diff, no caching
845 *
846 * @todo move this to TextDifferenceEngine, make DifferenceEngine abstract. At some point.
847 *
848 * @param string $otext Old text, must be already segmented
849 * @param string $ntext New text, must be already segmented
850 *
851 * @return bool|string
852 */
853 public function generateTextDiffBody( $otext, $ntext ) {
854 $diff = function () use ( $otext, $ntext ) {
855 $time = microtime( true );
856
857 $result = $this->textDiff( $otext, $ntext );
858
859 $time = intval( ( microtime( true ) - $time ) * 1000 );
860 MediaWikiServices::getInstance()->getStatsdDataFactory()->timing( 'diff_time', $time );
861 // Log requests slower than 99th percentile
862 if ( $time > 100 && $this->mOldPage && $this->mNewPage ) {
863 wfDebugLog( 'diff',
864 "$time ms diff: {$this->mOldid} -> {$this->mNewid} {$this->mNewPage}" );
865 }
866
867 return $result;
868 };
869
870 /**
871 * @param Status $status
872 * @throws FatalError
873 */
874 $error = function ( $status ) {
875 throw new FatalError( $status->getWikiText() );
876 };
877
878 // Use PoolCounter if the diff looks like it can be expensive
879 if ( strlen( $otext ) + strlen( $ntext ) > 20000 ) {
880 $work = new PoolCounterWorkViaCallback( 'diff',
881 md5( $otext ) . md5( $ntext ),
882 [ 'doWork' => $diff, 'error' => $error ]
883 );
884 return $work->execute();
885 }
886
887 return $diff();
888 }
889
890 /**
891 * Generates diff, to be wrapped internally in a logging/instrumentation
892 *
893 * @param string $otext Old text, must be already segmented
894 * @param string $ntext New text, must be already segmented
895 * @return bool|string
896 */
897 protected function textDiff( $otext, $ntext ) {
898 global $wgExternalDiffEngine, $wgContLang;
899
900 $otext = str_replace( "\r\n", "\n", $otext );
901 $ntext = str_replace( "\r\n", "\n", $ntext );
902
903 if ( $wgExternalDiffEngine == 'wikidiff' || $wgExternalDiffEngine == 'wikidiff3' ) {
904 wfDeprecated( "\$wgExternalDiffEngine = '{$wgExternalDiffEngine}'", '1.27' );
905 $wgExternalDiffEngine = false;
906 } elseif ( $wgExternalDiffEngine == 'wikidiff2' ) {
907 // Same as above, but with no deprecation warnings
908 $wgExternalDiffEngine = false;
909 } elseif ( !is_string( $wgExternalDiffEngine ) && $wgExternalDiffEngine !== false ) {
910 // And prevent people from shooting themselves in the foot...
911 wfWarn( '$wgExternalDiffEngine is set to a non-string value, forcing it to false' );
912 $wgExternalDiffEngine = false;
913 }
914
915 // Better external diff engine, the 2 may some day be dropped
916 // This one does the escaping and segmenting itself
917 if ( function_exists( 'wikidiff2_do_diff' ) && $wgExternalDiffEngine === false ) {
918 $wikidiff2Version = phpversion( 'wikidiff2' );
919 if (
920 $wikidiff2Version !== false &&
921 version_compare( $wikidiff2Version, '0.3.0', '>=' )
922 ) {
923 $text = wikidiff2_do_diff(
924 $otext,
925 $ntext,
926 2,
927 $this->getConfig()->get( 'WikiDiff2MovedParagraphDetectionCutoff' )
928 );
929 } else {
930 // Don't pass the 4th parameter for compatibility with older versions of wikidiff2
931 $text = wikidiff2_do_diff(
932 $otext,
933 $ntext,
934 2
935 );
936
937 // Log a warning in case the configuration value is set to not silently ignore it
938 if ( $this->getConfig()->get( 'WikiDiff2MovedParagraphDetectionCutoff' ) > 0 ) {
939 wfLogWarning( '$wgWikiDiff2MovedParagraphDetectionCutoff is set but has no
940 effect since the used version of WikiDiff2 does not support it.' );
941 }
942 }
943
944 $text .= $this->debug( 'wikidiff2' );
945
946 return $text;
947 } elseif ( $wgExternalDiffEngine !== false && is_executable( $wgExternalDiffEngine ) ) {
948 # Diff via the shell
949 $tmpDir = wfTempDir();
950 $tempName1 = tempnam( $tmpDir, 'diff_' );
951 $tempName2 = tempnam( $tmpDir, 'diff_' );
952
953 $tempFile1 = fopen( $tempName1, "w" );
954 if ( !$tempFile1 ) {
955 return false;
956 }
957 $tempFile2 = fopen( $tempName2, "w" );
958 if ( !$tempFile2 ) {
959 return false;
960 }
961 fwrite( $tempFile1, $otext );
962 fwrite( $tempFile2, $ntext );
963 fclose( $tempFile1 );
964 fclose( $tempFile2 );
965 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
966 $difftext = wfShellExec( $cmd );
967 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
968 unlink( $tempName1 );
969 unlink( $tempName2 );
970
971 return $difftext;
972 }
973
974 # Native PHP diff
975 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
976 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
977 $diffs = new Diff( $ota, $nta );
978 $formatter = new TableDiffFormatter();
979 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) );
980
981 return $difftext;
982 }
983
984 /**
985 * Generate a debug comment indicating diff generating time,
986 * server node, and generator backend.
987 *
988 * @param string $generator : What diff engine was used
989 *
990 * @return string
991 */
992 protected function debug( $generator = "internal" ) {
993 global $wgShowHostnames;
994 if ( !$this->enableDebugComment ) {
995 return '';
996 }
997 $data = [ $generator ];
998 if ( $wgShowHostnames ) {
999 $data[] = wfHostname();
1000 }
1001 $data[] = wfTimestamp( TS_DB );
1002
1003 return "<!-- diff generator: " .
1004 implode( " ", array_map( "htmlspecialchars", $data ) ) .
1005 " -->\n";
1006 }
1007
1008 /**
1009 * Replace line numbers with the text in the user's language
1010 *
1011 * @param string $text
1012 *
1013 * @return mixed
1014 */
1015 public function localiseLineNumbers( $text ) {
1016 return preg_replace_callback(
1017 '/<!--LINE (\d+)-->/',
1018 [ $this, 'localiseLineNumbersCb' ],
1019 $text
1020 );
1021 }
1022
1023 public function localiseLineNumbersCb( $matches ) {
1024 if ( $matches[1] === '1' && $this->mReducedLineNumbers ) {
1025 return '';
1026 }
1027
1028 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
1029 }
1030
1031 /**
1032 * If there are revisions between the ones being compared, return a note saying so.
1033 *
1034 * @return string
1035 */
1036 public function getMultiNotice() {
1037 if ( !is_object( $this->mOldRev ) || !is_object( $this->mNewRev ) ) {
1038 return '';
1039 } elseif ( !$this->mOldPage->equals( $this->mNewPage ) ) {
1040 // Comparing two different pages? Count would be meaningless.
1041 return '';
1042 }
1043
1044 if ( $this->mOldRev->getTimestamp() > $this->mNewRev->getTimestamp() ) {
1045 $oldRev = $this->mNewRev; // flip
1046 $newRev = $this->mOldRev; // flip
1047 } else { // normal case
1048 $oldRev = $this->mOldRev;
1049 $newRev = $this->mNewRev;
1050 }
1051
1052 // Sanity: don't show the notice if too many rows must be scanned
1053 // @todo show some special message for that case
1054 $nEdits = $this->mNewPage->countRevisionsBetween( $oldRev, $newRev, 1000 );
1055 if ( $nEdits > 0 && $nEdits <= 1000 ) {
1056 $limit = 100; // use diff-multi-manyusers if too many users
1057 $users = $this->mNewPage->getAuthorsBetween( $oldRev, $newRev, $limit );
1058 $numUsers = count( $users );
1059
1060 if ( $numUsers == 1 && $users[0] == $newRev->getUserText( Revision::RAW ) ) {
1061 $numUsers = 0; // special case to say "by the same user" instead of "by one other user"
1062 }
1063
1064 return self::intermediateEditsMsg( $nEdits, $numUsers, $limit );
1065 }
1066
1067 return ''; // nothing
1068 }
1069
1070 /**
1071 * Get a notice about how many intermediate edits and users there are
1072 *
1073 * @param int $numEdits
1074 * @param int $numUsers
1075 * @param int $limit
1076 *
1077 * @return string
1078 */
1079 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
1080 if ( $numUsers === 0 ) {
1081 $msg = 'diff-multi-sameuser';
1082 } elseif ( $numUsers > $limit ) {
1083 $msg = 'diff-multi-manyusers';
1084 $numUsers = $limit;
1085 } else {
1086 $msg = 'diff-multi-otherusers';
1087 }
1088
1089 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
1090 }
1091
1092 /**
1093 * Get a header for a specified revision.
1094 *
1095 * @param Revision $rev
1096 * @param string $complete 'complete' to get the header wrapped depending
1097 * the visibility of the revision and a link to edit the page.
1098 *
1099 * @return string HTML fragment
1100 */
1101 public function getRevisionHeader( Revision $rev, $complete = '' ) {
1102 $lang = $this->getLanguage();
1103 $user = $this->getUser();
1104 $revtimestamp = $rev->getTimestamp();
1105 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
1106 $dateofrev = $lang->userDate( $revtimestamp, $user );
1107 $timeofrev = $lang->userTime( $revtimestamp, $user );
1108
1109 $header = $this->msg(
1110 $rev->isCurrent() ? 'currentrev-asof' : 'revisionasof',
1111 $timestamp,
1112 $dateofrev,
1113 $timeofrev
1114 )->escaped();
1115
1116 if ( $complete !== 'complete' ) {
1117 return $header;
1118 }
1119
1120 $title = $rev->getTitle();
1121
1122 $header = Linker::linkKnown( $title, $header, [],
1123 [ 'oldid' => $rev->getId() ] );
1124
1125 if ( $rev->userCan( Revision::DELETED_TEXT, $user ) ) {
1126 $editQuery = [ 'action' => 'edit' ];
1127 if ( !$rev->isCurrent() ) {
1128 $editQuery['oldid'] = $rev->getId();
1129 }
1130
1131 $key = $title->quickUserCan( 'edit', $user ) ? 'editold' : 'viewsourceold';
1132 $msg = $this->msg( $key )->escaped();
1133 $editLink = $this->msg( 'parentheses' )->rawParams(
1134 Linker::linkKnown( $title, $msg, [], $editQuery ) )->escaped();
1135 $header .= ' ' . Html::rawElement(
1136 'span',
1137 [ 'class' => 'mw-diff-edit' ],
1138 $editLink
1139 );
1140 if ( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
1141 $header = Html::rawElement(
1142 'span',
1143 [ 'class' => 'history-deleted' ],
1144 $header
1145 );
1146 }
1147 } else {
1148 $header = Html::rawElement( 'span', [ 'class' => 'history-deleted' ], $header );
1149 }
1150
1151 return $header;
1152 }
1153
1154 /**
1155 * Add the header to a diff body
1156 *
1157 * @param string $diff Diff body
1158 * @param string $otitle Old revision header
1159 * @param string $ntitle New revision header
1160 * @param string $multi Notice telling user that there are intermediate
1161 * revisions between the ones being compared
1162 * @param string $notice Other notices, e.g. that user is viewing deleted content
1163 *
1164 * @return string
1165 */
1166 public function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
1167 // shared.css sets diff in interface language/dir, but the actual content
1168 // is often in a different language, mostly the page content language/dir
1169 $header = Html::openElement( 'table', [
1170 'class' => [ 'diff', 'diff-contentalign-' . $this->getDiffLang()->alignStart() ],
1171 'data-mw' => 'interface',
1172 ] );
1173 $userLang = htmlspecialchars( $this->getLanguage()->getHtmlCode() );
1174
1175 if ( !$diff && !$otitle ) {
1176 $header .= "
1177 <tr style=\"vertical-align: top;\" lang=\"{$userLang}\">
1178 <td class=\"diff-ntitle\">{$ntitle}</td>
1179 </tr>";
1180 $multiColspan = 1;
1181 } else {
1182 if ( $diff ) { // Safari/Chrome show broken output if cols not used
1183 $header .= "
1184 <col class=\"diff-marker\" />
1185 <col class=\"diff-content\" />
1186 <col class=\"diff-marker\" />
1187 <col class=\"diff-content\" />";
1188 $colspan = 2;
1189 $multiColspan = 4;
1190 } else {
1191 $colspan = 1;
1192 $multiColspan = 2;
1193 }
1194 if ( $otitle || $ntitle ) {
1195 $header .= "
1196 <tr style=\"vertical-align: top;\" lang=\"{$userLang}\">
1197 <td colspan=\"$colspan\" class=\"diff-otitle\">{$otitle}</td>
1198 <td colspan=\"$colspan\" class=\"diff-ntitle\">{$ntitle}</td>
1199 </tr>";
1200 }
1201 }
1202
1203 if ( $multi != '' ) {
1204 $header .= "<tr><td colspan=\"{$multiColspan}\" style=\"text-align: center;\" " .
1205 "class=\"diff-multi\" lang=\"{$userLang}\">{$multi}</td></tr>";
1206 }
1207 if ( $notice != '' ) {
1208 $header .= "<tr><td colspan=\"{$multiColspan}\" style=\"text-align: center;\" " .
1209 "lang=\"{$userLang}\">{$notice}</td></tr>";
1210 }
1211
1212 return $header . $diff . "</table>";
1213 }
1214
1215 /**
1216 * Use specified text instead of loading from the database
1217 * @param Content $oldContent
1218 * @param Content $newContent
1219 * @since 1.21
1220 */
1221 public function setContent( Content $oldContent, Content $newContent ) {
1222 $this->mOldContent = $oldContent;
1223 $this->mNewContent = $newContent;
1224
1225 $this->mTextLoaded = 2;
1226 $this->mRevisionsLoaded = true;
1227 }
1228
1229 /**
1230 * Set the language in which the diff text is written
1231 * (Defaults to page content language).
1232 * @param Language|string $lang
1233 * @since 1.19
1234 */
1235 public function setTextLanguage( $lang ) {
1236 $this->mDiffLang = wfGetLangObj( $lang );
1237 }
1238
1239 /**
1240 * Maps a revision pair definition as accepted by DifferenceEngine constructor
1241 * to a pair of actual integers representing revision ids.
1242 *
1243 * @param int $old Revision id, e.g. from URL parameter 'oldid'
1244 * @param int|string $new Revision id or strings 'next' or 'prev', e.g. from URL parameter 'diff'
1245 *
1246 * @return int[] List of two revision ids, older first, later second.
1247 * Zero signifies invalid argument passed.
1248 * false signifies that there is no previous/next revision ($old is the oldest/newest one).
1249 */
1250 public function mapDiffPrevNext( $old, $new ) {
1251 if ( $new === 'prev' ) {
1252 // Show diff between revision $old and the previous one. Get previous one from DB.
1253 $newid = intval( $old );
1254 $oldid = $this->getTitle()->getPreviousRevisionID( $newid );
1255 } elseif ( $new === 'next' ) {
1256 // Show diff between revision $old and the next one. Get next one from DB.
1257 $oldid = intval( $old );
1258 $newid = $this->getTitle()->getNextRevisionID( $oldid );
1259 } else {
1260 $oldid = intval( $old );
1261 $newid = intval( $new );
1262 }
1263
1264 return [ $oldid, $newid ];
1265 }
1266
1267 /**
1268 * Load revision IDs
1269 */
1270 private function loadRevisionIds() {
1271 if ( $this->mRevisionsIdsLoaded ) {
1272 return;
1273 }
1274
1275 $this->mRevisionsIdsLoaded = true;
1276
1277 $old = $this->mOldid;
1278 $new = $this->mNewid;
1279
1280 list( $this->mOldid, $this->mNewid ) = self::mapDiffPrevNext( $old, $new );
1281 if ( $new === 'next' && $this->mNewid === false ) {
1282 # if no result, NewId points to the newest old revision. The only newer
1283 # revision is cur, which is "0".
1284 $this->mNewid = 0;
1285 }
1286
1287 Hooks::run(
1288 'NewDifferenceEngine',
1289 [ $this->getTitle(), &$this->mOldid, &$this->mNewid, $old, $new ]
1290 );
1291 }
1292
1293 /**
1294 * Load revision metadata for the specified articles. If newid is 0, then compare
1295 * the old article in oldid to the current article; if oldid is 0, then
1296 * compare the current article to the immediately previous one (ignoring the
1297 * value of newid).
1298 *
1299 * If oldid is false, leave the corresponding revision object set
1300 * to false. This is impossible via ordinary user input, and is provided for
1301 * API convenience.
1302 *
1303 * @return bool
1304 */
1305 public function loadRevisionData() {
1306 if ( $this->mRevisionsLoaded ) {
1307 return true;
1308 }
1309
1310 // Whether it succeeds or fails, we don't want to try again
1311 $this->mRevisionsLoaded = true;
1312
1313 $this->loadRevisionIds();
1314
1315 // Load the new revision object
1316 if ( $this->mNewid ) {
1317 $this->mNewRev = Revision::newFromId( $this->mNewid );
1318 } else {
1319 $this->mNewRev = Revision::newFromTitle(
1320 $this->getTitle(),
1321 false,
1322 Revision::READ_NORMAL
1323 );
1324 }
1325
1326 if ( !$this->mNewRev instanceof Revision ) {
1327 return false;
1328 }
1329
1330 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1331 $this->mNewid = $this->mNewRev->getId();
1332 $this->mNewPage = $this->mNewRev->getTitle();
1333
1334 // Load the old revision object
1335 $this->mOldRev = false;
1336 if ( $this->mOldid ) {
1337 $this->mOldRev = Revision::newFromId( $this->mOldid );
1338 } elseif ( $this->mOldid === 0 ) {
1339 $rev = $this->mNewRev->getPrevious();
1340 if ( $rev ) {
1341 $this->mOldid = $rev->getId();
1342 $this->mOldRev = $rev;
1343 } else {
1344 // No previous revision; mark to show as first-version only.
1345 $this->mOldid = false;
1346 $this->mOldRev = false;
1347 }
1348 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1349
1350 if ( is_null( $this->mOldRev ) ) {
1351 return false;
1352 }
1353
1354 if ( $this->mOldRev ) {
1355 $this->mOldPage = $this->mOldRev->getTitle();
1356 }
1357
1358 // Load tags information for both revisions
1359 $dbr = wfGetDB( DB_REPLICA );
1360 if ( $this->mOldid !== false ) {
1361 $this->mOldTags = $dbr->selectField(
1362 'tag_summary',
1363 'ts_tags',
1364 [ 'ts_rev_id' => $this->mOldid ],
1365 __METHOD__
1366 );
1367 } else {
1368 $this->mOldTags = false;
1369 }
1370 $this->mNewTags = $dbr->selectField(
1371 'tag_summary',
1372 'ts_tags',
1373 [ 'ts_rev_id' => $this->mNewid ],
1374 __METHOD__
1375 );
1376
1377 return true;
1378 }
1379
1380 /**
1381 * Load the text of the revisions, as well as revision data.
1382 *
1383 * @return bool
1384 */
1385 public function loadText() {
1386 if ( $this->mTextLoaded == 2 ) {
1387 return true;
1388 }
1389
1390 // Whether it succeeds or fails, we don't want to try again
1391 $this->mTextLoaded = 2;
1392
1393 if ( !$this->loadRevisionData() ) {
1394 return false;
1395 }
1396
1397 if ( $this->mOldRev ) {
1398 $this->mOldContent = $this->mOldRev->getContent( Revision::FOR_THIS_USER, $this->getUser() );
1399 if ( $this->mOldContent === null ) {
1400 return false;
1401 }
1402 }
1403
1404 if ( $this->mNewRev ) {
1405 $this->mNewContent = $this->mNewRev->getContent( Revision::FOR_THIS_USER, $this->getUser() );
1406 Hooks::run( 'DifferenceEngineLoadTextAfterNewContentIsLoaded', [ $this ] );
1407 if ( $this->mNewContent === null ) {
1408 return false;
1409 }
1410 }
1411
1412 return true;
1413 }
1414
1415 /**
1416 * Load the text of the new revision, not the old one
1417 *
1418 * @return bool
1419 */
1420 public function loadNewText() {
1421 if ( $this->mTextLoaded >= 1 ) {
1422 return true;
1423 }
1424
1425 $this->mTextLoaded = 1;
1426
1427 if ( !$this->loadRevisionData() ) {
1428 return false;
1429 }
1430
1431 $this->mNewContent = $this->mNewRev->getContent( Revision::FOR_THIS_USER, $this->getUser() );
1432
1433 Hooks::run( 'DifferenceEngineAfterLoadNewText', [ $this ] );
1434
1435 return true;
1436 }
1437
1438 }