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