Merge "HistoryBlobCurStub: correct setting name in doc comment"
[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
24 /**
25 * Constant to indicate diff cache compatibility.
26 * Bump this when changing the diff formatting in a way that
27 * fixes important bugs or such to force cached diff views to
28 * clear.
29 */
30 define( 'MW_DIFF_VERSION', '1.11a' );
31
32 /**
33 * @todo document
34 * @ingroup DifferenceEngine
35 */
36 class DifferenceEngine extends ContextSource {
37 public $mOldid;
38 public $mNewid;
39 private $mOldTags;
40 private $mNewTags;
41
42 /**
43 * @var Content
44 */
45 public $mOldContent;
46 public $mNewContent;
47 protected $mDiffLang;
48
49 /**
50 * @var Title
51 */
52 public $mOldPage;
53 public $mNewPage;
54
55 /**
56 * @var Revision
57 */
58 public $mOldRev;
59 public $mNewRev;
60 private $mRevisionsIdsLoaded = false; // Have the revisions IDs been loaded
61 public $mRevisionsLoaded = false; // Have the revisions been loaded
62 public $mTextLoaded = 0; // How many text blobs have been loaded, 0, 1 or 2?
63 public $mCacheHit = false; // Was the diff fetched from cache?
64
65 /**
66 * Set this to true to add debug info to the HTML output.
67 * Warning: this may cause RSS readers to spuriously mark articles as "new"
68 * (bug 20601)
69 */
70 public $enableDebugComment = false;
71
72 // If true, line X is not displayed when X is 1, for example to increase
73 // readability and conserve space with many small diffs.
74 protected $mReducedLineNumbers = false;
75
76 // Link to action=markpatrolled
77 protected $mMarkPatrolledLink = null;
78
79 protected $unhide = false; # show rev_deleted content if allowed
80 /**#@-*/
81
82 /**
83 * Constructor
84 * @param $context IContextSource context to use, anything else will be ignored
85 * @param $old Integer old ID we want to show and diff with.
86 * @param $new String|int either 'prev' or 'next'. Default: 0.
87 * @param $rcid Integer Deprecated, no longer used!
88 * @param $refreshCache boolean If set, refreshes the diff cache
89 * @param $unhide boolean If set, allow viewing deleted revs
90 */
91 function __construct( $context = null, $old = 0, $new = 0, $rcid = 0,
92 $refreshCache = false, $unhide = false
93 ) {
94 if ( $context instanceof IContextSource ) {
95 $this->setContext( $context );
96 }
97
98 wfDebug( "DifferenceEngine old '$old' new '$new' rcid '$rcid'\n" );
99
100 $this->mOldid = $old;
101 $this->mNewid = $new;
102 $this->mRefreshCache = $refreshCache;
103 $this->unhide = $unhide;
104 }
105
106 /**
107 * @param $value bool
108 */
109 function setReducedLineNumbers( $value = true ) {
110 $this->mReducedLineNumbers = $value;
111 }
112
113 /**
114 * @return Language
115 */
116 function getDiffLang() {
117 if ( $this->mDiffLang === null ) {
118 # Default language in which the diff text is written.
119 $this->mDiffLang = $this->getTitle()->getPageLanguage();
120 }
121 return $this->mDiffLang;
122 }
123
124 /**
125 * @return bool
126 */
127 function wasCacheHit() {
128 return $this->mCacheHit;
129 }
130
131 /**
132 * @return int
133 */
134 function getOldid() {
135 $this->loadRevisionIds();
136 return $this->mOldid;
137 }
138
139 /**
140 * @return Bool|int
141 */
142 function getNewid() {
143 $this->loadRevisionIds();
144 return $this->mNewid;
145 }
146
147 /**
148 * Look up a special:Undelete link to the given deleted revision id,
149 * as a workaround for being unable to load deleted diffs in currently.
150 *
151 * @param int $id revision ID
152 * @return mixed URL or false
153 */
154 function deletedLink( $id ) {
155 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
156 $dbr = wfGetDB( DB_SLAVE );
157 $row = $dbr->selectRow( 'archive', '*',
158 array( 'ar_rev_id' => $id ),
159 __METHOD__ );
160 if ( $row ) {
161 $rev = Revision::newFromArchiveRow( $row );
162 $title = Title::makeTitleSafe( $row->ar_namespace, $row->ar_title );
163 return SpecialPage::getTitleFor( 'Undelete' )->getFullURL( array(
164 'target' => $title->getPrefixedText(),
165 'timestamp' => $rev->getTimestamp()
166 ));
167 }
168 }
169 return false;
170 }
171
172 /**
173 * Build a wikitext link toward a deleted revision, if viewable.
174 *
175 * @param int $id revision ID
176 * @return string wikitext fragment
177 */
178 function deletedIdMarker( $id ) {
179 $link = $this->deletedLink( $id );
180 if ( $link ) {
181 return "[$link $id]";
182 } else {
183 return $id;
184 }
185 }
186
187 private function showMissingRevision() {
188 $out = $this->getOutput();
189
190 $missing = array();
191 if ( $this->mOldRev === null ||
192 ( $this->mOldRev && $this->mOldContent === null )
193 ) {
194 $missing[] = $this->deletedIdMarker( $this->mOldid );
195 }
196 if ( $this->mNewRev === null ||
197 ( $this->mNewRev && $this->mNewContent === null )
198 ) {
199 $missing[] = $this->deletedIdMarker( $this->mNewid );
200 }
201
202 $out->setPageTitle( $this->msg( 'errorpagetitle' ) );
203 $out->addWikiMsg( 'difference-missing-revision',
204 $this->getLanguage()->listToText( $missing ), count( $missing ) );
205 }
206
207 function showDiffPage( $diffOnly = false ) {
208 wfProfileIn( __METHOD__ );
209
210 # Allow frames except in certain special cases
211 $out = $this->getOutput();
212 $out->allowClickjacking();
213 $out->setRobotPolicy( 'noindex,nofollow' );
214
215 if ( !$this->loadRevisionData() ) {
216 $this->showMissingRevision();
217 wfProfileOut( __METHOD__ );
218 return;
219 }
220
221 $user = $this->getUser();
222 $permErrors = $this->mNewPage->getUserPermissionsErrors( 'read', $user );
223 if ( $this->mOldPage ) { # mOldPage might not be set, see below.
224 $permErrors = wfMergeErrorArrays( $permErrors,
225 $this->mOldPage->getUserPermissionsErrors( 'read', $user ) );
226 }
227 if ( count( $permErrors ) ) {
228 wfProfileOut( __METHOD__ );
229 throw new PermissionsError( 'read', $permErrors );
230 }
231
232 $rollback = '';
233 $undoLink = '';
234
235 $query = array();
236 # Carry over 'diffonly' param via navigation links
237 if ( $diffOnly != $user->getBoolOption( 'diffonly' ) ) {
238 $query['diffonly'] = $diffOnly;
239 }
240 # Cascade unhide param in links for easy deletion browsing
241 if ( $this->unhide ) {
242 $query['unhide'] = 1;
243 }
244
245 # Check if one of the revisions is deleted/suppressed
246 $deleted = $suppressed = false;
247 $allowed = $this->mNewRev->userCan( Revision::DELETED_TEXT, $user );
248
249 $revisionTools = array();
250
251 # mOldRev is false if the difference engine is called with a "vague" query for
252 # a diff between a version V and its previous version V' AND the version V
253 # is the first version of that article. In that case, V' does not exist.
254 if ( $this->mOldRev === false ) {
255 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage->getPrefixedText() ) );
256 $samePage = true;
257 $oldHeader = '';
258 } else {
259 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev, $this->mNewRev ) );
260
261 if ( $this->mNewPage->equals( $this->mOldPage ) ) {
262 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage->getPrefixedText() ) );
263 $samePage = true;
264 } else {
265 $out->setPageTitle( $this->msg( 'difference-title-multipage',
266 $this->mOldPage->getPrefixedText(), $this->mNewPage->getPrefixedText() ) );
267 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
268 $samePage = false;
269 }
270
271 if ( $samePage && $this->mNewPage->quickUserCan( 'edit', $user ) ) {
272 if ( $this->mNewRev->isCurrent() && $this->mNewPage->userCan( 'rollback', $user ) ) {
273 $rollbackLink = Linker::generateRollback( $this->mNewRev, $this->getContext() );
274 if ( $rollbackLink ) {
275 $out->preventClickjacking();
276 $rollback = '&#160;&#160;&#160;' . $rollbackLink;
277 }
278 }
279
280 if ( !$this->mOldRev->isDeleted( Revision::DELETED_TEXT ) &&
281 !$this->mNewRev->isDeleted( Revision::DELETED_TEXT )
282 ) {
283 $undoLink = Html::element( 'a', array(
284 'href' => $this->mNewPage->getLocalURL( array(
285 'action' => 'edit',
286 'undoafter' => $this->mOldid,
287 'undo' => $this->mNewid ) ),
288 'title' => Linker::titleAttrib( 'undo' )
289 ),
290 $this->msg( 'editundo' )->text()
291 );
292 $revisionTools[] = $undoLink;
293 }
294 }
295
296 # Make "previous revision link"
297 if ( $samePage && $this->mOldRev->getPrevious() ) {
298 $prevlink = Linker::linkKnown(
299 $this->mOldPage,
300 $this->msg( 'previousdiff' )->escaped(),
301 array( 'id' => 'differences-prevlink' ),
302 array( 'diff' => 'prev', 'oldid' => $this->mOldid ) + $query
303 );
304 } else {
305 $prevlink = '&#160;';
306 }
307
308 if ( $this->mOldRev->isMinor() ) {
309 $oldminor = ChangesList::flag( 'minor' );
310 } else {
311 $oldminor = '';
312 }
313
314 $ldel = $this->revisionDeleteLink( $this->mOldRev );
315 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev, 'complete' );
316 $oldChangeTags = ChangeTags::formatSummaryRow( $this->mOldTags, 'diff' );
317
318 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
319 '<div id="mw-diff-otitle2">' .
320 Linker::revUserTools( $this->mOldRev, !$this->unhide ) . '</div>' .
321 '<div id="mw-diff-otitle3">' . $oldminor .
322 Linker::revComment( $this->mOldRev, !$diffOnly, !$this->unhide ) . $ldel . '</div>' .
323 '<div id="mw-diff-otitle5">' . $oldChangeTags[0] . '</div>' .
324 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
325
326 if ( $this->mOldRev->isDeleted( Revision::DELETED_TEXT ) ) {
327 $deleted = true; // old revisions text is hidden
328 if ( $this->mOldRev->isDeleted( Revision::DELETED_RESTRICTED ) ) {
329 $suppressed = true; // also suppressed
330 }
331 }
332
333 # Check if this user can see the revisions
334 if ( !$this->mOldRev->userCan( Revision::DELETED_TEXT, $user ) ) {
335 $allowed = false;
336 }
337 }
338
339 # Make "next revision link"
340 # Skip next link on the top revision
341 if ( $samePage && !$this->mNewRev->isCurrent() ) {
342 $nextlink = Linker::linkKnown(
343 $this->mNewPage,
344 $this->msg( 'nextdiff' )->escaped(),
345 array( 'id' => 'differences-nextlink' ),
346 array( 'diff' => 'next', 'oldid' => $this->mNewid ) + $query
347 );
348 } else {
349 $nextlink = '&#160;';
350 }
351
352 if ( $this->mNewRev->isMinor() ) {
353 $newminor = ChangesList::flag( 'minor' );
354 } else {
355 $newminor = '';
356 }
357
358 # Handle RevisionDelete links...
359 $rdel = $this->revisionDeleteLink( $this->mNewRev );
360
361 # Allow extensions to define their own revision tools
362 wfRunHooks( 'DiffRevisionTools', array( $this->mNewRev, &$revisionTools ) );
363 $formattedRevisionTools = array();
364 // Put each one in parentheses (poor man's button)
365 foreach ( $revisionTools as $tool ) {
366 $formattedRevisionTools[] = $this->msg( 'parentheses' )->rawParams( $tool )->escaped();
367 }
368 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev, 'complete' ) .
369 ' ' . implode( ' ', $formattedRevisionTools );
370 $newChangeTags = ChangeTags::formatSummaryRow( $this->mNewTags, 'diff' );
371
372 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
373 '<div id="mw-diff-ntitle2">' . Linker::revUserTools( $this->mNewRev, !$this->unhide ) .
374 " $rollback</div>" .
375 '<div id="mw-diff-ntitle3">' . $newminor .
376 Linker::revComment( $this->mNewRev, !$diffOnly, !$this->unhide ) . $rdel . '</div>' .
377 '<div id="mw-diff-ntitle5">' . $newChangeTags[0] . '</div>' .
378 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
379
380 if ( $this->mNewRev->isDeleted( Revision::DELETED_TEXT ) ) {
381 $deleted = true; // new revisions text is hidden
382 if ( $this->mNewRev->isDeleted( Revision::DELETED_RESTRICTED ) ) {
383 $suppressed = true; // also suppressed
384 }
385 }
386
387 # If the diff cannot be shown due to a deleted revision, then output
388 # the diff header and links to unhide (if available)...
389 if ( $deleted && ( !$this->unhide || !$allowed ) ) {
390 $this->showDiffStyle();
391 $multi = $this->getMultiNotice();
392 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
393 if ( !$allowed ) {
394 $msg = $suppressed ? 'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
395 # Give explanation for why revision is not visible
396 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
397 array( $msg ) );
398 } else {
399 # Give explanation and add a link to view the diff...
400 $query = $this->getRequest()->appendQueryValue( 'unhide', '1', true );
401 $link = $this->getTitle()->getFullURL( $query );
402 $msg = $suppressed ? 'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
403 $out->wrapWikiMsg(
404 "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
405 array( $msg, $link )
406 );
407 }
408 # Otherwise, output a regular diff...
409 } else {
410 # Add deletion notice if the user is viewing deleted content
411 $notice = '';
412 if ( $deleted ) {
413 $msg = $suppressed ? 'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
414 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" .
415 $this->msg( $msg )->parse() .
416 "</div>\n";
417 }
418 $this->showDiff( $oldHeader, $newHeader, $notice );
419 if ( !$diffOnly ) {
420 $this->renderNewRevision();
421 }
422 }
423 wfProfileOut( __METHOD__ );
424 }
425
426 /**
427 * Get a link to mark the change as patrolled, or '' if there's either no
428 * revision to patrol or the user is not allowed to to it.
429 * Side effect: When the patrol link is build, this method will call
430 * OutputPage::preventClickjacking() and load mediawiki.page.patrol.ajax.
431 *
432 * @return String
433 */
434 protected function markPatrolledLink() {
435 global $wgUseRCPatrol, $wgEnableAPI, $wgEnableWriteAPI;
436 $user = $this->getUser();
437
438 if ( $this->mMarkPatrolledLink === null ) {
439 // Prepare a change patrol link, if applicable
440 if (
441 // Is patrolling enabled and the user allowed to?
442 $wgUseRCPatrol && $this->mNewPage->quickUserCan( 'patrol', $user ) &&
443 // Only do this if the revision isn't more than 6 hours older
444 // than the Max RC age (6h because the RC might not be cleaned out regularly)
445 RecentChange::isInRCLifespan( $this->mNewRev->getTimestamp(), 21600 )
446 ) {
447 // Look for an unpatrolled change corresponding to this diff
448
449 $db = wfGetDB( DB_SLAVE );
450 $change = RecentChange::newFromConds(
451 array(
452 'rc_timestamp' => $db->timestamp( $this->mNewRev->getTimestamp() ),
453 'rc_this_oldid' => $this->mNewid,
454 'rc_patrolled' => 0
455 ),
456 __METHOD__,
457 array( 'USE INDEX' => 'rc_timestamp' )
458 );
459
460 if ( $change && $change->getPerformer()->getName() !== $user->getName() ) {
461 $rcid = $change->getAttribute( 'rc_id' );
462 } else {
463 // None found or the page has been created by the current user.
464 // If the user could patrol this it already would be patrolled
465 $rcid = 0;
466 }
467 // Build the link
468 if ( $rcid ) {
469 $this->getOutput()->preventClickjacking();
470 if ( $wgEnableAPI && $wgEnableWriteAPI
471 && $user->isAllowed( 'writeapi' )
472 ) {
473 $this->getOutput()->addModules( 'mediawiki.page.patrol.ajax' );
474 }
475
476 $token = $user->getEditToken( $rcid );
477 $this->mMarkPatrolledLink = ' <span class="patrollink">[' . Linker::linkKnown(
478 $this->mNewPage,
479 $this->msg( 'markaspatrolleddiff' )->escaped(),
480 array(),
481 array(
482 'action' => 'markpatrolled',
483 'rcid' => $rcid,
484 'token' => $token,
485 )
486 ) . ']</span>';
487 } else {
488 $this->mMarkPatrolledLink = '';
489 }
490 } else {
491 $this->mMarkPatrolledLink = '';
492 }
493 }
494
495 return $this->mMarkPatrolledLink;
496 }
497
498 /**
499 * @param $rev Revision
500 * @return String
501 */
502 protected function revisionDeleteLink( $rev ) {
503 $link = Linker::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
504 if ( $link !== '' ) {
505 $link = '&#160;&#160;&#160;' . $link . ' ';
506 }
507 return $link;
508 }
509
510 /**
511 * Show the new revision of the page.
512 */
513 function renderNewRevision() {
514 wfProfileIn( __METHOD__ );
515 $out = $this->getOutput();
516 $revHeader = $this->getRevisionHeader( $this->mNewRev );
517 # Add "current version as of X" title
518 $out->addHTML( "<hr class='diff-hr' />
519 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
520 # Page content may be handled by a hooked call instead...
521 # @codingStandardsIgnoreStart Ignoring long lines.
522 if ( wfRunHooks( 'ArticleContentOnDiff', array( $this, $out ) ) ) {
523 $this->loadNewText();
524 $out->setRevisionId( $this->mNewid );
525 $out->setRevisionTimestamp( $this->mNewRev->getTimestamp() );
526 $out->setArticleFlag( true );
527
528 // NOTE: only needed for B/C: custom rendering of JS/CSS via hook
529 if ( $this->mNewPage->isCssJsSubpage() || $this->mNewPage->isCssOrJsPage() ) {
530 // Stolen from Article::view --AG 2007-10-11
531 // Give hooks a chance to customise the output
532 // @todo standardize this crap into one function
533 if ( ContentHandler::runLegacyHooks( 'ShowRawCssJs', array( $this->mNewContent, $this->mNewPage, $out ) ) ) {
534 // NOTE: deprecated hook, B/C only
535 // use the content object's own rendering
536 $cnt = $this->mNewRev->getContent();
537 $po = $cnt ? $cnt->getParserOutput( $this->mNewRev->getTitle(), $this->mNewRev->getId() ) : null;
538 $txt = $po ? $po->getText() : '';
539 $out->addHTML( $txt );
540 }
541 } elseif ( !wfRunHooks( 'ArticleContentViewCustom', array( $this->mNewContent, $this->mNewPage, $out ) ) ) {
542 // Handled by extension
543 } elseif ( !ContentHandler::runLegacyHooks( 'ArticleViewCustom', array( $this->mNewContent, $this->mNewPage, $out ) ) ) {
544 // NOTE: deprecated hook, B/C only
545 // Handled by extension
546 } else {
547 // Normal page
548 if ( $this->getTitle()->equals( $this->mNewPage ) ) {
549 // If the Title stored in the context is the same as the one
550 // of the new revision, we can use its associated WikiPage
551 // object.
552 $wikiPage = $this->getWikiPage();
553 } else {
554 // Otherwise we need to create our own WikiPage object
555 $wikiPage = WikiPage::factory( $this->mNewPage );
556 }
557
558 $parserOutput = $this->getParserOutput( $wikiPage, $this->mNewRev );
559
560 # Also try to load it as a redirect
561 $rt = $this->mNewContent ? $this->mNewContent->getRedirectTarget() : null;
562
563 if ( $rt ) {
564 $article = Article::newFromTitle( $this->mNewPage, $this->getContext() );
565 $out->addHTML( $article->viewRedirect( $rt ) );
566
567 # WikiPage::getParserOutput() should not return false, but just in case
568 if ( $parserOutput ) {
569 # Show categories etc.
570 $out->addParserOutputNoText( $parserOutput );
571 }
572 } elseif ( $parserOutput ) {
573 $out->addParserOutput( $parserOutput );
574 }
575 }
576 }
577 # @codingStandardsIgnoreEnd
578
579 # Add redundant patrol link on bottom...
580 $out->addHTML( $this->markPatrolledLink() );
581
582 wfProfileOut( __METHOD__ );
583 }
584
585 protected function getParserOutput( WikiPage $page, Revision $rev ) {
586 $parserOptions = $page->makeParserOptions( $this->getContext() );
587
588 if ( !$rev->isCurrent() || !$rev->getTitle()->quickUserCan( "edit" ) ) {
589 $parserOptions->setEditSection( false );
590 }
591
592 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
593 return $parserOutput;
594 }
595
596 /**
597 * Get the diff text, send it to the OutputPage object
598 * Returns false if the diff could not be generated, otherwise returns true
599 *
600 * @param string|bool $otitle Header for old text or false
601 * @param string|bool $ntitle Header for new text or false
602 * @param string $notice
603 * @return bool
604 */
605 function showDiff( $otitle, $ntitle, $notice = '' ) {
606 $diff = $this->getDiff( $otitle, $ntitle, $notice );
607 if ( $diff === false ) {
608 $this->showMissingRevision();
609 return false;
610 } else {
611 $this->showDiffStyle();
612 $this->getOutput()->addHTML( $diff );
613 return true;
614 }
615 }
616
617 /**
618 * Add style sheets and supporting JS for diff display.
619 */
620 function showDiffStyle() {
621 $this->getOutput()->addModuleStyles( 'mediawiki.action.history.diff' );
622 }
623
624 /**
625 * Get complete diff table, including header
626 *
627 * @param string|bool $otitle Header for old text or false
628 * @param string|bool $ntitle Header for new text or false
629 * @param string $notice HTML between diff header and body
630 * @return mixed
631 */
632 function getDiff( $otitle, $ntitle, $notice = '' ) {
633 $body = $this->getDiffBody();
634 if ( $body === false ) {
635 return false;
636 }
637
638 $multi = $this->getMultiNotice();
639 // Display a message when the diff is empty
640 if ( $body === '' ) {
641 $notice .= '<div class="mw-diff-empty">' .
642 $this->msg( 'diff-empty' )->parse() .
643 "</div>\n";
644 }
645
646 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
647 }
648
649 /**
650 * Get the diff table body, without header
651 *
652 * @return mixed (string/false)
653 */
654 public function getDiffBody() {
655 global $wgMemc;
656 wfProfileIn( __METHOD__ );
657 $this->mCacheHit = true;
658 // Check if the diff should be hidden from this user
659 if ( !$this->loadRevisionData() ) {
660 wfProfileOut( __METHOD__ );
661 return false;
662 } elseif ( $this->mOldRev &&
663 !$this->mOldRev->userCan( Revision::DELETED_TEXT, $this->getUser() )
664 ) {
665 wfProfileOut( __METHOD__ );
666 return false;
667 } elseif ( $this->mNewRev &&
668 !$this->mNewRev->userCan( Revision::DELETED_TEXT, $this->getUser() )
669 ) {
670 wfProfileOut( __METHOD__ );
671 return false;
672 }
673 // Short-circuit
674 if ( $this->mOldRev === false || ( $this->mOldRev && $this->mNewRev
675 && $this->mOldRev->getID() == $this->mNewRev->getID() ) )
676 {
677 wfProfileOut( __METHOD__ );
678 return '';
679 }
680 // Cacheable?
681 $key = false;
682 if ( $this->mOldid && $this->mNewid ) {
683 $key = $this->getDiffBodyCacheKey();
684
685 // Try cache
686 if ( !$this->mRefreshCache ) {
687 $difftext = $wgMemc->get( $key );
688 if ( $difftext ) {
689 wfIncrStats( 'diff_cache_hit' );
690 $difftext = $this->localiseLineNumbers( $difftext );
691 $difftext .= "\n<!-- diff cache key $key -->\n";
692 wfProfileOut( __METHOD__ );
693 return $difftext;
694 }
695 } // don't try to load but save the result
696 }
697 $this->mCacheHit = false;
698
699 // Loadtext is permission safe, this just clears out the diff
700 if ( !$this->loadText() ) {
701 wfProfileOut( __METHOD__ );
702 return false;
703 }
704
705 $difftext = $this->generateContentDiffBody( $this->mOldContent, $this->mNewContent );
706
707 // Save to cache for 7 days
708 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
709 wfIncrStats( 'diff_uncacheable' );
710 } elseif ( $key !== false && $difftext !== false ) {
711 wfIncrStats( 'diff_cache_miss' );
712 $wgMemc->set( $key, $difftext, 7 * 86400 );
713 } else {
714 wfIncrStats( 'diff_uncacheable' );
715 }
716 // Replace line numbers with the text in the user's language
717 if ( $difftext !== false ) {
718 $difftext = $this->localiseLineNumbers( $difftext );
719 }
720 wfProfileOut( __METHOD__ );
721 return $difftext;
722 }
723
724 /**
725 * Returns the cache key for diff body text or content.
726 *
727 * @return string
728 * @since 1.23
729 * @throws MWException
730 */
731 protected function getDiffBodyCacheKey() {
732 if ( !$this->mOldid || !$this->mNewid ) {
733 throw new MWException( 'mOldid and mNewid must be set to get diff cache key.' );
734 }
735
736 return wfMemcKey( 'diff', 'version', MW_DIFF_VERSION,
737 'oldid', $this->mOldid, 'newid', $this->mNewid );
738 }
739
740 /**
741 * Generate a diff, no caching.
742 *
743 * This implementation uses generateTextDiffBody() to generate a diff based on the default
744 * serialization of the given Content objects. This will fail if $old or $new are not
745 * instances of TextContent.
746 *
747 * Subclasses may override this to provide a different rendering for the diff,
748 * perhaps taking advantage of the content's native form. This is required for all content
749 * models that are not text based.
750 *
751 * @param $old Content: old content
752 * @param $new Content: new content
753 *
754 * @return bool|string
755 * @since 1.21
756 * @throws MWException if $old or $new are not instances of TextContent.
757 */
758 function generateContentDiffBody( Content $old, Content $new ) {
759 if ( !( $old instanceof TextContent ) ) {
760 throw new MWException( "Diff not implemented for " . get_class( $old ) . "; "
761 . "override generateContentDiffBody to fix this." );
762 }
763
764 if ( !( $new instanceof TextContent ) ) {
765 throw new MWException( "Diff not implemented for " . get_class( $new ) . "; "
766 . "override generateContentDiffBody to fix this." );
767 }
768
769 $otext = $old->serialize();
770 $ntext = $new->serialize();
771
772 return $this->generateTextDiffBody( $otext, $ntext );
773 }
774
775 /**
776 * Generate a diff, no caching
777 *
778 * @param string $otext old text, must be already segmented
779 * @param string $ntext new text, must be already segmented
780 * @return bool|string
781 * @deprecated since 1.21, use generateContentDiffBody() instead!
782 */
783 function generateDiffBody( $otext, $ntext ) {
784 ContentHandler::deprecated( __METHOD__, "1.21" );
785
786 return $this->generateTextDiffBody( $otext, $ntext );
787 }
788
789 /**
790 * Generate a diff, no caching
791 *
792 * @todo move this to TextDifferenceEngine, make DifferenceEngine abstract. At some point.
793 *
794 * @param string $otext old text, must be already segmented
795 * @param string $ntext new text, must be already segmented
796 * @return bool|string
797 */
798 function generateTextDiffBody( $otext, $ntext ) {
799 global $wgExternalDiffEngine, $wgContLang;
800
801 wfProfileIn( __METHOD__ );
802
803 $otext = str_replace( "\r\n", "\n", $otext );
804 $ntext = str_replace( "\r\n", "\n", $ntext );
805
806 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
807 # For historical reasons, external diff engine expects
808 # input text to be HTML-escaped already
809 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
810 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
811 wfProfileOut( __METHOD__ );
812 return $wgContLang->unsegmentForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
813 $this->debug( 'wikidiff1' );
814 }
815
816 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
817 # Better external diff engine, the 2 may some day be dropped
818 # This one does the escaping and segmenting itself
819 wfProfileIn( 'wikidiff2_do_diff' );
820 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
821 $text .= $this->debug( 'wikidiff2' );
822 wfProfileOut( 'wikidiff2_do_diff' );
823 wfProfileOut( __METHOD__ );
824 return $text;
825 }
826 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
827 # Diff via the shell
828 $tmpDir = wfTempDir();
829 $tempName1 = tempnam( $tmpDir, 'diff_' );
830 $tempName2 = tempnam( $tmpDir, 'diff_' );
831
832 $tempFile1 = fopen( $tempName1, "w" );
833 if ( !$tempFile1 ) {
834 wfProfileOut( __METHOD__ );
835 return false;
836 }
837 $tempFile2 = fopen( $tempName2, "w" );
838 if ( !$tempFile2 ) {
839 wfProfileOut( __METHOD__ );
840 return false;
841 }
842 fwrite( $tempFile1, $otext );
843 fwrite( $tempFile2, $ntext );
844 fclose( $tempFile1 );
845 fclose( $tempFile2 );
846 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
847 wfProfileIn( __METHOD__ . "-shellexec" );
848 $difftext = wfShellExec( $cmd );
849 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
850 wfProfileOut( __METHOD__ . "-shellexec" );
851 unlink( $tempName1 );
852 unlink( $tempName2 );
853 wfProfileOut( __METHOD__ );
854 return $difftext;
855 }
856
857 # Native PHP diff
858 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
859 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
860 $diffs = new Diff( $ota, $nta );
861 $formatter = new TableDiffFormatter();
862 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
863 wfProfileOut( __METHOD__ );
864 return $difftext;
865 }
866
867 /**
868 * Generate a debug comment indicating diff generating time,
869 * server node, and generator backend.
870 * @return string
871 */
872 protected function debug( $generator = "internal" ) {
873 global $wgShowHostnames;
874 if ( !$this->enableDebugComment ) {
875 return '';
876 }
877 $data = array( $generator );
878 if ( $wgShowHostnames ) {
879 $data[] = wfHostname();
880 }
881 $data[] = wfTimestamp( TS_DB );
882 return "<!-- diff generator: " .
883 implode( " ",
884 array_map(
885 "htmlspecialchars",
886 $data ) ) .
887 " -->\n";
888 }
889
890 /**
891 * Replace line numbers with the text in the user's language
892 * @return mixed
893 */
894 function localiseLineNumbers( $text ) {
895 return preg_replace_callback( '/<!--LINE (\d+)-->/',
896 array( &$this, 'localiseLineNumbersCb' ), $text );
897 }
898
899 function localiseLineNumbersCb( $matches ) {
900 if ( $matches[1] === '1' && $this->mReducedLineNumbers ) {
901 return '';
902 }
903 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
904 }
905
906 /**
907 * If there are revisions between the ones being compared, return a note saying so.
908 * @return string
909 */
910 function getMultiNotice() {
911 if ( !is_object( $this->mOldRev ) || !is_object( $this->mNewRev ) ) {
912 return '';
913 } elseif ( !$this->mOldPage->equals( $this->mNewPage ) ) {
914 // Comparing two different pages? Count would be meaningless.
915 return '';
916 }
917
918 if ( $this->mOldRev->getTimestamp() > $this->mNewRev->getTimestamp() ) {
919 $oldRev = $this->mNewRev; // flip
920 $newRev = $this->mOldRev; // flip
921 } else { // normal case
922 $oldRev = $this->mOldRev;
923 $newRev = $this->mNewRev;
924 }
925
926 $nEdits = $this->mNewPage->countRevisionsBetween( $oldRev, $newRev );
927 if ( $nEdits > 0 ) {
928 $limit = 100; // use diff-multi-manyusers if too many users
929 $numUsers = $this->mNewPage->countAuthorsBetween( $oldRev, $newRev, $limit );
930 return self::intermediateEditsMsg( $nEdits, $numUsers, $limit );
931 }
932 return ''; // nothing
933 }
934
935 /**
936 * Get a notice about how many intermediate edits and users there are
937 * @param $numEdits int
938 * @param $numUsers int
939 * @param $limit int
940 * @return string
941 */
942 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
943 if ( $numUsers > $limit ) {
944 $msg = 'diff-multi-manyusers';
945 $numUsers = $limit;
946 } else {
947 $msg = 'diff-multi';
948 }
949 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
950 }
951
952 /**
953 * Get a header for a specified revision.
954 *
955 * @param $rev Revision
956 * @param string $complete 'complete' to get the header wrapped depending
957 * the visibility of the revision and a link to edit the page.
958 * @return String HTML fragment
959 */
960 protected function getRevisionHeader( Revision $rev, $complete = '' ) {
961 $lang = $this->getLanguage();
962 $user = $this->getUser();
963 $revtimestamp = $rev->getTimestamp();
964 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
965 $dateofrev = $lang->userDate( $revtimestamp, $user );
966 $timeofrev = $lang->userTime( $revtimestamp, $user );
967
968 $header = $this->msg(
969 $rev->isCurrent() ? 'currentrev-asof' : 'revisionasof',
970 $timestamp,
971 $dateofrev,
972 $timeofrev
973 )->escaped();
974
975 if ( $complete !== 'complete' ) {
976 return $header;
977 }
978
979 $title = $rev->getTitle();
980
981 $header = Linker::linkKnown( $title, $header, array(),
982 array( 'oldid' => $rev->getID() ) );
983
984 if ( $rev->userCan( Revision::DELETED_TEXT, $user ) ) {
985 $editQuery = array( 'action' => 'edit' );
986 if ( !$rev->isCurrent() ) {
987 $editQuery['oldid'] = $rev->getID();
988 }
989
990 $key = $title->quickUserCan( 'edit', $user ) ? 'editold' : 'viewsourceold';
991 $msg = $this->msg( $key )->escaped();
992 $header .= ' ' . $this->msg( 'parentheses' )->rawParams(
993 Linker::linkKnown( $title, $msg, array(), $editQuery ) )->plain();
994 if ( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
995 $header = Html::rawElement(
996 'span',
997 array( 'class' => 'history-deleted' ),
998 $header
999 );
1000 }
1001 } else {
1002 $header = Html::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
1003 }
1004
1005 return $header;
1006 }
1007
1008 /**
1009 * Add the header to a diff body
1010 *
1011 * @return string
1012 */
1013 function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
1014 // shared.css sets diff in interface language/dir, but the actual content
1015 // is often in a different language, mostly the page content language/dir
1016 $tableClass = 'diff diff-contentalign-' . htmlspecialchars( $this->getDiffLang()->alignStart() );
1017 $header = "<table class='$tableClass'>";
1018
1019 if ( !$diff && !$otitle ) {
1020 $header .= "
1021 <tr style='vertical-align: top;'>
1022 <td class='diff-ntitle'>{$ntitle}</td>
1023 </tr>";
1024 $multiColspan = 1;
1025 } else {
1026 if ( $diff ) { // Safari/Chrome show broken output if cols not used
1027 $header .= "
1028 <col class='diff-marker' />
1029 <col class='diff-content' />
1030 <col class='diff-marker' />
1031 <col class='diff-content' />";
1032 $colspan = 2;
1033 $multiColspan = 4;
1034 } else {
1035 $colspan = 1;
1036 $multiColspan = 2;
1037 }
1038 if ( $otitle || $ntitle ) {
1039 $header .= "
1040 <tr style='vertical-align: top;'>
1041 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
1042 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
1043 </tr>";
1044 }
1045 }
1046
1047 if ( $multi != '' ) {
1048 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;' " .
1049 "class='diff-multi'>{$multi}</td></tr>";
1050 }
1051 if ( $notice != '' ) {
1052 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;'>{$notice}</td></tr>";
1053 }
1054
1055 return $header . $diff . "</table>";
1056 }
1057
1058 /**
1059 * Use specified text instead of loading from the database
1060 * @deprecated since 1.21, use setContent() instead.
1061 */
1062 function setText( $oldText, $newText ) {
1063 ContentHandler::deprecated( __METHOD__, "1.21" );
1064
1065 $oldContent = ContentHandler::makeContent( $oldText, $this->getTitle() );
1066 $newContent = ContentHandler::makeContent( $newText, $this->getTitle() );
1067
1068 $this->setContent( $oldContent, $newContent );
1069 }
1070
1071 /**
1072 * Use specified text instead of loading from the database
1073 * @since 1.21
1074 */
1075 function setContent( Content $oldContent, Content $newContent ) {
1076 $this->mOldContent = $oldContent;
1077 $this->mNewContent = $newContent;
1078
1079 $this->mTextLoaded = 2;
1080 $this->mRevisionsLoaded = true;
1081 }
1082
1083 /**
1084 * Set the language in which the diff text is written
1085 * (Defaults to page content language).
1086 * @since 1.19
1087 */
1088 function setTextLanguage( $lang ) {
1089 $this->mDiffLang = wfGetLangObj( $lang );
1090 }
1091
1092 /**
1093 * Maps a revision pair definition as accepted by DifferenceEngine constructor
1094 * to a pair of actual integers representing revision ids.
1095 *
1096 * @param int $old Revision id, e.g. from URL parameter 'oldid'
1097 * @param int|string $new Revision id or strings 'next' or 'prev', e.g. from URL parameter 'diff'
1098 * @return array Array of two revision ids, older first, later second.
1099 * Zero signifies invalid argument passed.
1100 * false signifies that there is no previous/next revision ($old is the oldest/newest one).
1101 */
1102 public function mapDiffPrevNext( $old, $new ) {
1103 if ( $new === 'prev' ) {
1104 // Show diff between revision $old and the previous one. Get previous one from DB.
1105 $newid = intval( $old );
1106 $oldid = $this->getTitle()->getPreviousRevisionID( $newid );
1107 } elseif ( $new === 'next' ) {
1108 // Show diff between revision $old and the next one. Get next one from DB.
1109 $oldid = intval( $old );
1110 $newid = $this->getTitle()->getNextRevisionID( $oldid );
1111 } else {
1112 $oldid = intval( $old );
1113 $newid = intval( $new );
1114 }
1115
1116 return array( $oldid, $newid );
1117 }
1118
1119 /**
1120 * Load revision IDs
1121 */
1122 private function loadRevisionIds() {
1123 if ( $this->mRevisionsIdsLoaded ) {
1124 return;
1125 }
1126
1127 $this->mRevisionsIdsLoaded = true;
1128
1129 $old = $this->mOldid;
1130 $new = $this->mNewid;
1131
1132 list( $this->mOldid, $this->mNewid ) = self::mapDiffPrevNext( $old, $new );
1133 if ( $new === 'next' && $this->mNewid === false ) {
1134 # if no result, NewId points to the newest old revision. The only newer
1135 # revision is cur, which is "0".
1136 $this->mNewid = 0;
1137 }
1138
1139 wfRunHooks( 'NewDifferenceEngine', array( $this->getTitle(), &$this->mOldid, &$this->mNewid, $old, $new ) );
1140 }
1141
1142 /**
1143 * Load revision metadata for the specified articles. If newid is 0, then compare
1144 * the old article in oldid to the current article; if oldid is 0, then
1145 * compare the current article to the immediately previous one (ignoring the
1146 * value of newid).
1147 *
1148 * If oldid is false, leave the corresponding revision object set
1149 * to false. This is impossible via ordinary user input, and is provided for
1150 * API convenience.
1151 *
1152 * @return bool
1153 */
1154 function loadRevisionData() {
1155 if ( $this->mRevisionsLoaded ) {
1156 return true;
1157 }
1158
1159 // Whether it succeeds or fails, we don't want to try again
1160 $this->mRevisionsLoaded = true;
1161
1162 $this->loadRevisionIds();
1163
1164 // Load the new revision object
1165 if ( $this->mNewid ) {
1166 $this->mNewRev = Revision::newFromId( $this->mNewid );
1167 } else {
1168 $this->mNewRev = Revision::newFromTitle(
1169 $this->getTitle(),
1170 false,
1171 Revision::READ_NORMAL
1172 );
1173 }
1174
1175 if ( !$this->mNewRev instanceof Revision ) {
1176 return false;
1177 }
1178
1179 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1180 $this->mNewid = $this->mNewRev->getId();
1181 $this->mNewPage = $this->mNewRev->getTitle();
1182
1183 // Load the old revision object
1184 $this->mOldRev = false;
1185 if ( $this->mOldid ) {
1186 $this->mOldRev = Revision::newFromId( $this->mOldid );
1187 } elseif ( $this->mOldid === 0 ) {
1188 $rev = $this->mNewRev->getPrevious();
1189 if ( $rev ) {
1190 $this->mOldid = $rev->getId();
1191 $this->mOldRev = $rev;
1192 } else {
1193 // No previous revision; mark to show as first-version only.
1194 $this->mOldid = false;
1195 $this->mOldRev = false;
1196 }
1197 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1198
1199 if ( is_null( $this->mOldRev ) ) {
1200 return false;
1201 }
1202
1203 if ( $this->mOldRev ) {
1204 $this->mOldPage = $this->mOldRev->getTitle();
1205 }
1206
1207 // Load tags information for both revisions
1208 $dbr = wfGetDB( DB_SLAVE );
1209 if ( $this->mOldid !== false ) {
1210 $this->mOldTags = $dbr->selectField(
1211 'tag_summary',
1212 'ts_tags',
1213 array( 'ts_rev_id' => $this->mOldid ),
1214 __METHOD__
1215 );
1216 } else {
1217 $this->mOldTags = false;
1218 }
1219 $this->mNewTags = $dbr->selectField(
1220 'tag_summary',
1221 'ts_tags',
1222 array( 'ts_rev_id' => $this->mNewid ),
1223 __METHOD__
1224 );
1225
1226 return true;
1227 }
1228
1229 /**
1230 * Load the text of the revisions, as well as revision data.
1231 *
1232 * @return bool
1233 */
1234 function loadText() {
1235 if ( $this->mTextLoaded == 2 ) {
1236 return true;
1237 }
1238
1239 // Whether it succeeds or fails, we don't want to try again
1240 $this->mTextLoaded = 2;
1241
1242 if ( !$this->loadRevisionData() ) {
1243 return false;
1244 }
1245
1246 if ( $this->mOldRev ) {
1247 $this->mOldContent = $this->mOldRev->getContent( Revision::FOR_THIS_USER, $this->getUser() );
1248 if ( $this->mOldContent === null ) {
1249 return false;
1250 }
1251 }
1252
1253 if ( $this->mNewRev ) {
1254 $this->mNewContent = $this->mNewRev->getContent( Revision::FOR_THIS_USER, $this->getUser() );
1255 if ( $this->mNewContent === null ) {
1256 return false;
1257 }
1258 }
1259
1260 return true;
1261 }
1262
1263 /**
1264 * Load the text of the new revision, not the old one
1265 *
1266 * @return bool
1267 */
1268 function loadNewText() {
1269 if ( $this->mTextLoaded >= 1 ) {
1270 return true;
1271 }
1272
1273 $this->mTextLoaded = 1;
1274
1275 if ( !$this->loadRevisionData() ) {
1276 return false;
1277 }
1278
1279 $this->mNewContent = $this->mNewRev->getContent( Revision::FOR_THIS_USER, $this->getUser() );
1280
1281 return true;
1282 }
1283 }