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;
55 var $mOldRev, $mNewRev;
56 private $mRevisionsIdsLoaded = false; // Have the revisions IDs been loaded
57 var $mRevisionsLoaded = false; // Have the revisions been loaded
58 var $mTextLoaded = 0; // How many text blobs have been loaded, 0, 1 or 2?
59 var $mCacheHit = false; // Was the diff fetched from cache?
62 * Set this to true to add debug info to the HTML output.
63 * Warning: this may cause RSS readers to spuriously mark articles as "new"
66 var $enableDebugComment = false;
68 // If true, line X is not displayed when X is 1, for example to increase
69 // readability and conserve space with many small diffs.
70 protected $mReducedLineNumbers = false;
72 // Link to action=markpatrolled
73 protected $mMarkPatrolledLink = null;
75 protected $unhide = false; # show rev_deleted content if allowed
80 * @param $context IContextSource context to use, anything else will be ignored
81 * @param $old Integer old ID we want to show and diff with.
82 * @param $new String either 'prev' or 'next'.
83 * @param $rcid Integer Deprecated, no longer used!
84 * @param $refreshCache boolean If set, refreshes the diff cache
85 * @param $unhide boolean If set, allow viewing deleted revs
87 function __construct( $context = null, $old = 0, $new = 0, $rcid = 0,
88 $refreshCache = false, $unhide = false )
90 if ( $context instanceof IContextSource
) {
91 $this->setContext( $context );
94 wfDebug( "DifferenceEngine old '$old' new '$new' rcid '$rcid'\n" );
98 $this->mRefreshCache
= $refreshCache;
99 $this->unhide
= $unhide;
105 function setReducedLineNumbers( $value = true ) {
106 $this->mReducedLineNumbers
= $value;
112 function getDiffLang() {
113 if ( $this->mDiffLang
=== null ) {
114 # Default language in which the diff text is written.
115 $this->mDiffLang
= $this->getTitle()->getPageLanguage();
117 return $this->mDiffLang
;
123 function wasCacheHit() {
124 return $this->mCacheHit
;
130 function getOldid() {
131 $this->loadRevisionIds();
132 return $this->mOldid
;
138 function getNewid() {
139 $this->loadRevisionIds();
140 return $this->mNewid
;
144 * Look up a special:Undelete link to the given deleted revision id,
145 * as a workaround for being unable to load deleted diffs in currently.
147 * @param int $id revision ID
148 * @return mixed URL or false
150 function deletedLink( $id ) {
151 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
152 $dbr = wfGetDB( DB_SLAVE
);
153 $row = $dbr->selectRow( 'archive', '*',
154 array( 'ar_rev_id' => $id ),
157 $rev = Revision
::newFromArchiveRow( $row );
158 $title = Title
::makeTitleSafe( $row->ar_namespace
, $row->ar_title
);
159 return SpecialPage
::getTitleFor( 'Undelete' )->getFullURL( array(
160 'target' => $title->getPrefixedText(),
161 'timestamp' => $rev->getTimestamp()
169 * Build a wikitext link toward a deleted revision, if viewable.
171 * @param int $id revision ID
172 * @return string wikitext fragment
174 function deletedIdMarker( $id ) {
175 $link = $this->deletedLink( $id );
177 return "[$link $id]";
183 private function showMissingRevision() {
184 $out = $this->getOutput();
187 if ( $this->mOldRev
=== null ) {
188 $missing[] = $this->deletedIdMarker( $this->mOldid
);
190 if ( $this->mNewRev
=== null ) {
191 $missing[] = $this->deletedIdMarker( $this->mNewid
);
194 $out->setPageTitle( $this->msg( 'errorpagetitle' ) );
195 $out->addWikiMsg( 'difference-missing-revision',
196 $this->getLanguage()->listToText( $missing ), count( $missing ) );
199 function showDiffPage( $diffOnly = false ) {
200 wfProfileIn( __METHOD__
);
202 # Allow frames except in certain special cases
203 $out = $this->getOutput();
204 $out->allowClickjacking();
205 $out->setRobotPolicy( 'noindex,nofollow' );
207 if ( !$this->loadRevisionData() ) {
208 $this->showMissingRevision();
209 wfProfileOut( __METHOD__
);
213 $user = $this->getUser();
214 $permErrors = $this->mNewPage
->getUserPermissionsErrors( 'read', $user );
215 if ( $this->mOldPage
) { # mOldPage might not be set, see below.
216 $permErrors = wfMergeErrorArrays( $permErrors,
217 $this->mOldPage
->getUserPermissionsErrors( 'read', $user ) );
219 if ( count( $permErrors ) ) {
220 wfProfileOut( __METHOD__
);
221 throw new PermissionsError( 'read', $permErrors );
228 # Carry over 'diffonly' param via navigation links
229 if ( $diffOnly != $user->getBoolOption( 'diffonly' ) ) {
230 $query['diffonly'] = $diffOnly;
232 # Cascade unhide param in links for easy deletion browsing
233 if ( $this->unhide
) {
234 $query['unhide'] = 1;
237 # Check if one of the revisions is deleted/suppressed
238 $deleted = $suppressed = false;
239 $allowed = $this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $user );
241 $revisionTools = array();
243 # mOldRev is false if the difference engine is called with a "vague" query for
244 # a diff between a version V and its previous version V' AND the version V
245 # is the first version of that article. In that case, V' does not exist.
246 if ( $this->mOldRev
=== false ) {
247 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
251 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
253 if ( $this->mNewPage
->equals( $this->mOldPage
) ) {
254 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
257 $out->setPageTitle( $this->msg( 'difference-title-multipage', $this->mOldPage
->getPrefixedText(),
258 $this->mNewPage
->getPrefixedText() ) );
259 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
263 if ( $samePage && $this->mNewPage
->quickUserCan( 'edit', $user ) ) {
264 if ( $this->mNewRev
->isCurrent() && $this->mNewPage
->userCan( 'rollback', $user ) ) {
265 $rollbackLink = Linker
::generateRollback( $this->mNewRev
, $this->getContext() );
266 if ( $rollbackLink ) {
267 $out->preventClickjacking();
268 $rollback = '   ' . $rollbackLink;
271 if ( !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
272 $undoLink = Html
::element( 'a', array(
273 'href' => $this->mNewPage
->getLocalURL( array(
275 'undoafter' => $this->mOldid
,
276 'undo' => $this->mNewid
) ),
277 'title' => Linker
::titleAttrib( 'undo' )
279 $this->msg( 'editundo' )->text()
281 $revisionTools[] = $undoLink;
285 # Make "previous revision link"
286 if ( $samePage && $this->mOldRev
->getPrevious() ) {
287 $prevlink = Linker
::linkKnown(
289 $this->msg( 'previousdiff' )->escaped(),
290 array( 'id' => 'differences-prevlink' ),
291 array( 'diff' => 'prev', 'oldid' => $this->mOldid
) +
$query
294 $prevlink = ' ';
297 if ( $this->mOldRev
->isMinor() ) {
298 $oldminor = ChangesList
::flag( 'minor' );
303 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
304 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev
, 'complete' );
306 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
307 '<div id="mw-diff-otitle2">' .
308 Linker
::revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
309 '<div id="mw-diff-otitle3">' . $oldminor .
310 Linker
::revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
311 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
313 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
314 $deleted = true; // old revisions text is hidden
315 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
316 $suppressed = true; // also suppressed
320 # Check if this user can see the revisions
321 if ( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $user ) ) {
326 # Make "next revision link"
327 # Skip next link on the top revision
328 if ( $samePage && !$this->mNewRev
->isCurrent() ) {
329 $nextlink = Linker
::linkKnown(
331 $this->msg( 'nextdiff' )->escaped(),
332 array( 'id' => 'differences-nextlink' ),
333 array( 'diff' => 'next', 'oldid' => $this->mNewid
) +
$query
336 $nextlink = ' ';
339 if ( $this->mNewRev
->isMinor() ) {
340 $newminor = ChangesList
::flag( 'minor' );
345 # Handle RevisionDelete links...
346 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
348 # Allow extensions to define their own revision tools
349 wfRunHooks( 'DiffRevisionTools', array( $this->mNewRev
, &$revisionTools ) );
350 $formattedRevisionTools = array();
351 // Put each one in parentheses (poor man's button)
352 foreach ( $revisionTools as $tool ) {
353 $formattedRevisionTools[] = $this->msg( 'parentheses' )->rawParams( $tool )->escaped();
355 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev
, 'complete' ) . ' ' . implode( ' ', $formattedRevisionTools );
357 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
358 '<div id="mw-diff-ntitle2">' . Linker
::revUserTools( $this->mNewRev
, !$this->unhide
) .
360 '<div id="mw-diff-ntitle3">' . $newminor .
361 Linker
::revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
362 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
364 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
365 $deleted = true; // new revisions text is hidden
366 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
367 $suppressed = true; // also suppressed
371 # If the diff cannot be shown due to a deleted revision, then output
372 # the diff header and links to unhide (if available)...
373 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
374 $this->showDiffStyle();
375 $multi = $this->getMultiNotice();
376 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
378 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
379 # Give explanation for why revision is not visible
380 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
383 # Give explanation and add a link to view the diff...
384 $link = $this->getTitle()->getFullURL( $this->getRequest()->appendQueryValue( 'unhide', '1', true ) );
385 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
386 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n", array( $msg, $link ) );
388 # Otherwise, output a regular diff...
390 # Add deletion notice if the user is viewing deleted content
393 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
394 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" . $this->msg( $msg )->parse() . "</div>\n";
396 $this->showDiff( $oldHeader, $newHeader, $notice );
398 $this->renderNewRevision();
401 wfProfileOut( __METHOD__
);
405 * Get a link to mark the change as patrolled, or '' if there's either no
406 * revision to patrol or the user is not allowed to to it.
407 * Side effect: When the patrol link is build, this method will call
408 * OutputPage::preventClickjacking() and load mediawiki.page.patrol.ajax.
412 protected function markPatrolledLink() {
413 global $wgUseRCPatrol, $wgRCMaxAge;
414 $cache = wfGetMainCache();
416 if ( $this->mMarkPatrolledLink
=== null ) {
417 // Prepare a change patrol link, if applicable
419 // Is patrolling enabled and the user allowed to?
420 $wgUseRCPatrol && $this->mNewPage
->quickUserCan( 'patrol', $this->getUser() ) &&
421 // Only do this if the revision isn't more than 6 hours older
422 // than the Max RC age (6h because the RC might not be cleaned out regularly)
423 RecentChange
::isInRCLifespan( $this->mNewRev
->getTimestamp(), 21600 ) &&
424 // Maybe the result is cached
425 !$cache->get( wfMemcKey( 'NotPatrollableRevId', $this->mNewid
) )
427 // Look for an unpatrolled change corresponding to this diff
429 $db = wfGetDB( DB_SLAVE
);
430 $change = RecentChange
::newFromConds(
432 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
433 'rc_this_oldid' => $this->mNewid
,
434 'rc_last_oldid' => $this->mOldid
,
438 array( 'USE INDEX' => 'rc_timestamp' )
442 $rcid = $change->getAttribute( 'rc_id' );
449 $this->getOutput()->preventClickjacking();
450 $this->getOutput()->addModules( 'mediawiki.page.patrol.ajax' );
452 $token = $this->getUser()->getEditToken( $rcid );
453 $this->mMarkPatrolledLink
= ' <span class="patrollink">[' . Linker
::linkKnown(
455 $this->msg( 'markaspatrolleddiff' )->escaped(),
458 'action' => 'markpatrolled',
464 $cache->set( wfMemcKey( 'NotPatrollableRevId', $this->mNewid
), '1', $wgRCMaxAge );
465 $this->mMarkPatrolledLink
= '';
468 $this->mMarkPatrolledLink
= '';
472 return $this->mMarkPatrolledLink
;
476 * @param $rev Revision
479 protected function revisionDeleteLink( $rev ) {
480 $link = Linker
::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
481 if ( $link !== '' ) {
482 $link = '   ' . $link . ' ';
488 * Show the new revision of the page.
490 function renderNewRevision() {
491 wfProfileIn( __METHOD__
);
492 $out = $this->getOutput();
493 $revHeader = $this->getRevisionHeader( $this->mNewRev
);
494 # Add "current version as of X" title
495 $out->addHTML( "<hr class='diff-hr' />
496 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
497 # Page content may be handled by a hooked call instead...
498 if ( wfRunHooks( 'ArticleContentOnDiff', array( $this, $out ) ) ) {
499 $this->loadNewText();
500 $out->setRevisionId( $this->mNewid
);
501 $out->setRevisionTimestamp( $this->mNewRev
->getTimestamp() );
502 $out->setArticleFlag( true );
504 // NOTE: only needed for B/C: custom rendering of JS/CSS via hook
505 if ( $this->mNewPage
->isCssJsSubpage() ||
$this->mNewPage
->isCssOrJsPage() ) {
506 // Stolen from Article::view --AG 2007-10-11
507 // Give hooks a chance to customise the output
508 // @todo standardize this crap into one function
509 if ( ContentHandler
::runLegacyHooks( 'ShowRawCssJs', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
510 // NOTE: deprecated hook, B/C only
511 // use the content object's own rendering
512 $cnt = $this->mNewRev
->getContent();
513 $po = $cnt ?
$cnt->getParserOutput( $this->mNewRev
->getTitle(), $this->mNewRev
->getId() ) : null;
514 $txt = $po ?
$po->getText() : '';
515 $out->addHTML( $txt );
517 } elseif ( !wfRunHooks( 'ArticleContentViewCustom', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
518 // Handled by extension
519 } elseif ( !ContentHandler
::runLegacyHooks( 'ArticleViewCustom', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
520 // NOTE: deprecated hook, B/C only
521 // Handled by extension
524 if ( $this->getTitle()->equals( $this->mNewPage
) ) {
525 // If the Title stored in the context is the same as the one
526 // of the new revision, we can use its associated WikiPage
528 $wikiPage = $this->getWikiPage();
530 // Otherwise we need to create our own WikiPage object
531 $wikiPage = WikiPage
::factory( $this->mNewPage
);
534 $parserOutput = $this->getParserOutput( $wikiPage, $this->mNewRev
);
536 # Also try to load it as a redirect
537 $rt = $this->mNewContent ?
$this->mNewContent
->getRedirectTarget() : null;
540 $article = Article
::newFromTitle( $this->mNewPage
, $this->getContext() );
541 $out->addHTML( $article->viewRedirect( $rt ) );
543 # WikiPage::getParserOutput() should not return false, but just in case
544 if ( $parserOutput ) {
545 # Show categories etc.
546 $out->addParserOutputNoText( $parserOutput );
548 } elseif ( $parserOutput ) {
549 $out->addParserOutput( $parserOutput );
553 # Add redundant patrol link on bottom...
554 $out->addHTML( $this->markPatrolledLink() );
556 wfProfileOut( __METHOD__
);
559 protected function getParserOutput( WikiPage
$page, Revision
$rev ) {
560 $parserOptions = $page->makeParserOptions( $this->getContext() );
562 if ( !$rev->isCurrent() ||
!$rev->getTitle()->quickUserCan( "edit" ) ) {
563 $parserOptions->setEditSection( false );
566 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
567 return $parserOutput;
571 * Get the diff text, send it to the OutputPage object
572 * Returns false if the diff could not be generated, otherwise returns true
576 function showDiff( $otitle, $ntitle, $notice = '' ) {
577 $diff = $this->getDiff( $otitle, $ntitle, $notice );
578 if ( $diff === false ) {
579 $this->showMissingRevision();
582 $this->showDiffStyle();
583 $this->getOutput()->addHTML( $diff );
589 * Add style sheets and supporting JS for diff display.
591 function showDiffStyle() {
592 $this->getOutput()->addModuleStyles( 'mediawiki.action.history.diff' );
596 * Get complete diff table, including header
598 * @param string|bool $otitle Header for old text or false
599 * @param string|bool $ntitle Header for new text or false
600 * @param string $notice HTML between diff header and body
603 function getDiff( $otitle, $ntitle, $notice = '' ) {
604 $body = $this->getDiffBody();
605 if ( $body === false ) {
608 $multi = $this->getMultiNotice();
609 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
614 * Get the diff table body, without header
616 * @return mixed (string/false)
618 public function getDiffBody() {
620 wfProfileIn( __METHOD__
);
621 $this->mCacheHit
= true;
622 // Check if the diff should be hidden from this user
623 if ( !$this->loadRevisionData() ) {
624 wfProfileOut( __METHOD__
);
626 } elseif ( $this->mOldRev
&& !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
627 wfProfileOut( __METHOD__
);
629 } elseif ( $this->mNewRev
&& !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
630 wfProfileOut( __METHOD__
);
634 // If mOldRev is false, it means that the
635 if ( $this->mOldRev
=== false ||
( $this->mOldRev
&& $this->mNewRev
636 && $this->mOldRev
->getID() == $this->mNewRev
->getID() ) )
638 wfProfileOut( __METHOD__
);
643 if ( $this->mOldid
&& $this->mNewid
) {
644 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
,
645 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
647 if ( !$this->mRefreshCache
) {
648 $difftext = $wgMemc->get( $key );
650 wfIncrStats( 'diff_cache_hit' );
651 $difftext = $this->localiseLineNumbers( $difftext );
652 $difftext .= "\n<!-- diff cache key $key -->\n";
653 wfProfileOut( __METHOD__
);
656 } // don't try to load but save the result
658 $this->mCacheHit
= false;
660 // Loadtext is permission safe, this just clears out the diff
661 if ( !$this->loadText() ) {
662 wfProfileOut( __METHOD__
);
666 $difftext = $this->generateContentDiffBody( $this->mOldContent
, $this->mNewContent
);
668 // Save to cache for 7 days
669 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
670 wfIncrStats( 'diff_uncacheable' );
671 } elseif ( $key !== false && $difftext !== false ) {
672 wfIncrStats( 'diff_cache_miss' );
673 $wgMemc->set( $key, $difftext, 7 * 86400 );
675 wfIncrStats( 'diff_uncacheable' );
677 // Replace line numbers with the text in the user's language
678 if ( $difftext !== false ) {
679 $difftext = $this->localiseLineNumbers( $difftext );
681 wfProfileOut( __METHOD__
);
686 * Make sure the proper modules are loaded before we try to
689 private function initDiffEngines() {
690 global $wgExternalDiffEngine;
691 if ( $wgExternalDiffEngine == 'wikidiff' && !function_exists( 'wikidiff_do_diff' ) ) {
692 wfProfileIn( __METHOD__
. '-php_wikidiff.so' );
693 wfDl( 'php_wikidiff' );
694 wfProfileOut( __METHOD__
. '-php_wikidiff.so' );
696 elseif ( $wgExternalDiffEngine == 'wikidiff2' && !function_exists( 'wikidiff2_do_diff' ) ) {
697 wfProfileIn( __METHOD__
. '-php_wikidiff2.so' );
699 wfProfileOut( __METHOD__
. '-php_wikidiff2.so' );
704 * Generate a diff, no caching.
706 * This implementation uses generateTextDiffBody() to generate a diff based on the default
707 * serialization of the given Content objects. This will fail if $old or $new are not
708 * instances of TextContent.
710 * Subclasses may override this to provide a different rendering for the diff,
711 * perhaps taking advantage of the content's native form. This is required for all content
712 * models that are not text based.
714 * @param $old Content: old content
715 * @param $new Content: new content
717 * @return bool|string
719 * @throws MWException if $old or $new are not instances of TextContent.
721 function generateContentDiffBody( Content
$old, Content
$new ) {
722 if ( !( $old instanceof TextContent
) ) {
723 throw new MWException( "Diff not implemented for " . get_class( $old ) . "; "
724 . "override generateContentDiffBody to fix this." );
727 if ( !( $new instanceof TextContent
) ) {
728 throw new MWException( "Diff not implemented for " . get_class( $new ) . "; "
729 . "override generateContentDiffBody to fix this." );
732 $otext = $old->serialize();
733 $ntext = $new->serialize();
735 return $this->generateTextDiffBody( $otext, $ntext );
739 * Generate a diff, no caching
741 * @param string $otext old text, must be already segmented
742 * @param string $ntext new text, must be already segmented
743 * @return bool|string
744 * @deprecated since 1.21, use generateContentDiffBody() instead!
746 function generateDiffBody( $otext, $ntext ) {
747 ContentHandler
::deprecated( __METHOD__
, "1.21" );
749 return $this->generateTextDiffBody( $otext, $ntext );
753 * Generate a diff, no caching
755 * @todo move this to TextDifferenceEngine, make DifferenceEngine abstract. At some point.
757 * @param string $otext old text, must be already segmented
758 * @param string $ntext new text, must be already segmented
759 * @return bool|string
761 function generateTextDiffBody( $otext, $ntext ) {
762 global $wgExternalDiffEngine, $wgContLang;
764 wfProfileIn( __METHOD__
);
766 $otext = str_replace( "\r\n", "\n", $otext );
767 $ntext = str_replace( "\r\n", "\n", $ntext );
769 $this->initDiffEngines();
771 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
772 # For historical reasons, external diff engine expects
773 # input text to be HTML-escaped already
774 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
775 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
776 wfProfileOut( __METHOD__
);
777 return $wgContLang->unsegmentForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
778 $this->debug( 'wikidiff1' );
781 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
782 # Better external diff engine, the 2 may some day be dropped
783 # This one does the escaping and segmenting itself
784 wfProfileIn( 'wikidiff2_do_diff' );
785 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
786 $text .= $this->debug( 'wikidiff2' );
787 wfProfileOut( 'wikidiff2_do_diff' );
788 wfProfileOut( __METHOD__
);
791 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
793 $tmpDir = wfTempDir();
794 $tempName1 = tempnam( $tmpDir, 'diff_' );
795 $tempName2 = tempnam( $tmpDir, 'diff_' );
797 $tempFile1 = fopen( $tempName1, "w" );
799 wfProfileOut( __METHOD__
);
802 $tempFile2 = fopen( $tempName2, "w" );
804 wfProfileOut( __METHOD__
);
807 fwrite( $tempFile1, $otext );
808 fwrite( $tempFile2, $ntext );
809 fclose( $tempFile1 );
810 fclose( $tempFile2 );
811 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
812 wfProfileIn( __METHOD__
. "-shellexec" );
813 $difftext = wfShellExec( $cmd );
814 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
815 wfProfileOut( __METHOD__
. "-shellexec" );
816 unlink( $tempName1 );
817 unlink( $tempName2 );
818 wfProfileOut( __METHOD__
);
823 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
824 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
825 $diffs = new Diff( $ota, $nta );
826 $formatter = new TableDiffFormatter();
827 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
828 wfProfileOut( __METHOD__
);
833 * Generate a debug comment indicating diff generating time,
834 * server node, and generator backend.
837 protected function debug( $generator = "internal" ) {
838 global $wgShowHostnames;
839 if ( !$this->enableDebugComment
) {
842 $data = array( $generator );
843 if ( $wgShowHostnames ) {
844 $data[] = wfHostname();
846 $data[] = wfTimestamp( TS_DB
);
847 return "<!-- diff generator: " .
856 * Replace line numbers with the text in the user's language
859 function localiseLineNumbers( $text ) {
860 return preg_replace_callback( '/<!--LINE (\d+)-->/',
861 array( &$this, 'localiseLineNumbersCb' ), $text );
864 function localiseLineNumbersCb( $matches ) {
865 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) {
868 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
872 * If there are revisions between the ones being compared, return a note saying so.
875 function getMultiNotice() {
876 if ( !is_object( $this->mOldRev
) ||
!is_object( $this->mNewRev
) ) {
878 } elseif ( !$this->mOldPage
->equals( $this->mNewPage
) ) {
879 // Comparing two different pages? Count would be meaningless.
883 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
884 $oldRev = $this->mNewRev
; // flip
885 $newRev = $this->mOldRev
; // flip
886 } else { // normal case
887 $oldRev = $this->mOldRev
;
888 $newRev = $this->mNewRev
;
891 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev );
893 $limit = 100; // use diff-multi-manyusers if too many users
894 $numUsers = $this->mNewPage
->countAuthorsBetween( $oldRev, $newRev, $limit );
895 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
897 return ''; // nothing
901 * Get a notice about how many intermediate edits and users there are
902 * @param $numEdits int
903 * @param $numUsers int
907 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
908 if ( $numUsers > $limit ) {
909 $msg = 'diff-multi-manyusers';
914 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
918 * Get a header for a specified revision.
920 * @param $rev Revision
921 * @param string $complete 'complete' to get the header wrapped depending
922 * the visibility of the revision and a link to edit the page.
923 * @return String HTML fragment
925 protected function getRevisionHeader( Revision
$rev, $complete = '' ) {
926 $lang = $this->getLanguage();
927 $user = $this->getUser();
928 $revtimestamp = $rev->getTimestamp();
929 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
930 $dateofrev = $lang->userDate( $revtimestamp, $user );
931 $timeofrev = $lang->userTime( $revtimestamp, $user );
933 $header = $this->msg(
934 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
940 if ( $complete !== 'complete' ) {
944 $title = $rev->getTitle();
946 $header = Linker
::linkKnown( $title, $header, array(),
947 array( 'oldid' => $rev->getID() ) );
949 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
950 $editQuery = array( 'action' => 'edit' );
951 if ( !$rev->isCurrent() ) {
952 $editQuery['oldid'] = $rev->getID();
955 $msg = $this->msg( $title->quickUserCan( 'edit', $user ) ?
'editold' : 'viewsourceold' )->escaped();
956 $header .= ' ' . $this->msg( 'parentheses' )->rawParams(
957 Linker
::linkKnown( $title, $msg, array(), $editQuery ) )->plain();
958 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
959 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
962 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
969 * Add the header to a diff body
973 function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
974 // shared.css sets diff in interface language/dir, but the actual content
975 // is often in a different language, mostly the page content language/dir
976 $tableClass = 'diff diff-contentalign-' . htmlspecialchars( $this->getDiffLang()->alignStart() );
977 $header = "<table class='$tableClass'>";
979 if ( !$diff && !$otitle ) {
981 <tr style='vertical-align: top;'>
982 <td class='diff-ntitle'>{$ntitle}</td>
986 if ( $diff ) { // Safari/Chrome show broken output if cols not used
988 <col class='diff-marker' />
989 <col class='diff-content' />
990 <col class='diff-marker' />
991 <col class='diff-content' />";
999 <tr style='vertical-align: top;'>
1000 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
1001 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
1005 if ( $multi != '' ) {
1006 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;' class='diff-multi'>{$multi}</td></tr>";
1008 if ( $notice != '' ) {
1009 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;'>{$notice}</td></tr>";
1012 return $header . $diff . "</table>";
1016 * Use specified text instead of loading from the database
1017 * @deprecated since 1.21, use setContent() instead.
1019 function setText( $oldText, $newText ) {
1020 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1022 $oldContent = ContentHandler
::makeContent( $oldText, $this->getTitle() );
1023 $newContent = ContentHandler
::makeContent( $newText, $this->getTitle() );
1025 $this->setContent( $oldContent, $newContent );
1029 * Use specified text instead of loading from the database
1032 function setContent( Content
$oldContent, Content
$newContent ) {
1033 $this->mOldContent
= $oldContent;
1034 $this->mNewContent
= $newContent;
1036 $this->mTextLoaded
= 2;
1037 $this->mRevisionsLoaded
= true;
1041 * Set the language in which the diff text is written
1042 * (Defaults to page content language).
1045 function setTextLanguage( $lang ) {
1046 $this->mDiffLang
= wfGetLangObj( $lang );
1052 private function loadRevisionIds() {
1053 if ( $this->mRevisionsIdsLoaded
) {
1057 $this->mRevisionsIdsLoaded
= true;
1059 $old = $this->mOldid
;
1060 $new = $this->mNewid
;
1062 if ( $new === 'prev' ) {
1063 # Show diff between revision $old and the previous one.
1064 # Get previous one from DB.
1065 $this->mNewid
= intval( $old );
1066 $this->mOldid
= $this->getTitle()->getPreviousRevisionID( $this->mNewid
);
1067 } elseif ( $new === 'next' ) {
1068 # Show diff between revision $old and the next one.
1069 # Get next one from DB.
1070 $this->mOldid
= intval( $old );
1071 $this->mNewid
= $this->getTitle()->getNextRevisionID( $this->mOldid
);
1072 if ( $this->mNewid
=== false ) {
1073 # if no result, NewId points to the newest old revision. The only newer
1074 # revision is cur, which is "0".
1078 $this->mOldid
= intval( $old );
1079 $this->mNewid
= intval( $new );
1080 wfRunHooks( 'NewDifferenceEngine', array( $this->getTitle(), &$this->mOldid
, &$this->mNewid
, $old, $new ) );
1085 * Load revision metadata for the specified articles. If newid is 0, then compare
1086 * the old article in oldid to the current article; if oldid is 0, then
1087 * compare the current article to the immediately previous one (ignoring the
1090 * If oldid is false, leave the corresponding revision object set
1091 * to false. This is impossible via ordinary user input, and is provided for
1096 function loadRevisionData() {
1097 if ( $this->mRevisionsLoaded
) {
1101 // Whether it succeeds or fails, we don't want to try again
1102 $this->mRevisionsLoaded
= true;
1104 $this->loadRevisionIds();
1106 // Load the new revision object
1107 $this->mNewRev
= $this->mNewid
1108 ? Revision
::newFromId( $this->mNewid
)
1109 : Revision
::newFromTitle( $this->getTitle(), false, Revision
::READ_NORMAL
);
1111 if ( !$this->mNewRev
instanceof Revision
) {
1115 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1116 $this->mNewid
= $this->mNewRev
->getId();
1117 $this->mNewPage
= $this->mNewRev
->getTitle();
1119 // Load the old revision object
1120 $this->mOldRev
= false;
1121 if ( $this->mOldid
) {
1122 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1123 } elseif ( $this->mOldid
=== 0 ) {
1124 $rev = $this->mNewRev
->getPrevious();
1126 $this->mOldid
= $rev->getId();
1127 $this->mOldRev
= $rev;
1129 // No previous revision; mark to show as first-version only.
1130 $this->mOldid
= false;
1131 $this->mOldRev
= false;
1133 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1135 if ( is_null( $this->mOldRev
) ) {
1139 if ( $this->mOldRev
) {
1140 $this->mOldPage
= $this->mOldRev
->getTitle();
1147 * Load the text of the revisions, as well as revision data.
1151 function loadText() {
1152 if ( $this->mTextLoaded
== 2 ) {
1155 // Whether it succeeds or fails, we don't want to try again
1156 $this->mTextLoaded
= 2;
1159 if ( !$this->loadRevisionData() ) {
1162 if ( $this->mOldRev
) {
1163 $this->mOldContent
= $this->mOldRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1164 if ( $this->mOldContent
=== null ) {
1168 if ( $this->mNewRev
) {
1169 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1170 if ( $this->mNewContent
=== null ) {
1178 * Load the text of the new revision, not the old one
1182 function loadNewText() {
1183 if ( $this->mTextLoaded
>= 1 ) {
1186 $this->mTextLoaded
= 1;
1188 if ( !$this->loadRevisionData() ) {
1191 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );