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