3 * User interface for the difference engine.
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.
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.
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
21 * @ingroup DifferenceEngine
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
30 define( 'MW_DIFF_VERSION', '1.11a' );
34 * @ingroup DifferenceEngine
36 class DifferenceEngine
extends ContextSource
{
41 var $mOldTags, $mNewTags;
45 var $mOldContent, $mNewContent;
51 var $mOldPage, $mNewPage;
56 var $mOldRev, $mNewRev;
57 private $mRevisionsIdsLoaded = false; // Have the revisions IDs been loaded
58 var $mRevisionsLoaded = false; // Have the revisions been loaded
59 var $mTextLoaded = 0; // How many text blobs have been loaded, 0, 1 or 2?
60 var $mCacheHit = false; // Was the diff fetched from cache?
63 * Set this to true to add debug info to the HTML output.
64 * Warning: this may cause RSS readers to spuriously mark articles as "new"
67 var $enableDebugComment = false;
69 // If true, line X is not displayed when X is 1, for example to increase
70 // readability and conserve space with many small diffs.
71 protected $mReducedLineNumbers = false;
73 // Link to action=markpatrolled
74 protected $mMarkPatrolledLink = null;
76 protected $unhide = false; # show rev_deleted content if allowed
81 * @param $context IContextSource context to use, anything else will be ignored
82 * @param $old Integer old ID we want to show and diff with.
83 * @param $new String either 'prev' or 'next'.
84 * @param $rcid Integer Deprecated, no longer used!
85 * @param $refreshCache boolean If set, refreshes the diff cache
86 * @param $unhide boolean If set, allow viewing deleted revs
88 function __construct( $context = null, $old = 0, $new = 0, $rcid = 0,
89 $refreshCache = false, $unhide = false )
91 if ( $context instanceof IContextSource
) {
92 $this->setContext( $context );
95 wfDebug( "DifferenceEngine old '$old' new '$new' rcid '$rcid'\n" );
99 $this->mRefreshCache
= $refreshCache;
100 $this->unhide
= $unhide;
106 function setReducedLineNumbers( $value = true ) {
107 $this->mReducedLineNumbers
= $value;
113 function getDiffLang() {
114 if ( $this->mDiffLang
=== null ) {
115 # Default language in which the diff text is written.
116 $this->mDiffLang
= $this->getTitle()->getPageLanguage();
118 return $this->mDiffLang
;
124 function wasCacheHit() {
125 return $this->mCacheHit
;
131 function getOldid() {
132 $this->loadRevisionIds();
133 return $this->mOldid
;
139 function getNewid() {
140 $this->loadRevisionIds();
141 return $this->mNewid
;
145 * Look up a special:Undelete link to the given deleted revision id,
146 * as a workaround for being unable to load deleted diffs in currently.
148 * @param int $id revision ID
149 * @return mixed URL or false
151 function deletedLink( $id ) {
152 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
153 $dbr = wfGetDB( DB_SLAVE
);
154 $row = $dbr->selectRow( 'archive', '*',
155 array( 'ar_rev_id' => $id ),
158 $rev = Revision
::newFromArchiveRow( $row );
159 $title = Title
::makeTitleSafe( $row->ar_namespace
, $row->ar_title
);
160 return SpecialPage
::getTitleFor( 'Undelete' )->getFullURL( array(
161 'target' => $title->getPrefixedText(),
162 'timestamp' => $rev->getTimestamp()
170 * Build a wikitext link toward a deleted revision, if viewable.
172 * @param int $id revision ID
173 * @return string wikitext fragment
175 function deletedIdMarker( $id ) {
176 $link = $this->deletedLink( $id );
178 return "[$link $id]";
184 private function showMissingRevision() {
185 $out = $this->getOutput();
188 if ( $this->mOldRev
=== null ||
189 ( $this->mOldRev
&& $this->mOldContent
=== null )
191 $missing[] = $this->deletedIdMarker( $this->mOldid
);
193 if ( $this->mNewRev
=== null ||
194 ( $this->mNewRev
&& $this->mNewContent
=== null )
196 $missing[] = $this->deletedIdMarker( $this->mNewid
);
199 $out->setPageTitle( $this->msg( 'errorpagetitle' ) );
200 $out->addWikiMsg( 'difference-missing-revision',
201 $this->getLanguage()->listToText( $missing ), count( $missing ) );
204 function showDiffPage( $diffOnly = false ) {
205 wfProfileIn( __METHOD__
);
207 # Allow frames except in certain special cases
208 $out = $this->getOutput();
209 $out->allowClickjacking();
210 $out->setRobotPolicy( 'noindex,nofollow' );
212 if ( !$this->loadRevisionData() ) {
213 $this->showMissingRevision();
214 wfProfileOut( __METHOD__
);
218 $user = $this->getUser();
219 $permErrors = $this->mNewPage
->getUserPermissionsErrors( 'read', $user );
220 if ( $this->mOldPage
) { # mOldPage might not be set, see below.
221 $permErrors = wfMergeErrorArrays( $permErrors,
222 $this->mOldPage
->getUserPermissionsErrors( 'read', $user ) );
224 if ( count( $permErrors ) ) {
225 wfProfileOut( __METHOD__
);
226 throw new PermissionsError( 'read', $permErrors );
233 # Carry over 'diffonly' param via navigation links
234 if ( $diffOnly != $user->getBoolOption( 'diffonly' ) ) {
235 $query['diffonly'] = $diffOnly;
237 # Cascade unhide param in links for easy deletion browsing
238 if ( $this->unhide
) {
239 $query['unhide'] = 1;
242 # Check if one of the revisions is deleted/suppressed
243 $deleted = $suppressed = false;
244 $allowed = $this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $user );
246 $revisionTools = array();
248 # mOldRev is false if the difference engine is called with a "vague" query for
249 # a diff between a version V and its previous version V' AND the version V
250 # is the first version of that article. In that case, V' does not exist.
251 if ( $this->mOldRev
=== false ) {
252 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
256 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
258 if ( $this->mNewPage
->equals( $this->mOldPage
) ) {
259 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
262 $out->setPageTitle( $this->msg( 'difference-title-multipage', $this->mOldPage
->getPrefixedText(),
263 $this->mNewPage
->getPrefixedText() ) );
264 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
268 if ( $samePage && $this->mNewPage
->quickUserCan( 'edit', $user ) ) {
269 if ( $this->mNewRev
->isCurrent() && $this->mNewPage
->userCan( 'rollback', $user ) ) {
270 $rollbackLink = Linker
::generateRollback( $this->mNewRev
, $this->getContext() );
271 if ( $rollbackLink ) {
272 $out->preventClickjacking();
273 $rollback = '   ' . $rollbackLink;
276 if ( !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
277 $undoLink = Html
::element( 'a', array(
278 'href' => $this->mNewPage
->getLocalURL( array(
280 'undoafter' => $this->mOldid
,
281 'undo' => $this->mNewid
) ),
282 'title' => Linker
::titleAttrib( 'undo' )
284 $this->msg( 'editundo' )->text()
286 $revisionTools[] = $undoLink;
290 # Make "previous revision link"
291 if ( $samePage && $this->mOldRev
->getPrevious() ) {
292 $prevlink = Linker
::linkKnown(
294 $this->msg( 'previousdiff' )->escaped(),
295 array( 'id' => 'differences-prevlink' ),
296 array( 'diff' => 'prev', 'oldid' => $this->mOldid
) +
$query
299 $prevlink = ' ';
302 if ( $this->mOldRev
->isMinor() ) {
303 $oldminor = ChangesList
::flag( 'minor' );
308 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
309 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev
, 'complete' );
310 $oldChangeTags = ChangeTags
::formatSummaryRow( $this->mOldTags
, 'diff' );
312 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
313 '<div id="mw-diff-otitle2">' .
314 Linker
::revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
315 '<div id="mw-diff-otitle3">' . $oldminor .
316 Linker
::revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
317 '<div id="mw-diff-otitle5">' . $oldChangeTags[0] . '</div>' .
318 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
320 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
321 $deleted = true; // old revisions text is hidden
322 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
323 $suppressed = true; // also suppressed
327 # Check if this user can see the revisions
328 if ( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $user ) ) {
333 # Make "next revision link"
334 # Skip next link on the top revision
335 if ( $samePage && !$this->mNewRev
->isCurrent() ) {
336 $nextlink = Linker
::linkKnown(
338 $this->msg( 'nextdiff' )->escaped(),
339 array( 'id' => 'differences-nextlink' ),
340 array( 'diff' => 'next', 'oldid' => $this->mNewid
) +
$query
343 $nextlink = ' ';
346 if ( $this->mNewRev
->isMinor() ) {
347 $newminor = ChangesList
::flag( 'minor' );
352 # Handle RevisionDelete links...
353 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
355 # Allow extensions to define their own revision tools
356 wfRunHooks( 'DiffRevisionTools', array( $this->mNewRev
, &$revisionTools ) );
357 $formattedRevisionTools = array();
358 // Put each one in parentheses (poor man's button)
359 foreach ( $revisionTools as $tool ) {
360 $formattedRevisionTools[] = $this->msg( 'parentheses' )->rawParams( $tool )->escaped();
362 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev
, 'complete' ) . ' ' . implode( ' ', $formattedRevisionTools );
363 $newChangeTags = ChangeTags
::formatSummaryRow( $this->mNewTags
, 'diff' );
365 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
366 '<div id="mw-diff-ntitle2">' . Linker
::revUserTools( $this->mNewRev
, !$this->unhide
) .
368 '<div id="mw-diff-ntitle3">' . $newminor .
369 Linker
::revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
370 '<div id="mw-diff-ntitle5">' . $newChangeTags[0] . '</div>' .
371 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
373 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
374 $deleted = true; // new revisions text is hidden
375 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
376 $suppressed = true; // also suppressed
380 # If the diff cannot be shown due to a deleted revision, then output
381 # the diff header and links to unhide (if available)...
382 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
383 $this->showDiffStyle();
384 $multi = $this->getMultiNotice();
385 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
387 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
388 # Give explanation for why revision is not visible
389 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
392 # Give explanation and add a link to view the diff...
393 $link = $this->getTitle()->getFullURL( $this->getRequest()->appendQueryValue( 'unhide', '1', true ) );
394 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
395 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n", array( $msg, $link ) );
397 # Otherwise, output a regular diff...
399 # Add deletion notice if the user is viewing deleted content
402 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
403 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" . $this->msg( $msg )->parse() . "</div>\n";
405 $this->showDiff( $oldHeader, $newHeader, $notice );
407 $this->renderNewRevision();
410 wfProfileOut( __METHOD__
);
414 * Get a link to mark the change as patrolled, or '' if there's either no
415 * revision to patrol or the user is not allowed to to it.
416 * Side effect: When the patrol link is build, this method will call
417 * OutputPage::preventClickjacking() and load mediawiki.page.patrol.ajax.
421 protected function markPatrolledLink() {
422 global $wgUseRCPatrol, $wgEnableAPI, $wgEnableWriteAPI;
423 $user = $this->getUser();
425 if ( $this->mMarkPatrolledLink
=== null ) {
426 // Prepare a change patrol link, if applicable
428 // Is patrolling enabled and the user allowed to?
429 $wgUseRCPatrol && $this->mNewPage
->quickUserCan( 'patrol', $user ) &&
430 // Only do this if the revision isn't more than 6 hours older
431 // than the Max RC age (6h because the RC might not be cleaned out regularly)
432 RecentChange
::isInRCLifespan( $this->mNewRev
->getTimestamp(), 21600 )
434 // Look for an unpatrolled change corresponding to this diff
436 $db = wfGetDB( DB_SLAVE
);
437 $change = RecentChange
::newFromConds(
439 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
440 'rc_this_oldid' => $this->mNewid
,
444 array( 'USE INDEX' => 'rc_timestamp' )
447 if ( $change && $change->getPerformer()->getName() !== $user->getName() ) {
448 $rcid = $change->getAttribute( 'rc_id' );
450 // None found or the page has been created by the current user.
451 // If the user could patrol this it already would be patrolled
456 $this->getOutput()->preventClickjacking();
457 if ( $wgEnableAPI && $wgEnableWriteAPI
458 && $user->isAllowed( 'writeapi' )
460 $this->getOutput()->addModules( 'mediawiki.page.patrol.ajax' );
463 $token = $user->getEditToken( $rcid );
464 $this->mMarkPatrolledLink
= ' <span class="patrollink">[' . Linker
::linkKnown(
466 $this->msg( 'markaspatrolleddiff' )->escaped(),
469 'action' => 'markpatrolled',
475 $this->mMarkPatrolledLink
= '';
478 $this->mMarkPatrolledLink
= '';
482 return $this->mMarkPatrolledLink
;
486 * @param $rev Revision
489 protected function revisionDeleteLink( $rev ) {
490 $link = Linker
::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
491 if ( $link !== '' ) {
492 $link = '   ' . $link . ' ';
498 * Show the new revision of the page.
500 function renderNewRevision() {
501 wfProfileIn( __METHOD__
);
502 $out = $this->getOutput();
503 $revHeader = $this->getRevisionHeader( $this->mNewRev
);
504 # Add "current version as of X" title
505 $out->addHTML( "<hr class='diff-hr' />
506 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
507 # Page content may be handled by a hooked call instead...
508 if ( wfRunHooks( 'ArticleContentOnDiff', array( $this, $out ) ) ) {
509 $this->loadNewText();
510 $out->setRevisionId( $this->mNewid
);
511 $out->setRevisionTimestamp( $this->mNewRev
->getTimestamp() );
512 $out->setArticleFlag( true );
514 // NOTE: only needed for B/C: custom rendering of JS/CSS via hook
515 if ( $this->mNewPage
->isCssJsSubpage() ||
$this->mNewPage
->isCssOrJsPage() ) {
516 // Stolen from Article::view --AG 2007-10-11
517 // Give hooks a chance to customise the output
518 // @todo standardize this crap into one function
519 if ( ContentHandler
::runLegacyHooks( 'ShowRawCssJs', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
520 // NOTE: deprecated hook, B/C only
521 // use the content object's own rendering
522 $cnt = $this->mNewRev
->getContent();
523 $po = $cnt ?
$cnt->getParserOutput( $this->mNewRev
->getTitle(), $this->mNewRev
->getId() ) : null;
524 $txt = $po ?
$po->getText() : '';
525 $out->addHTML( $txt );
527 } elseif ( !wfRunHooks( 'ArticleContentViewCustom', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
528 // Handled by extension
529 } elseif ( !ContentHandler
::runLegacyHooks( 'ArticleViewCustom', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
530 // NOTE: deprecated hook, B/C only
531 // Handled by extension
534 if ( $this->getTitle()->equals( $this->mNewPage
) ) {
535 // If the Title stored in the context is the same as the one
536 // of the new revision, we can use its associated WikiPage
538 $wikiPage = $this->getWikiPage();
540 // Otherwise we need to create our own WikiPage object
541 $wikiPage = WikiPage
::factory( $this->mNewPage
);
544 $parserOutput = $this->getParserOutput( $wikiPage, $this->mNewRev
);
546 # Also try to load it as a redirect
547 $rt = $this->mNewContent ?
$this->mNewContent
->getRedirectTarget() : null;
550 $article = Article
::newFromTitle( $this->mNewPage
, $this->getContext() );
551 $out->addHTML( $article->viewRedirect( $rt ) );
553 # WikiPage::getParserOutput() should not return false, but just in case
554 if ( $parserOutput ) {
555 # Show categories etc.
556 $out->addParserOutputNoText( $parserOutput );
558 } elseif ( $parserOutput ) {
559 $out->addParserOutput( $parserOutput );
563 # Add redundant patrol link on bottom...
564 $out->addHTML( $this->markPatrolledLink() );
566 wfProfileOut( __METHOD__
);
569 protected function getParserOutput( WikiPage
$page, Revision
$rev ) {
570 $parserOptions = $page->makeParserOptions( $this->getContext() );
572 if ( !$rev->isCurrent() ||
!$rev->getTitle()->quickUserCan( "edit" ) ) {
573 $parserOptions->setEditSection( false );
576 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
577 return $parserOutput;
581 * Get the diff text, send it to the OutputPage object
582 * Returns false if the diff could not be generated, otherwise returns true
586 function showDiff( $otitle, $ntitle, $notice = '' ) {
587 $diff = $this->getDiff( $otitle, $ntitle, $notice );
588 if ( $diff === false ) {
589 $this->showMissingRevision();
592 $this->showDiffStyle();
593 $this->getOutput()->addHTML( $diff );
599 * Add style sheets and supporting JS for diff display.
601 function showDiffStyle() {
602 $this->getOutput()->addModuleStyles( 'mediawiki.action.history.diff' );
606 * Get complete diff table, including header
608 * @param string|bool $otitle Header for old text or false
609 * @param string|bool $ntitle Header for new text or false
610 * @param string $notice HTML between diff header and body
613 function getDiff( $otitle, $ntitle, $notice = '' ) {
614 $body = $this->getDiffBody();
615 if ( $body === false ) {
618 $multi = $this->getMultiNotice();
619 // Display a message when the diff is empty
620 if ( $body === '' ) {
621 $notice .= '<div class="mw-diff-empty">' . $this->msg( 'diff-empty' )->parse() . "</div>\n";
623 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
628 * Get the diff table body, without header
630 * @return mixed (string/false)
632 public function getDiffBody() {
634 wfProfileIn( __METHOD__
);
635 $this->mCacheHit
= true;
636 // Check if the diff should be hidden from this user
637 if ( !$this->loadRevisionData() ) {
638 wfProfileOut( __METHOD__
);
640 } elseif ( $this->mOldRev
&& !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
641 wfProfileOut( __METHOD__
);
643 } elseif ( $this->mNewRev
&& !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
644 wfProfileOut( __METHOD__
);
648 if ( $this->mOldRev
=== false ||
( $this->mOldRev
&& $this->mNewRev
649 && $this->mOldRev
->getID() == $this->mNewRev
->getID() ) )
651 wfProfileOut( __METHOD__
);
656 if ( $this->mOldid
&& $this->mNewid
) {
657 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
,
658 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
660 if ( !$this->mRefreshCache
) {
661 $difftext = $wgMemc->get( $key );
663 wfIncrStats( 'diff_cache_hit' );
664 $difftext = $this->localiseLineNumbers( $difftext );
665 $difftext .= "\n<!-- diff cache key $key -->\n";
666 wfProfileOut( __METHOD__
);
669 } // don't try to load but save the result
671 $this->mCacheHit
= false;
673 // Loadtext is permission safe, this just clears out the diff
674 if ( !$this->loadText() ) {
675 wfProfileOut( __METHOD__
);
679 $difftext = $this->generateContentDiffBody( $this->mOldContent
, $this->mNewContent
);
681 // Save to cache for 7 days
682 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
683 wfIncrStats( 'diff_uncacheable' );
684 } elseif ( $key !== false && $difftext !== false ) {
685 wfIncrStats( 'diff_cache_miss' );
686 $wgMemc->set( $key, $difftext, 7 * 86400 );
688 wfIncrStats( 'diff_uncacheable' );
690 // Replace line numbers with the text in the user's language
691 if ( $difftext !== false ) {
692 $difftext = $this->localiseLineNumbers( $difftext );
694 wfProfileOut( __METHOD__
);
699 * Generate a diff, no caching.
701 * This implementation uses generateTextDiffBody() to generate a diff based on the default
702 * serialization of the given Content objects. This will fail if $old or $new are not
703 * instances of TextContent.
705 * Subclasses may override this to provide a different rendering for the diff,
706 * perhaps taking advantage of the content's native form. This is required for all content
707 * models that are not text based.
709 * @param $old Content: old content
710 * @param $new Content: new content
712 * @return bool|string
714 * @throws MWException if $old or $new are not instances of TextContent.
716 function generateContentDiffBody( Content
$old, Content
$new ) {
717 if ( !( $old instanceof TextContent
) ) {
718 throw new MWException( "Diff not implemented for " . get_class( $old ) . "; "
719 . "override generateContentDiffBody to fix this." );
722 if ( !( $new instanceof TextContent
) ) {
723 throw new MWException( "Diff not implemented for " . get_class( $new ) . "; "
724 . "override generateContentDiffBody to fix this." );
727 $otext = $old->serialize();
728 $ntext = $new->serialize();
730 return $this->generateTextDiffBody( $otext, $ntext );
734 * Generate a diff, no caching
736 * @param string $otext old text, must be already segmented
737 * @param string $ntext new text, must be already segmented
738 * @return bool|string
739 * @deprecated since 1.21, use generateContentDiffBody() instead!
741 function generateDiffBody( $otext, $ntext ) {
742 ContentHandler
::deprecated( __METHOD__
, "1.21" );
744 return $this->generateTextDiffBody( $otext, $ntext );
748 * Generate a diff, no caching
750 * @todo move this to TextDifferenceEngine, make DifferenceEngine abstract. At some point.
752 * @param string $otext old text, must be already segmented
753 * @param string $ntext new text, must be already segmented
754 * @return bool|string
756 function generateTextDiffBody( $otext, $ntext ) {
757 global $wgExternalDiffEngine, $wgContLang;
759 wfProfileIn( __METHOD__
);
761 $otext = str_replace( "\r\n", "\n", $otext );
762 $ntext = str_replace( "\r\n", "\n", $ntext );
764 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
765 # For historical reasons, external diff engine expects
766 # input text to be HTML-escaped already
767 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
768 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
769 wfProfileOut( __METHOD__
);
770 return $wgContLang->unsegmentForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
771 $this->debug( 'wikidiff1' );
774 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
775 # Better external diff engine, the 2 may some day be dropped
776 # This one does the escaping and segmenting itself
777 wfProfileIn( 'wikidiff2_do_diff' );
778 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
779 $text .= $this->debug( 'wikidiff2' );
780 wfProfileOut( 'wikidiff2_do_diff' );
781 wfProfileOut( __METHOD__
);
784 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
786 $tmpDir = wfTempDir();
787 $tempName1 = tempnam( $tmpDir, 'diff_' );
788 $tempName2 = tempnam( $tmpDir, 'diff_' );
790 $tempFile1 = fopen( $tempName1, "w" );
792 wfProfileOut( __METHOD__
);
795 $tempFile2 = fopen( $tempName2, "w" );
797 wfProfileOut( __METHOD__
);
800 fwrite( $tempFile1, $otext );
801 fwrite( $tempFile2, $ntext );
802 fclose( $tempFile1 );
803 fclose( $tempFile2 );
804 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
805 wfProfileIn( __METHOD__
. "-shellexec" );
806 $difftext = wfShellExec( $cmd );
807 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
808 wfProfileOut( __METHOD__
. "-shellexec" );
809 unlink( $tempName1 );
810 unlink( $tempName2 );
811 wfProfileOut( __METHOD__
);
816 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
817 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
818 $diffs = new Diff( $ota, $nta );
819 $formatter = new TableDiffFormatter();
820 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
821 wfProfileOut( __METHOD__
);
826 * Generate a debug comment indicating diff generating time,
827 * server node, and generator backend.
830 protected function debug( $generator = "internal" ) {
831 global $wgShowHostnames;
832 if ( !$this->enableDebugComment
) {
835 $data = array( $generator );
836 if ( $wgShowHostnames ) {
837 $data[] = wfHostname();
839 $data[] = wfTimestamp( TS_DB
);
840 return "<!-- diff generator: " .
849 * Replace line numbers with the text in the user's language
852 function localiseLineNumbers( $text ) {
853 return preg_replace_callback( '/<!--LINE (\d+)-->/',
854 array( &$this, 'localiseLineNumbersCb' ), $text );
857 function localiseLineNumbersCb( $matches ) {
858 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) {
861 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
865 * If there are revisions between the ones being compared, return a note saying so.
868 function getMultiNotice() {
869 if ( !is_object( $this->mOldRev
) ||
!is_object( $this->mNewRev
) ) {
871 } elseif ( !$this->mOldPage
->equals( $this->mNewPage
) ) {
872 // Comparing two different pages? Count would be meaningless.
876 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
877 $oldRev = $this->mNewRev
; // flip
878 $newRev = $this->mOldRev
; // flip
879 } else { // normal case
880 $oldRev = $this->mOldRev
;
881 $newRev = $this->mNewRev
;
884 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev );
886 $limit = 100; // use diff-multi-manyusers if too many users
887 $numUsers = $this->mNewPage
->countAuthorsBetween( $oldRev, $newRev, $limit );
888 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
890 return ''; // nothing
894 * Get a notice about how many intermediate edits and users there are
895 * @param $numEdits int
896 * @param $numUsers int
900 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
901 if ( $numUsers > $limit ) {
902 $msg = 'diff-multi-manyusers';
907 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
911 * Get a header for a specified revision.
913 * @param $rev Revision
914 * @param string $complete 'complete' to get the header wrapped depending
915 * the visibility of the revision and a link to edit the page.
916 * @return String HTML fragment
918 protected function getRevisionHeader( Revision
$rev, $complete = '' ) {
919 $lang = $this->getLanguage();
920 $user = $this->getUser();
921 $revtimestamp = $rev->getTimestamp();
922 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
923 $dateofrev = $lang->userDate( $revtimestamp, $user );
924 $timeofrev = $lang->userTime( $revtimestamp, $user );
926 $header = $this->msg(
927 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
933 if ( $complete !== 'complete' ) {
937 $title = $rev->getTitle();
939 $header = Linker
::linkKnown( $title, $header, array(),
940 array( 'oldid' => $rev->getID() ) );
942 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
943 $editQuery = array( 'action' => 'edit' );
944 if ( !$rev->isCurrent() ) {
945 $editQuery['oldid'] = $rev->getID();
948 $msg = $this->msg( $title->quickUserCan( 'edit', $user ) ?
'editold' : 'viewsourceold' )->escaped();
949 $header .= ' ' . $this->msg( 'parentheses' )->rawParams(
950 Linker
::linkKnown( $title, $msg, array(), $editQuery ) )->plain();
951 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
952 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
955 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
962 * Add the header to a diff body
966 function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
967 // shared.css sets diff in interface language/dir, but the actual content
968 // is often in a different language, mostly the page content language/dir
969 $tableClass = 'diff diff-contentalign-' . htmlspecialchars( $this->getDiffLang()->alignStart() );
970 $header = "<table class='$tableClass'>";
972 if ( !$diff && !$otitle ) {
974 <tr style='vertical-align: top;'>
975 <td class='diff-ntitle'>{$ntitle}</td>
979 if ( $diff ) { // Safari/Chrome show broken output if cols not used
981 <col class='diff-marker' />
982 <col class='diff-content' />
983 <col class='diff-marker' />
984 <col class='diff-content' />";
991 if ( $otitle ||
$ntitle ) {
993 <tr style='vertical-align: top;'>
994 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
995 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
1000 if ( $multi != '' ) {
1001 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;' class='diff-multi'>{$multi}</td></tr>";
1003 if ( $notice != '' ) {
1004 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;'>{$notice}</td></tr>";
1007 return $header . $diff . "</table>";
1011 * Use specified text instead of loading from the database
1012 * @deprecated since 1.21, use setContent() instead.
1014 function setText( $oldText, $newText ) {
1015 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1017 $oldContent = ContentHandler
::makeContent( $oldText, $this->getTitle() );
1018 $newContent = ContentHandler
::makeContent( $newText, $this->getTitle() );
1020 $this->setContent( $oldContent, $newContent );
1024 * Use specified text instead of loading from the database
1027 function setContent( Content
$oldContent, Content
$newContent ) {
1028 $this->mOldContent
= $oldContent;
1029 $this->mNewContent
= $newContent;
1031 $this->mTextLoaded
= 2;
1032 $this->mRevisionsLoaded
= true;
1036 * Set the language in which the diff text is written
1037 * (Defaults to page content language).
1040 function setTextLanguage( $lang ) {
1041 $this->mDiffLang
= wfGetLangObj( $lang );
1045 * Maps a revision pair definition as accepted by DifferenceEngine constructor
1046 * to a pair of actual integers representing revision ids.
1048 * @param int $old Revision id, e.g. from URL parameter 'oldid'
1049 * @param int|string $new Revision id or strings 'next' or 'prev', e.g. from URL parameter 'diff'
1050 * @return array Array of two revision ids, older first, later second.
1051 * Zero signifies invalid argument passed.
1052 * false signifies that there is no previous/next revision ($old is the oldest/newest one).
1054 public function mapDiffPrevNext( $old, $new ) {
1055 if ( $new === 'prev' ) {
1056 // Show diff between revision $old and the previous one. Get previous one from DB.
1057 $newid = intval( $old );
1058 $oldid = $this->getTitle()->getPreviousRevisionID( $newid );
1059 } elseif ( $new === 'next' ) {
1060 // Show diff between revision $old and the next one. Get next one from DB.
1061 $oldid = intval( $old );
1062 $newid = $this->getTitle()->getNextRevisionID( $oldid );
1064 $oldid = intval( $old );
1065 $newid = intval( $new );
1068 return array( $oldid, $newid );
1074 private function loadRevisionIds() {
1075 if ( $this->mRevisionsIdsLoaded
) {
1079 $this->mRevisionsIdsLoaded
= true;
1081 $old = $this->mOldid
;
1082 $new = $this->mNewid
;
1084 list( $this->mOldid
, $this->mNewid
) = self
::mapDiffPrevNext( $old, $new );
1085 if ( $new === 'next' && $this->mNewid
=== false ) {
1086 # if no result, NewId points to the newest old revision. The only newer
1087 # revision is cur, which is "0".
1091 wfRunHooks( 'NewDifferenceEngine', array( $this->getTitle(), &$this->mOldid
, &$this->mNewid
, $old, $new ) );
1095 * Load revision metadata for the specified articles. If newid is 0, then compare
1096 * the old article in oldid to the current article; if oldid is 0, then
1097 * compare the current article to the immediately previous one (ignoring the
1100 * If oldid is false, leave the corresponding revision object set
1101 * to false. This is impossible via ordinary user input, and is provided for
1106 function loadRevisionData() {
1107 if ( $this->mRevisionsLoaded
) {
1111 // Whether it succeeds or fails, we don't want to try again
1112 $this->mRevisionsLoaded
= true;
1114 $this->loadRevisionIds();
1116 // Load the new revision object
1117 $this->mNewRev
= $this->mNewid
1118 ? Revision
::newFromId( $this->mNewid
)
1119 : Revision
::newFromTitle( $this->getTitle(), false, Revision
::READ_NORMAL
);
1121 if ( !$this->mNewRev
instanceof Revision
) {
1125 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1126 $this->mNewid
= $this->mNewRev
->getId();
1127 $this->mNewPage
= $this->mNewRev
->getTitle();
1129 // Load the old revision object
1130 $this->mOldRev
= false;
1131 if ( $this->mOldid
) {
1132 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1133 } elseif ( $this->mOldid
=== 0 ) {
1134 $rev = $this->mNewRev
->getPrevious();
1136 $this->mOldid
= $rev->getId();
1137 $this->mOldRev
= $rev;
1139 // No previous revision; mark to show as first-version only.
1140 $this->mOldid
= false;
1141 $this->mOldRev
= false;
1143 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1145 if ( is_null( $this->mOldRev
) ) {
1149 if ( $this->mOldRev
) {
1150 $this->mOldPage
= $this->mOldRev
->getTitle();
1153 // Load tags information for both revisions
1154 $dbr = wfGetDB( DB_SLAVE
);
1155 if ( $this->mOldid
!== false ) {
1156 $this->mOldTags
= $dbr->selectField(
1159 array( 'ts_rev_id' => $this->mOldid
),
1163 $this->mOldTags
= false;
1165 $this->mNewTags
= $dbr->selectField(
1168 array( 'ts_rev_id' => $this->mNewid
),
1176 * Load the text of the revisions, as well as revision data.
1180 function loadText() {
1181 if ( $this->mTextLoaded
== 2 ) {
1185 // Whether it succeeds or fails, we don't want to try again
1186 $this->mTextLoaded
= 2;
1188 if ( !$this->loadRevisionData() ) {
1192 if ( $this->mOldRev
) {
1193 $this->mOldContent
= $this->mOldRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1194 if ( $this->mOldContent
=== null ) {
1199 if ( $this->mNewRev
) {
1200 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1201 if ( $this->mNewContent
=== null ) {
1210 * Load the text of the new revision, not the old one
1214 function loadNewText() {
1215 if ( $this->mTextLoaded
>= 1 ) {
1219 $this->mTextLoaded
= 1;
1221 if ( !$this->loadRevisionData() ) {
1225 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );