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