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