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 private function showMissingRevision() {
183 $out = $this->getOutput();
186 if ( $this->mOldRev
=== null ) {
187 $missing[] = $this->deletedIdMarker( $this->mOldid
);
189 if ( $this->mNewRev
=== null ) {
190 $missing[] = $this->deletedIdMarker( $this->mNewid
);
193 $out->setPageTitle( $this->msg( 'errorpagetitle' ) );
194 $out->addWikiMsg( 'difference-missing-revision',
195 $this->getLanguage()->listToText( $missing ), count( $missing ) );
198 function showDiffPage( $diffOnly = false ) {
199 wfProfileIn( __METHOD__
);
201 # Allow frames except in certain special cases
202 $out = $this->getOutput();
203 $out->allowClickjacking();
204 $out->setRobotPolicy( 'noindex,nofollow' );
206 if ( !$this->loadRevisionData() ) {
207 $this->showMissingRevision();
208 wfProfileOut( __METHOD__
);
212 $user = $this->getUser();
213 $permErrors = $this->mNewPage
->getUserPermissionsErrors( 'read', $user );
214 if ( $this->mOldPage
) { # mOldPage might not be set, see below.
215 $permErrors = wfMergeErrorArrays( $permErrors,
216 $this->mOldPage
->getUserPermissionsErrors( 'read', $user ) );
218 if ( count( $permErrors ) ) {
219 wfProfileOut( __METHOD__
);
220 throw new PermissionsError( 'read', $permErrors );
223 # If external diffs are enabled both globally and for the user,
224 # we'll use the application/x-external-editor interface to call
225 # an external diff tool like kompare, kdiff3, etc.
226 if ( ExternalEdit
::useExternalEngine( $this->getContext(), 'diff' ) ) {
227 //TODO: come up with a good solution for non-text content here.
228 // at least, the content format needs to be passed to the client somehow.
229 // Currently, action=raw will just fail for non-text content.
232 'File' => array( 'Extension' => 'wiki', 'URL' =>
233 # This should be mOldPage, but it may not be set, see below.
234 $this->mNewPage
->getCanonicalURL( array(
235 'action' => 'raw', 'oldid' => $this->mOldid
) )
237 'File2' => array( 'Extension' => 'wiki', 'URL' =>
238 $this->mNewPage
->getCanonicalURL( array(
239 'action' => 'raw', 'oldid' => $this->mNewid
) )
243 $externalEditor = new ExternalEdit( $this->getContext(), $urls );
244 $externalEditor->execute();
246 wfProfileOut( __METHOD__
);
254 # Carry over 'diffonly' param via navigation links
255 if ( $diffOnly != $user->getBoolOption( 'diffonly' ) ) {
256 $query['diffonly'] = $diffOnly;
258 # Cascade unhide param in links for easy deletion browsing
259 if ( $this->unhide
) {
260 $query['unhide'] = 1;
263 # Check if one of the revisions is deleted/suppressed
264 $deleted = $suppressed = false;
265 $allowed = $this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $user );
267 # mOldRev is false if the difference engine is called with a "vague" query for
268 # a diff between a version V and its previous version V' AND the version V
269 # is the first version of that article. In that case, V' does not exist.
270 if ( $this->mOldRev
=== false ) {
271 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
275 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
277 $sk = $this->getSkin();
278 if ( method_exists( $sk, 'suppressQuickbar' ) ) {
279 $sk->suppressQuickbar();
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 $out->preventClickjacking();
295 $rollback = '   ' . Linker
::generateRollback( $this->mNewRev
, $this->getContext() );
297 if ( !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
298 $undoLink = ' ' . $this->msg( 'parentheses' )->rawParams(
299 Html
::element( 'a', array(
300 'href' => $this->mNewPage
->getLocalUrl( array(
302 'undoafter' => $this->mOldid
,
303 'undo' => $this->mNewid
) ),
304 'title' => Linker
::titleAttrib( 'undo' )
306 $this->msg( 'editundo' )->text()
311 # Make "previous revision link"
312 if ( $samePage && $this->mOldRev
->getPrevious() ) {
313 $prevlink = Linker
::linkKnown(
315 $this->msg( 'previousdiff' )->escaped(),
316 array( 'id' => 'differences-prevlink' ),
317 array( 'diff' => 'prev', 'oldid' => $this->mOldid
) +
$query
320 $prevlink = ' ';
323 if ( $this->mOldRev
->isMinor() ) {
324 $oldminor = ChangesList
::flag( 'minor' );
329 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
330 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev
, 'complete' );
332 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
333 '<div id="mw-diff-otitle2">' .
334 Linker
::revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
335 '<div id="mw-diff-otitle3">' . $oldminor .
336 Linker
::revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
337 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
339 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
340 $deleted = true; // old revisions text is hidden
341 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
342 $suppressed = true; // also suppressed
346 # Check if this user can see the revisions
347 if ( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $user ) ) {
352 # Make "next revision link"
353 # Skip next link on the top revision
354 if ( $samePage && !$this->mNewRev
->isCurrent() ) {
355 $nextlink = Linker
::linkKnown(
357 $this->msg( 'nextdiff' )->escaped(),
358 array( 'id' => 'differences-nextlink' ),
359 array( 'diff' => 'next', 'oldid' => $this->mNewid
) +
$query
362 $nextlink = ' ';
365 if ( $this->mNewRev
->isMinor() ) {
366 $newminor = ChangesList
::flag( 'minor' );
371 # Handle RevisionDelete links...
372 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
373 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev
, 'complete' ) . $undoLink;
375 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
376 '<div id="mw-diff-ntitle2">' . Linker
::revUserTools( $this->mNewRev
, !$this->unhide
) .
378 '<div id="mw-diff-ntitle3">' . $newminor .
379 Linker
::revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
380 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
382 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
383 $deleted = true; // new revisions text is hidden
384 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
385 $suppressed = true; // also suppressed
388 # If the diff cannot be shown due to a deleted revision, then output
389 # the diff header and links to unhide (if available)...
390 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
391 $this->showDiffStyle();
392 $multi = $this->getMultiNotice();
393 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
395 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
396 # Give explanation for why revision is not visible
397 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
400 # Give explanation and add a link to view the diff...
401 $link = $this->getTitle()->getFullUrl( $this->getRequest()->appendQueryValue( 'unhide', '1', true ) );
402 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
403 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n", array( $msg, $link ) );
405 # Otherwise, output a regular diff...
407 # Add deletion notice if the user is viewing deleted content
410 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
411 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" . $this->msg( $msg )->parse() . "</div>\n";
413 $this->showDiff( $oldHeader, $newHeader, $notice );
415 $this->renderNewRevision();
418 wfProfileOut( __METHOD__
);
422 * Get a link to mark the change as patrolled, or '' if there's either no
423 * revision to patrol or the user is not allowed to to it.
424 * Side effect: this method will call OutputPage::preventClickjacking()
425 * when a link is builded.
429 protected function markPatrolledLink() {
430 global $wgUseRCPatrol;
432 if ( $this->mMarkPatrolledLink
=== null ) {
433 // Prepare a change patrol link, if applicable
434 if ( $wgUseRCPatrol && $this->mNewPage
->quickUserCan( 'patrol', $this->getUser() ) ) {
435 // If we've been given an explicit change identifier, use it; saves time
436 if ( $this->mRcidMarkPatrolled
) {
437 $rcid = $this->mRcidMarkPatrolled
;
438 $rc = RecentChange
::newFromId( $rcid );
439 // Already patrolled?
440 $rcid = is_object( $rc ) && !$rc->getAttribute( 'rc_patrolled' ) ?
$rcid : 0;
442 // Look for an unpatrolled change corresponding to this diff
443 $db = wfGetDB( DB_SLAVE
);
444 $change = RecentChange
::newFromConds(
446 // Redundant user,timestamp condition so we can use the existing index
447 'rc_user_text' => $this->mNewRev
->getRawUserText(),
448 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
449 'rc_this_oldid' => $this->mNewid
,
450 'rc_last_oldid' => $this->mOldid
,
455 if ( $change instanceof RecentChange
) {
456 $rcid = $change->mAttribs
['rc_id'];
457 $this->mRcidMarkPatrolled
= $rcid;
465 $this->getOutput()->preventClickjacking();
466 $token = $this->getUser()->getEditToken( $rcid );
467 $this->mMarkPatrolledLink
= ' <span class="patrollink">[' . Linker
::linkKnown(
469 $this->msg( 'markaspatrolleddiff' )->escaped(),
472 'action' => 'markpatrolled',
478 $this->mMarkPatrolledLink
= '';
481 $this->mMarkPatrolledLink
= '';
485 return $this->mMarkPatrolledLink
;
489 * @param $rev Revision
492 protected function revisionDeleteLink( $rev ) {
493 $link = Linker
::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
494 if ( $link !== '' ) {
495 $link = '   ' . $link . ' ';
501 * Show the new revision of the page.
503 function renderNewRevision() {
504 wfProfileIn( __METHOD__
);
505 $out = $this->getOutput();
506 $revHeader = $this->getRevisionHeader( $this->mNewRev
);
507 # Add "current version as of X" title
508 $out->addHTML( "<hr class='diff-hr' />
509 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
510 # Page content may be handled by a hooked call instead...
511 if ( wfRunHooks( 'ArticleContentOnDiff', array( $this, $out ) ) ) {
512 $this->loadNewText();
513 $out->setRevisionId( $this->mNewid
);
514 $out->setRevisionTimestamp( $this->mNewRev
->getTimestamp() );
515 $out->setArticleFlag( true );
517 // NOTE: only needed for B/C: custom rendering of JS/CSS via hook
518 if ( $this->mNewPage
->isCssJsSubpage() ||
$this->mNewPage
->isCssOrJsPage() ) {
519 // Stolen from Article::view --AG 2007-10-11
520 // Give hooks a chance to customise the output
521 // @TODO: standardize this crap into one function
522 if ( ContentHandler
::runLegacyHooks( 'ShowRawCssJs', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
523 // NOTE: deprecated hook, B/C only
524 // use the content object's own rendering
525 $po = $this->mNewRev
->getContent()->getParserOutput( $this->mNewRev
->getTitle(), $this->mNewRev
->getId() );
526 $out->addHTML( $po->getText() );
528 } elseif( !wfRunHooks( 'ArticleContentViewCustom', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
529 // Handled by extension
530 } elseif( !ContentHandler
::runLegacyHooks( 'ArticleViewCustom', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
531 // NOTE: deprecated hook, B/C only
532 // Handled by extension
535 if ( $this->getTitle()->equals( $this->mNewPage
) ) {
536 // If the Title stored in the context is the same as the one
537 // of the new revision, we can use its associated WikiPage
539 $wikiPage = $this->getWikiPage();
541 // Otherwise we need to create our own WikiPage object
542 $wikiPage = WikiPage
::factory( $this->mNewPage
);
545 $parserOutput = $this->getParserOutput( $wikiPage, $this->mNewRev
);
547 # WikiPage::getParserOutput() should not return false, but just in case
548 if( $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 $otitle Title: old title
599 * @param $ntitle Title: new title
600 * @param $notice String: 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 * Subclasses may override this to provide a
708 * @param $old Content: old content
709 * @param $new Content: new content
713 function generateContentDiffBody( Content
$old, Content
$new ) {
714 if ( !( $old instanceof TextContent
) ) {
715 throw new MWException( "Diff not implemented for " . get_class( $old ) . "; "
716 . "override generateContentDiffBody to fix this." );
719 if ( !( $new instanceof TextContent
) ) {
720 throw new MWException( "Diff not implemented for " . get_class( $new ) . "; "
721 . "override generateContentDiffBody to fix this." );
724 $otext = $old->serialize();
725 $ntext = $new->serialize();
727 return $this->generateTextDiffBody( $otext, $ntext );
731 * Generate a diff, no caching
733 * @param $otext String: old text, must be already segmented
734 * @param $ntext String: new text, must be already segmented
735 * @deprecated since 1.21, use generateContentDiffBody() instead!
737 function generateDiffBody( $otext, $ntext ) {
738 wfDeprecated( __METHOD__
, "1.21" );
740 return $this->generateTextDiffBody( $otext, $ntext );
744 * Generate a diff, no caching
746 * @todo move this to TextDifferenceEngine, make DifferenceEngine abstract. At some point.
748 * @param $otext String: old text, must be already segmented
749 * @param $ntext String: new text, must be already segmented
750 * @return bool|string
752 function generateTextDiffBody( $otext, $ntext ) {
753 global $wgExternalDiffEngine, $wgContLang;
755 wfProfileIn( __METHOD__
);
757 $otext = str_replace( "\r\n", "\n", $otext );
758 $ntext = str_replace( "\r\n", "\n", $ntext );
760 $this->initDiffEngines();
762 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
763 # For historical reasons, external diff engine expects
764 # input text to be HTML-escaped already
765 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
766 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
767 wfProfileOut( __METHOD__
);
768 return $wgContLang->unsegmentForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
769 $this->debug( 'wikidiff1' );
772 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
773 # Better external diff engine, the 2 may some day be dropped
774 # This one does the escaping and segmenting itself
775 wfProfileIn( 'wikidiff2_do_diff' );
776 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
777 $text .= $this->debug( 'wikidiff2' );
778 wfProfileOut( 'wikidiff2_do_diff' );
779 wfProfileOut( __METHOD__
);
782 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
784 $tmpDir = wfTempDir();
785 $tempName1 = tempnam( $tmpDir, 'diff_' );
786 $tempName2 = tempnam( $tmpDir, 'diff_' );
788 $tempFile1 = fopen( $tempName1, "w" );
790 wfProfileOut( __METHOD__
);
793 $tempFile2 = fopen( $tempName2, "w" );
795 wfProfileOut( __METHOD__
);
798 fwrite( $tempFile1, $otext );
799 fwrite( $tempFile2, $ntext );
800 fclose( $tempFile1 );
801 fclose( $tempFile2 );
802 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
803 wfProfileIn( __METHOD__
. "-shellexec" );
804 $difftext = wfShellExec( $cmd );
805 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
806 wfProfileOut( __METHOD__
. "-shellexec" );
807 unlink( $tempName1 );
808 unlink( $tempName2 );
809 wfProfileOut( __METHOD__
);
814 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
815 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
816 $diffs = new Diff( $ota, $nta );
817 $formatter = new TableDiffFormatter();
818 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
819 wfProfileOut( __METHOD__
);
824 * Generate a debug comment indicating diff generating time,
825 * server node, and generator backend.
828 protected function debug( $generator = "internal" ) {
829 global $wgShowHostnames;
830 if ( !$this->enableDebugComment
) {
833 $data = array( $generator );
834 if ( $wgShowHostnames ) {
835 $data[] = wfHostname();
837 $data[] = wfTimestamp( TS_DB
);
838 return "<!-- diff generator: " .
847 * Replace line numbers with the text in the user's language
850 function localiseLineNumbers( $text ) {
851 return preg_replace_callback( '/<!--LINE (\d+)-->/',
852 array( &$this, 'localiseLineNumbersCb' ), $text );
855 function localiseLineNumbersCb( $matches ) {
856 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) return '';
857 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
862 * If there are revisions between the ones being compared, return a note saying so.
865 function getMultiNotice() {
866 if ( !is_object( $this->mOldRev
) ||
!is_object( $this->mNewRev
) ) {
868 } elseif ( !$this->mOldPage
->equals( $this->mNewPage
) ) {
869 // Comparing two different pages? Count would be meaningless.
873 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
874 $oldRev = $this->mNewRev
; // flip
875 $newRev = $this->mOldRev
; // flip
876 } else { // normal case
877 $oldRev = $this->mOldRev
;
878 $newRev = $this->mNewRev
;
881 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev );
883 $limit = 100; // use diff-multi-manyusers if too many users
884 $numUsers = $this->mNewPage
->countAuthorsBetween( $oldRev, $newRev, $limit );
885 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
887 return ''; // nothing
891 * Get a notice about how many intermediate edits and users there are
892 * @param $numEdits int
893 * @param $numUsers int
897 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
898 if ( $numUsers > $limit ) {
899 $msg = 'diff-multi-manyusers';
904 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
908 * Get a header for a specified revision.
910 * @param $rev Revision
911 * @param $complete String: 'complete' to get the header wrapped depending
912 * the visibility of the revision and a link to edit the page.
913 * @return String HTML fragment
915 protected function getRevisionHeader( Revision
$rev, $complete = '' ) {
916 $lang = $this->getLanguage();
917 $user = $this->getUser();
918 $revtimestamp = $rev->getTimestamp();
919 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
920 $dateofrev = $lang->userDate( $revtimestamp, $user );
921 $timeofrev = $lang->userTime( $revtimestamp, $user );
923 $header = $this->msg(
924 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
930 if ( $complete !== 'complete' ) {
934 $title = $rev->getTitle();
936 $header = Linker
::linkKnown( $title, $header, array(),
937 array( 'oldid' => $rev->getID() ) );
939 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
940 $editQuery = array( 'action' => 'edit' );
941 if ( !$rev->isCurrent() ) {
942 $editQuery['oldid'] = $rev->getID();
945 $msg = $this->msg( $title->quickUserCan( 'edit', $user ) ?
'editold' : 'viewsourceold' )->escaped();
946 $header .= ' ' . $this->msg( 'parentheses' )->rawParams(
947 Linker
::linkKnown( $title, $msg, array(), $editQuery ) )->plain();
948 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
949 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
952 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
959 * Add the header to a diff body
963 function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
964 // shared.css sets diff in interface language/dir, but the actual content
965 // is often in a different language, mostly the page content language/dir
966 $tableClass = 'diff diff-contentalign-' . htmlspecialchars( $this->getDiffLang()->alignStart() );
967 $header = "<table class='$tableClass'>";
969 if ( !$diff && !$otitle ) {
971 <tr style='vertical-align: top;'>
972 <td class='diff-ntitle'>{$ntitle}</td>
976 if ( $diff ) { // Safari/Chrome show broken output if cols not used
978 <col class='diff-marker' />
979 <col class='diff-content' />
980 <col class='diff-marker' />
981 <col class='diff-content' />";
989 <tr style='vertical-align: top;'>
990 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
991 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
995 if ( $multi != '' ) {
996 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;' class='diff-multi'>{$multi}</td></tr>";
998 if ( $notice != '' ) {
999 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;'>{$notice}</td></tr>";
1002 return $header . $diff . "</table>";
1006 * Use specified text instead of loading from the database
1007 * @deprecated since 1.21, use setContent() instead.
1009 function setText( $oldText, $newText ) {
1010 wfDeprecated( __METHOD__
, "1.21" );
1012 $oldContent = ContentHandler
::makeContent( $oldText, $this->getTitle() );
1013 $newContent = ContentHandler
::makeContent( $newText, $this->getTitle() );
1015 $this->setContent( $oldContent, $newContent );
1019 * Use specified text instead of loading from the database
1022 function setContent( Content
$oldContent, Content
$newContent ) {
1023 $this->mOldContent
= $oldContent;
1024 $this->mNewContent
= $newContent;
1026 $this->mTextLoaded
= 2;
1027 $this->mRevisionsLoaded
= true;
1031 * Set the language in which the diff text is written
1032 * (Defaults to page content language).
1035 function setTextLanguage( $lang ) {
1036 $this->mDiffLang
= wfGetLangObj( $lang );
1042 private function loadRevisionIds() {
1043 if ( $this->mRevisionsIdsLoaded
) {
1047 $this->mRevisionsIdsLoaded
= true;
1049 $old = $this->mOldid
;
1050 $new = $this->mNewid
;
1052 if ( $new === 'prev' ) {
1053 # Show diff between revision $old and the previous one.
1054 # Get previous one from DB.
1055 $this->mNewid
= intval( $old );
1056 $this->mOldid
= $this->getTitle()->getPreviousRevisionID( $this->mNewid
);
1057 } elseif ( $new === 'next' ) {
1058 # Show diff between revision $old and the next one.
1059 # Get next one from DB.
1060 $this->mOldid
= intval( $old );
1061 $this->mNewid
= $this->getTitle()->getNextRevisionID( $this->mOldid
);
1062 if ( $this->mNewid
=== false ) {
1063 # if no result, NewId points to the newest old revision. The only newer
1064 # revision is cur, which is "0".
1068 $this->mOldid
= intval( $old );
1069 $this->mNewid
= intval( $new );
1070 wfRunHooks( 'NewDifferenceEngine', array( $this->getTitle(), &$this->mOldid
, &$this->mNewid
, $old, $new ) );
1075 * Load revision metadata for the specified articles. If newid is 0, then compare
1076 * the old article in oldid to the current article; if oldid is 0, then
1077 * compare the current article to the immediately previous one (ignoring the
1080 * If oldid is false, leave the corresponding revision object set
1081 * to false. This is impossible via ordinary user input, and is provided for
1086 function loadRevisionData() {
1087 if ( $this->mRevisionsLoaded
) {
1091 // Whether it succeeds or fails, we don't want to try again
1092 $this->mRevisionsLoaded
= true;
1094 $this->loadRevisionIds();
1096 // Load the new revision object
1097 $this->mNewRev
= $this->mNewid
1098 ? Revision
::newFromId( $this->mNewid
)
1099 : Revision
::newFromTitle( $this->getTitle(), false, Revision
::READ_NORMAL
);
1101 if ( !$this->mNewRev
instanceof Revision
) {
1105 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1106 $this->mNewid
= $this->mNewRev
->getId();
1107 $this->mNewPage
= $this->mNewRev
->getTitle();
1109 // Load the old revision object
1110 $this->mOldRev
= false;
1111 if ( $this->mOldid
) {
1112 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1113 } elseif ( $this->mOldid
=== 0 ) {
1114 $rev = $this->mNewRev
->getPrevious();
1116 $this->mOldid
= $rev->getId();
1117 $this->mOldRev
= $rev;
1119 // No previous revision; mark to show as first-version only.
1120 $this->mOldid
= false;
1121 $this->mOldRev
= false;
1123 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1125 if ( is_null( $this->mOldRev
) ) {
1129 if ( $this->mOldRev
) {
1130 $this->mOldPage
= $this->mOldRev
->getTitle();
1137 * Load the text of the revisions, as well as revision data.
1141 function loadText() {
1142 if ( $this->mTextLoaded
== 2 ) {
1145 // Whether it succeeds or fails, we don't want to try again
1146 $this->mTextLoaded
= 2;
1149 if ( !$this->loadRevisionData() ) {
1152 if ( $this->mOldRev
) {
1153 $this->mOldContent
= $this->mOldRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1154 if ( $this->mOldContent
=== false ) {
1158 if ( $this->mNewRev
) {
1159 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1160 if ( $this->mNewContent
=== false ) {
1168 * Load the text of the new revision, not the old one
1172 function loadNewText() {
1173 if ( $this->mTextLoaded
>= 1 ) {
1176 $this->mTextLoaded
= 1;
1178 if ( !$this->loadRevisionData() ) {
1181 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );