3ff5c986cbbdf0f13b8da28bf4066bf06a5a412d
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 $mOldTags, $mNewTags;
45 var $mOldContent, $mNewContent;
51 var $mOldPage, $mNewPage;
56 var $mOldRev, $mNewRev;
57 private $mRevisionsIdsLoaded = false; // Have the revisions IDs been loaded
58 var $mRevisionsLoaded = false; // Have the revisions been loaded
59 var $mTextLoaded = 0; // How many text blobs have been loaded, 0, 1 or 2?
60 var $mCacheHit = false; // Was the diff fetched from cache?
63 * Set this to true to add debug info to the HTML output.
64 * Warning: this may cause RSS readers to spuriously mark articles as "new"
67 var $enableDebugComment = false;
69 // If true, line X is not displayed when X is 1, for example to increase
70 // readability and conserve space with many small diffs.
71 protected $mReducedLineNumbers = false;
73 // Link to action=markpatrolled
74 protected $mMarkPatrolledLink = null;
76 protected $unhide = false; # show rev_deleted content if allowed
81 * @param $context IContextSource context to use, anything else will be ignored
82 * @param $old Integer old ID we want to show and diff with.
83 * @param $new String either 'prev' or 'next'.
84 * @param $rcid Integer Deprecated, no longer used!
85 * @param $refreshCache boolean If set, refreshes the diff cache
86 * @param $unhide boolean If set, allow viewing deleted revs
88 function __construct( $context = null, $old = 0, $new = 0, $rcid = 0,
89 $refreshCache = false, $unhide = false )
91 if ( $context instanceof IContextSource
) {
92 $this->setContext( $context );
95 wfDebug( "DifferenceEngine old '$old' new '$new' rcid '$rcid'\n" );
99 $this->mRefreshCache
= $refreshCache;
100 $this->unhide
= $unhide;
106 function setReducedLineNumbers( $value = true ) {
107 $this->mReducedLineNumbers
= $value;
113 function getDiffLang() {
114 if ( $this->mDiffLang
=== null ) {
115 # Default language in which the diff text is written.
116 $this->mDiffLang
= $this->getTitle()->getPageLanguage();
118 return $this->mDiffLang
;
124 function wasCacheHit() {
125 return $this->mCacheHit
;
131 function getOldid() {
132 $this->loadRevisionIds();
133 return $this->mOldid
;
139 function getNewid() {
140 $this->loadRevisionIds();
141 return $this->mNewid
;
145 * Look up a special:Undelete link to the given deleted revision id,
146 * as a workaround for being unable to load deleted diffs in currently.
148 * @param int $id revision ID
149 * @return mixed URL or false
151 function deletedLink( $id ) {
152 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
153 $dbr = wfGetDB( DB_SLAVE
);
154 $row = $dbr->selectRow( 'archive', '*',
155 array( 'ar_rev_id' => $id ),
158 $rev = Revision
::newFromArchiveRow( $row );
159 $title = Title
::makeTitleSafe( $row->ar_namespace
, $row->ar_title
);
160 return SpecialPage
::getTitleFor( 'Undelete' )->getFullURL( array(
161 'target' => $title->getPrefixedText(),
162 'timestamp' => $rev->getTimestamp()
170 * Build a wikitext link toward a deleted revision, if viewable.
172 * @param int $id revision ID
173 * @return string wikitext fragment
175 function deletedIdMarker( $id ) {
176 $link = $this->deletedLink( $id );
178 return "[$link $id]";
184 private function showMissingRevision() {
185 $out = $this->getOutput();
188 if ( $this->mOldRev
=== null ) {
189 $missing[] = $this->deletedIdMarker( $this->mOldid
);
191 if ( $this->mNewRev
=== null ) {
192 $missing[] = $this->deletedIdMarker( $this->mNewid
);
195 $out->setPageTitle( $this->msg( 'errorpagetitle' ) );
196 $out->addWikiMsg( 'difference-missing-revision',
197 $this->getLanguage()->listToText( $missing ), count( $missing ) );
200 function showDiffPage( $diffOnly = false ) {
201 wfProfileIn( __METHOD__
);
203 # Allow frames except in certain special cases
204 $out = $this->getOutput();
205 $out->allowClickjacking();
206 $out->setRobotPolicy( 'noindex,nofollow' );
208 if ( !$this->loadRevisionData() ) {
209 $this->showMissingRevision();
210 wfProfileOut( __METHOD__
);
214 $user = $this->getUser();
215 $permErrors = $this->mNewPage
->getUserPermissionsErrors( 'read', $user );
216 if ( $this->mOldPage
) { # mOldPage might not be set, see below.
217 $permErrors = wfMergeErrorArrays( $permErrors,
218 $this->mOldPage
->getUserPermissionsErrors( 'read', $user ) );
220 if ( count( $permErrors ) ) {
221 wfProfileOut( __METHOD__
);
222 throw new PermissionsError( 'read', $permErrors );
229 # Carry over 'diffonly' param via navigation links
230 if ( $diffOnly != $user->getBoolOption( 'diffonly' ) ) {
231 $query['diffonly'] = $diffOnly;
233 # Cascade unhide param in links for easy deletion browsing
234 if ( $this->unhide
) {
235 $query['unhide'] = 1;
238 # Check if one of the revisions is deleted/suppressed
239 $deleted = $suppressed = false;
240 $allowed = $this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $user );
242 $revisionTools = array();
244 # mOldRev is false if the difference engine is called with a "vague" query for
245 # a diff between a version V and its previous version V' AND the version V
246 # is the first version of that article. In that case, V' does not exist.
247 if ( $this->mOldRev
=== false ) {
248 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
252 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
254 if ( $this->mNewPage
->equals( $this->mOldPage
) ) {
255 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
258 $out->setPageTitle( $this->msg( 'difference-title-multipage', $this->mOldPage
->getPrefixedText(),
259 $this->mNewPage
->getPrefixedText() ) );
260 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
264 if ( $samePage && $this->mNewPage
->quickUserCan( 'edit', $user ) ) {
265 if ( $this->mNewRev
->isCurrent() && $this->mNewPage
->userCan( 'rollback', $user ) ) {
266 $rollbackLink = Linker
::generateRollback( $this->mNewRev
, $this->getContext() );
267 if ( $rollbackLink ) {
268 $out->preventClickjacking();
269 $rollback = '   ' . $rollbackLink;
272 if ( !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) && !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
273 $undoLink = Html
::element( 'a', array(
274 'href' => $this->mNewPage
->getLocalURL( array(
276 'undoafter' => $this->mOldid
,
277 'undo' => $this->mNewid
) ),
278 'title' => Linker
::titleAttrib( 'undo' )
280 $this->msg( 'editundo' )->text()
282 $revisionTools[] = $undoLink;
286 # Make "previous revision link"
287 if ( $samePage && $this->mOldRev
->getPrevious() ) {
288 $prevlink = Linker
::linkKnown(
290 $this->msg( 'previousdiff' )->escaped(),
291 array( 'id' => 'differences-prevlink' ),
292 array( 'diff' => 'prev', 'oldid' => $this->mOldid
) +
$query
295 $prevlink = ' ';
298 if ( $this->mOldRev
->isMinor() ) {
299 $oldminor = ChangesList
::flag( 'minor' );
304 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
305 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev
, 'complete' );
306 $oldChangeTags = ChangeTags
::formatSummaryRow( $this->mOldTags
, 'diff' );
308 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
309 '<div id="mw-diff-otitle2">' .
310 Linker
::revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
311 '<div id="mw-diff-otitle3">' . $oldminor .
312 Linker
::revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
313 '<div id="mw-diff-otitle5">' . $oldChangeTags[0] . '</div>' .
314 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
316 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
317 $deleted = true; // old revisions text is hidden
318 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
319 $suppressed = true; // also suppressed
323 # Check if this user can see the revisions
324 if ( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $user ) ) {
329 # Make "next revision link"
330 # Skip next link on the top revision
331 if ( $samePage && !$this->mNewRev
->isCurrent() ) {
332 $nextlink = Linker
::linkKnown(
334 $this->msg( 'nextdiff' )->escaped(),
335 array( 'id' => 'differences-nextlink' ),
336 array( 'diff' => 'next', 'oldid' => $this->mNewid
) +
$query
339 $nextlink = ' ';
342 if ( $this->mNewRev
->isMinor() ) {
343 $newminor = ChangesList
::flag( 'minor' );
348 # Handle RevisionDelete links...
349 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
351 # Allow extensions to define their own revision tools
352 wfRunHooks( 'DiffRevisionTools', array( $this->mNewRev
, &$revisionTools ) );
353 $formattedRevisionTools = array();
354 // Put each one in parentheses (poor man's button)
355 foreach ( $revisionTools as $tool ) {
356 $formattedRevisionTools[] = $this->msg( 'parentheses' )->rawParams( $tool )->escaped();
358 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev
, 'complete' ) . ' ' . implode( ' ', $formattedRevisionTools );
359 $newChangeTags = ChangeTags
::formatSummaryRow( $this->mNewTags
, 'diff' );
361 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
362 '<div id="mw-diff-ntitle2">' . Linker
::revUserTools( $this->mNewRev
, !$this->unhide
) .
364 '<div id="mw-diff-ntitle3">' . $newminor .
365 Linker
::revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
366 '<div id="mw-diff-ntitle5">' . $newChangeTags[0] . '</div>' .
367 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
369 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
370 $deleted = true; // new revisions text is hidden
371 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
372 $suppressed = true; // also suppressed
376 # If the diff cannot be shown due to a deleted revision, then output
377 # the diff header and links to unhide (if available)...
378 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
379 $this->showDiffStyle();
380 $multi = $this->getMultiNotice();
381 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
383 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
384 # Give explanation for why revision is not visible
385 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
388 # Give explanation and add a link to view the diff...
389 $link = $this->getTitle()->getFullURL( $this->getRequest()->appendQueryValue( 'unhide', '1', true ) );
390 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
391 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n", array( $msg, $link ) );
393 # Otherwise, output a regular diff...
395 # Add deletion notice if the user is viewing deleted content
398 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
399 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" . $this->msg( $msg )->parse() . "</div>\n";
401 $this->showDiff( $oldHeader, $newHeader, $notice );
403 $this->renderNewRevision();
406 wfProfileOut( __METHOD__
);
410 * Get a link to mark the change as patrolled, or '' if there's either no
411 * revision to patrol or the user is not allowed to to it.
412 * Side effect: When the patrol link is build, this method will call
413 * OutputPage::preventClickjacking() and load mediawiki.page.patrol.ajax.
417 protected function markPatrolledLink() {
418 global $wgUseRCPatrol, $wgEnableAPI, $wgEnableWriteAPI;
419 $user = $this->getUser();
421 if ( $this->mMarkPatrolledLink
=== null ) {
422 // Prepare a change patrol link, if applicable
424 // Is patrolling enabled and the user allowed to?
425 $wgUseRCPatrol && $this->mNewPage
->quickUserCan( 'patrol', $user ) &&
426 // Only do this if the revision isn't more than 6 hours older
427 // than the Max RC age (6h because the RC might not be cleaned out regularly)
428 RecentChange
::isInRCLifespan( $this->mNewRev
->getTimestamp(), 21600 )
430 // Look for an unpatrolled change corresponding to this diff
432 $db = wfGetDB( DB_SLAVE
);
433 $change = RecentChange
::newFromConds(
435 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
436 'rc_this_oldid' => $this->mNewid
,
440 array( 'USE INDEX' => 'rc_timestamp' )
443 if ( $change && $change->getPerformer()->getName() !== $user->getName() ) {
444 $rcid = $change->getAttribute( 'rc_id' );
446 // None found or the page has been created by the current user.
447 // If the user could patrol this it already would be patrolled
452 $this->getOutput()->preventClickjacking();
453 if ( $wgEnableAPI && $wgEnableWriteAPI
454 && $user->isAllowed( 'writeapi' )
456 $this->getOutput()->addModules( 'mediawiki.page.patrol.ajax' );
459 $token = $user->getEditToken( $rcid );
460 $this->mMarkPatrolledLink
= ' <span class="patrollink">[' . Linker
::linkKnown(
462 $this->msg( 'markaspatrolleddiff' )->escaped(),
465 'action' => 'markpatrolled',
471 $this->mMarkPatrolledLink
= '';
474 $this->mMarkPatrolledLink
= '';
478 return $this->mMarkPatrolledLink
;
482 * @param $rev Revision
485 protected function revisionDeleteLink( $rev ) {
486 $link = Linker
::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
487 if ( $link !== '' ) {
488 $link = '   ' . $link . ' ';
494 * Show the new revision of the page.
496 function renderNewRevision() {
497 wfProfileIn( __METHOD__
);
498 $out = $this->getOutput();
499 $revHeader = $this->getRevisionHeader( $this->mNewRev
);
500 # Add "current version as of X" title
501 $out->addHTML( "<hr class='diff-hr' />
502 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
503 # Page content may be handled by a hooked call instead...
504 if ( wfRunHooks( 'ArticleContentOnDiff', array( $this, $out ) ) ) {
505 $this->loadNewText();
506 $out->setRevisionId( $this->mNewid
);
507 $out->setRevisionTimestamp( $this->mNewRev
->getTimestamp() );
508 $out->setArticleFlag( true );
510 // NOTE: only needed for B/C: custom rendering of JS/CSS via hook
511 if ( $this->mNewPage
->isCssJsSubpage() ||
$this->mNewPage
->isCssOrJsPage() ) {
512 // Stolen from Article::view --AG 2007-10-11
513 // Give hooks a chance to customise the output
514 // @todo standardize this crap into one function
515 if ( ContentHandler
::runLegacyHooks( 'ShowRawCssJs', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
516 // NOTE: deprecated hook, B/C only
517 // use the content object's own rendering
518 $cnt = $this->mNewRev
->getContent();
519 $po = $cnt ?
$cnt->getParserOutput( $this->mNewRev
->getTitle(), $this->mNewRev
->getId() ) : null;
520 $txt = $po ?
$po->getText() : '';
521 $out->addHTML( $txt );
523 } elseif ( !wfRunHooks( 'ArticleContentViewCustom', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
524 // Handled by extension
525 } elseif ( !ContentHandler
::runLegacyHooks( 'ArticleViewCustom', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
526 // NOTE: deprecated 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 # Also try to load it as a redirect
543 $rt = $this->mNewContent ?
$this->mNewContent
->getRedirectTarget() : null;
546 $article = Article
::newFromTitle( $this->mNewPage
, $this->getContext() );
547 $out->addHTML( $article->viewRedirect( $rt ) );
549 # WikiPage::getParserOutput() should not return false, but just in case
550 if ( $parserOutput ) {
551 # Show categories etc.
552 $out->addParserOutputNoText( $parserOutput );
554 } elseif ( $parserOutput ) {
555 $out->addParserOutput( $parserOutput );
559 # Add redundant patrol link on bottom...
560 $out->addHTML( $this->markPatrolledLink() );
562 wfProfileOut( __METHOD__
);
565 protected function getParserOutput( WikiPage
$page, Revision
$rev ) {
566 $parserOptions = $page->makeParserOptions( $this->getContext() );
568 if ( !$rev->isCurrent() ||
!$rev->getTitle()->quickUserCan( "edit" ) ) {
569 $parserOptions->setEditSection( false );
572 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
573 return $parserOutput;
577 * Get the diff text, send it to the OutputPage object
578 * Returns false if the diff could not be generated, otherwise returns true
582 function showDiff( $otitle, $ntitle, $notice = '' ) {
583 $diff = $this->getDiff( $otitle, $ntitle, $notice );
584 if ( $diff === false ) {
585 $this->showMissingRevision();
588 $this->showDiffStyle();
589 $this->getOutput()->addHTML( $diff );
595 * Add style sheets and supporting JS for diff display.
597 function showDiffStyle() {
598 $this->getOutput()->addModuleStyles( 'mediawiki.action.history.diff' );
602 * Get complete diff table, including header
604 * @param string|bool $otitle Header for old text or false
605 * @param string|bool $ntitle Header for new text or false
606 * @param string $notice HTML between diff header and body
609 function getDiff( $otitle, $ntitle, $notice = '' ) {
610 $body = $this->getDiffBody();
611 if ( $body === false ) {
614 $multi = $this->getMultiNotice();
615 // Display a message when the diff is empty
616 if ( $body === '' ) {
617 $notice .= '<div class="mw-diff-empty">' . $this->msg( 'diff-empty' )->parse() . "</div>\n";
619 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
624 * Get the diff table body, without header
626 * @return mixed (string/false)
628 public function getDiffBody() {
630 wfProfileIn( __METHOD__
);
631 $this->mCacheHit
= true;
632 // Check if the diff should be hidden from this user
633 if ( !$this->loadRevisionData() ) {
634 wfProfileOut( __METHOD__
);
636 } elseif ( $this->mOldRev
&& !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
637 wfProfileOut( __METHOD__
);
639 } elseif ( $this->mNewRev
&& !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
640 wfProfileOut( __METHOD__
);
644 if ( $this->mOldRev
=== false ||
( $this->mOldRev
&& $this->mNewRev
645 && $this->mOldRev
->getID() == $this->mNewRev
->getID() ) )
647 wfProfileOut( __METHOD__
);
652 if ( $this->mOldid
&& $this->mNewid
) {
653 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
,
654 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
656 if ( !$this->mRefreshCache
) {
657 $difftext = $wgMemc->get( $key );
659 wfIncrStats( 'diff_cache_hit' );
660 $difftext = $this->localiseLineNumbers( $difftext );
661 $difftext .= "\n<!-- diff cache key $key -->\n";
662 wfProfileOut( __METHOD__
);
665 } // don't try to load but save the result
667 $this->mCacheHit
= false;
669 // Loadtext is permission safe, this just clears out the diff
670 if ( !$this->loadText() ) {
671 wfProfileOut( __METHOD__
);
675 $difftext = $this->generateContentDiffBody( $this->mOldContent
, $this->mNewContent
);
677 // Save to cache for 7 days
678 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
679 wfIncrStats( 'diff_uncacheable' );
680 } elseif ( $key !== false && $difftext !== false ) {
681 wfIncrStats( 'diff_cache_miss' );
682 $wgMemc->set( $key, $difftext, 7 * 86400 );
684 wfIncrStats( 'diff_uncacheable' );
686 // Replace line numbers with the text in the user's language
687 if ( $difftext !== false ) {
688 $difftext = $this->localiseLineNumbers( $difftext );
690 wfProfileOut( __METHOD__
);
695 * Make sure the proper modules are loaded before we try to
698 private function initDiffEngines() {
699 global $wgExternalDiffEngine;
700 if ( $wgExternalDiffEngine == 'wikidiff' && !function_exists( 'wikidiff_do_diff' ) ) {
701 wfProfileIn( __METHOD__
. '-php_wikidiff.so' );
702 wfDl( 'php_wikidiff' );
703 wfProfileOut( __METHOD__
. '-php_wikidiff.so' );
705 elseif ( $wgExternalDiffEngine == 'wikidiff2' && !function_exists( 'wikidiff2_do_diff' ) ) {
706 wfProfileIn( __METHOD__
. '-php_wikidiff2.so' );
708 wfProfileOut( __METHOD__
. '-php_wikidiff2.so' );
713 * Generate a diff, no caching.
715 * This implementation uses generateTextDiffBody() to generate a diff based on the default
716 * serialization of the given Content objects. This will fail if $old or $new are not
717 * instances of TextContent.
719 * Subclasses may override this to provide a different rendering for the diff,
720 * perhaps taking advantage of the content's native form. This is required for all content
721 * models that are not text based.
723 * @param $old Content: old content
724 * @param $new Content: new content
726 * @return bool|string
728 * @throws MWException if $old or $new are not instances of TextContent.
730 function generateContentDiffBody( Content
$old, Content
$new ) {
731 if ( !( $old instanceof TextContent
) ) {
732 throw new MWException( "Diff not implemented for " . get_class( $old ) . "; "
733 . "override generateContentDiffBody to fix this." );
736 if ( !( $new instanceof TextContent
) ) {
737 throw new MWException( "Diff not implemented for " . get_class( $new ) . "; "
738 . "override generateContentDiffBody to fix this." );
741 $otext = $old->serialize();
742 $ntext = $new->serialize();
744 return $this->generateTextDiffBody( $otext, $ntext );
748 * Generate a diff, no caching
750 * @param string $otext old text, must be already segmented
751 * @param string $ntext new text, must be already segmented
752 * @return bool|string
753 * @deprecated since 1.21, use generateContentDiffBody() instead!
755 function generateDiffBody( $otext, $ntext ) {
756 ContentHandler
::deprecated( __METHOD__
, "1.21" );
758 return $this->generateTextDiffBody( $otext, $ntext );
762 * Generate a diff, no caching
764 * @todo move this to TextDifferenceEngine, make DifferenceEngine abstract. At some point.
766 * @param string $otext old text, must be already segmented
767 * @param string $ntext new text, must be already segmented
768 * @return bool|string
770 function generateTextDiffBody( $otext, $ntext ) {
771 global $wgExternalDiffEngine, $wgContLang;
773 wfProfileIn( __METHOD__
);
775 $otext = str_replace( "\r\n", "\n", $otext );
776 $ntext = str_replace( "\r\n", "\n", $ntext );
778 $this->initDiffEngines();
780 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
781 # For historical reasons, external diff engine expects
782 # input text to be HTML-escaped already
783 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
784 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
785 wfProfileOut( __METHOD__
);
786 return $wgContLang->unsegmentForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
787 $this->debug( 'wikidiff1' );
790 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
791 # Better external diff engine, the 2 may some day be dropped
792 # This one does the escaping and segmenting itself
793 wfProfileIn( 'wikidiff2_do_diff' );
794 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
795 $text .= $this->debug( 'wikidiff2' );
796 wfProfileOut( 'wikidiff2_do_diff' );
797 wfProfileOut( __METHOD__
);
800 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
802 $tmpDir = wfTempDir();
803 $tempName1 = tempnam( $tmpDir, 'diff_' );
804 $tempName2 = tempnam( $tmpDir, 'diff_' );
806 $tempFile1 = fopen( $tempName1, "w" );
808 wfProfileOut( __METHOD__
);
811 $tempFile2 = fopen( $tempName2, "w" );
813 wfProfileOut( __METHOD__
);
816 fwrite( $tempFile1, $otext );
817 fwrite( $tempFile2, $ntext );
818 fclose( $tempFile1 );
819 fclose( $tempFile2 );
820 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
821 wfProfileIn( __METHOD__
. "-shellexec" );
822 $difftext = wfShellExec( $cmd );
823 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
824 wfProfileOut( __METHOD__
. "-shellexec" );
825 unlink( $tempName1 );
826 unlink( $tempName2 );
827 wfProfileOut( __METHOD__
);
832 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
833 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
834 $diffs = new Diff( $ota, $nta );
835 $formatter = new TableDiffFormatter();
836 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
837 wfProfileOut( __METHOD__
);
842 * Generate a debug comment indicating diff generating time,
843 * server node, and generator backend.
846 protected function debug( $generator = "internal" ) {
847 global $wgShowHostnames;
848 if ( !$this->enableDebugComment
) {
851 $data = array( $generator );
852 if ( $wgShowHostnames ) {
853 $data[] = wfHostname();
855 $data[] = wfTimestamp( TS_DB
);
856 return "<!-- diff generator: " .
865 * Replace line numbers with the text in the user's language
868 function localiseLineNumbers( $text ) {
869 return preg_replace_callback( '/<!--LINE (\d+)-->/',
870 array( &$this, 'localiseLineNumbersCb' ), $text );
873 function localiseLineNumbersCb( $matches ) {
874 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) {
877 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
881 * If there are revisions between the ones being compared, return a note saying so.
884 function getMultiNotice() {
885 if ( !is_object( $this->mOldRev
) ||
!is_object( $this->mNewRev
) ) {
887 } elseif ( !$this->mOldPage
->equals( $this->mNewPage
) ) {
888 // Comparing two different pages? Count would be meaningless.
892 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
893 $oldRev = $this->mNewRev
; // flip
894 $newRev = $this->mOldRev
; // flip
895 } else { // normal case
896 $oldRev = $this->mOldRev
;
897 $newRev = $this->mNewRev
;
900 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev );
902 $limit = 100; // use diff-multi-manyusers if too many users
903 $numUsers = $this->mNewPage
->countAuthorsBetween( $oldRev, $newRev, $limit );
904 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
906 return ''; // nothing
910 * Get a notice about how many intermediate edits and users there are
911 * @param $numEdits int
912 * @param $numUsers int
916 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
917 if ( $numUsers > $limit ) {
918 $msg = 'diff-multi-manyusers';
923 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
927 * Get a header for a specified revision.
929 * @param $rev Revision
930 * @param string $complete 'complete' to get the header wrapped depending
931 * the visibility of the revision and a link to edit the page.
932 * @return String HTML fragment
934 protected function getRevisionHeader( Revision
$rev, $complete = '' ) {
935 $lang = $this->getLanguage();
936 $user = $this->getUser();
937 $revtimestamp = $rev->getTimestamp();
938 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
939 $dateofrev = $lang->userDate( $revtimestamp, $user );
940 $timeofrev = $lang->userTime( $revtimestamp, $user );
942 $header = $this->msg(
943 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
949 if ( $complete !== 'complete' ) {
953 $title = $rev->getTitle();
955 $header = Linker
::linkKnown( $title, $header, array(),
956 array( 'oldid' => $rev->getID() ) );
958 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
959 $editQuery = array( 'action' => 'edit' );
960 if ( !$rev->isCurrent() ) {
961 $editQuery['oldid'] = $rev->getID();
964 $msg = $this->msg( $title->quickUserCan( 'edit', $user ) ?
'editold' : 'viewsourceold' )->escaped();
965 $header .= ' ' . $this->msg( 'parentheses' )->rawParams(
966 Linker
::linkKnown( $title, $msg, array(), $editQuery ) )->plain();
967 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
968 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
971 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
978 * Add the header to a diff body
982 function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
983 // shared.css sets diff in interface language/dir, but the actual content
984 // is often in a different language, mostly the page content language/dir
985 $tableClass = 'diff diff-contentalign-' . htmlspecialchars( $this->getDiffLang()->alignStart() );
986 $header = "<table class='$tableClass'>";
988 if ( !$diff && !$otitle ) {
990 <tr style='vertical-align: top;'>
991 <td class='diff-ntitle'>{$ntitle}</td>
995 if ( $diff ) { // Safari/Chrome show broken output if cols not used
997 <col class='diff-marker' />
998 <col class='diff-content' />
999 <col class='diff-marker' />
1000 <col class='diff-content' />";
1007 if ( $otitle ||
$ntitle ) {
1009 <tr style='vertical-align: top;'>
1010 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
1011 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
1016 if ( $multi != '' ) {
1017 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;' class='diff-multi'>{$multi}</td></tr>";
1019 if ( $notice != '' ) {
1020 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;'>{$notice}</td></tr>";
1023 return $header . $diff . "</table>";
1027 * Use specified text instead of loading from the database
1028 * @deprecated since 1.21, use setContent() instead.
1030 function setText( $oldText, $newText ) {
1031 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1033 $oldContent = ContentHandler
::makeContent( $oldText, $this->getTitle() );
1034 $newContent = ContentHandler
::makeContent( $newText, $this->getTitle() );
1036 $this->setContent( $oldContent, $newContent );
1040 * Use specified text instead of loading from the database
1043 function setContent( Content
$oldContent, Content
$newContent ) {
1044 $this->mOldContent
= $oldContent;
1045 $this->mNewContent
= $newContent;
1047 $this->mTextLoaded
= 2;
1048 $this->mRevisionsLoaded
= true;
1052 * Set the language in which the diff text is written
1053 * (Defaults to page content language).
1056 function setTextLanguage( $lang ) {
1057 $this->mDiffLang
= wfGetLangObj( $lang );
1063 private function loadRevisionIds() {
1064 if ( $this->mRevisionsIdsLoaded
) {
1068 $this->mRevisionsIdsLoaded
= true;
1070 $old = $this->mOldid
;
1071 $new = $this->mNewid
;
1073 if ( $new === 'prev' ) {
1074 # Show diff between revision $old and the previous one.
1075 # Get previous one from DB.
1076 $this->mNewid
= intval( $old );
1077 $this->mOldid
= $this->getTitle()->getPreviousRevisionID( $this->mNewid
);
1078 } elseif ( $new === 'next' ) {
1079 # Show diff between revision $old and the next one.
1080 # Get next one from DB.
1081 $this->mOldid
= intval( $old );
1082 $this->mNewid
= $this->getTitle()->getNextRevisionID( $this->mOldid
);
1083 if ( $this->mNewid
=== false ) {
1084 # if no result, NewId points to the newest old revision. The only newer
1085 # revision is cur, which is "0".
1089 $this->mOldid
= intval( $old );
1090 $this->mNewid
= intval( $new );
1091 wfRunHooks( 'NewDifferenceEngine', array( $this->getTitle(), &$this->mOldid
, &$this->mNewid
, $old, $new ) );
1096 * Load revision metadata for the specified articles. If newid is 0, then compare
1097 * the old article in oldid to the current article; if oldid is 0, then
1098 * compare the current article to the immediately previous one (ignoring the
1101 * If oldid is false, leave the corresponding revision object set
1102 * to false. This is impossible via ordinary user input, and is provided for
1107 function loadRevisionData() {
1108 if ( $this->mRevisionsLoaded
) {
1112 // Whether it succeeds or fails, we don't want to try again
1113 $this->mRevisionsLoaded
= true;
1115 $this->loadRevisionIds();
1117 // Load the new revision object
1118 $this->mNewRev
= $this->mNewid
1119 ? Revision
::newFromId( $this->mNewid
)
1120 : Revision
::newFromTitle( $this->getTitle(), false, Revision
::READ_NORMAL
);
1122 if ( !$this->mNewRev
instanceof Revision
) {
1126 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1127 $this->mNewid
= $this->mNewRev
->getId();
1128 $this->mNewPage
= $this->mNewRev
->getTitle();
1130 // Load the old revision object
1131 $this->mOldRev
= false;
1132 if ( $this->mOldid
) {
1133 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1134 } elseif ( $this->mOldid
=== 0 ) {
1135 $rev = $this->mNewRev
->getPrevious();
1137 $this->mOldid
= $rev->getId();
1138 $this->mOldRev
= $rev;
1140 // No previous revision; mark to show as first-version only.
1141 $this->mOldid
= false;
1142 $this->mOldRev
= false;
1144 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1146 if ( is_null( $this->mOldRev
) ) {
1150 if ( $this->mOldRev
) {
1151 $this->mOldPage
= $this->mOldRev
->getTitle();
1154 // Load tags information for both revisions
1155 $dbr = wfGetDB( DB_SLAVE
);
1156 if ( $this->mOldid
!== false ) {
1157 $this->mOldTags
= $dbr->selectField(
1160 array( 'ts_rev_id' => $this->mOldid
),
1164 $this->mOldTags
= false;
1166 $this->mNewTags
= $dbr->selectField(
1169 array( 'ts_rev_id' => $this->mNewid
),
1177 * Load the text of the revisions, as well as revision data.
1181 function loadText() {
1182 if ( $this->mTextLoaded
== 2 ) {
1185 // Whether it succeeds or fails, we don't want to try again
1186 $this->mTextLoaded
= 2;
1189 if ( !$this->loadRevisionData() ) {
1192 if ( $this->mOldRev
) {
1193 $this->mOldContent
= $this->mOldRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1194 if ( $this->mOldContent
=== null ) {
1198 if ( $this->mNewRev
) {
1199 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1200 if ( $this->mNewContent
=== null ) {
1208 * Load the text of the new revision, not the old one
1212 function loadNewText() {
1213 if ( $this->mTextLoaded
>= 1 ) {
1216 $this->mTextLoaded
= 1;
1218 if ( !$this->loadRevisionData() ) {
1221 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );