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