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