Merge "Use LogFormatter::getLinkRenderer in LogFormatter extensions"
[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 # @codingStandardsIgnoreStart Ignoring long lines.
609 if ( Hooks::run( 'ArticleContentOnDiff', [ $this, $out ] ) ) {
610 $this->loadNewText();
611 $out->setRevisionId( $this->mNewid );
612 $out->setRevisionTimestamp( $this->mNewRev->getTimestamp() );
613 $out->setArticleFlag( true );
614
615 if ( !Hooks::run( 'ArticleContentViewCustom', [ $this->mNewContent, $this->mNewPage, $out ] ) ) {
616 // Handled by extension
617 } else {
618 // Normal page
619 if ( $this->getTitle()->equals( $this->mNewPage ) ) {
620 // If the Title stored in the context is the same as the one
621 // of the new revision, we can use its associated WikiPage
622 // object.
623 $wikiPage = $this->getWikiPage();
624 } else {
625 // Otherwise we need to create our own WikiPage object
626 $wikiPage = WikiPage::factory( $this->mNewPage );
627 }
628
629 $parserOutput = $this->getParserOutput( $wikiPage, $this->mNewRev );
630
631 # WikiPage::getParserOutput() should not return false, but just in case
632 if ( $parserOutput ) {
633 // Allow extensions to change parser output here
634 if ( Hooks::run( 'DifferenceEngineRenderRevisionAddParserOutput', [ $this, $out, $parserOutput, $wikiPage ] ) ) {
635 $out->addParserOutput( $parserOutput );
636 }
637 }
638 }
639 }
640 # @codingStandardsIgnoreEnd
641
642 // Allow extensions to optionally not show the final patrolled link
643 if ( Hooks::run( 'DifferenceEngineRenderRevisionShowFinalPatrolLink' ) ) {
644 # Add redundant patrol link on bottom...
645 $out->addHTML( $this->markPatrolledLink() );
646 }
647 }
648
649 protected function getParserOutput( WikiPage $page, Revision $rev ) {
650 $parserOptions = $page->makeParserOptions( $this->getContext() );
651
652 if ( !$rev->isCurrent() || !$rev->getTitle()->quickUserCan( 'edit', $this->getUser() ) ) {
653 $parserOptions->setEditSection( false );
654 }
655
656 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
657
658 return $parserOutput;
659 }
660
661 /**
662 * Get the diff text, send it to the OutputPage object
663 * Returns false if the diff could not be generated, otherwise returns true
664 *
665 * @param string|bool $otitle Header for old text or false
666 * @param string|bool $ntitle Header for new text or false
667 * @param string $notice HTML between diff header and body
668 *
669 * @return bool
670 */
671 public function showDiff( $otitle, $ntitle, $notice = '' ) {
672 // Allow extensions to affect the output here
673 Hooks::run( 'DifferenceEngineShowDiff', [ $this ] );
674
675 $diff = $this->getDiff( $otitle, $ntitle, $notice );
676 if ( $diff === false ) {
677 $this->showMissingRevision();
678
679 return false;
680 } else {
681 $this->showDiffStyle();
682 $this->getOutput()->addHTML( $diff );
683
684 return true;
685 }
686 }
687
688 /**
689 * Add style sheets for diff display.
690 */
691 public function showDiffStyle() {
692 $this->getOutput()->addModuleStyles( 'mediawiki.diff.styles' );
693 }
694
695 /**
696 * Get complete diff table, including header
697 *
698 * @param string|bool $otitle Header for old text or false
699 * @param string|bool $ntitle Header for new text or false
700 * @param string $notice HTML between diff header and body
701 *
702 * @return mixed
703 */
704 public function getDiff( $otitle, $ntitle, $notice = '' ) {
705 $body = $this->getDiffBody();
706 if ( $body === false ) {
707 return false;
708 }
709
710 $multi = $this->getMultiNotice();
711 // Display a message when the diff is empty
712 if ( $body === '' ) {
713 $notice .= '<div class="mw-diff-empty">' .
714 $this->msg( 'diff-empty' )->parse() .
715 "</div>\n";
716 }
717
718 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
719 }
720
721 /**
722 * Get the diff table body, without header
723 *
724 * @return mixed (string/false)
725 */
726 public function getDiffBody() {
727 $this->mCacheHit = true;
728 // Check if the diff should be hidden from this user
729 if ( !$this->loadRevisionData() ) {
730 return false;
731 } elseif ( $this->mOldRev &&
732 !$this->mOldRev->userCan( Revision::DELETED_TEXT, $this->getUser() )
733 ) {
734 return false;
735 } elseif ( $this->mNewRev &&
736 !$this->mNewRev->userCan( Revision::DELETED_TEXT, $this->getUser() )
737 ) {
738 return false;
739 }
740 // Short-circuit
741 if ( $this->mOldRev === false || ( $this->mOldRev && $this->mNewRev
742 && $this->mOldRev->getId() == $this->mNewRev->getId() )
743 ) {
744 if ( Hooks::run( 'DifferenceEngineShowEmptyOldContent', [ $this ] ) ) {
745 return '';
746 }
747 }
748 // Cacheable?
749 $key = false;
750 $cache = ObjectCache::getMainWANInstance();
751 if ( $this->mOldid && $this->mNewid ) {
752 $key = $this->getDiffBodyCacheKey();
753
754 // Try cache
755 if ( !$this->mRefreshCache ) {
756 $difftext = $cache->get( $key );
757 if ( $difftext ) {
758 wfIncrStats( 'diff_cache.hit' );
759 $difftext = $this->localiseLineNumbers( $difftext );
760 $difftext .= "\n<!-- diff cache key $key -->\n";
761
762 return $difftext;
763 }
764 } // don't try to load but save the result
765 }
766 $this->mCacheHit = false;
767
768 // Loadtext is permission safe, this just clears out the diff
769 if ( !$this->loadText() ) {
770 return false;
771 }
772
773 $difftext = $this->generateContentDiffBody( $this->mOldContent, $this->mNewContent );
774
775 // Avoid PHP 7.1 warning from passing $this by reference
776 $diffEngine = $this;
777
778 // Save to cache for 7 days
779 if ( !Hooks::run( 'AbortDiffCache', [ &$diffEngine ] ) ) {
780 wfIncrStats( 'diff_cache.uncacheable' );
781 } elseif ( $key !== false && $difftext !== false ) {
782 wfIncrStats( 'diff_cache.miss' );
783 $cache->set( $key, $difftext, 7 * 86400 );
784 } else {
785 wfIncrStats( 'diff_cache.uncacheable' );
786 }
787 // Replace line numbers with the text in the user's language
788 if ( $difftext !== false ) {
789 $difftext = $this->localiseLineNumbers( $difftext );
790 }
791
792 return $difftext;
793 }
794
795 /**
796 * Returns the cache key for diff body text or content.
797 *
798 * @since 1.23
799 *
800 * @throws MWException
801 * @return string
802 */
803 protected function getDiffBodyCacheKey() {
804 if ( !$this->mOldid || !$this->mNewid ) {
805 throw new MWException( 'mOldid and mNewid must be set to get diff cache key.' );
806 }
807
808 return wfMemcKey( 'diff', 'version', self::DIFF_VERSION,
809 'oldid', $this->mOldid, 'newid', $this->mNewid );
810 }
811
812 /**
813 * Generate a diff, no caching.
814 *
815 * This implementation uses generateTextDiffBody() to generate a diff based on the default
816 * serialization of the given Content objects. This will fail if $old or $new are not
817 * instances of TextContent.
818 *
819 * Subclasses may override this to provide a different rendering for the diff,
820 * perhaps taking advantage of the content's native form. This is required for all content
821 * models that are not text based.
822 *
823 * @since 1.21
824 *
825 * @param Content $old Old content
826 * @param Content $new New content
827 *
828 * @throws MWException If old or new content is not an instance of TextContent.
829 * @return bool|string
830 */
831 public function generateContentDiffBody( Content $old, Content $new ) {
832 if ( !( $old instanceof TextContent ) ) {
833 throw new MWException( "Diff not implemented for " . get_class( $old ) . "; " .
834 "override generateContentDiffBody to fix this." );
835 }
836
837 if ( !( $new instanceof TextContent ) ) {
838 throw new MWException( "Diff not implemented for " . get_class( $new ) . "; "
839 . "override generateContentDiffBody to fix this." );
840 }
841
842 $otext = $old->serialize();
843 $ntext = $new->serialize();
844
845 return $this->generateTextDiffBody( $otext, $ntext );
846 }
847
848 /**
849 * Generate a diff, no caching
850 *
851 * @todo move this to TextDifferenceEngine, make DifferenceEngine abstract. At some point.
852 *
853 * @param string $otext Old text, must be already segmented
854 * @param string $ntext New text, must be already segmented
855 *
856 * @return bool|string
857 */
858 public function generateTextDiffBody( $otext, $ntext ) {
859 $diff = function () use ( $otext, $ntext ) {
860 $time = microtime( true );
861
862 $result = $this->textDiff( $otext, $ntext );
863
864 $time = intval( ( microtime( true ) - $time ) * 1000 );
865 MediaWikiServices::getInstance()->getStatsdDataFactory()->timing( 'diff_time', $time );
866 // Log requests slower than 99th percentile
867 if ( $time > 100 && $this->mOldPage && $this->mNewPage ) {
868 wfDebugLog( 'diff',
869 "$time ms diff: {$this->mOldid} -> {$this->mNewid} {$this->mNewPage}" );
870 }
871
872 return $result;
873 };
874
875 /**
876 * @param Status $status
877 * @throws FatalError
878 */
879 $error = function ( $status ) {
880 throw new FatalError( $status->getWikiText() );
881 };
882
883 // Use PoolCounter if the diff looks like it can be expensive
884 if ( strlen( $otext ) + strlen( $ntext ) > 20000 ) {
885 $work = new PoolCounterWorkViaCallback( 'diff',
886 md5( $otext ) . md5( $ntext ),
887 [ 'doWork' => $diff, 'error' => $error ]
888 );
889 return $work->execute();
890 }
891
892 return $diff();
893 }
894
895 /**
896 * Generates diff, to be wrapped internally in a logging/instrumentation
897 *
898 * @param string $otext Old text, must be already segmented
899 * @param string $ntext New text, must be already segmented
900 * @return bool|string
901 */
902 protected function textDiff( $otext, $ntext ) {
903 global $wgExternalDiffEngine, $wgContLang;
904
905 $otext = str_replace( "\r\n", "\n", $otext );
906 $ntext = str_replace( "\r\n", "\n", $ntext );
907
908 if ( $wgExternalDiffEngine == 'wikidiff' || $wgExternalDiffEngine == 'wikidiff3' ) {
909 wfDeprecated( "\$wgExternalDiffEngine = '{$wgExternalDiffEngine}'", '1.27' );
910 $wgExternalDiffEngine = false;
911 } elseif ( $wgExternalDiffEngine == 'wikidiff2' ) {
912 // Same as above, but with no deprecation warnings
913 $wgExternalDiffEngine = false;
914 } elseif ( !is_string( $wgExternalDiffEngine ) && $wgExternalDiffEngine !== false ) {
915 // And prevent people from shooting themselves in the foot...
916 wfWarn( '$wgExternalDiffEngine is set to a non-string value, forcing it to false' );
917 $wgExternalDiffEngine = false;
918 }
919
920 // Better external diff engine, the 2 may some day be dropped
921 // This one does the escaping and segmenting itself
922 if ( function_exists( 'wikidiff2_do_diff' ) && $wgExternalDiffEngine === false ) {
923 $wikidiff2Version = phpversion( 'wikidiff2' );
924 if (
925 $wikidiff2Version !== false &&
926 version_compare( $wikidiff2Version, '0.3', '>=' )
927 ) {
928 $text = wikidiff2_do_diff(
929 $otext,
930 $ntext,
931 2,
932 $this->getConfig()->get( 'WikiDiff2MovedParagraphDetectionCutoff' )
933 );
934 } else {
935 // Don't pass the 4th parameter for compatibility with older versions of wikidiff2
936 $text = wikidiff2_do_diff(
937 $otext,
938 $ntext,
939 2
940 );
941
942 // Log a warning in case the configuration value is set to not silently ignore it
943 if ( $this->getConfig()->get( 'WikiDiff2MovedParagraphDetectionCutoff' ) > 0 ) {
944 wfLogWarning( '$wgWikiDiff2MovedParagraphDetectionCutoff is set but has no
945 effect since the used version of WikiDiff2 does not support it.' );
946 }
947 }
948
949 $text .= $this->debug( 'wikidiff2' );
950
951 return $text;
952 } elseif ( $wgExternalDiffEngine !== false && is_executable( $wgExternalDiffEngine ) ) {
953 # Diff via the shell
954 $tmpDir = wfTempDir();
955 $tempName1 = tempnam( $tmpDir, 'diff_' );
956 $tempName2 = tempnam( $tmpDir, 'diff_' );
957
958 $tempFile1 = fopen( $tempName1, "w" );
959 if ( !$tempFile1 ) {
960 return false;
961 }
962 $tempFile2 = fopen( $tempName2, "w" );
963 if ( !$tempFile2 ) {
964 return false;
965 }
966 fwrite( $tempFile1, $otext );
967 fwrite( $tempFile2, $ntext );
968 fclose( $tempFile1 );
969 fclose( $tempFile2 );
970 $cmd = [ $wgExternalDiffEngine, $tempName1, $tempName2 ];
971 $result = Shell::command( $cmd )
972 ->execute();
973 $exitCode = $result->getExitCode();
974 if ( $exitCode !== 0 ) {
975 throw new Exception( "External diff command returned code {$exitCode}. Stderr: "
976 . wfEscapeWikiText( $result->getStderr() )
977 );
978 }
979 $difftext = $result->getStdout();
980 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
981 unlink( $tempName1 );
982 unlink( $tempName2 );
983
984 return $difftext;
985 }
986
987 # Native PHP diff
988 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
989 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
990 $diffs = new Diff( $ota, $nta );
991 $formatter = new TableDiffFormatter();
992 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) );
993
994 return $difftext;
995 }
996
997 /**
998 * Generate a debug comment indicating diff generating time,
999 * server node, and generator backend.
1000 *
1001 * @param string $generator : What diff engine was used
1002 *
1003 * @return string
1004 */
1005 protected function debug( $generator = "internal" ) {
1006 global $wgShowHostnames;
1007 if ( !$this->enableDebugComment ) {
1008 return '';
1009 }
1010 $data = [ $generator ];
1011 if ( $wgShowHostnames ) {
1012 $data[] = wfHostname();
1013 }
1014 $data[] = wfTimestamp( TS_DB );
1015
1016 return "<!-- diff generator: " .
1017 implode( " ", array_map( "htmlspecialchars", $data ) ) .
1018 " -->\n";
1019 }
1020
1021 /**
1022 * Replace line numbers with the text in the user's language
1023 *
1024 * @param string $text
1025 *
1026 * @return mixed
1027 */
1028 public function localiseLineNumbers( $text ) {
1029 return preg_replace_callback(
1030 '/<!--LINE (\d+)-->/',
1031 [ $this, 'localiseLineNumbersCb' ],
1032 $text
1033 );
1034 }
1035
1036 public function localiseLineNumbersCb( $matches ) {
1037 if ( $matches[1] === '1' && $this->mReducedLineNumbers ) {
1038 return '';
1039 }
1040
1041 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
1042 }
1043
1044 /**
1045 * If there are revisions between the ones being compared, return a note saying so.
1046 *
1047 * @return string
1048 */
1049 public function getMultiNotice() {
1050 if ( !is_object( $this->mOldRev ) || !is_object( $this->mNewRev ) ) {
1051 return '';
1052 } elseif ( !$this->mOldPage->equals( $this->mNewPage ) ) {
1053 // Comparing two different pages? Count would be meaningless.
1054 return '';
1055 }
1056
1057 if ( $this->mOldRev->getTimestamp() > $this->mNewRev->getTimestamp() ) {
1058 $oldRev = $this->mNewRev; // flip
1059 $newRev = $this->mOldRev; // flip
1060 } else { // normal case
1061 $oldRev = $this->mOldRev;
1062 $newRev = $this->mNewRev;
1063 }
1064
1065 // Sanity: don't show the notice if too many rows must be scanned
1066 // @todo show some special message for that case
1067 $nEdits = $this->mNewPage->countRevisionsBetween( $oldRev, $newRev, 1000 );
1068 if ( $nEdits > 0 && $nEdits <= 1000 ) {
1069 $limit = 100; // use diff-multi-manyusers if too many users
1070 $users = $this->mNewPage->getAuthorsBetween( $oldRev, $newRev, $limit );
1071 $numUsers = count( $users );
1072
1073 if ( $numUsers == 1 && $users[0] == $newRev->getUserText( Revision::RAW ) ) {
1074 $numUsers = 0; // special case to say "by the same user" instead of "by one other user"
1075 }
1076
1077 return self::intermediateEditsMsg( $nEdits, $numUsers, $limit );
1078 }
1079
1080 return ''; // nothing
1081 }
1082
1083 /**
1084 * Get a notice about how many intermediate edits and users there are
1085 *
1086 * @param int $numEdits
1087 * @param int $numUsers
1088 * @param int $limit
1089 *
1090 * @return string
1091 */
1092 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
1093 if ( $numUsers === 0 ) {
1094 $msg = 'diff-multi-sameuser';
1095 } elseif ( $numUsers > $limit ) {
1096 $msg = 'diff-multi-manyusers';
1097 $numUsers = $limit;
1098 } else {
1099 $msg = 'diff-multi-otherusers';
1100 }
1101
1102 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
1103 }
1104
1105 /**
1106 * Get a header for a specified revision.
1107 *
1108 * @param Revision $rev
1109 * @param string $complete 'complete' to get the header wrapped depending
1110 * the visibility of the revision and a link to edit the page.
1111 *
1112 * @return string HTML fragment
1113 */
1114 public function getRevisionHeader( Revision $rev, $complete = '' ) {
1115 $lang = $this->getLanguage();
1116 $user = $this->getUser();
1117 $revtimestamp = $rev->getTimestamp();
1118 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
1119 $dateofrev = $lang->userDate( $revtimestamp, $user );
1120 $timeofrev = $lang->userTime( $revtimestamp, $user );
1121
1122 $header = $this->msg(
1123 $rev->isCurrent() ? 'currentrev-asof' : 'revisionasof',
1124 $timestamp,
1125 $dateofrev,
1126 $timeofrev
1127 )->escaped();
1128
1129 if ( $complete !== 'complete' ) {
1130 return $header;
1131 }
1132
1133 $title = $rev->getTitle();
1134
1135 $header = Linker::linkKnown( $title, $header, [],
1136 [ 'oldid' => $rev->getId() ] );
1137
1138 if ( $rev->userCan( Revision::DELETED_TEXT, $user ) ) {
1139 $editQuery = [ 'action' => 'edit' ];
1140 if ( !$rev->isCurrent() ) {
1141 $editQuery['oldid'] = $rev->getId();
1142 }
1143
1144 $key = $title->quickUserCan( 'edit', $user ) ? 'editold' : 'viewsourceold';
1145 $msg = $this->msg( $key )->escaped();
1146 $editLink = $this->msg( 'parentheses' )->rawParams(
1147 Linker::linkKnown( $title, $msg, [], $editQuery ) )->escaped();
1148 $header .= ' ' . Html::rawElement(
1149 'span',
1150 [ 'class' => 'mw-diff-edit' ],
1151 $editLink
1152 );
1153 if ( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
1154 $header = Html::rawElement(
1155 'span',
1156 [ 'class' => 'history-deleted' ],
1157 $header
1158 );
1159 }
1160 } else {
1161 $header = Html::rawElement( 'span', [ 'class' => 'history-deleted' ], $header );
1162 }
1163
1164 return $header;
1165 }
1166
1167 /**
1168 * Add the header to a diff body
1169 *
1170 * @param string $diff Diff body
1171 * @param string $otitle Old revision header
1172 * @param string $ntitle New revision header
1173 * @param string $multi Notice telling user that there are intermediate
1174 * revisions between the ones being compared
1175 * @param string $notice Other notices, e.g. that user is viewing deleted content
1176 *
1177 * @return string
1178 */
1179 public function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
1180 // shared.css sets diff in interface language/dir, but the actual content
1181 // is often in a different language, mostly the page content language/dir
1182 $header = Html::openElement( 'table', [
1183 'class' => [ 'diff', 'diff-contentalign-' . $this->getDiffLang()->alignStart() ],
1184 'data-mw' => 'interface',
1185 ] );
1186 $userLang = htmlspecialchars( $this->getLanguage()->getHtmlCode() );
1187
1188 if ( !$diff && !$otitle ) {
1189 $header .= "
1190 <tr style=\"vertical-align: top;\" lang=\"{$userLang}\">
1191 <td class=\"diff-ntitle\">{$ntitle}</td>
1192 </tr>";
1193 $multiColspan = 1;
1194 } else {
1195 if ( $diff ) { // Safari/Chrome show broken output if cols not used
1196 $header .= "
1197 <col class=\"diff-marker\" />
1198 <col class=\"diff-content\" />
1199 <col class=\"diff-marker\" />
1200 <col class=\"diff-content\" />";
1201 $colspan = 2;
1202 $multiColspan = 4;
1203 } else {
1204 $colspan = 1;
1205 $multiColspan = 2;
1206 }
1207 if ( $otitle || $ntitle ) {
1208 $header .= "
1209 <tr style=\"vertical-align: top;\" lang=\"{$userLang}\">
1210 <td colspan=\"$colspan\" class=\"diff-otitle\">{$otitle}</td>
1211 <td colspan=\"$colspan\" class=\"diff-ntitle\">{$ntitle}</td>
1212 </tr>";
1213 }
1214 }
1215
1216 if ( $multi != '' ) {
1217 $header .= "<tr><td colspan=\"{$multiColspan}\" style=\"text-align: center;\" " .
1218 "class=\"diff-multi\" lang=\"{$userLang}\">{$multi}</td></tr>";
1219 }
1220 if ( $notice != '' ) {
1221 $header .= "<tr><td colspan=\"{$multiColspan}\" style=\"text-align: center;\" " .
1222 "lang=\"{$userLang}\">{$notice}</td></tr>";
1223 }
1224
1225 return $header . $diff . "</table>";
1226 }
1227
1228 /**
1229 * Use specified text instead of loading from the database
1230 * @param Content $oldContent
1231 * @param Content $newContent
1232 * @since 1.21
1233 */
1234 public function setContent( Content $oldContent, Content $newContent ) {
1235 $this->mOldContent = $oldContent;
1236 $this->mNewContent = $newContent;
1237
1238 $this->mTextLoaded = 2;
1239 $this->mRevisionsLoaded = true;
1240 }
1241
1242 /**
1243 * Set the language in which the diff text is written
1244 * (Defaults to page content language).
1245 * @param Language|string $lang
1246 * @since 1.19
1247 */
1248 public function setTextLanguage( $lang ) {
1249 $this->mDiffLang = wfGetLangObj( $lang );
1250 }
1251
1252 /**
1253 * Maps a revision pair definition as accepted by DifferenceEngine constructor
1254 * to a pair of actual integers representing revision ids.
1255 *
1256 * @param int $old Revision id, e.g. from URL parameter 'oldid'
1257 * @param int|string $new Revision id or strings 'next' or 'prev', e.g. from URL parameter 'diff'
1258 *
1259 * @return int[] List of two revision ids, older first, later second.
1260 * Zero signifies invalid argument passed.
1261 * false signifies that there is no previous/next revision ($old is the oldest/newest one).
1262 */
1263 public function mapDiffPrevNext( $old, $new ) {
1264 if ( $new === 'prev' ) {
1265 // Show diff between revision $old and the previous one. Get previous one from DB.
1266 $newid = intval( $old );
1267 $oldid = $this->getTitle()->getPreviousRevisionID( $newid );
1268 } elseif ( $new === 'next' ) {
1269 // Show diff between revision $old and the next one. Get next one from DB.
1270 $oldid = intval( $old );
1271 $newid = $this->getTitle()->getNextRevisionID( $oldid );
1272 } else {
1273 $oldid = intval( $old );
1274 $newid = intval( $new );
1275 }
1276
1277 return [ $oldid, $newid ];
1278 }
1279
1280 /**
1281 * Load revision IDs
1282 */
1283 private function loadRevisionIds() {
1284 if ( $this->mRevisionsIdsLoaded ) {
1285 return;
1286 }
1287
1288 $this->mRevisionsIdsLoaded = true;
1289
1290 $old = $this->mOldid;
1291 $new = $this->mNewid;
1292
1293 list( $this->mOldid, $this->mNewid ) = self::mapDiffPrevNext( $old, $new );
1294 if ( $new === 'next' && $this->mNewid === false ) {
1295 # if no result, NewId points to the newest old revision. The only newer
1296 # revision is cur, which is "0".
1297 $this->mNewid = 0;
1298 }
1299
1300 Hooks::run(
1301 'NewDifferenceEngine',
1302 [ $this->getTitle(), &$this->mOldid, &$this->mNewid, $old, $new ]
1303 );
1304 }
1305
1306 /**
1307 * Load revision metadata for the specified articles. If newid is 0, then compare
1308 * the old article in oldid to the current article; if oldid is 0, then
1309 * compare the current article to the immediately previous one (ignoring the
1310 * value of newid).
1311 *
1312 * If oldid is false, leave the corresponding revision object set
1313 * to false. This is impossible via ordinary user input, and is provided for
1314 * API convenience.
1315 *
1316 * @return bool
1317 */
1318 public function loadRevisionData() {
1319 if ( $this->mRevisionsLoaded ) {
1320 return true;
1321 }
1322
1323 // Whether it succeeds or fails, we don't want to try again
1324 $this->mRevisionsLoaded = true;
1325
1326 $this->loadRevisionIds();
1327
1328 // Load the new revision object
1329 if ( $this->mNewid ) {
1330 $this->mNewRev = Revision::newFromId( $this->mNewid );
1331 } else {
1332 $this->mNewRev = Revision::newFromTitle(
1333 $this->getTitle(),
1334 false,
1335 Revision::READ_NORMAL
1336 );
1337 }
1338
1339 if ( !$this->mNewRev instanceof Revision ) {
1340 return false;
1341 }
1342
1343 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1344 $this->mNewid = $this->mNewRev->getId();
1345 $this->mNewPage = $this->mNewRev->getTitle();
1346
1347 // Load the old revision object
1348 $this->mOldRev = false;
1349 if ( $this->mOldid ) {
1350 $this->mOldRev = Revision::newFromId( $this->mOldid );
1351 } elseif ( $this->mOldid === 0 ) {
1352 $rev = $this->mNewRev->getPrevious();
1353 if ( $rev ) {
1354 $this->mOldid = $rev->getId();
1355 $this->mOldRev = $rev;
1356 } else {
1357 // No previous revision; mark to show as first-version only.
1358 $this->mOldid = false;
1359 $this->mOldRev = false;
1360 }
1361 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1362
1363 if ( is_null( $this->mOldRev ) ) {
1364 return false;
1365 }
1366
1367 if ( $this->mOldRev ) {
1368 $this->mOldPage = $this->mOldRev->getTitle();
1369 }
1370
1371 // Load tags information for both revisions
1372 $dbr = wfGetDB( DB_REPLICA );
1373 if ( $this->mOldid !== false ) {
1374 $this->mOldTags = $dbr->selectField(
1375 'tag_summary',
1376 'ts_tags',
1377 [ 'ts_rev_id' => $this->mOldid ],
1378 __METHOD__
1379 );
1380 } else {
1381 $this->mOldTags = false;
1382 }
1383 $this->mNewTags = $dbr->selectField(
1384 'tag_summary',
1385 'ts_tags',
1386 [ 'ts_rev_id' => $this->mNewid ],
1387 __METHOD__
1388 );
1389
1390 return true;
1391 }
1392
1393 /**
1394 * Load the text of the revisions, as well as revision data.
1395 *
1396 * @return bool
1397 */
1398 public function loadText() {
1399 if ( $this->mTextLoaded == 2 ) {
1400 return true;
1401 }
1402
1403 // Whether it succeeds or fails, we don't want to try again
1404 $this->mTextLoaded = 2;
1405
1406 if ( !$this->loadRevisionData() ) {
1407 return false;
1408 }
1409
1410 if ( $this->mOldRev ) {
1411 $this->mOldContent = $this->mOldRev->getContent( Revision::FOR_THIS_USER, $this->getUser() );
1412 if ( $this->mOldContent === null ) {
1413 return false;
1414 }
1415 }
1416
1417 if ( $this->mNewRev ) {
1418 $this->mNewContent = $this->mNewRev->getContent( Revision::FOR_THIS_USER, $this->getUser() );
1419 Hooks::run( 'DifferenceEngineLoadTextAfterNewContentIsLoaded', [ $this ] );
1420 if ( $this->mNewContent === null ) {
1421 return false;
1422 }
1423 }
1424
1425 return true;
1426 }
1427
1428 /**
1429 * Load the text of the new revision, not the old one
1430 *
1431 * @return bool
1432 */
1433 public function loadNewText() {
1434 if ( $this->mTextLoaded >= 1 ) {
1435 return true;
1436 }
1437
1438 $this->mTextLoaded = 1;
1439
1440 if ( !$this->loadRevisionData() ) {
1441 return false;
1442 }
1443
1444 $this->mNewContent = $this->mNewRev->getContent( Revision::FOR_THIS_USER, $this->getUser() );
1445
1446 Hooks::run( 'DifferenceEngineAfterLoadNewText', [ $this ] );
1447
1448 return true;
1449 }
1450
1451 }