e1db2c7ac37b432c8b7f83e3b5c4f0b94a3e0e12
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' ) ) { #FIXME: how to handle this for non-text content?
228 'File' => array( 'Extension' => 'wiki', 'URL' =>
229 # This should be mOldPage, but it may not be set, see below.
230 $this->mNewPage
->getCanonicalURL( array(
231 'action' => 'raw', 'oldid' => $this->mOldid
) )
233 'File2' => array( 'Extension' => 'wiki', 'URL' =>
234 $this->mNewPage
->getCanonicalURL( array(
235 'action' => 'raw', 'oldid' => $this->mNewid
) )
239 $externalEditor = new ExternalEdit( $this->getContext(), $urls );
240 $externalEditor->execute();
242 wfProfileOut( __METHOD__
);
250 # Carry over 'diffonly' param via navigation links
251 if ( $diffOnly != $user->getBoolOption( 'diffonly' ) ) {
252 $query['diffonly'] = $diffOnly;
254 # Cascade unhide param in links for easy deletion browsing
255 if ( $this->unhide
) {
256 $query['unhide'] = 1;
259 # Check if one of the revisions is deleted/suppressed
260 $deleted = $suppressed = false;
261 $allowed = $this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $user );
263 # mOldRev is false if the difference engine is called with a "vague" query for
264 # a diff between a version V and its previous version V' AND the version V
265 # is the first version of that article. In that case, V' does not exist.
266 if ( $this->mOldRev
=== false ) {
267 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
271 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
273 $sk = $this->getSkin();
274 if ( method_exists( $sk, 'suppressQuickbar' ) ) {
275 $sk->suppressQuickbar();
278 if ( $this->mNewPage
->equals( $this->mOldPage
) ) {
279 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
282 $out->setPageTitle( $this->msg( 'difference-title-multipage', $this->mOldPage
->getPrefixedText(),
283 $this->mNewPage
->getPrefixedText() ) );
284 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
288 if ( $samePage && $this->mNewPage
->quickUserCan( 'edit', $user ) ) {
289 if ( $this->mNewRev
->isCurrent() && $this->mNewPage
->userCan( 'rollback', $user ) ) {
290 $out->preventClickjacking();
291 $rollback = '   ' . Linker
::generateRollback( $this->mNewRev
, $this->getContext() );
293 if ( !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
294 $undoLink = ' ' . $this->msg( 'parentheses' )->rawParams(
295 Html
::element( 'a', array(
296 'href' => $this->mNewPage
->getLocalUrl( array(
298 'undoafter' => $this->mOldid
,
299 'undo' => $this->mNewid
) ),
300 'title' => Linker
::titleAttrib( 'undo' )
302 $this->msg( 'editundo' )->text()
307 # Make "previous revision link"
308 if ( $samePage && $this->mOldRev
->getPrevious() ) {
309 $prevlink = Linker
::linkKnown(
311 $this->msg( 'previousdiff' )->escaped(),
312 array( 'id' => 'differences-prevlink' ),
313 array( 'diff' => 'prev', 'oldid' => $this->mOldid
) +
$query
316 $prevlink = ' ';
319 if ( $this->mOldRev
->isMinor() ) {
320 $oldminor = ChangesList
::flag( 'minor' );
325 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
326 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev
, 'complete' );
328 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
329 '<div id="mw-diff-otitle2">' .
330 Linker
::revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
331 '<div id="mw-diff-otitle3">' . $oldminor .
332 Linker
::revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
333 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
335 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
336 $deleted = true; // old revisions text is hidden
337 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
338 $suppressed = true; // also suppressed
342 # Check if this user can see the revisions
343 if ( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $user ) ) {
348 # Make "next revision link"
349 # Skip next link on the top revision
350 if ( $samePage && !$this->mNewRev
->isCurrent() ) {
351 $nextlink = Linker
::linkKnown(
353 $this->msg( 'nextdiff' )->escaped(),
354 array( 'id' => 'differences-nextlink' ),
355 array( 'diff' => 'next', 'oldid' => $this->mNewid
) +
$query
358 $nextlink = ' ';
361 if ( $this->mNewRev
->isMinor() ) {
362 $newminor = ChangesList
::flag( 'minor' );
367 # Handle RevisionDelete links...
368 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
369 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev
, 'complete' ) . $undoLink;
371 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
372 '<div id="mw-diff-ntitle2">' . Linker
::revUserTools( $this->mNewRev
, !$this->unhide
) .
374 '<div id="mw-diff-ntitle3">' . $newminor .
375 Linker
::revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
376 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
378 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
379 $deleted = true; // new revisions text is hidden
380 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
381 $suppressed = true; // also suppressed
384 # If the diff cannot be shown due to a deleted revision, then output
385 # the diff header and links to unhide (if available)...
386 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
387 $this->showDiffStyle();
388 $multi = $this->getMultiNotice();
389 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
391 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
392 # Give explanation for why revision is not visible
393 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
396 # Give explanation and add a link to view the diff...
397 $link = $this->getTitle()->getFullUrl( $this->getRequest()->appendQueryValue( 'unhide', '1', true ) );
398 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
399 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n", array( $msg, $link ) );
401 # Otherwise, output a regular diff...
403 # Add deletion notice if the user is viewing deleted content
406 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
407 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" . $this->msg( $msg )->parse() . "</div>\n";
409 $this->showDiff( $oldHeader, $newHeader, $notice );
411 $this->renderNewRevision();
414 wfProfileOut( __METHOD__
);
418 * Get a link to mark the change as patrolled, or '' if there's either no
419 * revision to patrol or the user is not allowed to to it.
420 * Side effect: this method will call OutputPage::preventClickjacking()
421 * when a link is builded.
425 protected function markPatrolledLink() {
426 global $wgUseRCPatrol;
428 if ( $this->mMarkPatrolledLink
=== null ) {
429 // Prepare a change patrol link, if applicable
430 if ( $wgUseRCPatrol && $this->mNewPage
->quickUserCan( 'patrol', $this->getUser() ) ) {
431 // If we've been given an explicit change identifier, use it; saves time
432 if ( $this->mRcidMarkPatrolled
) {
433 $rcid = $this->mRcidMarkPatrolled
;
434 $rc = RecentChange
::newFromId( $rcid );
435 // Already patrolled?
436 $rcid = is_object( $rc ) && !$rc->getAttribute( 'rc_patrolled' ) ?
$rcid : 0;
438 // Look for an unpatrolled change corresponding to this diff
439 $db = wfGetDB( DB_SLAVE
);
440 $change = RecentChange
::newFromConds(
442 // Redundant user,timestamp condition so we can use the existing index
443 'rc_user_text' => $this->mNewRev
->getRawUserText(),
444 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
445 'rc_this_oldid' => $this->mNewid
,
446 'rc_last_oldid' => $this->mOldid
,
451 if ( $change instanceof RecentChange
) {
452 $rcid = $change->mAttribs
['rc_id'];
453 $this->mRcidMarkPatrolled
= $rcid;
461 $this->getOutput()->preventClickjacking();
462 $token = $this->getUser()->getEditToken( $rcid );
463 $this->mMarkPatrolledLink
= ' <span class="patrollink">[' . Linker
::linkKnown(
465 $this->msg( 'markaspatrolleddiff' )->escaped(),
468 'action' => 'markpatrolled',
474 $this->mMarkPatrolledLink
= '';
477 $this->mMarkPatrolledLink
= '';
481 return $this->mMarkPatrolledLink
;
485 * @param $rev Revision
488 protected function revisionDeleteLink( $rev ) {
489 $link = Linker
::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
490 if ( $link !== '' ) {
491 $link = '   ' . $link . ' ';
497 * Show the new revision of the page.
499 function renderNewRevision() {
500 wfProfileIn( __METHOD__
);
501 $out = $this->getOutput();
502 $revHeader = $this->getRevisionHeader( $this->mNewRev
);
503 # Add "current version as of X" title
504 $out->addHTML( "<hr class='diff-hr' />
505 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
506 # Page content may be handled by a hooked call instead...
507 if ( wfRunHooks( 'ArticleContentOnDiff', array( $this, $out ) ) ) {
508 $this->loadNewText();
509 $out->setRevisionId( $this->mNewid
);
510 $out->setRevisionTimestamp( $this->mNewRev
->getTimestamp() );
511 $out->setArticleFlag( true );
513 if ( $this->mNewPage
->isCssJsSubpage() ||
$this->mNewPage
->isCssOrJsPage() ) { #NOTE: only needed for B/C: custom rendering of JS/CSS via hook
514 // Stolen from Article::view --AG 2007-10-11
515 // Give hooks a chance to customise the output
516 // @TODO: standardize this crap into one function
517 if ( !Hook
::isRegistered( 'ShowRawCssJs' )
518 ||
wfRunHooks( 'ShowRawCssJs', array( ContentHandler
::getContentText( $this->mNewContent
), $this->mNewPage
, $out ) ) ) { #NOTE: deperecated hook, B/C only
519 // use the content object's own rendering
520 $po = $this->mContentObject
->getParserOutput();
521 $out->addHTML( $po->getText() );
523 } elseif( !wfRunHooks( 'ArticleContentViewCustom', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
524 // Handled by extension
525 } elseif( Hooks
::isRegistered( 'ArticleViewCustom' )
526 && !wfRunHooks( 'ArticleViewCustom', array( ContentHandler
::getContentText( $this->mNewContent
), $this->mNewPage
, $out ) ) ) { #NOTE: deperecated hook, B/C only
527 // Handled by extension
530 if ( $this->getTitle()->equals( $this->mNewPage
) ) {
531 // If the Title stored in the context is the same as the one
532 // of the new revision, we can use its associated WikiPage
534 $wikiPage = $this->getWikiPage();
536 // Otherwise we need to create our own WikiPage object
537 $wikiPage = WikiPage
::factory( $this->mNewPage
);
540 $parserOutput = $this->getParserOutput( $wikiPage, $this->mNewRev
);
542 # WikiPage::getParserOutput() should not return false, but just in case
543 if( $parserOutput ) {
544 $out->addParserOutput( $parserOutput );
548 # Add redundant patrol link on bottom...
549 $out->addHTML( $this->markPatrolledLink() );
551 wfProfileOut( __METHOD__
);
554 protected function getParserOutput( WikiPage
$page, Revision
$rev ) {
555 $parserOptions = ParserOptions
::newFromContext( $this->getContext() );
556 $parserOptions->enableLimitReport();
557 $parserOptions->setTidy( true );
559 if ( !$rev->isCurrent() ||
!$rev->getTitle()->quickUserCan( "edit" ) ) {
560 $parserOptions->setEditSection( false );
563 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
564 return $parserOutput;
568 * Get the diff text, send it to the OutputPage object
569 * Returns false if the diff could not be generated, otherwise returns true
573 function showDiff( $otitle, $ntitle, $notice = '' ) {
574 $diff = $this->getDiff( $otitle, $ntitle, $notice );
575 if ( $diff === false ) {
576 $this->showMissingRevision();
579 $this->showDiffStyle();
580 $this->getOutput()->addHTML( $diff );
586 * Add style sheets and supporting JS for diff display.
588 function showDiffStyle() {
589 $this->getOutput()->addModuleStyles( 'mediawiki.action.history.diff' );
593 * Get complete diff table, including header
595 * @param $otitle Title: old title
596 * @param $ntitle Title: new title
597 * @param $notice String: HTML between diff header and body
600 function getDiff( $otitle, $ntitle, $notice = '' ) {
601 $body = $this->getDiffBody();
602 if ( $body === false ) {
605 $multi = $this->getMultiNotice();
606 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
611 * Get the diff table body, without header
613 * @return mixed (string/false)
615 public function getDiffBody() {
617 wfProfileIn( __METHOD__
);
618 $this->mCacheHit
= true;
619 // Check if the diff should be hidden from this user
620 if ( !$this->loadRevisionData() ) {
621 wfProfileOut( __METHOD__
);
623 } elseif ( $this->mOldRev
&& !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
624 wfProfileOut( __METHOD__
);
626 } elseif ( $this->mNewRev
&& !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
627 wfProfileOut( __METHOD__
);
631 // If mOldRev is false, it means that the
632 if ( $this->mOldRev
=== false ||
( $this->mOldRev
&& $this->mNewRev
633 && $this->mOldRev
->getID() == $this->mNewRev
->getID() ) )
635 wfProfileOut( __METHOD__
);
640 if ( $this->mOldid
&& $this->mNewid
) {
641 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
,
642 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
644 if ( !$this->mRefreshCache
) {
645 $difftext = $wgMemc->get( $key );
647 wfIncrStats( 'diff_cache_hit' );
648 $difftext = $this->localiseLineNumbers( $difftext );
649 $difftext .= "\n<!-- diff cache key $key -->\n";
650 wfProfileOut( __METHOD__
);
653 } // don't try to load but save the result
655 $this->mCacheHit
= false;
657 // Loadtext is permission safe, this just clears out the diff
658 if ( !$this->loadText() ) {
659 wfProfileOut( __METHOD__
);
663 $difftext = $this->generateContentDiffBody( $this->mOldContent
, $this->mNewContent
);
665 // Save to cache for 7 days
666 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
667 wfIncrStats( 'diff_uncacheable' );
668 } elseif ( $key !== false && $difftext !== false ) {
669 wfIncrStats( 'diff_cache_miss' );
670 $wgMemc->set( $key, $difftext, 7 * 86400 );
672 wfIncrStats( 'diff_uncacheable' );
674 // Replace line numbers with the text in the user's language
675 if ( $difftext !== false ) {
676 $difftext = $this->localiseLineNumbers( $difftext );
678 wfProfileOut( __METHOD__
);
683 * Make sure the proper modules are loaded before we try to
686 private function initDiffEngines() {
687 global $wgExternalDiffEngine;
688 if ( $wgExternalDiffEngine == 'wikidiff' && !function_exists( 'wikidiff_do_diff' ) ) {
689 wfProfileIn( __METHOD__
. '-php_wikidiff.so' );
690 wfDl( 'php_wikidiff' );
691 wfProfileOut( __METHOD__
. '-php_wikidiff.so' );
693 elseif ( $wgExternalDiffEngine == 'wikidiff2' && !function_exists( 'wikidiff2_do_diff' ) ) {
694 wfProfileIn( __METHOD__
. '-php_wikidiff2.so' );
696 wfProfileOut( __METHOD__
. '-php_wikidiff2.so' );
701 * Generate a diff, no caching.
703 * Subclasses may override this to provide a
705 * @param $old Content: old content
706 * @param $new Content: new content
710 function generateContentDiffBody( Content
$old, Content
$new ) {
711 #XXX: generate a warning if $old or $new are not instances of TextContent?
712 #XXX: fail if $old and $new don't have the same content model? or what?
714 $otext = $old->serialize();
715 $ntext = $new->serialize();
717 #XXX: text should be "already segmented". what does that mean?
718 return $this->generateTextDiffBody( $otext, $ntext );
722 * Generate a diff, no caching
724 * @param $otext String: old text, must be already segmented
725 * @param $ntext String: new text, must be already segmented
726 * @deprecated since 1.WD, use generateContentDiffBody() instead!
728 function generateDiffBody( $otext, $ntext ) {
729 wfDeprecated( __METHOD__
, "1.WD" );
731 return $this->generateTextDiffBody( $otext, $ntext );
735 * Generate a diff, no caching
737 * @todo move this to TextDifferenceEngine, make DifferenceEngine abstract. At some point.
739 * @param $otext String: old text, must be already segmented
740 * @param $ntext String: new text, must be already segmented
741 * @return bool|string
743 function generateTextDiffBody( $otext, $ntext ) {
744 global $wgExternalDiffEngine, $wgContLang;
746 wfProfileIn( __METHOD__
);
748 $otext = str_replace( "\r\n", "\n", $otext );
749 $ntext = str_replace( "\r\n", "\n", $ntext );
751 $this->initDiffEngines();
753 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
754 # For historical reasons, external diff engine expects
755 # input text to be HTML-escaped already
756 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
757 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
758 wfProfileOut( __METHOD__
);
759 return $wgContLang->unsegmentForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
760 $this->debug( 'wikidiff1' );
763 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
764 # Better external diff engine, the 2 may some day be dropped
765 # This one does the escaping and segmenting itself
766 wfProfileIn( 'wikidiff2_do_diff' );
767 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
768 $text .= $this->debug( 'wikidiff2' );
769 wfProfileOut( 'wikidiff2_do_diff' );
770 wfProfileOut( __METHOD__
);
773 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
775 $tmpDir = wfTempDir();
776 $tempName1 = tempnam( $tmpDir, 'diff_' );
777 $tempName2 = tempnam( $tmpDir, 'diff_' );
779 $tempFile1 = fopen( $tempName1, "w" );
781 wfProfileOut( __METHOD__
);
784 $tempFile2 = fopen( $tempName2, "w" );
786 wfProfileOut( __METHOD__
);
789 fwrite( $tempFile1, $otext );
790 fwrite( $tempFile2, $ntext );
791 fclose( $tempFile1 );
792 fclose( $tempFile2 );
793 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
794 wfProfileIn( __METHOD__
. "-shellexec" );
795 $difftext = wfShellExec( $cmd );
796 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
797 wfProfileOut( __METHOD__
. "-shellexec" );
798 unlink( $tempName1 );
799 unlink( $tempName2 );
800 wfProfileOut( __METHOD__
);
805 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
806 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
807 $diffs = new Diff( $ota, $nta );
808 $formatter = new TableDiffFormatter();
809 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
810 wfProfileOut( __METHOD__
);
815 * Generate a debug comment indicating diff generating time,
816 * server node, and generator backend.
819 protected function debug( $generator = "internal" ) {
820 global $wgShowHostnames;
821 if ( !$this->enableDebugComment
) {
824 $data = array( $generator );
825 if ( $wgShowHostnames ) {
826 $data[] = wfHostname();
828 $data[] = wfTimestamp( TS_DB
);
829 return "<!-- diff generator: " .
838 * Replace line numbers with the text in the user's language
841 function localiseLineNumbers( $text ) {
842 return preg_replace_callback( '/<!--LINE (\d+)-->/',
843 array( &$this, 'localiseLineNumbersCb' ), $text );
846 function localiseLineNumbersCb( $matches ) {
847 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) return '';
848 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
853 * If there are revisions between the ones being compared, return a note saying so.
856 function getMultiNotice() {
857 if ( !is_object( $this->mOldRev
) ||
!is_object( $this->mNewRev
) ) {
859 } elseif ( !$this->mOldPage
->equals( $this->mNewPage
) ) {
860 // Comparing two different pages? Count would be meaningless.
864 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
865 $oldRev = $this->mNewRev
; // flip
866 $newRev = $this->mOldRev
; // flip
867 } else { // normal case
868 $oldRev = $this->mOldRev
;
869 $newRev = $this->mNewRev
;
872 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev );
874 $limit = 100; // use diff-multi-manyusers if too many users
875 $numUsers = $this->mNewPage
->countAuthorsBetween( $oldRev, $newRev, $limit );
876 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
878 return ''; // nothing
882 * Get a notice about how many intermediate edits and users there are
883 * @param $numEdits int
884 * @param $numUsers int
888 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
889 if ( $numUsers > $limit ) {
890 $msg = 'diff-multi-manyusers';
895 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
899 * Get a header for a specified revision.
901 * @param $rev Revision
902 * @param $complete String: 'complete' to get the header wrapped depending
903 * the visibility of the revision and a link to edit the page.
904 * @return String HTML fragment
906 protected function getRevisionHeader( Revision
$rev, $complete = '' ) {
907 $lang = $this->getLanguage();
908 $user = $this->getUser();
909 $revtimestamp = $rev->getTimestamp();
910 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
911 $dateofrev = $lang->userDate( $revtimestamp, $user );
912 $timeofrev = $lang->userTime( $revtimestamp, $user );
914 $header = $this->msg(
915 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
921 if ( $complete !== 'complete' ) {
925 $title = $rev->getTitle();
927 $header = Linker
::linkKnown( $title, $header, array(),
928 array( 'oldid' => $rev->getID() ) );
930 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
931 $editQuery = array( 'action' => 'edit' );
932 if ( !$rev->isCurrent() ) {
933 $editQuery['oldid'] = $rev->getID();
936 $msg = $this->msg( $title->quickUserCan( 'edit', $user ) ?
'editold' : 'viewsourceold' )->escaped();
937 $header .= ' ' . $this->msg( 'parentheses' )->rawParams(
938 Linker
::linkKnown( $title, $msg, array(), $editQuery ) )->plain();
939 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
940 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
943 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
950 * Add the header to a diff body
954 function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
955 // shared.css sets diff in interface language/dir, but the actual content
956 // is often in a different language, mostly the page content language/dir
957 $tableClass = 'diff diff-contentalign-' . htmlspecialchars( $this->getDiffLang()->alignStart() );
958 $header = "<table class='$tableClass'>";
960 if ( !$diff && !$otitle ) {
963 <td class='diff-ntitle'>{$ntitle}</td>
967 if ( $diff ) { // Safari/Chrome show broken output if cols not used
969 <col class='diff-marker' />
970 <col class='diff-content' />
971 <col class='diff-marker' />
972 <col class='diff-content' />";
981 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
982 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
986 if ( $multi != '' ) {
987 $header .= "<tr><td colspan='{$multiColspan}' align='center' class='diff-multi'>{$multi}</td></tr>";
989 if ( $notice != '' ) {
990 $header .= "<tr><td colspan='{$multiColspan}' align='center'>{$notice}</td></tr>";
993 return $header . $diff . "</table>";
997 * Use specified text instead of loading from the database
998 * @deprecated since 1.WD
1000 function setText( $oldText, $newText ) { #FIXME: no longer use this, use setContent()!
1001 wfDeprecated( __METHOD__
, "1.WD" );
1003 $oldContent = ContentHandler
::makeContent( $oldText, $this->getTitle() );
1004 $newContent = ContentHandler
::makeContent( $newText, $this->getTitle() );
1006 $this->setContent( $oldContent, $newContent );
1010 * Use specified text instead of loading from the database
1013 function setContent( Content
$oldContent, Content
$newContent ) {
1014 $this->mOldContent
= $oldContent;
1015 $this->mNewContent
= $newContent;
1017 $this->mTextLoaded
= 2;
1018 $this->mRevisionsLoaded
= true;
1022 * Set the language in which the diff text is written
1023 * (Defaults to page content language).
1026 function setTextLanguage( $lang ) {
1027 $this->mDiffLang
= wfGetLangObj( $lang );
1033 private function loadRevisionIds() {
1034 if ( $this->mRevisionsIdsLoaded
) {
1038 $this->mRevisionsIdsLoaded
= true;
1040 $old = $this->mOldid
;
1041 $new = $this->mNewid
;
1043 if ( $new === 'prev' ) {
1044 # Show diff between revision $old and the previous one.
1045 # Get previous one from DB.
1046 $this->mNewid
= intval( $old );
1047 $this->mOldid
= $this->getTitle()->getPreviousRevisionID( $this->mNewid
);
1048 } elseif ( $new === 'next' ) {
1049 # Show diff between revision $old and the next one.
1050 # Get next one from DB.
1051 $this->mOldid
= intval( $old );
1052 $this->mNewid
= $this->getTitle()->getNextRevisionID( $this->mOldid
);
1053 if ( $this->mNewid
=== false ) {
1054 # if no result, NewId points to the newest old revision. The only newer
1055 # revision is cur, which is "0".
1059 $this->mOldid
= intval( $old );
1060 $this->mNewid
= intval( $new );
1061 wfRunHooks( 'NewDifferenceEngine', array( $this->getTitle(), &$this->mOldid
, &$this->mNewid
, $old, $new ) );
1066 * Load revision metadata for the specified articles. If newid is 0, then compare
1067 * the old article in oldid to the current article; if oldid is 0, then
1068 * compare the current article to the immediately previous one (ignoring the
1071 * If oldid is false, leave the corresponding revision object set
1072 * to false. This is impossible via ordinary user input, and is provided for
1077 function loadRevisionData() {
1078 if ( $this->mRevisionsLoaded
) {
1082 // Whether it succeeds or fails, we don't want to try again
1083 $this->mRevisionsLoaded
= true;
1085 $this->loadRevisionIds();
1087 // Load the new revision object
1088 $this->mNewRev
= $this->mNewid
1089 ? Revision
::newFromId( $this->mNewid
)
1090 : Revision
::newFromTitle( $this->getTitle(), false, Revision
::READ_NORMAL
);
1092 if ( !$this->mNewRev
instanceof Revision
) {
1096 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1097 $this->mNewid
= $this->mNewRev
->getId();
1098 $this->mNewPage
= $this->mNewRev
->getTitle();
1100 // Load the old revision object
1101 $this->mOldRev
= false;
1102 if ( $this->mOldid
) {
1103 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1104 } elseif ( $this->mOldid
=== 0 ) {
1105 $rev = $this->mNewRev
->getPrevious();
1107 $this->mOldid
= $rev->getId();
1108 $this->mOldRev
= $rev;
1110 // No previous revision; mark to show as first-version only.
1111 $this->mOldid
= false;
1112 $this->mOldRev
= false;
1114 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1116 if ( is_null( $this->mOldRev
) ) {
1120 if ( $this->mOldRev
) {
1121 $this->mOldPage
= $this->mOldRev
->getTitle();
1128 * Load the text of the revisions, as well as revision data.
1132 function loadText() {
1133 if ( $this->mTextLoaded
== 2 ) {
1136 // Whether it succeeds or fails, we don't want to try again
1137 $this->mTextLoaded
= 2;
1140 if ( !$this->loadRevisionData() ) {
1143 if ( $this->mOldRev
) {
1144 $this->mOldContent
= $this->mOldRev
->getContent( Revision
::FOR_THIS_USER
);
1145 if ( $this->mOldContent
=== false ) {
1149 if ( $this->mNewRev
) {
1150 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
);
1151 if ( $this->mNewContent
=== false ) {
1159 * Load the text of the new revision, not the old one
1163 function loadNewText() {
1164 if ( $this->mTextLoaded
>= 1 ) {
1167 $this->mTextLoaded
= 1;
1169 if ( !$this->loadRevisionData() ) {
1172 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
);