3 * User interface for the difference engine.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup DifferenceEngine
25 * Constant to indicate diff cache compatibility.
26 * Bump this when changing the diff formatting in a way that
27 * fixes important bugs or such to force cached diff views to
30 define( 'MW_DIFF_VERSION', '1.11a' );
34 * @ingroup DifferenceEngine
36 class DifferenceEngine
extends ContextSource
{
41 var $mOldContent, $mNewContent;
47 var $mOldPage, $mNewPage;
48 var $mRcidMarkPatrolled;
53 var $mOldRev, $mNewRev;
54 private $mRevisionsIdsLoaded = false; // Have the revisions IDs been loaded
55 var $mRevisionsLoaded = false; // Have the revisions been loaded
56 var $mTextLoaded = 0; // How many text blobs have been loaded, 0, 1 or 2?
57 var $mCacheHit = false; // Was the diff fetched from cache?
60 * Set this to true to add debug info to the HTML output.
61 * Warning: this may cause RSS readers to spuriously mark articles as "new"
64 var $enableDebugComment = false;
66 // If true, line X is not displayed when X is 1, for example to increase
67 // readability and conserve space with many small diffs.
68 protected $mReducedLineNumbers = false;
70 // Link to action=markpatrolled
71 protected $mMarkPatrolledLink = null;
73 protected $unhide = false; # show rev_deleted content if allowed
78 * @param $context IContextSource context to use, anything else will be ignored
79 * @param $old Integer old ID we want to show and diff with.
80 * @param $new String either 'prev' or 'next'.
81 * @param $rcid Integer ??? FIXME (default 0)
82 * @param $refreshCache boolean If set, refreshes the diff cache
83 * @param $unhide boolean If set, allow viewing deleted revs
85 function __construct( $context = null, $old = 0, $new = 0, $rcid = 0,
86 $refreshCache = false, $unhide = false )
88 if ( $context instanceof IContextSource
) {
89 $this->setContext( $context );
92 wfDebug( "DifferenceEngine old '$old' new '$new' rcid '$rcid'\n" );
96 $this->mRcidMarkPatrolled
= intval( $rcid ); # force it to be an integer
97 $this->mRefreshCache
= $refreshCache;
98 $this->unhide
= $unhide;
104 function setReducedLineNumbers( $value = true ) {
105 $this->mReducedLineNumbers
= $value;
111 function getDiffLang() {
112 if ( $this->mDiffLang
=== null ) {
113 # Default language in which the diff text is written.
114 $this->mDiffLang
= $this->getTitle()->getPageLanguage();
116 return $this->mDiffLang
;
122 function wasCacheHit() {
123 return $this->mCacheHit
;
129 function getOldid() {
130 $this->loadRevisionIds();
131 return $this->mOldid
;
137 function getNewid() {
138 $this->loadRevisionIds();
139 return $this->mNewid
;
143 * Look up a special:Undelete link to the given deleted revision id,
144 * as a workaround for being unable to load deleted diffs in currently.
146 * @param int $id revision ID
147 * @return mixed URL or false
149 function deletedLink( $id ) {
150 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
151 $dbr = wfGetDB( DB_SLAVE
);
152 $row = $dbr->selectRow('archive', '*',
153 array( 'ar_rev_id' => $id ),
156 $rev = Revision
::newFromArchiveRow( $row );
157 $title = Title
::makeTitleSafe( $row->ar_namespace
, $row->ar_title
);
158 return SpecialPage
::getTitleFor( 'Undelete' )->getFullURL( array(
159 'target' => $title->getPrefixedText(),
160 'timestamp' => $rev->getTimestamp()
168 * Build a wikitext link toward a deleted revision, if viewable.
170 * @param int $id revision ID
171 * @return string wikitext fragment
173 function deletedIdMarker( $id ) {
174 $link = $this->deletedLink( $id );
176 return "[$link $id]";
182 function showDiffPage( $diffOnly = false ) {
183 wfProfileIn( __METHOD__
);
185 # Allow frames except in certain special cases
186 $out = $this->getOutput();
187 $out->allowClickjacking();
188 $out->setRobotPolicy( 'noindex,nofollow' );
190 if ( !$this->loadRevisionData() ) {
191 // Sounds like a deleted revision... Let's see what we can do.
192 $t = $this->getTitle()->getPrefixedText();
193 $d = $this->msg( 'missingarticle-diff',
194 $this->deletedIdMarker( $this->mOldid
),
195 $this->deletedIdMarker( $this->mNewid
) )->escaped();
196 $out->setPageTitle( $this->msg( 'errorpagetitle' ) );
197 $out->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", "<span class='plainlinks'>$d</span>" );
198 wfProfileOut( __METHOD__
);
202 $user = $this->getUser();
203 $permErrors = $this->mNewPage
->getUserPermissionsErrors( 'read', $user );
204 if ( $this->mOldPage
) { # mOldPage might not be set, see below.
205 $permErrors = wfMergeErrorArrays( $permErrors,
206 $this->mOldPage
->getUserPermissionsErrors( 'read', $user ) );
208 if ( count( $permErrors ) ) {
209 wfProfileOut( __METHOD__
);
210 throw new PermissionsError( 'read', $permErrors );
213 # If external diffs are enabled both globally and for the user,
214 # we'll use the application/x-external-editor interface to call
215 # an external diff tool like kompare, kdiff3, etc.
216 if ( ExternalEdit
::useExternalEngine( $this->getContext(), 'diff' ) ) { #FIXME: how to handle this for non-text content?
218 'File' => array( 'Extension' => 'wiki', 'URL' =>
219 # This should be mOldPage, but it may not be set, see below.
220 $this->mNewPage
->getCanonicalURL( array(
221 'action' => 'raw', 'oldid' => $this->mOldid
) )
223 'File2' => array( 'Extension' => 'wiki', 'URL' =>
224 $this->mNewPage
->getCanonicalURL( array(
225 'action' => 'raw', 'oldid' => $this->mNewid
) )
229 $externalEditor = new ExternalEdit( $this->getContext(), $urls );
230 $externalEditor->execute();
232 wfProfileOut( __METHOD__
);
240 # Carry over 'diffonly' param via navigation links
241 if ( $diffOnly != $user->getBoolOption( 'diffonly' ) ) {
242 $query['diffonly'] = $diffOnly;
244 # Cascade unhide param in links for easy deletion browsing
245 if ( $this->unhide
) {
246 $query['unhide'] = 1;
249 # Check if one of the revisions is deleted/suppressed
250 $deleted = $suppressed = false;
251 $allowed = $this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $user );
253 # mOldRev is false if the difference engine is called with a "vague" query for
254 # a diff between a version V and its previous version V' AND the version V
255 # is the first version of that article. In that case, V' does not exist.
256 if ( $this->mOldRev
=== false ) {
257 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
261 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
263 $sk = $this->getSkin();
264 if ( method_exists( $sk, 'suppressQuickbar' ) ) {
265 $sk->suppressQuickbar();
268 if ( $this->mNewPage
->equals( $this->mOldPage
) ) {
269 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
272 $out->setPageTitle( $this->msg( 'difference-title-multipage', $this->mOldPage
->getPrefixedText(),
273 $this->mNewPage
->getPrefixedText() ) );
274 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
278 if ( $samePage && $this->mNewPage
->quickUserCan( 'edit', $user ) ) {
279 if ( $this->mNewRev
->isCurrent() && $this->mNewPage
->userCan( 'rollback', $user ) ) {
280 $out->preventClickjacking();
281 $rollback = '   ' . Linker
::generateRollback( $this->mNewRev
, $this->getContext() );
283 if ( !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
284 $undoLink = ' ' . $this->msg( 'parentheses' )->rawParams(
285 Html
::element( 'a', array(
286 'href' => $this->mNewPage
->getLocalUrl( array(
288 'undoafter' => $this->mOldid
,
289 'undo' => $this->mNewid
) ),
290 'title' => Linker
::titleAttrib( 'undo' )
292 $this->msg( 'editundo' )->text()
297 # Make "previous revision link"
298 if ( $samePage && $this->mOldRev
->getPrevious() ) {
299 $prevlink = Linker
::linkKnown(
301 $this->msg( 'previousdiff' )->escaped(),
302 array( 'id' => 'differences-prevlink' ),
303 array( 'diff' => 'prev', 'oldid' => $this->mOldid
) +
$query
306 $prevlink = ' ';
309 if ( $this->mOldRev
->isMinor() ) {
310 $oldminor = ChangesList
::flag( 'minor' );
315 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
316 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev
, 'complete' );
318 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
319 '<div id="mw-diff-otitle2">' .
320 Linker
::revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
321 '<div id="mw-diff-otitle3">' . $oldminor .
322 Linker
::revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
323 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
325 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
326 $deleted = true; // old revisions text is hidden
327 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
328 $suppressed = true; // also suppressed
332 # Check if this user can see the revisions
333 if ( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $user ) ) {
338 # Make "next revision link"
339 # Skip next link on the top revision
340 if ( $samePage && !$this->mNewRev
->isCurrent() ) {
341 $nextlink = Linker
::linkKnown(
343 $this->msg( 'nextdiff' )->escaped(),
344 array( 'id' => 'differences-nextlink' ),
345 array( 'diff' => 'next', 'oldid' => $this->mNewid
) +
$query
348 $nextlink = ' ';
351 if ( $this->mNewRev
->isMinor() ) {
352 $newminor = ChangesList
::flag( 'minor' );
357 # Handle RevisionDelete links...
358 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
359 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev
, 'complete' ) . $undoLink;
361 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
362 '<div id="mw-diff-ntitle2">' . Linker
::revUserTools( $this->mNewRev
, !$this->unhide
) .
364 '<div id="mw-diff-ntitle3">' . $newminor .
365 Linker
::revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
366 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
368 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
369 $deleted = true; // new revisions text is hidden
370 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
371 $suppressed = true; // also suppressed
374 # If the diff cannot be shown due to a deleted revision, then output
375 # the diff header and links to unhide (if available)...
376 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
377 $this->showDiffStyle();
378 $multi = $this->getMultiNotice();
379 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
381 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
382 # Give explanation for why revision is not visible
383 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
386 # Give explanation and add a link to view the diff...
387 $link = $this->getTitle()->getFullUrl( $this->getRequest()->appendQueryValue( 'unhide', '1', true ) );
388 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
389 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n", array( $msg, $link ) );
391 # Otherwise, output a regular diff...
393 # Add deletion notice if the user is viewing deleted content
396 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
397 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" . $this->msg( $msg )->parse() . "</div>\n";
399 $this->showDiff( $oldHeader, $newHeader, $notice );
401 $this->renderNewRevision();
404 wfProfileOut( __METHOD__
);
408 * Get a link to mark the change as patrolled, or '' if there's either no
409 * revision to patrol or the user is not allowed to to it.
410 * Side effect: this method will call OutputPage::preventClickjacking()
411 * when a link is builded.
415 protected function markPatrolledLink() {
416 global $wgUseRCPatrol;
418 if ( $this->mMarkPatrolledLink
=== null ) {
419 // Prepare a change patrol link, if applicable
420 if ( $wgUseRCPatrol && $this->mNewPage
->quickUserCan( 'patrol', $this->getUser() ) ) {
421 // If we've been given an explicit change identifier, use it; saves time
422 if ( $this->mRcidMarkPatrolled
) {
423 $rcid = $this->mRcidMarkPatrolled
;
424 $rc = RecentChange
::newFromId( $rcid );
425 // Already patrolled?
426 $rcid = is_object( $rc ) && !$rc->getAttribute( 'rc_patrolled' ) ?
$rcid : 0;
428 // Look for an unpatrolled change corresponding to this diff
429 $db = wfGetDB( DB_SLAVE
);
430 $change = RecentChange
::newFromConds(
432 // Redundant user,timestamp condition so we can use the existing index
433 'rc_user_text' => $this->mNewRev
->getRawUserText(),
434 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
435 'rc_this_oldid' => $this->mNewid
,
436 'rc_last_oldid' => $this->mOldid
,
441 if ( $change instanceof RecentChange
) {
442 $rcid = $change->mAttribs
['rc_id'];
443 $this->mRcidMarkPatrolled
= $rcid;
451 $this->getOutput()->preventClickjacking();
452 $token = $this->getUser()->getEditToken( $rcid );
453 $this->mMarkPatrolledLink
= ' <span class="patrollink">[' . Linker
::linkKnown(
455 $this->msg( 'markaspatrolleddiff' )->escaped(),
458 'action' => 'markpatrolled',
464 $this->mMarkPatrolledLink
= '';
467 $this->mMarkPatrolledLink
= '';
471 return $this->mMarkPatrolledLink
;
475 * @param $rev Revision
478 protected function revisionDeleteLink( $rev ) {
479 $link = Linker
::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
480 if ( $link !== '' ) {
481 $link = '   ' . $link . ' ';
487 * Show the new revision of the page.
489 function renderNewRevision() {
490 wfProfileIn( __METHOD__
);
491 $out = $this->getOutput();
492 $revHeader = $this->getRevisionHeader( $this->mNewRev
);
493 # Add "current version as of X" title
494 $out->addHTML( "<hr class='diff-hr' />
495 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
496 # Page content may be handled by a hooked call instead...
497 if ( wfRunHooks( 'ArticleContentOnDiff', array( $this, $out ) ) ) {
498 $this->loadNewText();
499 $out->setRevisionId( $this->mNewid
);
500 $out->setRevisionTimestamp( $this->mNewRev
->getTimestamp() );
501 $out->setArticleFlag( true );
503 if ( $this->mNewPage
->isCssJsSubpage() ||
$this->mNewPage
->isCssOrJsPage() ) { #NOTE: only needed for B/C: custom rendering of JS/CSS via hook
504 // Stolen from Article::view --AG 2007-10-11
505 // Give hooks a chance to customise the output
506 // @TODO: standardize this crap into one function
507 if ( !Hook
::isRegistered( 'ShowRawCssJs' )
508 ||
wfRunHooks( 'ShowRawCssJs', array( ContentHandler
::getContentText( $this->mNewContent
), $this->mNewPage
, $out ) ) ) { #NOTE: deperecated hook, B/C only
509 // use the content object's own rendering
510 $po = $this->mContentObject
->getParserOutput();
511 $out->addHTML( $po->getText() );
513 } elseif( !wfRunHooks( 'ArticleContentViewCustom', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
514 // Handled by extension
515 } elseif( Hooks
::isRegistered( 'ArticleViewCustom' )
516 && !wfRunHooks( 'ArticleViewCustom', array( ContentHandler
::getContentText( $this->mNewContent
), $this->mNewPage
, $out ) ) ) { #NOTE: deperecated hook, B/C only
517 // Handled by extension
520 if ( $this->getTitle()->equals( $this->mNewPage
) ) {
521 // If the Title stored in the context is the same as the one
522 // of the new revision, we can use its associated WikiPage
524 $wikiPage = $this->getWikiPage();
526 // Otherwise we need to create our own WikiPage object
527 $wikiPage = WikiPage
::factory( $this->mNewPage
);
530 $parserOutput = $this->getParserOutput( $wikiPage, $this->mNewRev
);
532 # WikiPage::getParserOutput() should not return false, but just in case
533 if( $parserOutput ) {
534 $out->addParserOutput( $parserOutput );
538 # Add redundant patrol link on bottom...
539 $out->addHTML( $this->markPatrolledLink() );
541 wfProfileOut( __METHOD__
);
544 protected function getParserOutput( WikiPage
$page, Revision
$rev ) {
545 $parserOptions = ParserOptions
::newFromContext( $this->getContext() );
546 $parserOptions->enableLimitReport();
547 $parserOptions->setTidy( true );
549 if ( !$rev->isCurrent() ||
!$rev->getTitle()->quickUserCan( "edit" ) ) {
550 $parserOptions->setEditSection( false );
553 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
554 return $parserOutput;
558 * Get the diff text, send it to the OutputPage object
559 * Returns false if the diff could not be generated, otherwise returns true
563 function showDiff( $otitle, $ntitle, $notice = '' ) {
564 $diff = $this->getDiff( $otitle, $ntitle, $notice );
565 if ( $diff === false ) {
566 $this->getOutput()->addWikiMsg( 'missing-article', "<nowiki>(fixme, bug)</nowiki>", '' );
569 $this->showDiffStyle();
570 $this->getOutput()->addHTML( $diff );
576 * Add style sheets and supporting JS for diff display.
578 function showDiffStyle() {
579 $this->getOutput()->addModuleStyles( 'mediawiki.action.history.diff' );
583 * Get complete diff table, including header
585 * @param $otitle Title: old title
586 * @param $ntitle Title: new title
587 * @param $notice String: HTML between diff header and body
590 function getDiff( $otitle, $ntitle, $notice = '' ) {
591 $body = $this->getDiffBody();
592 if ( $body === false ) {
595 $multi = $this->getMultiNotice();
596 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
601 * Get the diff table body, without header
603 * @return mixed (string/false)
605 public function getDiffBody() {
607 wfProfileIn( __METHOD__
);
608 $this->mCacheHit
= true;
609 // Check if the diff should be hidden from this user
610 if ( !$this->loadRevisionData() ) {
611 wfProfileOut( __METHOD__
);
613 } elseif ( $this->mOldRev
&& !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
614 wfProfileOut( __METHOD__
);
616 } elseif ( $this->mNewRev
&& !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
617 wfProfileOut( __METHOD__
);
621 // If mOldRev is false, it means that the
622 if ( $this->mOldRev
=== false ||
( $this->mOldRev
&& $this->mNewRev
623 && $this->mOldRev
->getID() == $this->mNewRev
->getID() ) )
625 wfProfileOut( __METHOD__
);
630 if ( $this->mOldid
&& $this->mNewid
) {
631 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
,
632 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
634 if ( !$this->mRefreshCache
) {
635 $difftext = $wgMemc->get( $key );
637 wfIncrStats( 'diff_cache_hit' );
638 $difftext = $this->localiseLineNumbers( $difftext );
639 $difftext .= "\n<!-- diff cache key $key -->\n";
640 wfProfileOut( __METHOD__
);
643 } // don't try to load but save the result
645 $this->mCacheHit
= false;
647 // Loadtext is permission safe, this just clears out the diff
648 if ( !$this->loadText() ) {
649 wfProfileOut( __METHOD__
);
653 $difftext = $this->generateContentDiffBody( $this->mOldContent
, $this->mNewContent
);
655 // Save to cache for 7 days
656 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
657 wfIncrStats( 'diff_uncacheable' );
658 } elseif ( $key !== false && $difftext !== false ) {
659 wfIncrStats( 'diff_cache_miss' );
660 $wgMemc->set( $key, $difftext, 7 * 86400 );
662 wfIncrStats( 'diff_uncacheable' );
664 // Replace line numbers with the text in the user's language
665 if ( $difftext !== false ) {
666 $difftext = $this->localiseLineNumbers( $difftext );
668 wfProfileOut( __METHOD__
);
673 * Make sure the proper modules are loaded before we try to
676 private function initDiffEngines() {
677 global $wgExternalDiffEngine;
678 if ( $wgExternalDiffEngine == 'wikidiff' && !function_exists( 'wikidiff_do_diff' ) ) {
679 wfProfileIn( __METHOD__
. '-php_wikidiff.so' );
680 wfDl( 'php_wikidiff' );
681 wfProfileOut( __METHOD__
. '-php_wikidiff.so' );
683 elseif ( $wgExternalDiffEngine == 'wikidiff2' && !function_exists( 'wikidiff2_do_diff' ) ) {
684 wfProfileIn( __METHOD__
. '-php_wikidiff2.so' );
686 wfProfileOut( __METHOD__
. '-php_wikidiff2.so' );
691 * Generate a diff, no caching.
693 * Subclasses may override this to provide a
695 * @param $old Content: old content
696 * @param $new Content: new content
700 function generateContentDiffBody( Content
$old, Content
$new ) {
701 #XXX: generate a warning if $old or $new are not instances of TextContent?
702 #XXX: fail if $old and $new don't have the same content model? or what?
704 $otext = $old->serialize();
705 $ntext = $new->serialize();
707 #XXX: text should be "already segmented". what does that mean?
708 return $this->generateTextDiffBody( $otext, $ntext );
712 * Generate a diff, no caching
714 * @param $otext String: old text, must be already segmented
715 * @param $ntext String: new text, must be already segmented
716 * @deprecated since 1.WD, use generateContentDiffBody() instead!
718 function generateDiffBody( $otext, $ntext ) {
719 wfDeprecated( __METHOD__
, "1.WD" );
721 return $this->generateTextDiffBody( $otext, $ntext );
725 * Generate a diff, no caching
727 * @todo move this to TextDifferenceEngine, make DifferenceEngine abstract. At some point.
729 * @param $otext String: old text, must be already segmented
730 * @param $ntext String: new text, must be already segmented
731 * @return bool|string
733 function generateTextDiffBody( $otext, $ntext ) {
734 global $wgExternalDiffEngine, $wgContLang;
736 wfProfileIn( __METHOD__
);
738 $otext = str_replace( "\r\n", "\n", $otext );
739 $ntext = str_replace( "\r\n", "\n", $ntext );
741 $this->initDiffEngines();
743 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
744 # For historical reasons, external diff engine expects
745 # input text to be HTML-escaped already
746 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
747 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
748 wfProfileOut( __METHOD__
);
749 return $wgContLang->unsegmentForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
750 $this->debug( 'wikidiff1' );
753 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
754 # Better external diff engine, the 2 may some day be dropped
755 # This one does the escaping and segmenting itself
756 wfProfileIn( 'wikidiff2_do_diff' );
757 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
758 $text .= $this->debug( 'wikidiff2' );
759 wfProfileOut( 'wikidiff2_do_diff' );
760 wfProfileOut( __METHOD__
);
763 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
765 $tmpDir = wfTempDir();
766 $tempName1 = tempnam( $tmpDir, 'diff_' );
767 $tempName2 = tempnam( $tmpDir, 'diff_' );
769 $tempFile1 = fopen( $tempName1, "w" );
771 wfProfileOut( __METHOD__
);
774 $tempFile2 = fopen( $tempName2, "w" );
776 wfProfileOut( __METHOD__
);
779 fwrite( $tempFile1, $otext );
780 fwrite( $tempFile2, $ntext );
781 fclose( $tempFile1 );
782 fclose( $tempFile2 );
783 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
784 wfProfileIn( __METHOD__
. "-shellexec" );
785 $difftext = wfShellExec( $cmd );
786 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
787 wfProfileOut( __METHOD__
. "-shellexec" );
788 unlink( $tempName1 );
789 unlink( $tempName2 );
790 wfProfileOut( __METHOD__
);
795 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
796 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
797 $diffs = new Diff( $ota, $nta );
798 $formatter = new TableDiffFormatter();
799 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
800 wfProfileOut( __METHOD__
);
805 * Generate a debug comment indicating diff generating time,
806 * server node, and generator backend.
809 protected function debug( $generator = "internal" ) {
810 global $wgShowHostnames;
811 if ( !$this->enableDebugComment
) {
814 $data = array( $generator );
815 if ( $wgShowHostnames ) {
816 $data[] = wfHostname();
818 $data[] = wfTimestamp( TS_DB
);
819 return "<!-- diff generator: " .
828 * Replace line numbers with the text in the user's language
831 function localiseLineNumbers( $text ) {
832 return preg_replace_callback( '/<!--LINE (\d+)-->/',
833 array( &$this, 'localiseLineNumbersCb' ), $text );
836 function localiseLineNumbersCb( $matches ) {
837 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) return '';
838 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
843 * If there are revisions between the ones being compared, return a note saying so.
846 function getMultiNotice() {
847 if ( !is_object( $this->mOldRev
) ||
!is_object( $this->mNewRev
) ) {
849 } elseif ( !$this->mOldPage
->equals( $this->mNewPage
) ) {
850 // Comparing two different pages? Count would be meaningless.
854 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
855 $oldRev = $this->mNewRev
; // flip
856 $newRev = $this->mOldRev
; // flip
857 } else { // normal case
858 $oldRev = $this->mOldRev
;
859 $newRev = $this->mNewRev
;
862 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev );
864 $limit = 100; // use diff-multi-manyusers if too many users
865 $numUsers = $this->mNewPage
->countAuthorsBetween( $oldRev, $newRev, $limit );
866 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
868 return ''; // nothing
872 * Get a notice about how many intermediate edits and users there are
873 * @param $numEdits int
874 * @param $numUsers int
878 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
879 if ( $numUsers > $limit ) {
880 $msg = 'diff-multi-manyusers';
885 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
889 * Get a header for a specified revision.
891 * @param $rev Revision
892 * @param $complete String: 'complete' to get the header wrapped depending
893 * the visibility of the revision and a link to edit the page.
894 * @return String HTML fragment
896 protected function getRevisionHeader( Revision
$rev, $complete = '' ) {
897 $lang = $this->getLanguage();
898 $user = $this->getUser();
899 $revtimestamp = $rev->getTimestamp();
900 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
901 $dateofrev = $lang->userDate( $revtimestamp, $user );
902 $timeofrev = $lang->userTime( $revtimestamp, $user );
904 $header = $this->msg(
905 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
911 if ( $complete !== 'complete' ) {
915 $title = $rev->getTitle();
917 $header = Linker
::linkKnown( $title, $header, array(),
918 array( 'oldid' => $rev->getID() ) );
920 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
921 $editQuery = array( 'action' => 'edit' );
922 if ( !$rev->isCurrent() ) {
923 $editQuery['oldid'] = $rev->getID();
926 $msg = $this->msg( $title->quickUserCan( 'edit', $user ) ?
'editold' : 'viewsourceold' )->escaped();
927 $header .= ' ' . $this->msg( 'parentheses' )->rawParams(
928 Linker
::linkKnown( $title, $msg, array(), $editQuery ) )->plain();
929 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
930 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
933 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
940 * Add the header to a diff body
944 function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
945 // shared.css sets diff in interface language/dir, but the actual content
946 // is often in a different language, mostly the page content language/dir
947 $tableClass = 'diff diff-contentalign-' . htmlspecialchars( $this->getDiffLang()->alignStart() );
948 $header = "<table class='$tableClass'>";
950 if ( !$diff && !$otitle ) {
953 <td class='diff-ntitle'>{$ntitle}</td>
957 if ( $diff ) { // Safari/Chrome show broken output if cols not used
959 <col class='diff-marker' />
960 <col class='diff-content' />
961 <col class='diff-marker' />
962 <col class='diff-content' />";
971 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
972 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
976 if ( $multi != '' ) {
977 $header .= "<tr><td colspan='{$multiColspan}' align='center' class='diff-multi'>{$multi}</td></tr>";
979 if ( $notice != '' ) {
980 $header .= "<tr><td colspan='{$multiColspan}' align='center'>{$notice}</td></tr>";
983 return $header . $diff . "</table>";
987 * Use specified text instead of loading from the database
988 * @deprecated since 1.WD
990 function setText( $oldText, $newText ) { #FIXME: no longer use this, use setContent()!
991 wfDeprecated( __METHOD__
, "1.WD" );
993 $oldContent = ContentHandler
::makeContent( $oldText, $this->getTitle() );
994 $newContent = ContentHandler
::makeContent( $newText, $this->getTitle() );
996 $this->setContent( $oldContent, $newContent );
1000 * Use specified text instead of loading from the database
1003 function setContent( Content
$oldContent, Content
$newContent ) {
1004 $this->mOldContent
= $oldContent;
1005 $this->mNewContent
= $newContent;
1007 $this->mTextLoaded
= 2;
1008 $this->mRevisionsLoaded
= true;
1012 * Set the language in which the diff text is written
1013 * (Defaults to page content language).
1016 function setTextLanguage( $lang ) {
1017 $this->mDiffLang
= wfGetLangObj( $lang );
1023 private function loadRevisionIds() {
1024 if ( $this->mRevisionsIdsLoaded
) {
1028 $this->mRevisionsIdsLoaded
= true;
1030 $old = $this->mOldid
;
1031 $new = $this->mNewid
;
1033 if ( $new === 'prev' ) {
1034 # Show diff between revision $old and the previous one.
1035 # Get previous one from DB.
1036 $this->mNewid
= intval( $old );
1037 $this->mOldid
= $this->getTitle()->getPreviousRevisionID( $this->mNewid
);
1038 } elseif ( $new === 'next' ) {
1039 # Show diff between revision $old and the next one.
1040 # Get next one from DB.
1041 $this->mOldid
= intval( $old );
1042 $this->mNewid
= $this->getTitle()->getNextRevisionID( $this->mOldid
);
1043 if ( $this->mNewid
=== false ) {
1044 # if no result, NewId points to the newest old revision. The only newer
1045 # revision is cur, which is "0".
1049 $this->mOldid
= intval( $old );
1050 $this->mNewid
= intval( $new );
1051 wfRunHooks( 'NewDifferenceEngine', array( $this->getTitle(), &$this->mOldid
, &$this->mNewid
, $old, $new ) );
1056 * Load revision metadata for the specified articles. If newid is 0, then compare
1057 * the old article in oldid to the current article; if oldid is 0, then
1058 * compare the current article to the immediately previous one (ignoring the
1061 * If oldid is false, leave the corresponding revision object set
1062 * to false. This is impossible via ordinary user input, and is provided for
1067 function loadRevisionData() {
1068 if ( $this->mRevisionsLoaded
) {
1072 // Whether it succeeds or fails, we don't want to try again
1073 $this->mRevisionsLoaded
= true;
1075 $this->loadRevisionIds();
1077 // Load the new revision object
1078 $this->mNewRev
= $this->mNewid
1079 ? Revision
::newFromId( $this->mNewid
)
1080 : Revision
::newFromTitle( $this->getTitle(), false, Revision
::AVOID_MASTER
);
1082 if ( !$this->mNewRev
instanceof Revision
) {
1086 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1087 $this->mNewid
= $this->mNewRev
->getId();
1088 $this->mNewPage
= $this->mNewRev
->getTitle();
1090 // Load the old revision object
1091 $this->mOldRev
= false;
1092 if ( $this->mOldid
) {
1093 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1094 } elseif ( $this->mOldid
=== 0 ) {
1095 $rev = $this->mNewRev
->getPrevious();
1097 $this->mOldid
= $rev->getId();
1098 $this->mOldRev
= $rev;
1100 // No previous revision; mark to show as first-version only.
1101 $this->mOldid
= false;
1102 $this->mOldRev
= false;
1104 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1106 if ( is_null( $this->mOldRev
) ) {
1110 if ( $this->mOldRev
) {
1111 $this->mOldPage
= $this->mOldRev
->getTitle();
1118 * Load the text of the revisions, as well as revision data.
1122 function loadText() {
1123 if ( $this->mTextLoaded
== 2 ) {
1126 // Whether it succeeds or fails, we don't want to try again
1127 $this->mTextLoaded
= 2;
1130 if ( !$this->loadRevisionData() ) {
1133 if ( $this->mOldRev
) {
1134 $this->mOldContent
= $this->mOldRev
->getContent( Revision
::FOR_THIS_USER
);
1135 if ( $this->mOldContent
=== false ) {
1139 if ( $this->mNewRev
) {
1140 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
);
1141 if ( $this->mNewContent
=== false ) {
1149 * Load the text of the new revision, not the old one
1153 function loadNewText() {
1154 if ( $this->mTextLoaded
>= 1 ) {
1157 $this->mTextLoaded
= 1;
1159 if ( !$this->loadRevisionData() ) {
1162 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
);