Merge "INSTALL: Don't warn against using PHP "as a CGI plugin""
[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 // Same as above, but with no deprecation warnings
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 global $wgContLang;
996
997 $otext = str_replace( "\r\n", "\n", $otext );
998 $ntext = str_replace( "\r\n", "\n", $ntext );
999
1000 $engine = $this->getEngine();
1001
1002 // Better external diff engine, the 2 may some day be dropped
1003 // This one does the escaping and segmenting itself
1004 if ( $engine === 'wikidiff2' ) {
1005 $wikidiff2Version = phpversion( 'wikidiff2' );
1006 if (
1007 $wikidiff2Version !== false &&
1008 version_compare( $wikidiff2Version, '1.5.0', '>=' )
1009 ) {
1010 $text = wikidiff2_do_diff(
1011 $otext,
1012 $ntext,
1013 2,
1014 $this->getConfig()->get( 'WikiDiff2MovedParagraphDetectionCutoff' )
1015 );
1016 } else {
1017 // Don't pass the 4th parameter for compatibility with older versions of wikidiff2
1018 $text = wikidiff2_do_diff(
1019 $otext,
1020 $ntext,
1021 2
1022 );
1023
1024 // Log a warning in case the configuration value is set to not silently ignore it
1025 if ( $this->getConfig()->get( 'WikiDiff2MovedParagraphDetectionCutoff' ) > 0 ) {
1026 wfLogWarning( '$wgWikiDiff2MovedParagraphDetectionCutoff is set but has no
1027 effect since the used version of WikiDiff2 does not support it.' );
1028 }
1029 }
1030
1031 $text .= $this->debug( 'wikidiff2' );
1032
1033 return $text;
1034 } elseif ( $engine !== false ) {
1035 # Diff via the shell
1036 $tmpDir = wfTempDir();
1037 $tempName1 = tempnam( $tmpDir, 'diff_' );
1038 $tempName2 = tempnam( $tmpDir, 'diff_' );
1039
1040 $tempFile1 = fopen( $tempName1, "w" );
1041 if ( !$tempFile1 ) {
1042 return false;
1043 }
1044 $tempFile2 = fopen( $tempName2, "w" );
1045 if ( !$tempFile2 ) {
1046 return false;
1047 }
1048 fwrite( $tempFile1, $otext );
1049 fwrite( $tempFile2, $ntext );
1050 fclose( $tempFile1 );
1051 fclose( $tempFile2 );
1052 $cmd = [ $engine, $tempName1, $tempName2 ];
1053 $result = Shell::command( $cmd )
1054 ->execute();
1055 $exitCode = $result->getExitCode();
1056 if ( $exitCode !== 0 ) {
1057 throw new Exception( "External diff command returned code {$exitCode}. Stderr: "
1058 . wfEscapeWikiText( $result->getStderr() )
1059 );
1060 }
1061 $difftext = $result->getStdout();
1062 $difftext .= $this->debug( "external $engine" );
1063 unlink( $tempName1 );
1064 unlink( $tempName2 );
1065
1066 return $difftext;
1067 }
1068
1069 # Native PHP diff
1070 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
1071 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
1072 $diffs = new Diff( $ota, $nta );
1073 $formatter = new TableDiffFormatter();
1074 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) );
1075 $difftext .= $this->debug( 'native PHP' );
1076
1077 return $difftext;
1078 }
1079
1080 /**
1081 * Generate a debug comment indicating diff generating time,
1082 * server node, and generator backend.
1083 *
1084 * @param string $generator : What diff engine was used
1085 *
1086 * @return string
1087 */
1088 protected function debug( $generator = "internal" ) {
1089 global $wgShowHostnames;
1090 if ( !$this->enableDebugComment ) {
1091 return '';
1092 }
1093 $data = [ $generator ];
1094 if ( $wgShowHostnames ) {
1095 $data[] = wfHostname();
1096 }
1097 $data[] = wfTimestamp( TS_DB );
1098
1099 return "<!-- diff generator: " .
1100 implode( " ", array_map( "htmlspecialchars", $data ) ) .
1101 " -->\n";
1102 }
1103
1104 /**
1105 * Localise diff output
1106 *
1107 * @param string $text
1108 * @return string
1109 */
1110 private function localiseDiff( $text ) {
1111 $text = $this->localiseLineNumbers( $text );
1112 if ( $this->getEngine() === 'wikidiff2' &&
1113 version_compare( phpversion( 'wikidiff2' ), '1.5.1', '>=' )
1114 ) {
1115 $text = $this->addLocalisedTitleTooltips( $text );
1116 }
1117 return $text;
1118 }
1119
1120 /**
1121 * Replace line numbers with the text in the user's language
1122 *
1123 * @param string $text
1124 *
1125 * @return mixed
1126 */
1127 public function localiseLineNumbers( $text ) {
1128 return preg_replace_callback(
1129 '/<!--LINE (\d+)-->/',
1130 [ $this, 'localiseLineNumbersCb' ],
1131 $text
1132 );
1133 }
1134
1135 public function localiseLineNumbersCb( $matches ) {
1136 if ( $matches[1] === '1' && $this->mReducedLineNumbers ) {
1137 return '';
1138 }
1139
1140 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
1141 }
1142
1143 /**
1144 * Add title attributes for tooltips on moved paragraph indicators
1145 *
1146 * @param string $text
1147 * @return string
1148 */
1149 private function addLocalisedTitleTooltips( $text ) {
1150 return preg_replace_callback(
1151 '/class="mw-diff-movedpara-(left|right)"/',
1152 [ $this, 'addLocalisedTitleTooltipsCb' ],
1153 $text
1154 );
1155 }
1156
1157 /**
1158 * @param array $matches
1159 * @return string
1160 */
1161 private function addLocalisedTitleTooltipsCb( array $matches ) {
1162 $key = $matches[1] === 'right' ?
1163 'diff-paragraph-moved-toold' :
1164 'diff-paragraph-moved-tonew';
1165 return $matches[0] . ' title="' . $this->msg( $key )->escaped() . '"';
1166 }
1167
1168 /**
1169 * If there are revisions between the ones being compared, return a note saying so.
1170 *
1171 * @return string
1172 */
1173 public function getMultiNotice() {
1174 if ( !is_object( $this->mOldRev ) || !is_object( $this->mNewRev ) ) {
1175 return '';
1176 } elseif ( !$this->mOldPage->equals( $this->mNewPage ) ) {
1177 // Comparing two different pages? Count would be meaningless.
1178 return '';
1179 }
1180
1181 if ( $this->mOldRev->getTimestamp() > $this->mNewRev->getTimestamp() ) {
1182 $oldRev = $this->mNewRev; // flip
1183 $newRev = $this->mOldRev; // flip
1184 } else { // normal case
1185 $oldRev = $this->mOldRev;
1186 $newRev = $this->mNewRev;
1187 }
1188
1189 // Sanity: don't show the notice if too many rows must be scanned
1190 // @todo show some special message for that case
1191 $nEdits = $this->mNewPage->countRevisionsBetween( $oldRev, $newRev, 1000 );
1192 if ( $nEdits > 0 && $nEdits <= 1000 ) {
1193 $limit = 100; // use diff-multi-manyusers if too many users
1194 $users = $this->mNewPage->getAuthorsBetween( $oldRev, $newRev, $limit );
1195 $numUsers = count( $users );
1196
1197 if ( $numUsers == 1 && $users[0] == $newRev->getUserText( Revision::RAW ) ) {
1198 $numUsers = 0; // special case to say "by the same user" instead of "by one other user"
1199 }
1200
1201 return self::intermediateEditsMsg( $nEdits, $numUsers, $limit );
1202 }
1203
1204 return ''; // nothing
1205 }
1206
1207 /**
1208 * Get a notice about how many intermediate edits and users there are
1209 *
1210 * @param int $numEdits
1211 * @param int $numUsers
1212 * @param int $limit
1213 *
1214 * @return string
1215 */
1216 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
1217 if ( $numUsers === 0 ) {
1218 $msg = 'diff-multi-sameuser';
1219 } elseif ( $numUsers > $limit ) {
1220 $msg = 'diff-multi-manyusers';
1221 $numUsers = $limit;
1222 } else {
1223 $msg = 'diff-multi-otherusers';
1224 }
1225
1226 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
1227 }
1228
1229 /**
1230 * Get a header for a specified revision.
1231 *
1232 * @param Revision $rev
1233 * @param string $complete 'complete' to get the header wrapped depending
1234 * the visibility of the revision and a link to edit the page.
1235 *
1236 * @return string HTML fragment
1237 */
1238 public function getRevisionHeader( Revision $rev, $complete = '' ) {
1239 $lang = $this->getLanguage();
1240 $user = $this->getUser();
1241 $revtimestamp = $rev->getTimestamp();
1242 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
1243 $dateofrev = $lang->userDate( $revtimestamp, $user );
1244 $timeofrev = $lang->userTime( $revtimestamp, $user );
1245
1246 $header = $this->msg(
1247 $rev->isCurrent() ? 'currentrev-asof' : 'revisionasof',
1248 $timestamp,
1249 $dateofrev,
1250 $timeofrev
1251 )->escaped();
1252
1253 if ( $complete !== 'complete' ) {
1254 return $header;
1255 }
1256
1257 $title = $rev->getTitle();
1258
1259 $header = Linker::linkKnown( $title, $header, [],
1260 [ 'oldid' => $rev->getId() ] );
1261
1262 if ( $rev->userCan( Revision::DELETED_TEXT, $user ) ) {
1263 $editQuery = [ 'action' => 'edit' ];
1264 if ( !$rev->isCurrent() ) {
1265 $editQuery['oldid'] = $rev->getId();
1266 }
1267
1268 $key = $title->quickUserCan( 'edit', $user ) ? 'editold' : 'viewsourceold';
1269 $msg = $this->msg( $key )->escaped();
1270 $editLink = $this->msg( 'parentheses' )->rawParams(
1271 Linker::linkKnown( $title, $msg, [], $editQuery ) )->escaped();
1272 $header .= ' ' . Html::rawElement(
1273 'span',
1274 [ 'class' => 'mw-diff-edit' ],
1275 $editLink
1276 );
1277 if ( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
1278 $header = Html::rawElement(
1279 'span',
1280 [ 'class' => 'history-deleted' ],
1281 $header
1282 );
1283 }
1284 } else {
1285 $header = Html::rawElement( 'span', [ 'class' => 'history-deleted' ], $header );
1286 }
1287
1288 return $header;
1289 }
1290
1291 /**
1292 * Add the header to a diff body
1293 *
1294 * @param string $diff Diff body
1295 * @param string $otitle Old revision header
1296 * @param string $ntitle New revision header
1297 * @param string $multi Notice telling user that there are intermediate
1298 * revisions between the ones being compared
1299 * @param string $notice Other notices, e.g. that user is viewing deleted content
1300 *
1301 * @return string
1302 */
1303 public function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
1304 // shared.css sets diff in interface language/dir, but the actual content
1305 // is often in a different language, mostly the page content language/dir
1306 $header = Html::openElement( 'table', [
1307 'class' => [ 'diff', 'diff-contentalign-' . $this->getDiffLang()->alignStart() ],
1308 'data-mw' => 'interface',
1309 ] );
1310 $userLang = htmlspecialchars( $this->getLanguage()->getHtmlCode() );
1311
1312 if ( !$diff && !$otitle ) {
1313 $header .= "
1314 <tr class=\"diff-title\" lang=\"{$userLang}\">
1315 <td class=\"diff-ntitle\">{$ntitle}</td>
1316 </tr>";
1317 $multiColspan = 1;
1318 } else {
1319 if ( $diff ) { // Safari/Chrome show broken output if cols not used
1320 $header .= "
1321 <col class=\"diff-marker\" />
1322 <col class=\"diff-content\" />
1323 <col class=\"diff-marker\" />
1324 <col class=\"diff-content\" />";
1325 $colspan = 2;
1326 $multiColspan = 4;
1327 } else {
1328 $colspan = 1;
1329 $multiColspan = 2;
1330 }
1331 if ( $otitle || $ntitle ) {
1332 $header .= "
1333 <tr class=\"diff-title\" lang=\"{$userLang}\">
1334 <td colspan=\"$colspan\" class=\"diff-otitle\">{$otitle}</td>
1335 <td colspan=\"$colspan\" class=\"diff-ntitle\">{$ntitle}</td>
1336 </tr>";
1337 }
1338 }
1339
1340 if ( $multi != '' ) {
1341 $header .= "<tr><td colspan=\"{$multiColspan}\" " .
1342 "class=\"diff-multi\" lang=\"{$userLang}\">{$multi}</td></tr>";
1343 }
1344 if ( $notice != '' ) {
1345 $header .= "<tr><td colspan=\"{$multiColspan}\" " .
1346 "class=\"diff-notice\" lang=\"{$userLang}\">{$notice}</td></tr>";
1347 }
1348
1349 return $header . $diff . "</table>";
1350 }
1351
1352 /**
1353 * Use specified text instead of loading from the database
1354 * @param Content $oldContent
1355 * @param Content $newContent
1356 * @since 1.21
1357 */
1358 public function setContent( Content $oldContent, Content $newContent ) {
1359 $this->mOldContent = $oldContent;
1360 $this->mNewContent = $newContent;
1361
1362 $this->mTextLoaded = 2;
1363 $this->mRevisionsLoaded = true;
1364 $this->isContentOverridden = true;
1365 }
1366
1367 /**
1368 * Set the language in which the diff text is written
1369 *
1370 * @param Language $lang
1371 * @since 1.19
1372 */
1373 public function setTextLanguage( $lang ) {
1374 if ( !$lang instanceof Language ) {
1375 wfDeprecated( __METHOD__ . ' with other type than Language for $lang', '1.32' );
1376 }
1377 $this->mDiffLang = wfGetLangObj( $lang );
1378 }
1379
1380 /**
1381 * Maps a revision pair definition as accepted by DifferenceEngine constructor
1382 * to a pair of actual integers representing revision ids.
1383 *
1384 * @param int $old Revision id, e.g. from URL parameter 'oldid'
1385 * @param int|string $new Revision id or strings 'next' or 'prev', e.g. from URL parameter 'diff'
1386 *
1387 * @return int[] List of two revision ids, older first, later second.
1388 * Zero signifies invalid argument passed.
1389 * false signifies that there is no previous/next revision ($old is the oldest/newest one).
1390 */
1391 public function mapDiffPrevNext( $old, $new ) {
1392 if ( $new === 'prev' ) {
1393 // Show diff between revision $old and the previous one. Get previous one from DB.
1394 $newid = intval( $old );
1395 $oldid = $this->getTitle()->getPreviousRevisionID( $newid );
1396 } elseif ( $new === 'next' ) {
1397 // Show diff between revision $old and the next one. Get next one from DB.
1398 $oldid = intval( $old );
1399 $newid = $this->getTitle()->getNextRevisionID( $oldid );
1400 } else {
1401 $oldid = intval( $old );
1402 $newid = intval( $new );
1403 }
1404
1405 return [ $oldid, $newid ];
1406 }
1407
1408 /**
1409 * Load revision IDs
1410 */
1411 private function loadRevisionIds() {
1412 if ( $this->mRevisionsIdsLoaded ) {
1413 return;
1414 }
1415
1416 $this->mRevisionsIdsLoaded = true;
1417
1418 $old = $this->mOldid;
1419 $new = $this->mNewid;
1420
1421 list( $this->mOldid, $this->mNewid ) = self::mapDiffPrevNext( $old, $new );
1422 if ( $new === 'next' && $this->mNewid === false ) {
1423 # if no result, NewId points to the newest old revision. The only newer
1424 # revision is cur, which is "0".
1425 $this->mNewid = 0;
1426 }
1427
1428 Hooks::run(
1429 'NewDifferenceEngine',
1430 [ $this->getTitle(), &$this->mOldid, &$this->mNewid, $old, $new ]
1431 );
1432 }
1433
1434 /**
1435 * Load revision metadata for the specified articles. If newid is 0, then compare
1436 * the old article in oldid to the current article; if oldid is 0, then
1437 * compare the current article to the immediately previous one (ignoring the
1438 * value of newid).
1439 *
1440 * If oldid is false, leave the corresponding revision object set
1441 * to false. This is impossible via ordinary user input, and is provided for
1442 * API convenience.
1443 *
1444 * @return bool Whether both revisions were loaded successfully.
1445 */
1446 public function loadRevisionData() {
1447 if ( $this->mRevisionsLoaded ) {
1448 return $this->isContentOverridden || $this->mNewRev && $this->mOldRev;
1449 }
1450
1451 // Whether it succeeds or fails, we don't want to try again
1452 $this->mRevisionsLoaded = true;
1453
1454 $this->loadRevisionIds();
1455
1456 // Load the new revision object
1457 if ( $this->mNewid ) {
1458 $this->mNewRev = Revision::newFromId( $this->mNewid );
1459 } else {
1460 $this->mNewRev = Revision::newFromTitle(
1461 $this->getTitle(),
1462 false,
1463 Revision::READ_NORMAL
1464 );
1465 }
1466
1467 if ( !$this->mNewRev instanceof Revision ) {
1468 return false;
1469 }
1470
1471 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1472 $this->mNewid = $this->mNewRev->getId();
1473 $this->mNewPage = $this->mNewRev->getTitle();
1474
1475 // Load the old revision object
1476 $this->mOldRev = false;
1477 if ( $this->mOldid ) {
1478 $this->mOldRev = Revision::newFromId( $this->mOldid );
1479 } elseif ( $this->mOldid === 0 ) {
1480 $rev = $this->mNewRev->getPrevious();
1481 if ( $rev ) {
1482 $this->mOldid = $rev->getId();
1483 $this->mOldRev = $rev;
1484 } else {
1485 // No previous revision; mark to show as first-version only.
1486 $this->mOldid = false;
1487 $this->mOldRev = false;
1488 }
1489 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1490
1491 if ( is_null( $this->mOldRev ) ) {
1492 return false;
1493 }
1494
1495 if ( $this->mOldRev ) {
1496 $this->mOldPage = $this->mOldRev->getTitle();
1497 }
1498
1499 // Load tags information for both revisions
1500 $dbr = wfGetDB( DB_REPLICA );
1501 if ( $this->mOldid !== false ) {
1502 $this->mOldTags = $dbr->selectField(
1503 'tag_summary',
1504 'ts_tags',
1505 [ 'ts_rev_id' => $this->mOldid ],
1506 __METHOD__
1507 );
1508 } else {
1509 $this->mOldTags = false;
1510 }
1511 $this->mNewTags = $dbr->selectField(
1512 'tag_summary',
1513 'ts_tags',
1514 [ 'ts_rev_id' => $this->mNewid ],
1515 __METHOD__
1516 );
1517
1518 return true;
1519 }
1520
1521 /**
1522 * Load the text of the revisions, as well as revision data.
1523 *
1524 * @return bool Whether the content of both revisions could be loaded successfully.
1525 */
1526 public function loadText() {
1527 if ( $this->mTextLoaded == 2 ) {
1528 return $this->loadRevisionData() && $this->mOldContent && $this->mNewContent;
1529 }
1530
1531 // Whether it succeeds or fails, we don't want to try again
1532 $this->mTextLoaded = 2;
1533
1534 if ( !$this->loadRevisionData() ) {
1535 return false;
1536 }
1537
1538 if ( $this->mOldRev ) {
1539 $this->mOldContent = $this->mOldRev->getContent( Revision::FOR_THIS_USER, $this->getUser() );
1540 if ( $this->mOldContent === null ) {
1541 return false;
1542 }
1543 }
1544
1545 if ( $this->mNewRev ) {
1546 $this->mNewContent = $this->mNewRev->getContent( Revision::FOR_THIS_USER, $this->getUser() );
1547 Hooks::run( 'DifferenceEngineLoadTextAfterNewContentIsLoaded', [ $this ] );
1548 if ( $this->mNewContent === null ) {
1549 return false;
1550 }
1551 }
1552
1553 return true;
1554 }
1555
1556 /**
1557 * Load the text of the new revision, not the old one
1558 *
1559 * @return bool Whether the content of the new revision could be loaded successfully.
1560 */
1561 public function loadNewText() {
1562 if ( $this->mTextLoaded >= 1 ) {
1563 return $this->loadRevisionData();
1564 }
1565
1566 $this->mTextLoaded = 1;
1567
1568 if ( !$this->loadRevisionData() ) {
1569 return false;
1570 }
1571
1572 $this->mNewContent = $this->mNewRev->getContent( Revision::FOR_THIS_USER, $this->getUser() );
1573
1574 Hooks::run( 'DifferenceEngineAfterLoadNewText', [ $this ] );
1575
1576 return true;
1577 }
1578
1579 }