d03a5bee736b81122265b2d8d9e63b127c96f5c0
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 $revisionTools = array();
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() ) );
280 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
282 if ( $this->mNewPage
->equals( $this->mOldPage
) ) {
283 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
286 $out->setPageTitle( $this->msg( 'difference-title-multipage', $this->mOldPage
->getPrefixedText(),
287 $this->mNewPage
->getPrefixedText() ) );
288 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
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 = '   ' . $rollbackLink;
300 if ( !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
301 $undoLink = Html
::element( 'a', array(
302 'href' => $this->mNewPage
->getLocalURL( array(
304 'undoafter' => $this->mOldid
,
305 'undo' => $this->mNewid
) ),
306 'title' => Linker
::titleAttrib( 'undo' )
308 $this->msg( 'editundo' )->text()
310 $revisionTools[] = $undoLink;
314 # Make "previous revision link"
315 if ( $samePage && $this->mOldRev
->getPrevious() ) {
316 $prevlink = Linker
::linkKnown(
318 $this->msg( 'previousdiff' )->escaped(),
319 array( 'id' => 'differences-prevlink' ),
320 array( 'diff' => 'prev', 'oldid' => $this->mOldid
) +
$query
323 $prevlink = ' ';
326 if ( $this->mOldRev
->isMinor() ) {
327 $oldminor = ChangesList
::flag( 'minor' );
332 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
333 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev
, 'complete' );
335 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
336 '<div id="mw-diff-otitle2">' .
337 Linker
::revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
338 '<div id="mw-diff-otitle3">' . $oldminor .
339 Linker
::revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
340 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
342 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
343 $deleted = true; // old revisions text is hidden
344 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
345 $suppressed = true; // also suppressed
349 # Check if this user can see the revisions
350 if ( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $user ) ) {
355 # Make "next revision link"
356 # Skip next link on the top revision
357 if ( $samePage && !$this->mNewRev
->isCurrent() ) {
358 $nextlink = Linker
::linkKnown(
360 $this->msg( 'nextdiff' )->escaped(),
361 array( 'id' => 'differences-nextlink' ),
362 array( 'diff' => 'next', 'oldid' => $this->mNewid
) +
$query
365 $nextlink = ' ';
368 if ( $this->mNewRev
->isMinor() ) {
369 $newminor = ChangesList
::flag( 'minor' );
374 # Handle RevisionDelete links...
375 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
377 # Allow extensions to define their own revision tools
378 wfRunHooks( 'DiffRevisionTools', array( $this->mNewRev
, &$revisionTools ) );
379 $formattedRevisionTools = array();
380 // Put each one in parentheses (poor man's button)
381 foreach ( $revisionTools as $tool ) {
382 $formattedRevisionTools[] = $this->msg( 'parentheses' )->rawParams( $tool )->escaped();
384 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev
, 'complete' ) . ' ' . implode( ' ', $formattedRevisionTools );
386 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
387 '<div id="mw-diff-ntitle2">' . Linker
::revUserTools( $this->mNewRev
, !$this->unhide
) .
389 '<div id="mw-diff-ntitle3">' . $newminor .
390 Linker
::revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
391 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
393 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
394 $deleted = true; // new revisions text is hidden
395 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
396 $suppressed = true; // also suppressed
399 # If the diff cannot be shown due to a deleted revision, then output
400 # the diff header and links to unhide (if available)...
401 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
402 $this->showDiffStyle();
403 $multi = $this->getMultiNotice();
404 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
406 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
407 # Give explanation for why revision is not visible
408 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
411 # Give explanation and add a link to view the diff...
412 $link = $this->getTitle()->getFullURL( $this->getRequest()->appendQueryValue( 'unhide', '1', true ) );
413 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
414 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n", array( $msg, $link ) );
416 # Otherwise, output a regular diff...
418 # Add deletion notice if the user is viewing deleted content
421 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
422 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" . $this->msg( $msg )->parse() . "</div>\n";
424 $this->showDiff( $oldHeader, $newHeader, $notice );
426 $this->renderNewRevision();
429 wfProfileOut( __METHOD__
);
433 * Get a link to mark the change as patrolled, or '' if there's either no
434 * revision to patrol or the user is not allowed to to it.
435 * Side effect: When the patrol link is build, this method will call
436 * OutputPage::preventClickjacking() and load mediawiki.page.patrol.ajax.
440 protected function markPatrolledLink() {
441 global $wgUseRCPatrol;
443 if ( $this->mMarkPatrolledLink
=== null ) {
444 // Prepare a change patrol link, if applicable
445 if ( $wgUseRCPatrol && $this->mNewPage
->quickUserCan( 'patrol', $this->getUser() ) ) {
446 // If we've been given an explicit change identifier, use it; saves time
447 if ( $this->mRcidMarkPatrolled
) {
448 $rcid = $this->mRcidMarkPatrolled
;
449 $rc = RecentChange
::newFromId( $rcid );
450 // Already patrolled?
451 $rcid = is_object( $rc ) && !$rc->getAttribute( 'rc_patrolled' ) ?
$rcid : 0;
453 // Look for an unpatrolled change corresponding to this diff
454 $db = wfGetDB( DB_SLAVE
);
455 $change = RecentChange
::newFromConds(
457 // Redundant user,timestamp condition so we can use the existing index
458 'rc_user_text' => $this->mNewRev
->getRawUserText(),
459 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
460 'rc_this_oldid' => $this->mNewid
,
461 'rc_last_oldid' => $this->mOldid
,
466 if ( $change instanceof RecentChange
) {
467 $rcid = $change->mAttribs
['rc_id'];
468 $this->mRcidMarkPatrolled
= $rcid;
476 $this->getOutput()->preventClickjacking();
477 $this->getOutput()->addModules( 'mediawiki.page.patrol.ajax' );
479 $token = $this->getUser()->getEditToken( $rcid );
480 $this->mMarkPatrolledLink
= ' <span class="patrollink">[' . Linker
::linkKnown(
482 $this->msg( 'markaspatrolleddiff' )->escaped(),
485 'action' => 'markpatrolled',
491 $this->mMarkPatrolledLink
= '';
494 $this->mMarkPatrolledLink
= '';
498 return $this->mMarkPatrolledLink
;
502 * @param $rev Revision
505 protected function revisionDeleteLink( $rev ) {
506 $link = Linker
::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
507 if ( $link !== '' ) {
508 $link = '   ' . $link . ' ';
514 * Show the new revision of the page.
516 function renderNewRevision() {
517 wfProfileIn( __METHOD__
);
518 $out = $this->getOutput();
519 $revHeader = $this->getRevisionHeader( $this->mNewRev
);
520 # Add "current version as of X" title
521 $out->addHTML( "<hr class='diff-hr' />
522 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
523 # Page content may be handled by a hooked call instead...
524 if ( wfRunHooks( 'ArticleContentOnDiff', array( $this, $out ) ) ) {
525 $this->loadNewText();
526 $out->setRevisionId( $this->mNewid
);
527 $out->setRevisionTimestamp( $this->mNewRev
->getTimestamp() );
528 $out->setArticleFlag( true );
530 // NOTE: only needed for B/C: custom rendering of JS/CSS via hook
531 if ( $this->mNewPage
->isCssJsSubpage() ||
$this->mNewPage
->isCssOrJsPage() ) {
532 // Stolen from Article::view --AG 2007-10-11
533 // Give hooks a chance to customise the output
534 // @TODO: standardize this crap into one function
535 if ( ContentHandler
::runLegacyHooks( 'ShowRawCssJs', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
536 // NOTE: deprecated hook, B/C only
537 // use the content object's own rendering
538 $cnt = $this->mNewRev
->getContent();
539 $po = $cnt ?
$cnt->getParserOutput( $this->mNewRev
->getTitle(), $this->mNewRev
->getId() ) : null;
540 $txt = $po ?
$po->getText() : '';
541 $out->addHTML( $txt );
543 } elseif( !wfRunHooks( 'ArticleContentViewCustom', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
544 // Handled by extension
545 } elseif( !ContentHandler
::runLegacyHooks( 'ArticleViewCustom', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
546 // NOTE: deprecated hook, B/C only
547 // Handled by extension
550 if ( $this->getTitle()->equals( $this->mNewPage
) ) {
551 // If the Title stored in the context is the same as the one
552 // of the new revision, we can use its associated WikiPage
554 $wikiPage = $this->getWikiPage();
556 // Otherwise we need to create our own WikiPage object
557 $wikiPage = WikiPage
::factory( $this->mNewPage
);
560 $parserOutput = $this->getParserOutput( $wikiPage, $this->mNewRev
);
562 # Also try to load it as a redirect
563 $rt = $this->mNewContent ?
$this->mNewContent
->getRedirectTarget() : null;
566 $article = Article
::newFromTitle( $this->mNewPage
, $this->getContext() );
567 $out->addHTML( $article->viewRedirect( $rt ) );
569 # WikiPage::getParserOutput() should not return false, but just in case
570 if ( $parserOutput ) {
571 # Show categories etc.
572 $out->addParserOutputNoText( $parserOutput );
574 } else if ( $parserOutput ) {
575 $out->addParserOutput( $parserOutput );
579 # Add redundant patrol link on bottom...
580 $out->addHTML( $this->markPatrolledLink() );
582 wfProfileOut( __METHOD__
);
585 protected function getParserOutput( WikiPage
$page, Revision
$rev ) {
586 $parserOptions = $page->makeParserOptions( $this->getContext() );
588 if ( !$rev->isCurrent() ||
!$rev->getTitle()->quickUserCan( "edit" ) ) {
589 $parserOptions->setEditSection( false );
592 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
593 return $parserOutput;
597 * Get the diff text, send it to the OutputPage object
598 * Returns false if the diff could not be generated, otherwise returns true
602 function showDiff( $otitle, $ntitle, $notice = '' ) {
603 $diff = $this->getDiff( $otitle, $ntitle, $notice );
604 if ( $diff === false ) {
605 $this->showMissingRevision();
608 $this->showDiffStyle();
609 $this->getOutput()->addHTML( $diff );
615 * Add style sheets and supporting JS for diff display.
617 function showDiffStyle() {
618 $this->getOutput()->addModuleStyles( 'mediawiki.action.history.diff' );
622 * Get complete diff table, including header
624 * @param string|bool $otitle Header for old text or false
625 * @param string|bool $ntitle Header for new text or false
626 * @param string $notice HTML between diff header and body
629 function getDiff( $otitle, $ntitle, $notice = '' ) {
630 $body = $this->getDiffBody();
631 if ( $body === false ) {
634 $multi = $this->getMultiNotice();
635 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
640 * Get the diff table body, without header
642 * @return mixed (string/false)
644 public function getDiffBody() {
646 wfProfileIn( __METHOD__
);
647 $this->mCacheHit
= true;
648 // Check if the diff should be hidden from this user
649 if ( !$this->loadRevisionData() ) {
650 wfProfileOut( __METHOD__
);
652 } elseif ( $this->mOldRev
&& !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
653 wfProfileOut( __METHOD__
);
655 } elseif ( $this->mNewRev
&& !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
656 wfProfileOut( __METHOD__
);
660 // If mOldRev is false, it means that the
661 if ( $this->mOldRev
=== false ||
( $this->mOldRev
&& $this->mNewRev
662 && $this->mOldRev
->getID() == $this->mNewRev
->getID() ) )
664 wfProfileOut( __METHOD__
);
669 if ( $this->mOldid
&& $this->mNewid
) {
670 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
,
671 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
673 if ( !$this->mRefreshCache
) {
674 $difftext = $wgMemc->get( $key );
676 wfIncrStats( 'diff_cache_hit' );
677 $difftext = $this->localiseLineNumbers( $difftext );
678 $difftext .= "\n<!-- diff cache key $key -->\n";
679 wfProfileOut( __METHOD__
);
682 } // don't try to load but save the result
684 $this->mCacheHit
= false;
686 // Loadtext is permission safe, this just clears out the diff
687 if ( !$this->loadText() ) {
688 wfProfileOut( __METHOD__
);
692 $difftext = $this->generateContentDiffBody( $this->mOldContent
, $this->mNewContent
);
694 // Save to cache for 7 days
695 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
696 wfIncrStats( 'diff_uncacheable' );
697 } elseif ( $key !== false && $difftext !== false ) {
698 wfIncrStats( 'diff_cache_miss' );
699 $wgMemc->set( $key, $difftext, 7 * 86400 );
701 wfIncrStats( 'diff_uncacheable' );
703 // Replace line numbers with the text in the user's language
704 if ( $difftext !== false ) {
705 $difftext = $this->localiseLineNumbers( $difftext );
707 wfProfileOut( __METHOD__
);
712 * Make sure the proper modules are loaded before we try to
715 private function initDiffEngines() {
716 global $wgExternalDiffEngine;
717 if ( $wgExternalDiffEngine == 'wikidiff' && !function_exists( 'wikidiff_do_diff' ) ) {
718 wfProfileIn( __METHOD__
. '-php_wikidiff.so' );
719 wfDl( 'php_wikidiff' );
720 wfProfileOut( __METHOD__
. '-php_wikidiff.so' );
722 elseif ( $wgExternalDiffEngine == 'wikidiff2' && !function_exists( 'wikidiff2_do_diff' ) ) {
723 wfProfileIn( __METHOD__
. '-php_wikidiff2.so' );
725 wfProfileOut( __METHOD__
. '-php_wikidiff2.so' );
730 * Generate a diff, no caching.
732 * This implementation uses generateTextDiffBody() to generate a diff based on the default
733 * serialization of the given Content objects. This will fail if $old or $new are not
734 * instances of TextContent.
736 * Subclasses may override this to provide a different rendering for the diff,
737 * perhaps taking advantage of the content's native form. This is required for all content
738 * models that are not text based.
740 * @param $old Content: old content
741 * @param $new Content: new content
743 * @return bool|string
745 * @throws MWException if $old or $new are not instances of TextContent.
747 function generateContentDiffBody( Content
$old, Content
$new ) {
748 if ( !( $old instanceof TextContent
) ) {
749 throw new MWException( "Diff not implemented for " . get_class( $old ) . "; "
750 . "override generateContentDiffBody to fix this." );
753 if ( !( $new instanceof TextContent
) ) {
754 throw new MWException( "Diff not implemented for " . get_class( $new ) . "; "
755 . "override generateContentDiffBody to fix this." );
758 $otext = $old->serialize();
759 $ntext = $new->serialize();
761 return $this->generateTextDiffBody( $otext, $ntext );
765 * Generate a diff, no caching
767 * @param string $otext old text, must be already segmented
768 * @param string $ntext new text, must be already segmented
769 * @return bool|string
770 * @deprecated since 1.21, use generateContentDiffBody() instead!
772 function generateDiffBody( $otext, $ntext ) {
773 ContentHandler
::deprecated( __METHOD__
, "1.21" );
775 return $this->generateTextDiffBody( $otext, $ntext );
779 * Generate a diff, no caching
781 * @todo move this to TextDifferenceEngine, make DifferenceEngine abstract. At some point.
783 * @param string $otext old text, must be already segmented
784 * @param string $ntext new text, must be already segmented
785 * @return bool|string
787 function generateTextDiffBody( $otext, $ntext ) {
788 global $wgExternalDiffEngine, $wgContLang;
790 wfProfileIn( __METHOD__
);
792 $otext = str_replace( "\r\n", "\n", $otext );
793 $ntext = str_replace( "\r\n", "\n", $ntext );
795 $this->initDiffEngines();
797 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
798 # For historical reasons, external diff engine expects
799 # input text to be HTML-escaped already
800 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
801 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
802 wfProfileOut( __METHOD__
);
803 return $wgContLang->unsegmentForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
804 $this->debug( 'wikidiff1' );
807 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
808 # Better external diff engine, the 2 may some day be dropped
809 # This one does the escaping and segmenting itself
810 wfProfileIn( 'wikidiff2_do_diff' );
811 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
812 $text .= $this->debug( 'wikidiff2' );
813 wfProfileOut( 'wikidiff2_do_diff' );
814 wfProfileOut( __METHOD__
);
817 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
819 $tmpDir = wfTempDir();
820 $tempName1 = tempnam( $tmpDir, 'diff_' );
821 $tempName2 = tempnam( $tmpDir, 'diff_' );
823 $tempFile1 = fopen( $tempName1, "w" );
825 wfProfileOut( __METHOD__
);
828 $tempFile2 = fopen( $tempName2, "w" );
830 wfProfileOut( __METHOD__
);
833 fwrite( $tempFile1, $otext );
834 fwrite( $tempFile2, $ntext );
835 fclose( $tempFile1 );
836 fclose( $tempFile2 );
837 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
838 wfProfileIn( __METHOD__
. "-shellexec" );
839 $difftext = wfShellExec( $cmd );
840 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
841 wfProfileOut( __METHOD__
. "-shellexec" );
842 unlink( $tempName1 );
843 unlink( $tempName2 );
844 wfProfileOut( __METHOD__
);
849 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
850 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
851 $diffs = new Diff( $ota, $nta );
852 $formatter = new TableDiffFormatter();
853 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
854 wfProfileOut( __METHOD__
);
859 * Generate a debug comment indicating diff generating time,
860 * server node, and generator backend.
863 protected function debug( $generator = "internal" ) {
864 global $wgShowHostnames;
865 if ( !$this->enableDebugComment
) {
868 $data = array( $generator );
869 if ( $wgShowHostnames ) {
870 $data[] = wfHostname();
872 $data[] = wfTimestamp( TS_DB
);
873 return "<!-- diff generator: " .
882 * Replace line numbers with the text in the user's language
885 function localiseLineNumbers( $text ) {
886 return preg_replace_callback( '/<!--LINE (\d+)-->/',
887 array( &$this, 'localiseLineNumbersCb' ), $text );
890 function localiseLineNumbersCb( $matches ) {
891 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) return '';
892 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
896 * If there are revisions between the ones being compared, return a note saying so.
899 function getMultiNotice() {
900 if ( !is_object( $this->mOldRev
) ||
!is_object( $this->mNewRev
) ) {
902 } elseif ( !$this->mOldPage
->equals( $this->mNewPage
) ) {
903 // Comparing two different pages? Count would be meaningless.
907 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
908 $oldRev = $this->mNewRev
; // flip
909 $newRev = $this->mOldRev
; // flip
910 } else { // normal case
911 $oldRev = $this->mOldRev
;
912 $newRev = $this->mNewRev
;
915 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev );
917 $limit = 100; // use diff-multi-manyusers if too many users
918 $numUsers = $this->mNewPage
->countAuthorsBetween( $oldRev, $newRev, $limit );
919 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
921 return ''; // nothing
925 * Get a notice about how many intermediate edits and users there are
926 * @param $numEdits int
927 * @param $numUsers int
931 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
932 if ( $numUsers > $limit ) {
933 $msg = 'diff-multi-manyusers';
938 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
942 * Get a header for a specified revision.
944 * @param $rev Revision
945 * @param string $complete 'complete' to get the header wrapped depending
946 * the visibility of the revision and a link to edit the page.
947 * @return String HTML fragment
949 protected function getRevisionHeader( Revision
$rev, $complete = '' ) {
950 $lang = $this->getLanguage();
951 $user = $this->getUser();
952 $revtimestamp = $rev->getTimestamp();
953 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
954 $dateofrev = $lang->userDate( $revtimestamp, $user );
955 $timeofrev = $lang->userTime( $revtimestamp, $user );
957 $header = $this->msg(
958 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
964 if ( $complete !== 'complete' ) {
968 $title = $rev->getTitle();
970 $header = Linker
::linkKnown( $title, $header, array(),
971 array( 'oldid' => $rev->getID() ) );
973 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
974 $editQuery = array( 'action' => 'edit' );
975 if ( !$rev->isCurrent() ) {
976 $editQuery['oldid'] = $rev->getID();
979 $msg = $this->msg( $title->quickUserCan( 'edit', $user ) ?
'editold' : 'viewsourceold' )->escaped();
980 $header .= ' ' . $this->msg( 'parentheses' )->rawParams(
981 Linker
::linkKnown( $title, $msg, array(), $editQuery ) )->plain();
982 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
983 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
986 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
993 * Add the header to a diff body
997 function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
998 // shared.css sets diff in interface language/dir, but the actual content
999 // is often in a different language, mostly the page content language/dir
1000 $tableClass = 'diff diff-contentalign-' . htmlspecialchars( $this->getDiffLang()->alignStart() );
1001 $header = "<table class='$tableClass'>";
1003 if ( !$diff && !$otitle ) {
1005 <tr style='vertical-align: top;'>
1006 <td class='diff-ntitle'>{$ntitle}</td>
1010 if ( $diff ) { // Safari/Chrome show broken output if cols not used
1012 <col class='diff-marker' />
1013 <col class='diff-content' />
1014 <col class='diff-marker' />
1015 <col class='diff-content' />";
1023 <tr style='vertical-align: top;'>
1024 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
1025 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
1029 if ( $multi != '' ) {
1030 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;' class='diff-multi'>{$multi}</td></tr>";
1032 if ( $notice != '' ) {
1033 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;'>{$notice}</td></tr>";
1036 return $header . $diff . "</table>";
1040 * Use specified text instead of loading from the database
1041 * @deprecated since 1.21, use setContent() instead.
1043 function setText( $oldText, $newText ) {
1044 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1046 $oldContent = ContentHandler
::makeContent( $oldText, $this->getTitle() );
1047 $newContent = ContentHandler
::makeContent( $newText, $this->getTitle() );
1049 $this->setContent( $oldContent, $newContent );
1053 * Use specified text instead of loading from the database
1056 function setContent( Content
$oldContent, Content
$newContent ) {
1057 $this->mOldContent
= $oldContent;
1058 $this->mNewContent
= $newContent;
1060 $this->mTextLoaded
= 2;
1061 $this->mRevisionsLoaded
= true;
1065 * Set the language in which the diff text is written
1066 * (Defaults to page content language).
1069 function setTextLanguage( $lang ) {
1070 $this->mDiffLang
= wfGetLangObj( $lang );
1076 private function loadRevisionIds() {
1077 if ( $this->mRevisionsIdsLoaded
) {
1081 $this->mRevisionsIdsLoaded
= true;
1083 $old = $this->mOldid
;
1084 $new = $this->mNewid
;
1086 if ( $new === 'prev' ) {
1087 # Show diff between revision $old and the previous one.
1088 # Get previous one from DB.
1089 $this->mNewid
= intval( $old );
1090 $this->mOldid
= $this->getTitle()->getPreviousRevisionID( $this->mNewid
);
1091 } elseif ( $new === 'next' ) {
1092 # Show diff between revision $old and the next one.
1093 # Get next one from DB.
1094 $this->mOldid
= intval( $old );
1095 $this->mNewid
= $this->getTitle()->getNextRevisionID( $this->mOldid
);
1096 if ( $this->mNewid
=== false ) {
1097 # if no result, NewId points to the newest old revision. The only newer
1098 # revision is cur, which is "0".
1102 $this->mOldid
= intval( $old );
1103 $this->mNewid
= intval( $new );
1104 wfRunHooks( 'NewDifferenceEngine', array( $this->getTitle(), &$this->mOldid
, &$this->mNewid
, $old, $new ) );
1109 * Load revision metadata for the specified articles. If newid is 0, then compare
1110 * the old article in oldid to the current article; if oldid is 0, then
1111 * compare the current article to the immediately previous one (ignoring the
1114 * If oldid is false, leave the corresponding revision object set
1115 * to false. This is impossible via ordinary user input, and is provided for
1120 function loadRevisionData() {
1121 if ( $this->mRevisionsLoaded
) {
1125 // Whether it succeeds or fails, we don't want to try again
1126 $this->mRevisionsLoaded
= true;
1128 $this->loadRevisionIds();
1130 // Load the new revision object
1131 $this->mNewRev
= $this->mNewid
1132 ? Revision
::newFromId( $this->mNewid
)
1133 : Revision
::newFromTitle( $this->getTitle(), false, Revision
::READ_NORMAL
);
1135 if ( !$this->mNewRev
instanceof Revision
) {
1139 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1140 $this->mNewid
= $this->mNewRev
->getId();
1141 $this->mNewPage
= $this->mNewRev
->getTitle();
1143 // Load the old revision object
1144 $this->mOldRev
= false;
1145 if ( $this->mOldid
) {
1146 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1147 } elseif ( $this->mOldid
=== 0 ) {
1148 $rev = $this->mNewRev
->getPrevious();
1150 $this->mOldid
= $rev->getId();
1151 $this->mOldRev
= $rev;
1153 // No previous revision; mark to show as first-version only.
1154 $this->mOldid
= false;
1155 $this->mOldRev
= false;
1157 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1159 if ( is_null( $this->mOldRev
) ) {
1163 if ( $this->mOldRev
) {
1164 $this->mOldPage
= $this->mOldRev
->getTitle();
1171 * Load the text of the revisions, as well as revision data.
1175 function loadText() {
1176 if ( $this->mTextLoaded
== 2 ) {
1179 // Whether it succeeds or fails, we don't want to try again
1180 $this->mTextLoaded
= 2;
1183 if ( !$this->loadRevisionData() ) {
1186 if ( $this->mOldRev
) {
1187 $this->mOldContent
= $this->mOldRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1188 if ( $this->mOldContent
=== null ) {
1192 if ( $this->mNewRev
) {
1193 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1194 if ( $this->mNewContent
=== null ) {
1202 * Load the text of the new revision, not the old one
1206 function loadNewText() {
1207 if ( $this->mTextLoaded
>= 1 ) {
1210 $this->mTextLoaded
= 1;
1212 if ( !$this->loadRevisionData() ) {
1215 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );