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