3 * User interface for the difference engine
6 * @ingroup DifferenceEngine
10 * Constant to indicate diff cache compatibility.
11 * Bump this when changing the diff formatting in a way that
12 * fixes important bugs or such to force cached diff views to
15 define( 'MW_DIFF_VERSION', '1.11a' );
19 * @ingroup DifferenceEngine
21 class DifferenceEngine
extends ContextSource
{
26 var $mOldtext, $mNewtext;
32 var $mOldPage, $mNewPage;
33 var $mRcidMarkPatrolled;
38 var $mOldRev, $mNewRev;
39 private $mRevisionsIdsLoaded = false; // Have the revisions IDs been loaded
40 var $mRevisionsLoaded = false; // Have the revisions been loaded
41 var $mTextLoaded = 0; // How many text blobs have been loaded, 0, 1 or 2?
42 var $mCacheHit = false; // Was the diff fetched from cache?
45 * Set this to true to add debug info to the HTML output.
46 * Warning: this may cause RSS readers to spuriously mark articles as "new"
49 var $enableDebugComment = false;
51 // If true, line X is not displayed when X is 1, for example to increase
52 // readability and conserve space with many small diffs.
53 protected $mReducedLineNumbers = false;
55 // Link to action=markpatrolled
56 protected $mMarkPatrolledLink = null;
58 protected $unhide = false; # show rev_deleted content if allowed
63 * @param $context IContextSource context to use, anything else will be ignored
64 * @param $old Integer old ID we want to show and diff with.
65 * @param $new String either 'prev' or 'next'.
66 * @param $rcid Integer ??? FIXME (default 0)
67 * @param $refreshCache boolean If set, refreshes the diff cache
68 * @param $unhide boolean If set, allow viewing deleted revs
70 function __construct( $context = null, $old = 0, $new = 0, $rcid = 0,
71 $refreshCache = false, $unhide = false )
73 if ( $context instanceof IContextSource
) {
74 $this->setContext( $context );
77 wfDebug( "DifferenceEngine old '$old' new '$new' rcid '$rcid'\n" );
81 $this->mRcidMarkPatrolled
= intval( $rcid ); # force it to be an integer
82 $this->mRefreshCache
= $refreshCache;
83 $this->unhide
= $unhide;
89 function setReducedLineNumbers( $value = true ) {
90 $this->mReducedLineNumbers
= $value;
96 function getDiffLang() {
97 if ( $this->mDiffLang
=== null ) {
98 # Default language in which the diff text is written.
99 $this->mDiffLang
= $this->getTitle()->getPageLanguage();
101 return $this->mDiffLang
;
107 function wasCacheHit() {
108 return $this->mCacheHit
;
114 function getOldid() {
115 $this->loadRevisionIds();
116 return $this->mOldid
;
122 function getNewid() {
123 $this->loadRevisionIds();
124 return $this->mNewid
;
128 * Look up a special:Undelete link to the given deleted revision id,
129 * as a workaround for being unable to load deleted diffs in currently.
131 * @param int $id revision ID
132 * @return mixed URL or false
134 function deletedLink( $id ) {
135 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
136 $dbr = wfGetDB( DB_SLAVE
);
137 $row = $dbr->selectRow('archive', '*',
138 array( 'ar_rev_id' => $id ),
141 $rev = Revision
::newFromArchiveRow( $row );
142 $title = Title
::makeTitleSafe( $row->ar_namespace
, $row->ar_title
);
143 return SpecialPage
::getTitleFor( 'Undelete' )->getFullURL( array(
144 'target' => $title->getPrefixedText(),
145 'timestamp' => $rev->getTimestamp()
153 * Build a wikitext link toward a deleted revision, if viewable.
155 * @param int $id revision ID
156 * @return string wikitext fragment
158 function deletedIdMarker( $id ) {
159 $link = $this->deletedLink( $id );
161 return "[$link $id]";
167 function showDiffPage( $diffOnly = false ) {
168 wfProfileIn( __METHOD__
);
170 # Allow frames except in certain special cases
171 $out = $this->getOutput();
172 $out->allowClickjacking();
173 $out->setRobotPolicy( 'noindex,nofollow' );
175 if ( !$this->loadRevisionData() ) {
176 // Sounds like a deleted revision... Let's see what we can do.
177 $t = $this->getTitle()->getPrefixedText();
178 $d = $this->msg( 'missingarticle-diff',
179 $this->deletedIdMarker( $this->mOldid
),
180 $this->deletedIdMarker( $this->mNewid
) )->escaped();
181 $out->setPageTitle( $this->msg( 'errorpagetitle' ) );
182 $out->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", "<span class='plainlinks'>$d</span>" );
183 wfProfileOut( __METHOD__
);
187 $user = $this->getUser();
188 $permErrors = $this->mNewPage
->getUserPermissionsErrors( 'read', $user );
189 if ( $this->mOldPage
) { # mOldPage might not be set, see below.
190 $permErrors = wfMergeErrorArrays( $permErrors,
191 $this->mOldPage
->getUserPermissionsErrors( 'read', $user ) );
193 if ( count( $permErrors ) ) {
194 wfProfileOut( __METHOD__
);
195 throw new PermissionsError( 'read', $permErrors );
198 # If external diffs are enabled both globally and for the user,
199 # we'll use the application/x-external-editor interface to call
200 # an external diff tool like kompare, kdiff3, etc.
201 if ( ExternalEdit
::useExternalEngine( $this->getContext(), 'diff' ) ) {
203 'File' => array( 'Extension' => 'wiki', 'URL' =>
204 # This should be mOldPage, but it may not be set, see below.
205 $this->mNewPage
->getCanonicalURL( array(
206 'action' => 'raw', 'oldid' => $this->mOldid
) )
208 'File2' => array( 'Extension' => 'wiki', 'URL' =>
209 $this->mNewPage
->getCanonicalURL( array(
210 'action' => 'raw', 'oldid' => $this->mNewid
) )
214 $externalEditor = new ExternalEdit( $this->getContext(), $urls );
215 $externalEditor->execute();
217 wfProfileOut( __METHOD__
);
225 # Carry over 'diffonly' param via navigation links
226 if ( $diffOnly != $user->getBoolOption( 'diffonly' ) ) {
227 $query['diffonly'] = $diffOnly;
229 # Cascade unhide param in links for easy deletion browsing
230 if ( $this->unhide
) {
231 $query['unhide'] = 1;
234 # Check if one of the revisions is deleted/suppressed
235 $deleted = $suppressed = false;
236 $allowed = $this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $user );
238 # mOldRev is false if the difference engine is called with a "vague" query for
239 # a diff between a version V and its previous version V' AND the version V
240 # is the first version of that article. In that case, V' does not exist.
241 if ( $this->mOldRev
=== false ) {
242 $out->setPageTitle( $this->mNewPage
->getPrefixedText() );
243 $out->addSubtitle( $this->msg( 'difference' ) );
247 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
249 $sk = $this->getSkin();
250 if ( method_exists( $sk, 'suppressQuickbar' ) ) {
251 $sk->suppressQuickbar();
254 if ( $this->mNewPage
->equals( $this->mOldPage
) ) {
255 $out->setPageTitle( $this->mNewPage
->getPrefixedText() );
256 $out->addSubtitle( $this->msg( 'difference' ) );
259 $out->setPageTitle( $this->mOldPage
->getPrefixedText() . ', ' . $this->mNewPage
->getPrefixedText() );
260 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
264 if ( $samePage && $this->mNewPage
->userCan( 'edit', $user ) ) {
265 if ( $this->mNewRev
->isCurrent() && $this->mNewPage
->userCan( 'rollback', $user ) ) {
266 $out->preventClickjacking();
267 $rollback = '   ' . Linker
::generateRollback( $this->mNewRev
);
269 if ( !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
270 $undoLink = ' ' . $this->msg( 'parentheses' )->rawParams(
271 Html
::element( 'a', array(
272 'href' => $this->mNewPage
->getLocalUrl( array(
274 'undoafter' => $this->mOldid
,
275 'undo' => $this->mNewid
) ),
276 'title' => Linker
::titleAttrib( 'undo' )
278 $this->msg( 'editundo' )->text()
283 # Make "previous revision link"
284 if ( $samePage && $this->mOldRev
->getPrevious() ) {
285 $prevlink = Linker
::linkKnown(
287 $this->msg( 'previousdiff' )->escaped(),
288 array( 'id' => 'differences-prevlink' ),
289 array( 'diff' => 'prev', 'oldid' => $this->mOldid
) +
$query
292 $prevlink = ' ';
295 if ( $this->mOldRev
->isMinor() ) {
296 $oldminor = ChangesList
::flag( 'minor' );
301 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
302 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev
, 'complete' );
304 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
305 '<div id="mw-diff-otitle2">' .
306 Linker
::revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
307 '<div id="mw-diff-otitle3">' . $oldminor .
308 Linker
::revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
309 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
311 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
312 $deleted = true; // old revisions text is hidden
313 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
314 $suppressed = true; // also suppressed
318 # Check if this user can see the revisions
319 if ( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $user ) ) {
324 # Make "next revision link"
325 # Skip next link on the top revision
326 if ( $samePage && !$this->mNewRev
->isCurrent() ) {
327 $nextlink = Linker
::linkKnown(
329 $this->msg( 'nextdiff' )->escaped(),
330 array( 'id' => 'differences-nextlink' ),
331 array( 'diff' => 'next', 'oldid' => $this->mNewid
) +
$query
334 $nextlink = ' ';
337 if ( $this->mNewRev
->isMinor() ) {
338 $newminor = ChangesList
::flag( 'minor' );
343 # Handle RevisionDelete links...
344 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
345 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev
, 'complete' ) . $undoLink;
347 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
348 '<div id="mw-diff-ntitle2">' . Linker
::revUserTools( $this->mNewRev
, !$this->unhide
) .
350 '<div id="mw-diff-ntitle3">' . $newminor .
351 Linker
::revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
352 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
354 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
355 $deleted = true; // new revisions text is hidden
356 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) )
357 $suppressed = true; // also suppressed
360 # If the diff cannot be shown due to a deleted revision, then output
361 # the diff header and links to unhide (if available)...
362 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
363 $this->showDiffStyle();
364 $multi = $this->getMultiNotice();
365 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
367 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
368 # Give explanation for why revision is not visible
369 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
372 # Give explanation and add a link to view the diff...
373 $link = $this->getTitle()->getFullUrl( $this->getRequest()->appendQueryValue( 'unhide', '1', true ) );
374 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
375 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n", array( $msg, $link ) );
377 # Otherwise, output a regular diff...
379 # Add deletion notice if the user is viewing deleted content
382 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
383 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" . $this->msg( $msg )->parse() . "</div>\n";
385 $this->showDiff( $oldHeader, $newHeader, $notice );
387 $this->renderNewRevision();
390 wfProfileOut( __METHOD__
);
394 * Get a link to mark the change as patrolled, or '' if there's either no
395 * revision to patrol or the user is not allowed to to it.
396 * Side effect: this method will call OutputPage::preventClickjacking()
397 * when a link is builded.
401 protected function markPatrolledLink() {
402 global $wgUseRCPatrol;
404 if ( $this->mMarkPatrolledLink
=== null ) {
405 // Prepare a change patrol link, if applicable
406 if ( $wgUseRCPatrol && $this->mNewPage
->userCan( 'patrol', $this->getUser() ) ) {
407 // If we've been given an explicit change identifier, use it; saves time
408 if ( $this->mRcidMarkPatrolled
) {
409 $rcid = $this->mRcidMarkPatrolled
;
410 $rc = RecentChange
::newFromId( $rcid );
411 // Already patrolled?
412 $rcid = is_object( $rc ) && !$rc->getAttribute( 'rc_patrolled' ) ?
$rcid : 0;
414 // Look for an unpatrolled change corresponding to this diff
415 $db = wfGetDB( DB_SLAVE
);
416 $change = RecentChange
::newFromConds(
418 // Redundant user,timestamp condition so we can use the existing index
419 'rc_user_text' => $this->mNewRev
->getRawUserText(),
420 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
421 'rc_this_oldid' => $this->mNewid
,
422 'rc_last_oldid' => $this->mOldid
,
427 if ( $change instanceof RecentChange
) {
428 $rcid = $change->mAttribs
['rc_id'];
429 $this->mRcidMarkPatrolled
= $rcid;
437 $this->getOutput()->preventClickjacking();
438 $token = $this->getUser()->getEditToken( $rcid );
439 $this->mMarkPatrolledLink
= ' <span class="patrollink">[' . Linker
::linkKnown(
441 $this->msg( 'markaspatrolleddiff' )->escaped(),
444 'action' => 'markpatrolled',
450 $this->mMarkPatrolledLink
= '';
453 $this->mMarkPatrolledLink
= '';
457 return $this->mMarkPatrolledLink
;
461 * @param $rev Revision
464 protected function revisionDeleteLink( $rev ) {
465 $link = Linker
::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
466 if ( $link !== '' ) {
467 $link = '   ' . $link . ' ';
473 * Show the new revision of the page.
475 function renderNewRevision() {
476 wfProfileIn( __METHOD__
);
477 $out = $this->getOutput();
478 $revHeader = $this->getRevisionHeader( $this->mNewRev
);
479 # Add "current version as of X" title
480 $out->addHTML( "<hr class='diff-hr' />
481 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
482 # Page content may be handled by a hooked call instead...
483 if ( wfRunHooks( 'ArticleContentOnDiff', array( $this, $out ) ) ) {
484 $this->loadNewText();
485 $out->setRevisionId( $this->mNewid
);
486 $out->setRevisionTimestamp( $this->mNewRev
->getTimestamp() );
487 $out->setArticleFlag( true );
489 if ( $this->mNewPage
->isCssJsSubpage() ||
$this->mNewPage
->isCssOrJsPage() ) {
490 // Stolen from Article::view --AG 2007-10-11
491 // Give hooks a chance to customise the output
492 // @TODO: standardize this crap into one function
493 if ( wfRunHooks( 'ShowRawCssJs', array( $this->mNewtext
, $this->mNewPage
, $out ) ) ) {
494 // Wrap the whole lot in a <pre> and don't parse
496 preg_match( '!\.(css|js)$!u', $this->mNewPage
->getText(), $m );
497 $out->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
498 $out->addHTML( htmlspecialchars( $this->mNewtext
) );
499 $out->addHTML( "\n</pre>\n" );
501 } elseif ( !wfRunHooks( 'ArticleViewCustom', array( $this->mNewtext
, $this->mNewPage
, $out ) ) ) {
502 // Handled by extension
505 $wikiPage = WikiPage
::factory( $this->mNewPage
);
507 $parserOptions = ParserOptions
::newFromContext( $this->getContext() );
508 $parserOptions->enableLimitReport();
509 $parserOptions->setTidy( true );
511 if ( !$this->mNewRev
->isCurrent() ) {
512 $parserOptions->setEditSection( false );
515 $parserOutput = $wikiPage->getParserOutput( $parserOptions, $this->mNewid
);
517 # WikiPage::getParserOutput() should not return false, but just in case
518 if( $parserOutput ) {
519 $out->addParserOutput( $parserOutput );
523 # Add redundant patrol link on bottom...
524 $out->addHTML( $this->markPatrolledLink() );
526 wfProfileOut( __METHOD__
);
530 * Get the diff text, send it to the OutputPage object
531 * Returns false if the diff could not be generated, otherwise returns true
535 function showDiff( $otitle, $ntitle, $notice = '' ) {
536 $diff = $this->getDiff( $otitle, $ntitle, $notice );
537 if ( $diff === false ) {
538 $this->getOutput()->addWikiMsg( 'missing-article', "<nowiki>(fixme, bug)</nowiki>", '' );
541 $this->showDiffStyle();
542 $this->getOutput()->addHTML( $diff );
548 * Add style sheets and supporting JS for diff display.
550 function showDiffStyle() {
551 $this->getOutput()->addModuleStyles( 'mediawiki.action.history.diff' );
555 * Get complete diff table, including header
557 * @param $otitle Title: old title
558 * @param $ntitle Title: new title
559 * @param $notice String: HTML between diff header and body
562 function getDiff( $otitle, $ntitle, $notice = '' ) {
563 $body = $this->getDiffBody();
564 if ( $body === false ) {
567 $multi = $this->getMultiNotice();
568 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
573 * Get the diff table body, without header
575 * @return mixed (string/false)
577 public function getDiffBody() {
579 wfProfileIn( __METHOD__
);
580 $this->mCacheHit
= true;
581 // Check if the diff should be hidden from this user
582 if ( !$this->loadRevisionData() ) {
583 wfProfileOut( __METHOD__
);
585 } elseif ( $this->mOldRev
&& !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
586 wfProfileOut( __METHOD__
);
588 } elseif ( $this->mNewRev
&& !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
589 wfProfileOut( __METHOD__
);
593 // If mOldRev is false, it means that the
594 if ( $this->mOldRev
=== false ||
( $this->mOldRev
&& $this->mNewRev
595 && $this->mOldRev
->getID() == $this->mNewRev
->getID() ) )
597 wfProfileOut( __METHOD__
);
602 if ( $this->mOldid
&& $this->mNewid
) {
603 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
,
604 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
606 if ( !$this->mRefreshCache
) {
607 $difftext = $wgMemc->get( $key );
609 wfIncrStats( 'diff_cache_hit' );
610 $difftext = $this->localiseLineNumbers( $difftext );
611 $difftext .= "\n<!-- diff cache key $key -->\n";
612 wfProfileOut( __METHOD__
);
615 } // don't try to load but save the result
617 $this->mCacheHit
= false;
619 // Loadtext is permission safe, this just clears out the diff
620 if ( !$this->loadText() ) {
621 wfProfileOut( __METHOD__
);
625 $difftext = $this->generateDiffBody( $this->mOldtext
, $this->mNewtext
);
627 // Save to cache for 7 days
628 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
629 wfIncrStats( 'diff_uncacheable' );
630 } elseif ( $key !== false && $difftext !== false ) {
631 wfIncrStats( 'diff_cache_miss' );
632 $wgMemc->set( $key, $difftext, 7 * 86400 );
634 wfIncrStats( 'diff_uncacheable' );
636 // Replace line numbers with the text in the user's language
637 if ( $difftext !== false ) {
638 $difftext = $this->localiseLineNumbers( $difftext );
640 wfProfileOut( __METHOD__
);
645 * Make sure the proper modules are loaded before we try to
648 private function initDiffEngines() {
649 global $wgExternalDiffEngine;
650 if ( $wgExternalDiffEngine == 'wikidiff' && !function_exists( 'wikidiff_do_diff' ) ) {
651 wfProfileIn( __METHOD__
. '-php_wikidiff.so' );
652 wfDl( 'php_wikidiff' );
653 wfProfileOut( __METHOD__
. '-php_wikidiff.so' );
655 elseif ( $wgExternalDiffEngine == 'wikidiff2' && !function_exists( 'wikidiff2_do_diff' ) ) {
656 wfProfileIn( __METHOD__
. '-php_wikidiff2.so' );
658 wfProfileOut( __METHOD__
. '-php_wikidiff2.so' );
663 * Generate a diff, no caching
665 * @param $otext String: old text, must be already segmented
666 * @param $ntext String: new text, must be already segmented
668 function generateDiffBody( $otext, $ntext ) {
669 global $wgExternalDiffEngine, $wgContLang;
671 wfProfileIn( __METHOD__
);
673 $otext = str_replace( "\r\n", "\n", $otext );
674 $ntext = str_replace( "\r\n", "\n", $ntext );
676 $this->initDiffEngines();
678 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
679 # For historical reasons, external diff engine expects
680 # input text to be HTML-escaped already
681 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
682 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
683 wfProfileOut( __METHOD__
);
684 return $wgContLang->unsegmentForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
685 $this->debug( 'wikidiff1' );
688 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
689 # Better external diff engine, the 2 may some day be dropped
690 # This one does the escaping and segmenting itself
691 wfProfileIn( 'wikidiff2_do_diff' );
692 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
693 $text .= $this->debug( 'wikidiff2' );
694 wfProfileOut( 'wikidiff2_do_diff' );
695 wfProfileOut( __METHOD__
);
698 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
700 global $wgTmpDirectory;
701 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
702 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
704 $tempFile1 = fopen( $tempName1, "w" );
706 wfProfileOut( __METHOD__
);
709 $tempFile2 = fopen( $tempName2, "w" );
711 wfProfileOut( __METHOD__
);
714 fwrite( $tempFile1, $otext );
715 fwrite( $tempFile2, $ntext );
716 fclose( $tempFile1 );
717 fclose( $tempFile2 );
718 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
719 wfProfileIn( __METHOD__
. "-shellexec" );
720 $difftext = wfShellExec( $cmd );
721 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
722 wfProfileOut( __METHOD__
. "-shellexec" );
723 unlink( $tempName1 );
724 unlink( $tempName2 );
725 wfProfileOut( __METHOD__
);
730 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
731 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
732 $diffs = new Diff( $ota, $nta );
733 $formatter = new TableDiffFormatter();
734 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
735 wfProfileOut( __METHOD__
);
740 * Generate a debug comment indicating diff generating time,
741 * server node, and generator backend.
743 protected function debug( $generator = "internal" ) {
744 global $wgShowHostnames;
745 if ( !$this->enableDebugComment
) {
748 $data = array( $generator );
749 if ( $wgShowHostnames ) {
750 $data[] = wfHostname();
752 $data[] = wfTimestamp( TS_DB
);
753 return "<!-- diff generator: " .
762 * Replace line numbers with the text in the user's language
764 function localiseLineNumbers( $text ) {
765 return preg_replace_callback( '/<!--LINE (\d+)-->/',
766 array( &$this, 'localiseLineNumbersCb' ), $text );
769 function localiseLineNumbersCb( $matches ) {
770 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) return '';
771 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
776 * If there are revisions between the ones being compared, return a note saying so.
779 function getMultiNotice() {
780 if ( !is_object( $this->mOldRev
) ||
!is_object( $this->mNewRev
) ) {
782 } elseif ( !$this->mOldPage
->equals( $this->mNewPage
) ) {
783 // Comparing two different pages? Count would be meaningless.
787 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
788 $oldRev = $this->mNewRev
; // flip
789 $newRev = $this->mOldRev
; // flip
790 } else { // normal case
791 $oldRev = $this->mOldRev
;
792 $newRev = $this->mNewRev
;
795 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev );
797 $limit = 100; // use diff-multi-manyusers if too many users
798 $numUsers = $this->mNewPage
->countAuthorsBetween( $oldRev, $newRev, $limit );
799 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
801 return ''; // nothing
805 * Get a notice about how many intermediate edits and users there are
806 * @param $numEdits int
807 * @param $numUsers int
811 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
812 if ( $numUsers > $limit ) {
813 $msg = 'diff-multi-manyusers';
818 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
822 * Get a header for a specified revision.
824 * @param $rev Revision
825 * @param $complete String: 'complete' to get the header wrapped depending
826 * the visibility of the revision and a link to edit the page.
827 * @return String HTML fragment
829 private function getRevisionHeader( Revision
$rev, $complete = '' ) {
830 $lang = $this->getLanguage();
831 $user = $this->getUser();
832 $revtimestamp = $rev->getTimestamp();
833 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
834 $dateofrev = $lang->userDate( $revtimestamp, $user );
835 $timeofrev = $lang->userTime( $revtimestamp, $user );
837 $header = $this->msg(
838 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
844 if ( $complete !== 'complete' ) {
848 $title = $rev->getTitle();
850 $header = Linker
::linkKnown( $title, $header, array(),
851 array( 'oldid' => $rev->getID() ) );
853 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
854 $editQuery = array( 'action' => 'edit' );
855 if ( !$rev->isCurrent() ) {
856 $editQuery['oldid'] = $rev->getID();
859 $msg = $this->msg( $title->userCan( 'edit', $user ) ?
'editold' : 'viewsourceold' )->escaped();
860 $header .= ' (' . Linker
::linkKnown( $title, $msg, array(), $editQuery ) . ')';
861 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
862 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
865 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
872 * Add the header to a diff body
876 function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
877 // shared.css sets diff in interface language/dir, but the actual content
878 // is often in a different language, mostly the page content language/dir
879 $tableClass = 'diff diff-contentalign-' . htmlspecialchars( $this->getDiffLang()->alignStart() );
880 $header = "<table class='$tableClass'>";
882 if ( !$diff && !$otitle ) {
885 <td class='diff-ntitle'>{$ntitle}</td>
889 if ( $diff ) { // Safari/Chrome show broken output if cols not used
891 <col class='diff-marker' />
892 <col class='diff-content' />
893 <col class='diff-marker' />
894 <col class='diff-content' />";
903 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
904 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
908 if ( $multi != '' ) {
909 $header .= "<tr><td colspan='{$multiColspan}' align='center' class='diff-multi'>{$multi}</td></tr>";
911 if ( $notice != '' ) {
912 $header .= "<tr><td colspan='{$multiColspan}' align='center'>{$notice}</td></tr>";
915 return $header . $diff . "</table>";
919 * Use specified text instead of loading from the database
921 function setText( $oldText, $newText ) {
922 $this->mOldtext
= $oldText;
923 $this->mNewtext
= $newText;
924 $this->mTextLoaded
= 2;
925 $this->mRevisionsLoaded
= true;
929 * Set the language in which the diff text is written
930 * (Defaults to page content language).
933 function setTextLanguage( $lang ) {
934 $this->mDiffLang
= wfGetLangObj( $lang );
940 private function loadRevisionIds() {
941 if ( $this->mRevisionsIdsLoaded
) {
945 $this->mRevisionsIdsLoaded
= true;
947 $old = $this->mOldid
;
948 $new = $this->mNewid
;
950 if ( $new === 'prev' ) {
951 # Show diff between revision $old and the previous one.
952 # Get previous one from DB.
953 $this->mNewid
= intval( $old );
954 $this->mOldid
= $this->getTitle()->getPreviousRevisionID( $this->mNewid
);
955 } elseif ( $new === 'next' ) {
956 # Show diff between revision $old and the next one.
957 # Get next one from DB.
958 $this->mOldid
= intval( $old );
959 $this->mNewid
= $this->getTitle()->getNextRevisionID( $this->mOldid
);
960 if ( $this->mNewid
=== false ) {
961 # if no result, NewId points to the newest old revision. The only newer
962 # revision is cur, which is "0".
966 $this->mOldid
= intval( $old );
967 $this->mNewid
= intval( $new );
968 wfRunHooks( 'NewDifferenceEngine', array( $this->getTitle(), &$this->mOldid
, &$this->mNewid
, $old, $new ) );
973 * Load revision metadata for the specified articles. If newid is 0, then compare
974 * the old article in oldid to the current article; if oldid is 0, then
975 * compare the current article to the immediately previous one (ignoring the
978 * If oldid is false, leave the corresponding revision object set
979 * to false. This is impossible via ordinary user input, and is provided for
984 function loadRevisionData() {
985 if ( $this->mRevisionsLoaded
) {
989 // Whether it succeeds or fails, we don't want to try again
990 $this->mRevisionsLoaded
= true;
992 $this->loadRevisionIds();
994 // Load the new revision object
995 $this->mNewRev
= $this->mNewid
996 ? Revision
::newFromId( $this->mNewid
)
997 : Revision
::newFromTitle( $this->getTitle() );
999 if ( !$this->mNewRev
instanceof Revision
) {
1003 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1004 $this->mNewid
= $this->mNewRev
->getId();
1005 $this->mNewPage
= $this->mNewRev
->getTitle();
1007 // Load the old revision object
1008 $this->mOldRev
= false;
1009 if ( $this->mOldid
) {
1010 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1011 } elseif ( $this->mOldid
=== 0 ) {
1012 $rev = $this->mNewRev
->getPrevious();
1014 $this->mOldid
= $rev->getId();
1015 $this->mOldRev
= $rev;
1017 // No previous revision; mark to show as first-version only.
1018 $this->mOldid
= false;
1019 $this->mOldRev
= false;
1021 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1023 if ( is_null( $this->mOldRev
) ) {
1027 if ( $this->mOldRev
) {
1028 $this->mOldPage
= $this->mOldRev
->getTitle();
1035 * Load the text of the revisions, as well as revision data.
1039 function loadText() {
1040 if ( $this->mTextLoaded
== 2 ) {
1043 // Whether it succeeds or fails, we don't want to try again
1044 $this->mTextLoaded
= 2;
1047 if ( !$this->loadRevisionData() ) {
1050 if ( $this->mOldRev
) {
1051 $this->mOldtext
= $this->mOldRev
->getText( Revision
::FOR_THIS_USER
);
1052 if ( $this->mOldtext
=== false ) {
1056 if ( $this->mNewRev
) {
1057 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);
1058 if ( $this->mNewtext
=== false ) {
1066 * Load the text of the new revision, not the old one
1070 function loadNewText() {
1071 if ( $this->mTextLoaded
>= 1 ) {
1074 $this->mTextLoaded
= 1;
1076 if ( !$this->loadRevisionData() ) {
1079 $this->mNewtext
= $this->mNewRev
->getText( Revision
::FOR_THIS_USER
);