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
{
44 var $mOldContent, $mNewContent;
50 var $mOldPage, $mNewPage;
51 var $mRcidMarkPatrolled;
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 string $new either 'prev' or 'next'.
84 * @param $rcid Integer ??? FIXME (default 0)
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->mRcidMarkPatrolled
= intval( $rcid ); # force it to be an integer
100 $this->mRefreshCache
= $refreshCache;
101 $this->unhide
= $unhide;
107 function setReducedLineNumbers( $value = true ) {
108 $this->mReducedLineNumbers
= $value;
114 function getDiffLang() {
115 if ( $this->mDiffLang
=== null ) {
116 # Default language in which the diff text is written.
117 $this->mDiffLang
= $this->getTitle()->getPageLanguage();
119 return $this->mDiffLang
;
125 function wasCacheHit() {
126 return $this->mCacheHit
;
132 function getOldid() {
133 $this->loadRevisionIds();
134 return $this->mOldid
;
140 function getNewid() {
141 $this->loadRevisionIds();
142 return $this->mNewid
;
146 * Look up a special:Undelete link to the given deleted revision id,
147 * as a workaround for being unable to load deleted diffs in currently.
149 * @param int $id revision ID
150 * @return mixed URL or false
152 function deletedLink( $id ) {
153 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
154 $dbr = wfGetDB( DB_SLAVE
);
155 $row = $dbr->selectRow( 'archive', '*',
156 array( 'ar_rev_id' => $id ),
159 $rev = Revision
::newFromArchiveRow( $row );
160 $title = Title
::makeTitleSafe( $row->ar_namespace
, $row->ar_title
);
161 return SpecialPage
::getTitleFor( 'Undelete' )->getFullURL( array(
162 'target' => $title->getPrefixedText(),
163 'timestamp' => $rev->getTimestamp()
171 * Build a wikitext link toward a deleted revision, if viewable.
173 * @param int $id revision ID
174 * @return string wikitext fragment
176 function deletedIdMarker( $id ) {
177 $link = $this->deletedLink( $id );
179 return "[$link $id]";
185 private function showMissingRevision() {
186 $out = $this->getOutput();
189 if ( $this->mOldRev
=== null ) {
190 $missing[] = $this->deletedIdMarker( $this->mOldid
);
192 if ( $this->mNewRev
=== null ) {
193 $missing[] = $this->deletedIdMarker( $this->mNewid
);
196 $out->setPageTitle( $this->msg( 'errorpagetitle' ) );
197 $out->addWikiMsg( 'difference-missing-revision',
198 $this->getLanguage()->listToText( $missing ), count( $missing ) );
201 function showDiffPage( $diffOnly = false ) {
202 wfProfileIn( __METHOD__
);
204 # Allow frames except in certain special cases
205 $out = $this->getOutput();
206 $out->allowClickjacking();
207 $out->setRobotPolicy( 'noindex,nofollow' );
209 if ( !$this->loadRevisionData() ) {
210 $this->showMissingRevision();
211 wfProfileOut( __METHOD__
);
215 $user = $this->getUser();
216 $permErrors = $this->mNewPage
->getUserPermissionsErrors( 'read', $user );
217 if ( $this->mOldPage
) { # mOldPage might not be set, see below.
218 $permErrors = wfMergeErrorArrays( $permErrors,
219 $this->mOldPage
->getUserPermissionsErrors( 'read', $user ) );
221 if ( count( $permErrors ) ) {
222 wfProfileOut( __METHOD__
);
223 throw new PermissionsError( 'read', $permErrors );
226 # If external diffs are enabled both globally and for the user,
227 # we'll use the application/x-external-editor interface to call
228 # an external diff tool like kompare, kdiff3, etc.
229 if ( ExternalEdit
::useExternalEngine( $this->getContext(), 'diff' ) ) {
230 //TODO: come up with a good solution for non-text content here.
231 // at least, the content format needs to be passed to the client somehow.
232 // Currently, action=raw will just fail for non-text content.
235 'File' => array( 'Extension' => 'wiki', 'URL' =>
236 # This should be mOldPage, but it may not be set, see below.
237 $this->mNewPage
->getCanonicalURL( array(
238 'action' => 'raw', 'oldid' => $this->mOldid
) )
240 'File2' => array( 'Extension' => 'wiki', 'URL' =>
241 $this->mNewPage
->getCanonicalURL( array(
242 'action' => 'raw', 'oldid' => $this->mNewid
) )
246 $externalEditor = new ExternalEdit( $this->getContext(), $urls );
247 $externalEditor->execute();
249 wfProfileOut( __METHOD__
);
257 # Carry over 'diffonly' param via navigation links
258 if ( $diffOnly != $user->getBoolOption( 'diffonly' ) ) {
259 $query['diffonly'] = $diffOnly;
261 # Cascade unhide param in links for easy deletion browsing
262 if ( $this->unhide
) {
263 $query['unhide'] = 1;
266 # Check if one of the revisions is deleted/suppressed
267 $deleted = $suppressed = false;
268 $allowed = $this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $user );
270 # mOldRev is false if the difference engine is called with a "vague" query for
271 # a diff between a version V and its previous version V' AND the version V
272 # is the first version of that article. In that case, V' does not exist.
273 if ( $this->mOldRev
=== false ) {
274 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
278 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
280 $sk = $this->getSkin();
281 if ( method_exists( $sk, 'suppressQuickbar' ) ) {
282 $sk->suppressQuickbar();
285 if ( $this->mNewPage
->equals( $this->mOldPage
) ) {
286 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
289 $out->setPageTitle( $this->msg( 'difference-title-multipage', $this->mOldPage
->getPrefixedText(),
290 $this->mNewPage
->getPrefixedText() ) );
291 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
295 $revisionTools = array();
296 if ( $samePage && $this->mNewPage
->quickUserCan( 'edit', $user ) ) {
297 if ( $this->mNewRev
->isCurrent() && $this->mNewPage
->userCan( 'rollback', $user ) ) {
298 $rollbackLink = Linker
::generateRollback( $this->mNewRev
, $this->getContext() );
299 if ( $rollbackLink ) {
300 $out->preventClickjacking();
301 $rollback = '   ' . $rollbackLink;
304 if ( !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
305 $undoLink = Html
::element( 'a', array(
306 'href' => $this->mNewPage
->getLocalUrl( array(
308 'undoafter' => $this->mOldid
,
309 'undo' => $this->mNewid
) ),
310 'title' => Linker
::titleAttrib( 'undo' )
312 $this->msg( 'editundo' )->text()
314 $revisionTools[] = $undoLink;
318 # Make "previous revision link"
319 if ( $samePage && $this->mOldRev
->getPrevious() ) {
320 $prevlink = Linker
::linkKnown(
322 $this->msg( 'previousdiff' )->escaped(),
323 array( 'id' => 'differences-prevlink' ),
324 array( 'diff' => 'prev', 'oldid' => $this->mOldid
) +
$query
327 $prevlink = ' ';
330 if ( $this->mOldRev
->isMinor() ) {
331 $oldminor = ChangesList
::flag( 'minor' );
336 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
337 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev
, 'complete' );
339 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
340 '<div id="mw-diff-otitle2">' .
341 Linker
::revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
342 '<div id="mw-diff-otitle3">' . $oldminor .
343 Linker
::revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
344 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
346 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
347 $deleted = true; // old revisions text is hidden
348 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
349 $suppressed = true; // also suppressed
353 # Check if this user can see the revisions
354 if ( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $user ) ) {
359 # Make "next revision link"
360 # Skip next link on the top revision
361 if ( $samePage && !$this->mNewRev
->isCurrent() ) {
362 $nextlink = Linker
::linkKnown(
364 $this->msg( 'nextdiff' )->escaped(),
365 array( 'id' => 'differences-nextlink' ),
366 array( 'diff' => 'next', 'oldid' => $this->mNewid
) +
$query
369 $nextlink = ' ';
372 if ( $this->mNewRev
->isMinor() ) {
373 $newminor = ChangesList
::flag( 'minor' );
378 # Handle RevisionDelete links...
379 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
381 # Allow extensions to define their own revision tools
382 wfRunHooks( 'DiffRevisionTools', array( $this->mNewRev
, &$revisionTools ) );
383 $formattedRevisionTools = array();
384 // Put each one in parentheses (poor man's button)
385 foreach ( $revisionTools as $tool ) {
386 $formattedRevisionTools[] = $this->msg( 'parentheses' )->rawParams( $tool )->escaped();
388 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev
, 'complete' ) . ' ' . implode( ' ', $formattedRevisionTools );
390 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
391 '<div id="mw-diff-ntitle2">' . Linker
::revUserTools( $this->mNewRev
, !$this->unhide
) .
393 '<div id="mw-diff-ntitle3">' . $newminor .
394 Linker
::revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
395 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
397 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
398 $deleted = true; // new revisions text is hidden
399 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
400 $suppressed = true; // also suppressed
403 # If the diff cannot be shown due to a deleted revision, then output
404 # the diff header and links to unhide (if available)...
405 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
406 $this->showDiffStyle();
407 $multi = $this->getMultiNotice();
408 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
410 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
411 # Give explanation for why revision is not visible
412 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
415 # Give explanation and add a link to view the diff...
416 $link = $this->getTitle()->getFullUrl( $this->getRequest()->appendQueryValue( 'unhide', '1', true ) );
417 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
418 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n", array( $msg, $link ) );
420 # Otherwise, output a regular diff...
422 # Add deletion notice if the user is viewing deleted content
425 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
426 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" . $this->msg( $msg )->parse() . "</div>\n";
428 $this->showDiff( $oldHeader, $newHeader, $notice );
430 $this->renderNewRevision();
433 wfProfileOut( __METHOD__
);
437 * Get a link to mark the change as patrolled, or '' if there's either no
438 * revision to patrol or the user is not allowed to to it.
439 * Side effect: When the patrol link is build, this method will call
440 * OutputPage::preventClickjacking() and load mediawiki.page.patrol.ajax.
444 protected function markPatrolledLink() {
445 global $wgUseRCPatrol;
447 if ( $this->mMarkPatrolledLink
=== null ) {
448 // Prepare a change patrol link, if applicable
449 if ( $wgUseRCPatrol && $this->mNewPage
->quickUserCan( 'patrol', $this->getUser() ) ) {
450 // If we've been given an explicit change identifier, use it; saves time
451 if ( $this->mRcidMarkPatrolled
) {
452 $rcid = $this->mRcidMarkPatrolled
;
453 $rc = RecentChange
::newFromId( $rcid );
454 // Already patrolled?
455 $rcid = is_object( $rc ) && !$rc->getAttribute( 'rc_patrolled' ) ?
$rcid : 0;
457 // Look for an unpatrolled change corresponding to this diff
458 $db = wfGetDB( DB_SLAVE
);
459 $change = RecentChange
::newFromConds(
461 // Redundant user,timestamp condition so we can use the existing index
462 'rc_user_text' => $this->mNewRev
->getRawUserText(),
463 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
464 'rc_this_oldid' => $this->mNewid
,
465 'rc_last_oldid' => $this->mOldid
,
470 if ( $change instanceof RecentChange
) {
471 $rcid = $change->mAttribs
['rc_id'];
472 $this->mRcidMarkPatrolled
= $rcid;
480 $this->getOutput()->preventClickjacking();
481 $this->getOutput()->addModules( 'mediawiki.page.patrol.ajax' );
483 $token = $this->getUser()->getEditToken( $rcid );
484 $this->mMarkPatrolledLink
= ' <span class="patrollink">[' . Linker
::linkKnown(
486 $this->msg( 'markaspatrolleddiff' )->escaped(),
489 'action' => 'markpatrolled',
495 $this->mMarkPatrolledLink
= '';
498 $this->mMarkPatrolledLink
= '';
502 return $this->mMarkPatrolledLink
;
506 * @param $rev Revision
509 protected function revisionDeleteLink( $rev ) {
510 $link = Linker
::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
511 if ( $link !== '' ) {
512 $link = '   ' . $link . ' ';
518 * Show the new revision of the page.
520 function renderNewRevision() {
521 wfProfileIn( __METHOD__
);
522 $out = $this->getOutput();
523 $revHeader = $this->getRevisionHeader( $this->mNewRev
);
524 # Add "current version as of X" title
525 $out->addHTML( "<hr class='diff-hr' />
526 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
527 # Page content may be handled by a hooked call instead...
528 if ( wfRunHooks( 'ArticleContentOnDiff', array( $this, $out ) ) ) {
529 $this->loadNewText();
530 $out->setRevisionId( $this->mNewid
);
531 $out->setRevisionTimestamp( $this->mNewRev
->getTimestamp() );
532 $out->setArticleFlag( true );
534 // NOTE: only needed for B/C: custom rendering of JS/CSS via hook
535 if ( $this->mNewPage
->isCssJsSubpage() ||
$this->mNewPage
->isCssOrJsPage() ) {
536 // Stolen from Article::view --AG 2007-10-11
537 // Give hooks a chance to customise the output
538 // @TODO: standardize this crap into one function
539 if ( ContentHandler
::runLegacyHooks( 'ShowRawCssJs', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
540 // NOTE: deprecated hook, B/C only
541 // use the content object's own rendering
542 $cnt = $this->mNewRev
->getContent();
543 $po = $cnt ?
$cnt->getParserOutput( $this->mNewRev
->getTitle(), $this->mNewRev
->getId() ) : null;
544 $txt = $po ?
$po->getText() : '';
545 $out->addHTML( $txt );
547 } elseif( !wfRunHooks( 'ArticleContentViewCustom', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
548 // Handled by extension
549 } elseif( !ContentHandler
::runLegacyHooks( 'ArticleViewCustom', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
550 // NOTE: deprecated hook, B/C only
551 // Handled by extension
554 if ( $this->getTitle()->equals( $this->mNewPage
) ) {
555 // If the Title stored in the context is the same as the one
556 // of the new revision, we can use its associated WikiPage
558 $wikiPage = $this->getWikiPage();
560 // Otherwise we need to create our own WikiPage object
561 $wikiPage = WikiPage
::factory( $this->mNewPage
);
564 $parserOutput = $this->getParserOutput( $wikiPage, $this->mNewRev
);
566 # Also try to load it as a redirect
567 $rt = $this->mNewContent ?
$this->mNewContent
->getRedirectTarget() : null;
570 $article = Article
::newFromTitle( $this->mNewPage
, $this->getContext() );
571 $out->addHTML( $article->viewRedirect( $rt ) );
573 # WikiPage::getParserOutput() should not return false, but just in case
574 if ( $parserOutput ) {
575 # Show categories etc.
576 $out->addParserOutputNoText( $parserOutput );
578 } else if ( $parserOutput ) {
579 $out->addParserOutput( $parserOutput );
583 # Add redundant patrol link on bottom...
584 $out->addHTML( $this->markPatrolledLink() );
586 wfProfileOut( __METHOD__
);
589 protected function getParserOutput( WikiPage
$page, Revision
$rev ) {
590 $parserOptions = $page->makeParserOptions( $this->getContext() );
592 if ( !$rev->isCurrent() ||
!$rev->getTitle()->quickUserCan( "edit" ) ) {
593 $parserOptions->setEditSection( false );
596 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
597 return $parserOutput;
601 * Get the diff text, send it to the OutputPage object
602 * Returns false if the diff could not be generated, otherwise returns true
606 function showDiff( $otitle, $ntitle, $notice = '' ) {
607 $diff = $this->getDiff( $otitle, $ntitle, $notice );
608 if ( $diff === false ) {
609 $this->showMissingRevision();
612 $this->showDiffStyle();
613 $this->getOutput()->addHTML( $diff );
619 * Add style sheets and supporting JS for diff display.
621 function showDiffStyle() {
622 $this->getOutput()->addModuleStyles( 'mediawiki.action.history.diff' );
626 * Get complete diff table, including header
628 * @param string|bool $otitle Header for old text or false
629 * @param string|bool $ntitle Header for new text or false
630 * @param string $notice HTML between diff header and body
633 function getDiff( $otitle, $ntitle, $notice = '' ) {
634 $body = $this->getDiffBody();
635 if ( $body === false ) {
638 $multi = $this->getMultiNotice();
639 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
644 * Get the diff table body, without header
646 * @return mixed (string/false)
648 public function getDiffBody() {
650 wfProfileIn( __METHOD__
);
651 $this->mCacheHit
= true;
652 // Check if the diff should be hidden from this user
653 if ( !$this->loadRevisionData() ) {
654 wfProfileOut( __METHOD__
);
656 } elseif ( $this->mOldRev
&& !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
657 wfProfileOut( __METHOD__
);
659 } elseif ( $this->mNewRev
&& !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
660 wfProfileOut( __METHOD__
);
664 // If mOldRev is false, it means that the
665 if ( $this->mOldRev
=== false ||
( $this->mOldRev
&& $this->mNewRev
666 && $this->mOldRev
->getID() == $this->mNewRev
->getID() ) )
668 wfProfileOut( __METHOD__
);
673 if ( $this->mOldid
&& $this->mNewid
) {
674 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
,
675 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
677 if ( !$this->mRefreshCache
) {
678 $difftext = $wgMemc->get( $key );
680 wfIncrStats( 'diff_cache_hit' );
681 $difftext = $this->localiseLineNumbers( $difftext );
682 $difftext .= "\n<!-- diff cache key $key -->\n";
683 wfProfileOut( __METHOD__
);
686 } // don't try to load but save the result
688 $this->mCacheHit
= false;
690 // Loadtext is permission safe, this just clears out the diff
691 if ( !$this->loadText() ) {
692 wfProfileOut( __METHOD__
);
696 $difftext = $this->generateContentDiffBody( $this->mOldContent
, $this->mNewContent
);
698 // Save to cache for 7 days
699 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
700 wfIncrStats( 'diff_uncacheable' );
701 } elseif ( $key !== false && $difftext !== false ) {
702 wfIncrStats( 'diff_cache_miss' );
703 $wgMemc->set( $key, $difftext, 7 * 86400 );
705 wfIncrStats( 'diff_uncacheable' );
707 // Replace line numbers with the text in the user's language
708 if ( $difftext !== false ) {
709 $difftext = $this->localiseLineNumbers( $difftext );
711 wfProfileOut( __METHOD__
);
716 * Make sure the proper modules are loaded before we try to
719 private function initDiffEngines() {
720 global $wgExternalDiffEngine;
721 if ( $wgExternalDiffEngine == 'wikidiff' && !function_exists( 'wikidiff_do_diff' ) ) {
722 wfProfileIn( __METHOD__
. '-php_wikidiff.so' );
723 wfDl( 'php_wikidiff' );
724 wfProfileOut( __METHOD__
. '-php_wikidiff.so' );
726 elseif ( $wgExternalDiffEngine == 'wikidiff2' && !function_exists( 'wikidiff2_do_diff' ) ) {
727 wfProfileIn( __METHOD__
. '-php_wikidiff2.so' );
729 wfProfileOut( __METHOD__
. '-php_wikidiff2.so' );
734 * Generate a diff, no caching.
736 * This implementation uses generateTextDiffBody() to generate a diff based on the default
737 * serialization of the given Content objects. This will fail if $old or $new are not
738 * instances of TextContent.
740 * Subclasses may override this to provide a different rendering for the diff,
741 * perhaps taking advantage of the content's native form. This is required for all content
742 * models that are not text based.
744 * @param $old Content: old content
745 * @param $new Content: new content
747 * @return bool|string
749 * @throws MWException if $old or $new are not instances of TextContent.
751 function generateContentDiffBody( Content
$old, Content
$new ) {
752 if ( !( $old instanceof TextContent
) ) {
753 throw new MWException( "Diff not implemented for " . get_class( $old ) . "; "
754 . "override generateContentDiffBody to fix this." );
757 if ( !( $new instanceof TextContent
) ) {
758 throw new MWException( "Diff not implemented for " . get_class( $new ) . "; "
759 . "override generateContentDiffBody to fix this." );
762 $otext = $old->serialize();
763 $ntext = $new->serialize();
765 return $this->generateTextDiffBody( $otext, $ntext );
769 * Generate a diff, no caching
771 * @param string $otext old text, must be already segmented
772 * @param string $ntext new text, must be already segmented
773 * @return bool|string
774 * @deprecated since 1.21, use generateContentDiffBody() instead!
776 function generateDiffBody( $otext, $ntext ) {
777 ContentHandler
::deprecated( __METHOD__
, "1.21" );
779 return $this->generateTextDiffBody( $otext, $ntext );
783 * Generate a diff, no caching
785 * @todo move this to TextDifferenceEngine, make DifferenceEngine abstract. At some point.
787 * @param string $otext old text, must be already segmented
788 * @param string $ntext new text, must be already segmented
789 * @return bool|string
791 function generateTextDiffBody( $otext, $ntext ) {
792 global $wgExternalDiffEngine, $wgContLang;
794 wfProfileIn( __METHOD__
);
796 $otext = str_replace( "\r\n", "\n", $otext );
797 $ntext = str_replace( "\r\n", "\n", $ntext );
799 $this->initDiffEngines();
801 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
802 # For historical reasons, external diff engine expects
803 # input text to be HTML-escaped already
804 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
805 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
806 wfProfileOut( __METHOD__
);
807 return $wgContLang->unsegmentForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
808 $this->debug( 'wikidiff1' );
811 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
812 # Better external diff engine, the 2 may some day be dropped
813 # This one does the escaping and segmenting itself
814 wfProfileIn( 'wikidiff2_do_diff' );
815 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
816 $text .= $this->debug( 'wikidiff2' );
817 wfProfileOut( 'wikidiff2_do_diff' );
818 wfProfileOut( __METHOD__
);
821 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
823 $tmpDir = wfTempDir();
824 $tempName1 = tempnam( $tmpDir, 'diff_' );
825 $tempName2 = tempnam( $tmpDir, 'diff_' );
827 $tempFile1 = fopen( $tempName1, "w" );
829 wfProfileOut( __METHOD__
);
832 $tempFile2 = fopen( $tempName2, "w" );
834 wfProfileOut( __METHOD__
);
837 fwrite( $tempFile1, $otext );
838 fwrite( $tempFile2, $ntext );
839 fclose( $tempFile1 );
840 fclose( $tempFile2 );
841 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
842 wfProfileIn( __METHOD__
. "-shellexec" );
843 $difftext = wfShellExec( $cmd );
844 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
845 wfProfileOut( __METHOD__
. "-shellexec" );
846 unlink( $tempName1 );
847 unlink( $tempName2 );
848 wfProfileOut( __METHOD__
);
853 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
854 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
855 $diffs = new Diff( $ota, $nta );
856 $formatter = new TableDiffFormatter();
857 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
858 wfProfileOut( __METHOD__
);
863 * Generate a debug comment indicating diff generating time,
864 * server node, and generator backend.
867 protected function debug( $generator = "internal" ) {
868 global $wgShowHostnames;
869 if ( !$this->enableDebugComment
) {
872 $data = array( $generator );
873 if ( $wgShowHostnames ) {
874 $data[] = wfHostname();
876 $data[] = wfTimestamp( TS_DB
);
877 return "<!-- diff generator: " .
886 * Replace line numbers with the text in the user's language
889 function localiseLineNumbers( $text ) {
890 return preg_replace_callback( '/<!--LINE (\d+)-->/',
891 array( &$this, 'localiseLineNumbersCb' ), $text );
894 function localiseLineNumbersCb( $matches ) {
895 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) return '';
896 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
900 * If there are revisions between the ones being compared, return a note saying so.
903 function getMultiNotice() {
904 if ( !is_object( $this->mOldRev
) ||
!is_object( $this->mNewRev
) ) {
906 } elseif ( !$this->mOldPage
->equals( $this->mNewPage
) ) {
907 // Comparing two different pages? Count would be meaningless.
911 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
912 $oldRev = $this->mNewRev
; // flip
913 $newRev = $this->mOldRev
; // flip
914 } else { // normal case
915 $oldRev = $this->mOldRev
;
916 $newRev = $this->mNewRev
;
919 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev );
921 $limit = 100; // use diff-multi-manyusers if too many users
922 $numUsers = $this->mNewPage
->countAuthorsBetween( $oldRev, $newRev, $limit );
923 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
925 return ''; // nothing
929 * Get a notice about how many intermediate edits and users there are
930 * @param $numEdits int
931 * @param $numUsers int
935 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
936 if ( $numUsers > $limit ) {
937 $msg = 'diff-multi-manyusers';
942 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
946 * Get a header for a specified revision.
948 * @param $rev Revision
949 * @param string $complete 'complete' to get the header wrapped depending
950 * the visibility of the revision and a link to edit the page.
951 * @return String HTML fragment
953 protected function getRevisionHeader( Revision
$rev, $complete = '' ) {
954 $lang = $this->getLanguage();
955 $user = $this->getUser();
956 $revtimestamp = $rev->getTimestamp();
957 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
958 $dateofrev = $lang->userDate( $revtimestamp, $user );
959 $timeofrev = $lang->userTime( $revtimestamp, $user );
961 $header = $this->msg(
962 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
968 if ( $complete !== 'complete' ) {
972 $title = $rev->getTitle();
974 $header = Linker
::linkKnown( $title, $header, array(),
975 array( 'oldid' => $rev->getID() ) );
977 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
978 $editQuery = array( 'action' => 'edit' );
979 if ( !$rev->isCurrent() ) {
980 $editQuery['oldid'] = $rev->getID();
983 $msg = $this->msg( $title->quickUserCan( 'edit', $user ) ?
'editold' : 'viewsourceold' )->escaped();
984 $header .= ' ' . $this->msg( 'parentheses' )->rawParams(
985 Linker
::linkKnown( $title, $msg, array(), $editQuery ) )->plain();
986 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
987 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
990 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
997 * Add the header to a diff body
1001 function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
1002 // shared.css sets diff in interface language/dir, but the actual content
1003 // is often in a different language, mostly the page content language/dir
1004 $tableClass = 'diff diff-contentalign-' . htmlspecialchars( $this->getDiffLang()->alignStart() );
1005 $header = "<table class='$tableClass'>";
1007 if ( !$diff && !$otitle ) {
1009 <tr style='vertical-align: top;'>
1010 <td class='diff-ntitle'>{$ntitle}</td>
1014 if ( $diff ) { // Safari/Chrome show broken output if cols not used
1016 <col class='diff-marker' />
1017 <col class='diff-content' />
1018 <col class='diff-marker' />
1019 <col class='diff-content' />";
1027 <tr style='vertical-align: top;'>
1028 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
1029 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
1033 if ( $multi != '' ) {
1034 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;' class='diff-multi'>{$multi}</td></tr>";
1036 if ( $notice != '' ) {
1037 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;'>{$notice}</td></tr>";
1040 return $header . $diff . "</table>";
1044 * Use specified text instead of loading from the database
1045 * @deprecated since 1.21, use setContent() instead.
1047 function setText( $oldText, $newText ) {
1048 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1050 $oldContent = ContentHandler
::makeContent( $oldText, $this->getTitle() );
1051 $newContent = ContentHandler
::makeContent( $newText, $this->getTitle() );
1053 $this->setContent( $oldContent, $newContent );
1057 * Use specified text instead of loading from the database
1060 function setContent( Content
$oldContent, Content
$newContent ) {
1061 $this->mOldContent
= $oldContent;
1062 $this->mNewContent
= $newContent;
1064 $this->mTextLoaded
= 2;
1065 $this->mRevisionsLoaded
= true;
1069 * Set the language in which the diff text is written
1070 * (Defaults to page content language).
1073 function setTextLanguage( $lang ) {
1074 $this->mDiffLang
= wfGetLangObj( $lang );
1080 private function loadRevisionIds() {
1081 if ( $this->mRevisionsIdsLoaded
) {
1085 $this->mRevisionsIdsLoaded
= true;
1087 $old = $this->mOldid
;
1088 $new = $this->mNewid
;
1090 if ( $new === 'prev' ) {
1091 # Show diff between revision $old and the previous one.
1092 # Get previous one from DB.
1093 $this->mNewid
= intval( $old );
1094 $this->mOldid
= $this->getTitle()->getPreviousRevisionID( $this->mNewid
);
1095 } elseif ( $new === 'next' ) {
1096 # Show diff between revision $old and the next one.
1097 # Get next one from DB.
1098 $this->mOldid
= intval( $old );
1099 $this->mNewid
= $this->getTitle()->getNextRevisionID( $this->mOldid
);
1100 if ( $this->mNewid
=== false ) {
1101 # if no result, NewId points to the newest old revision. The only newer
1102 # revision is cur, which is "0".
1106 $this->mOldid
= intval( $old );
1107 $this->mNewid
= intval( $new );
1108 wfRunHooks( 'NewDifferenceEngine', array( $this->getTitle(), &$this->mOldid
, &$this->mNewid
, $old, $new ) );
1113 * Load revision metadata for the specified articles. If newid is 0, then compare
1114 * the old article in oldid to the current article; if oldid is 0, then
1115 * compare the current article to the immediately previous one (ignoring the
1118 * If oldid is false, leave the corresponding revision object set
1119 * to false. This is impossible via ordinary user input, and is provided for
1124 function loadRevisionData() {
1125 if ( $this->mRevisionsLoaded
) {
1129 // Whether it succeeds or fails, we don't want to try again
1130 $this->mRevisionsLoaded
= true;
1132 $this->loadRevisionIds();
1134 // Load the new revision object
1135 $this->mNewRev
= $this->mNewid
1136 ? Revision
::newFromId( $this->mNewid
)
1137 : Revision
::newFromTitle( $this->getTitle(), false, Revision
::READ_NORMAL
);
1139 if ( !$this->mNewRev
instanceof Revision
) {
1143 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1144 $this->mNewid
= $this->mNewRev
->getId();
1145 $this->mNewPage
= $this->mNewRev
->getTitle();
1147 // Load the old revision object
1148 $this->mOldRev
= false;
1149 if ( $this->mOldid
) {
1150 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1151 } elseif ( $this->mOldid
=== 0 ) {
1152 $rev = $this->mNewRev
->getPrevious();
1154 $this->mOldid
= $rev->getId();
1155 $this->mOldRev
= $rev;
1157 // No previous revision; mark to show as first-version only.
1158 $this->mOldid
= false;
1159 $this->mOldRev
= false;
1161 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1163 if ( is_null( $this->mOldRev
) ) {
1167 if ( $this->mOldRev
) {
1168 $this->mOldPage
= $this->mOldRev
->getTitle();
1175 * Load the text of the revisions, as well as revision data.
1179 function loadText() {
1180 if ( $this->mTextLoaded
== 2 ) {
1183 // Whether it succeeds or fails, we don't want to try again
1184 $this->mTextLoaded
= 2;
1187 if ( !$this->loadRevisionData() ) {
1190 if ( $this->mOldRev
) {
1191 $this->mOldContent
= $this->mOldRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1192 if ( $this->mOldContent
=== null ) {
1196 if ( $this->mNewRev
) {
1197 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1198 if ( $this->mNewContent
=== null ) {
1206 * Load the text of the new revision, not the old one
1210 function loadNewText() {
1211 if ( $this->mTextLoaded
>= 1 ) {
1214 $this->mTextLoaded
= 1;
1216 if ( !$this->loadRevisionData() ) {
1219 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );