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
{
60 private $mRevisionsIdsLoaded = false; // Have the revisions IDs been loaded
61 public $mRevisionsLoaded = false; // Have the revisions been loaded
62 public $mTextLoaded = 0; // How many text blobs have been loaded, 0, 1 or 2?
63 public $mCacheHit = false; // Was the diff fetched from cache?
66 * Set this to true to add debug info to the HTML output.
67 * Warning: this may cause RSS readers to spuriously mark articles as "new"
70 public $enableDebugComment = false;
72 // If true, line X is not displayed when X is 1, for example to increase
73 // readability and conserve space with many small diffs.
74 protected $mReducedLineNumbers = false;
76 // Link to action=markpatrolled
77 protected $mMarkPatrolledLink = null;
79 protected $unhide = false; # show rev_deleted content if allowed
84 * @param $context IContextSource context to use, anything else will be ignored
85 * @param $old Integer old ID we want to show and diff with.
86 * @param $new String|int either revision ID or 'prev' or 'next'. Default: 0.
87 * @param $rcid Integer Deprecated, no longer used!
88 * @param $refreshCache boolean If set, refreshes the diff cache
89 * @param $unhide boolean If set, allow viewing deleted revs
91 function __construct( $context = null, $old = 0, $new = 0, $rcid = 0,
92 $refreshCache = false, $unhide = false
94 if ( $context instanceof IContextSource
) {
95 $this->setContext( $context );
98 wfDebug( "DifferenceEngine old '$old' new '$new' rcid '$rcid'\n" );
100 $this->mOldid
= $old;
101 $this->mNewid
= $new;
102 $this->mRefreshCache
= $refreshCache;
103 $this->unhide
= $unhide;
109 function setReducedLineNumbers( $value = true ) {
110 $this->mReducedLineNumbers
= $value;
116 function getDiffLang() {
117 if ( $this->mDiffLang
=== null ) {
118 # Default language in which the diff text is written.
119 $this->mDiffLang
= $this->getTitle()->getPageLanguage();
121 return $this->mDiffLang
;
127 function wasCacheHit() {
128 return $this->mCacheHit
;
134 function getOldid() {
135 $this->loadRevisionIds();
136 return $this->mOldid
;
142 function getNewid() {
143 $this->loadRevisionIds();
144 return $this->mNewid
;
148 * Look up a special:Undelete link to the given deleted revision id,
149 * as a workaround for being unable to load deleted diffs in currently.
151 * @param int $id revision ID
152 * @return mixed URL or false
154 function deletedLink( $id ) {
155 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
156 $dbr = wfGetDB( DB_SLAVE
);
157 $row = $dbr->selectRow( 'archive', '*',
158 array( 'ar_rev_id' => $id ),
161 $rev = Revision
::newFromArchiveRow( $row );
162 $title = Title
::makeTitleSafe( $row->ar_namespace
, $row->ar_title
);
163 return SpecialPage
::getTitleFor( 'Undelete' )->getFullURL( array(
164 'target' => $title->getPrefixedText(),
165 'timestamp' => $rev->getTimestamp()
173 * Build a wikitext link toward a deleted revision, if viewable.
175 * @param int $id revision ID
176 * @return string wikitext fragment
178 function deletedIdMarker( $id ) {
179 $link = $this->deletedLink( $id );
181 return "[$link $id]";
187 private function showMissingRevision() {
188 $out = $this->getOutput();
191 if ( $this->mOldRev
=== null ||
192 ( $this->mOldRev
&& $this->mOldContent
=== null )
194 $missing[] = $this->deletedIdMarker( $this->mOldid
);
196 if ( $this->mNewRev
=== null ||
197 ( $this->mNewRev
&& $this->mNewContent
=== null )
199 $missing[] = $this->deletedIdMarker( $this->mNewid
);
202 $out->setPageTitle( $this->msg( 'errorpagetitle' ) );
203 $out->addWikiMsg( 'difference-missing-revision',
204 $this->getLanguage()->listToText( $missing ), count( $missing ) );
207 function showDiffPage( $diffOnly = false ) {
208 wfProfileIn( __METHOD__
);
210 # Allow frames except in certain special cases
211 $out = $this->getOutput();
212 $out->allowClickjacking();
213 $out->setRobotPolicy( 'noindex,nofollow' );
215 if ( !$this->loadRevisionData() ) {
216 $this->showMissingRevision();
217 wfProfileOut( __METHOD__
);
221 $user = $this->getUser();
222 $permErrors = $this->mNewPage
->getUserPermissionsErrors( 'read', $user );
223 if ( $this->mOldPage
) { # mOldPage might not be set, see below.
224 $permErrors = wfMergeErrorArrays( $permErrors,
225 $this->mOldPage
->getUserPermissionsErrors( 'read', $user ) );
227 if ( count( $permErrors ) ) {
228 wfProfileOut( __METHOD__
);
229 throw new PermissionsError( 'read', $permErrors );
235 # Carry over 'diffonly' param via navigation links
236 if ( $diffOnly != $user->getBoolOption( 'diffonly' ) ) {
237 $query['diffonly'] = $diffOnly;
239 # Cascade unhide param in links for easy deletion browsing
240 if ( $this->unhide
) {
241 $query['unhide'] = 1;
244 # Check if one of the revisions is deleted/suppressed
245 $deleted = $suppressed = false;
246 $allowed = $this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $user );
248 $revisionTools = array();
250 # mOldRev is false if the difference engine is called with a "vague" query for
251 # a diff between a version V and its previous version V' AND the version V
252 # is the first version of that article. In that case, V' does not exist.
253 if ( $this->mOldRev
=== false ) {
254 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
258 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
260 if ( $this->mNewPage
->equals( $this->mOldPage
) ) {
261 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
264 $out->setPageTitle( $this->msg( 'difference-title-multipage',
265 $this->mOldPage
->getPrefixedText(), $this->mNewPage
->getPrefixedText() ) );
266 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
270 if ( $samePage && $this->mNewPage
->quickUserCan( 'edit', $user ) ) {
271 if ( $this->mNewRev
->isCurrent() && $this->mNewPage
->userCan( 'rollback', $user ) ) {
272 $rollbackLink = Linker
::generateRollback( $this->mNewRev
, $this->getContext() );
273 if ( $rollbackLink ) {
274 $out->preventClickjacking();
275 $rollback = '   ' . $rollbackLink;
279 if ( !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) &&
280 !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
)
282 $undoLink = Html
::element( 'a', array(
283 'href' => $this->mNewPage
->getLocalURL( array(
285 'undoafter' => $this->mOldid
,
286 'undo' => $this->mNewid
) ),
287 'title' => Linker
::titleAttrib( 'undo' )
289 $this->msg( 'editundo' )->text()
291 $revisionTools[] = $undoLink;
295 # Make "previous revision link"
296 if ( $samePage && $this->mOldRev
->getPrevious() ) {
297 $prevlink = Linker
::linkKnown(
299 $this->msg( 'previousdiff' )->escaped(),
300 array( 'id' => 'differences-prevlink' ),
301 array( 'diff' => 'prev', 'oldid' => $this->mOldid
) +
$query
304 $prevlink = ' ';
307 if ( $this->mOldRev
->isMinor() ) {
308 $oldminor = ChangesList
::flag( 'minor' );
313 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
314 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev
, 'complete' );
315 $oldChangeTags = ChangeTags
::formatSummaryRow( $this->mOldTags
, 'diff' );
317 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
318 '<div id="mw-diff-otitle2">' .
319 Linker
::revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
320 '<div id="mw-diff-otitle3">' . $oldminor .
321 Linker
::revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
322 '<div id="mw-diff-otitle5">' . $oldChangeTags[0] . '</div>' .
323 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
325 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
326 $deleted = true; // old revisions text is hidden
327 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
328 $suppressed = true; // also suppressed
332 # Check if this user can see the revisions
333 if ( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $user ) ) {
338 # Make "next revision link"
339 # Skip next link on the top revision
340 if ( $samePage && !$this->mNewRev
->isCurrent() ) {
341 $nextlink = Linker
::linkKnown(
343 $this->msg( 'nextdiff' )->escaped(),
344 array( 'id' => 'differences-nextlink' ),
345 array( 'diff' => 'next', 'oldid' => $this->mNewid
) +
$query
348 $nextlink = ' ';
351 if ( $this->mNewRev
->isMinor() ) {
352 $newminor = ChangesList
::flag( 'minor' );
357 # Handle RevisionDelete links...
358 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
360 # Allow extensions to define their own revision tools
361 wfRunHooks( 'DiffRevisionTools', array( $this->mNewRev
, &$revisionTools ) );
362 $formattedRevisionTools = array();
363 // Put each one in parentheses (poor man's button)
364 foreach ( $revisionTools as $tool ) {
365 $formattedRevisionTools[] = $this->msg( 'parentheses' )->rawParams( $tool )->escaped();
367 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev
, 'complete' ) .
368 ' ' . implode( ' ', $formattedRevisionTools );
369 $newChangeTags = ChangeTags
::formatSummaryRow( $this->mNewTags
, 'diff' );
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-ntitle5">' . $newChangeTags[0] . '</div>' .
377 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
379 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
380 $deleted = true; // new revisions text is hidden
381 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
382 $suppressed = true; // also suppressed
386 # If the diff cannot be shown due to a deleted revision, then output
387 # the diff header and links to unhide (if available)...
388 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
389 $this->showDiffStyle();
390 $multi = $this->getMultiNotice();
391 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
393 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
394 # Give explanation for why revision is not visible
395 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
398 # Give explanation and add a link to view the diff...
399 $query = $this->getRequest()->appendQueryValue( 'unhide', '1', true );
400 $link = $this->getTitle()->getFullURL( $query );
401 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
403 "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
407 # Otherwise, output a regular diff...
409 # Add deletion notice if the user is viewing deleted content
412 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
413 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" .
414 $this->msg( $msg )->parse() .
417 $this->showDiff( $oldHeader, $newHeader, $notice );
419 $this->renderNewRevision();
422 wfProfileOut( __METHOD__
);
426 * Get a link to mark the change as patrolled, or '' if there's either no
427 * revision to patrol or the user is not allowed to to it.
428 * Side effect: When the patrol link is build, this method will call
429 * OutputPage::preventClickjacking() and load mediawiki.page.patrol.ajax.
433 protected function markPatrolledLink() {
434 global $wgUseRCPatrol, $wgEnableAPI, $wgEnableWriteAPI;
435 $user = $this->getUser();
437 if ( $this->mMarkPatrolledLink
=== null ) {
438 // Prepare a change patrol link, if applicable
440 // Is patrolling enabled and the user allowed to?
441 $wgUseRCPatrol && $this->mNewPage
->quickUserCan( 'patrol', $user ) &&
442 // Only do this if the revision isn't more than 6 hours older
443 // than the Max RC age (6h because the RC might not be cleaned out regularly)
444 RecentChange
::isInRCLifespan( $this->mNewRev
->getTimestamp(), 21600 )
446 // Look for an unpatrolled change corresponding to this diff
448 $db = wfGetDB( DB_SLAVE
);
449 $change = RecentChange
::newFromConds(
451 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
452 'rc_this_oldid' => $this->mNewid
,
456 array( 'USE INDEX' => 'rc_timestamp' )
459 if ( $change && $change->getPerformer()->getName() !== $user->getName() ) {
460 $rcid = $change->getAttribute( 'rc_id' );
462 // None found or the page has been created by the current user.
463 // If the user could patrol this it already would be patrolled
468 $this->getOutput()->preventClickjacking();
469 if ( $wgEnableAPI && $wgEnableWriteAPI
470 && $user->isAllowed( 'writeapi' )
472 $this->getOutput()->addModules( 'mediawiki.page.patrol.ajax' );
475 $token = $user->getEditToken( $rcid );
476 $this->mMarkPatrolledLink
= ' <span class="patrollink">[' . Linker
::linkKnown(
478 $this->msg( 'markaspatrolleddiff' )->escaped(),
481 'action' => 'markpatrolled',
487 $this->mMarkPatrolledLink
= '';
490 $this->mMarkPatrolledLink
= '';
494 return $this->mMarkPatrolledLink
;
498 * @param $rev Revision
501 protected function revisionDeleteLink( $rev ) {
502 $link = Linker
::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
503 if ( $link !== '' ) {
504 $link = '   ' . $link . ' ';
510 * Show the new revision of the page.
512 function renderNewRevision() {
513 wfProfileIn( __METHOD__
);
514 $out = $this->getOutput();
515 $revHeader = $this->getRevisionHeader( $this->mNewRev
);
516 # Add "current version as of X" title
517 $out->addHTML( "<hr class='diff-hr' />
518 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
519 # Page content may be handled by a hooked call instead...
520 # @codingStandardsIgnoreStart Ignoring long lines.
521 if ( wfRunHooks( 'ArticleContentOnDiff', array( $this, $out ) ) ) {
522 $this->loadNewText();
523 $out->setRevisionId( $this->mNewid
);
524 $out->setRevisionTimestamp( $this->mNewRev
->getTimestamp() );
525 $out->setArticleFlag( true );
527 // NOTE: only needed for B/C: custom rendering of JS/CSS via hook
528 if ( $this->mNewPage
->isCssJsSubpage() ||
$this->mNewPage
->isCssOrJsPage() ) {
529 // Stolen from Article::view --AG 2007-10-11
530 // Give hooks a chance to customise the output
531 // @todo standardize this crap into one function
532 if ( ContentHandler
::runLegacyHooks( 'ShowRawCssJs', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
533 // NOTE: deprecated hook, B/C only
534 // use the content object's own rendering
535 $cnt = $this->mNewRev
->getContent();
536 $po = $cnt ?
$cnt->getParserOutput( $this->mNewRev
->getTitle(), $this->mNewRev
->getId() ) : null;
537 $txt = $po ?
$po->getText() : '';
538 $out->addHTML( $txt );
540 } elseif ( !wfRunHooks( 'ArticleContentViewCustom', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
541 // Handled by extension
542 } elseif ( !ContentHandler
::runLegacyHooks( 'ArticleViewCustom', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
543 // NOTE: deprecated hook, B/C only
544 // Handled by extension
547 if ( $this->getTitle()->equals( $this->mNewPage
) ) {
548 // If the Title stored in the context is the same as the one
549 // of the new revision, we can use its associated WikiPage
551 $wikiPage = $this->getWikiPage();
553 // Otherwise we need to create our own WikiPage object
554 $wikiPage = WikiPage
::factory( $this->mNewPage
);
557 $parserOutput = $this->getParserOutput( $wikiPage, $this->mNewRev
);
559 # Also try to load it as a redirect
560 $rt = $this->mNewContent ?
$this->mNewContent
->getRedirectTarget() : null;
563 $article = Article
::newFromTitle( $this->mNewPage
, $this->getContext() );
564 $out->addHTML( $article->viewRedirect( $rt ) );
566 # WikiPage::getParserOutput() should not return false, but just in case
567 if ( $parserOutput ) {
568 # Show categories etc.
569 $out->addParserOutputNoText( $parserOutput );
571 } elseif ( $parserOutput ) {
572 $out->addParserOutput( $parserOutput );
576 # @codingStandardsIgnoreEnd
578 # Add redundant patrol link on bottom...
579 $out->addHTML( $this->markPatrolledLink() );
581 wfProfileOut( __METHOD__
);
584 protected function getParserOutput( WikiPage
$page, Revision
$rev ) {
585 $parserOptions = $page->makeParserOptions( $this->getContext() );
587 if ( !$rev->isCurrent() ||
!$rev->getTitle()->quickUserCan( "edit" ) ) {
588 $parserOptions->setEditSection( false );
591 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
592 return $parserOutput;
596 * Get the diff text, send it to the OutputPage object
597 * Returns false if the diff could not be generated, otherwise returns true
599 * @param string|bool $otitle Header for old text or false
600 * @param string|bool $ntitle Header for new text or false
601 * @param string $notice HTML between diff header and body
605 function showDiff( $otitle, $ntitle, $notice = '' ) {
606 $diff = $this->getDiff( $otitle, $ntitle, $notice );
607 if ( $diff === false ) {
608 $this->showMissingRevision();
611 $this->showDiffStyle();
612 $this->getOutput()->addHTML( $diff );
618 * Add style sheets and supporting JS for diff display.
620 function showDiffStyle() {
621 $this->getOutput()->addModuleStyles( 'mediawiki.action.history.diff' );
625 * Get complete diff table, including header
627 * @param string|bool $otitle Header for old text or false
628 * @param string|bool $ntitle Header for new text or false
629 * @param string $notice HTML between diff header and body
632 function getDiff( $otitle, $ntitle, $notice = '' ) {
633 $body = $this->getDiffBody();
634 if ( $body === false ) {
638 $multi = $this->getMultiNotice();
639 // Display a message when the diff is empty
640 if ( $body === '' ) {
641 $notice .= '<div class="mw-diff-empty">' .
642 $this->msg( 'diff-empty' )->parse() .
646 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
650 * Get the diff table body, without header
652 * @return mixed (string/false)
654 public function getDiffBody() {
656 wfProfileIn( __METHOD__
);
657 $this->mCacheHit
= true;
658 // Check if the diff should be hidden from this user
659 if ( !$this->loadRevisionData() ) {
660 wfProfileOut( __METHOD__
);
662 } elseif ( $this->mOldRev
&&
663 !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
665 wfProfileOut( __METHOD__
);
667 } elseif ( $this->mNewRev
&&
668 !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
670 wfProfileOut( __METHOD__
);
674 if ( $this->mOldRev
=== false ||
( $this->mOldRev
&& $this->mNewRev
675 && $this->mOldRev
->getID() == $this->mNewRev
->getID() ) )
677 wfProfileOut( __METHOD__
);
682 if ( $this->mOldid
&& $this->mNewid
) {
683 $key = $this->getDiffBodyCacheKey();
686 if ( !$this->mRefreshCache
) {
687 $difftext = $wgMemc->get( $key );
689 wfIncrStats( 'diff_cache_hit' );
690 $difftext = $this->localiseLineNumbers( $difftext );
691 $difftext .= "\n<!-- diff cache key $key -->\n";
692 wfProfileOut( __METHOD__
);
695 } // don't try to load but save the result
697 $this->mCacheHit
= false;
699 // Loadtext is permission safe, this just clears out the diff
700 if ( !$this->loadText() ) {
701 wfProfileOut( __METHOD__
);
705 $difftext = $this->generateContentDiffBody( $this->mOldContent
, $this->mNewContent
);
707 // Save to cache for 7 days
708 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
709 wfIncrStats( 'diff_uncacheable' );
710 } elseif ( $key !== false && $difftext !== false ) {
711 wfIncrStats( 'diff_cache_miss' );
712 $wgMemc->set( $key, $difftext, 7 * 86400 );
714 wfIncrStats( 'diff_uncacheable' );
716 // Replace line numbers with the text in the user's language
717 if ( $difftext !== false ) {
718 $difftext = $this->localiseLineNumbers( $difftext );
720 wfProfileOut( __METHOD__
);
725 * Returns the cache key for diff body text or content.
729 * @throws MWException
731 protected function getDiffBodyCacheKey() {
732 if ( !$this->mOldid ||
!$this->mNewid
) {
733 throw new MWException( 'mOldid and mNewid must be set to get diff cache key.' );
736 return wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
,
737 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
741 * Generate a diff, no caching.
743 * This implementation uses generateTextDiffBody() to generate a diff based on the default
744 * serialization of the given Content objects. This will fail if $old or $new are not
745 * instances of TextContent.
747 * Subclasses may override this to provide a different rendering for the diff,
748 * perhaps taking advantage of the content's native form. This is required for all content
749 * models that are not text based.
751 * @param $old Content: old content
752 * @param $new Content: new content
754 * @return bool|string
756 * @throws MWException if $old or $new are not instances of TextContent.
758 function generateContentDiffBody( Content
$old, Content
$new ) {
759 if ( !( $old instanceof TextContent
) ) {
760 throw new MWException( "Diff not implemented for " . get_class( $old ) . "; "
761 . "override generateContentDiffBody to fix this." );
764 if ( !( $new instanceof TextContent
) ) {
765 throw new MWException( "Diff not implemented for " . get_class( $new ) . "; "
766 . "override generateContentDiffBody to fix this." );
769 $otext = $old->serialize();
770 $ntext = $new->serialize();
772 return $this->generateTextDiffBody( $otext, $ntext );
776 * Generate a diff, no caching
778 * @param string $otext old text, must be already segmented
779 * @param string $ntext new text, must be already segmented
780 * @return bool|string
781 * @deprecated since 1.21, use generateContentDiffBody() instead!
783 function generateDiffBody( $otext, $ntext ) {
784 ContentHandler
::deprecated( __METHOD__
, "1.21" );
786 return $this->generateTextDiffBody( $otext, $ntext );
790 * Generate a diff, no caching
792 * @todo move this to TextDifferenceEngine, make DifferenceEngine abstract. At some point.
794 * @param string $otext old text, must be already segmented
795 * @param string $ntext new text, must be already segmented
796 * @return bool|string
798 function generateTextDiffBody( $otext, $ntext ) {
799 global $wgExternalDiffEngine, $wgContLang;
801 wfProfileIn( __METHOD__
);
803 $otext = str_replace( "\r\n", "\n", $otext );
804 $ntext = str_replace( "\r\n", "\n", $ntext );
806 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
807 # For historical reasons, external diff engine expects
808 # input text to be HTML-escaped already
809 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
810 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
811 wfProfileOut( __METHOD__
);
812 return $wgContLang->unsegmentForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
813 $this->debug( 'wikidiff1' );
816 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
817 # Better external diff engine, the 2 may some day be dropped
818 # This one does the escaping and segmenting itself
819 wfProfileIn( 'wikidiff2_do_diff' );
820 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
821 $text .= $this->debug( 'wikidiff2' );
822 wfProfileOut( 'wikidiff2_do_diff' );
823 wfProfileOut( __METHOD__
);
826 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
828 $tmpDir = wfTempDir();
829 $tempName1 = tempnam( $tmpDir, 'diff_' );
830 $tempName2 = tempnam( $tmpDir, 'diff_' );
832 $tempFile1 = fopen( $tempName1, "w" );
834 wfProfileOut( __METHOD__
);
837 $tempFile2 = fopen( $tempName2, "w" );
839 wfProfileOut( __METHOD__
);
842 fwrite( $tempFile1, $otext );
843 fwrite( $tempFile2, $ntext );
844 fclose( $tempFile1 );
845 fclose( $tempFile2 );
846 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
847 wfProfileIn( __METHOD__
. "-shellexec" );
848 $difftext = wfShellExec( $cmd );
849 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
850 wfProfileOut( __METHOD__
. "-shellexec" );
851 unlink( $tempName1 );
852 unlink( $tempName2 );
853 wfProfileOut( __METHOD__
);
858 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
859 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
860 $diffs = new Diff( $ota, $nta );
861 $formatter = new TableDiffFormatter();
862 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
863 wfProfileOut( __METHOD__
);
868 * Generate a debug comment indicating diff generating time,
869 * server node, and generator backend.
871 * @param String $generator: What diff engine was used
875 protected function debug( $generator = "internal" ) {
876 global $wgShowHostnames;
877 if ( !$this->enableDebugComment
) {
880 $data = array( $generator );
881 if ( $wgShowHostnames ) {
882 $data[] = wfHostname();
884 $data[] = wfTimestamp( TS_DB
);
885 return "<!-- diff generator: "
895 * Replace line numbers with the text in the user's language
897 * @param String $text
901 function localiseLineNumbers( $text ) {
902 return preg_replace_callback( '/<!--LINE (\d+)-->/',
903 array( &$this, 'localiseLineNumbersCb' ), $text );
906 function localiseLineNumbersCb( $matches ) {
907 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) {
910 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
914 * If there are revisions between the ones being compared, return a note saying so.
917 function getMultiNotice() {
918 if ( !is_object( $this->mOldRev
) ||
!is_object( $this->mNewRev
) ) {
920 } elseif ( !$this->mOldPage
->equals( $this->mNewPage
) ) {
921 // Comparing two different pages? Count would be meaningless.
925 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
926 $oldRev = $this->mNewRev
; // flip
927 $newRev = $this->mOldRev
; // flip
928 } else { // normal case
929 $oldRev = $this->mOldRev
;
930 $newRev = $this->mNewRev
;
933 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev );
935 $limit = 100; // use diff-multi-manyusers if too many users
936 $numUsers = $this->mNewPage
->countAuthorsBetween( $oldRev, $newRev, $limit );
937 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
939 return ''; // nothing
943 * Get a notice about how many intermediate edits and users there are
944 * @param $numEdits int
945 * @param $numUsers int
949 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
950 if ( $numUsers > $limit ) {
951 $msg = 'diff-multi-manyusers';
956 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
960 * Get a header for a specified revision.
962 * @param $rev Revision
963 * @param string $complete 'complete' to get the header wrapped depending
964 * the visibility of the revision and a link to edit the page.
965 * @return String HTML fragment
967 protected function getRevisionHeader( Revision
$rev, $complete = '' ) {
968 $lang = $this->getLanguage();
969 $user = $this->getUser();
970 $revtimestamp = $rev->getTimestamp();
971 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
972 $dateofrev = $lang->userDate( $revtimestamp, $user );
973 $timeofrev = $lang->userTime( $revtimestamp, $user );
975 $header = $this->msg(
976 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
982 if ( $complete !== 'complete' ) {
986 $title = $rev->getTitle();
988 $header = Linker
::linkKnown( $title, $header, array(),
989 array( 'oldid' => $rev->getID() ) );
991 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
992 $editQuery = array( 'action' => 'edit' );
993 if ( !$rev->isCurrent() ) {
994 $editQuery['oldid'] = $rev->getID();
997 $key = $title->quickUserCan( 'edit', $user ) ?
'editold' : 'viewsourceold';
998 $msg = $this->msg( $key )->escaped();
999 $header .= ' ' . $this->msg( 'parentheses' )->rawParams(
1000 Linker
::linkKnown( $title, $msg, array(), $editQuery ) )->plain();
1001 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
1002 $header = Html
::rawElement(
1004 array( 'class' => 'history-deleted' ),
1009 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
1016 * Add the header to a diff body
1018 * @param String $diff: Diff body
1019 * @param String $otitle: Old revision header
1020 * @param String $ntitle: New revision header
1021 * @param String $multi: Notice telling user that there are intermediate revisions between the ones being compared
1022 * @param String $notice: Other notices, e.g. that user is viewing deleted content
1026 function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
1027 // shared.css sets diff in interface language/dir, but the actual content
1028 // is often in a different language, mostly the page content language/dir
1029 $tableClass = 'diff diff-contentalign-' . htmlspecialchars( $this->getDiffLang()->alignStart() );
1030 $header = "<table class='$tableClass'>";
1032 if ( !$diff && !$otitle ) {
1034 <tr style='vertical-align: top;'>
1035 <td class='diff-ntitle'>{$ntitle}</td>
1039 if ( $diff ) { // Safari/Chrome show broken output if cols not used
1041 <col class='diff-marker' />
1042 <col class='diff-content' />
1043 <col class='diff-marker' />
1044 <col class='diff-content' />";
1051 if ( $otitle ||
$ntitle ) {
1053 <tr style='vertical-align: top;'>
1054 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
1055 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
1060 if ( $multi != '' ) {
1061 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;' " .
1062 "class='diff-multi'>{$multi}</td></tr>";
1064 if ( $notice != '' ) {
1065 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;'>{$notice}</td></tr>";
1068 return $header . $diff . "</table>";
1072 * Use specified text instead of loading from the database
1073 * @deprecated since 1.21, use setContent() instead.
1075 function setText( $oldText, $newText ) {
1076 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1078 $oldContent = ContentHandler
::makeContent( $oldText, $this->getTitle() );
1079 $newContent = ContentHandler
::makeContent( $newText, $this->getTitle() );
1081 $this->setContent( $oldContent, $newContent );
1085 * Use specified text instead of loading from the database
1088 function setContent( Content
$oldContent, Content
$newContent ) {
1089 $this->mOldContent
= $oldContent;
1090 $this->mNewContent
= $newContent;
1092 $this->mTextLoaded
= 2;
1093 $this->mRevisionsLoaded
= true;
1097 * Set the language in which the diff text is written
1098 * (Defaults to page content language).
1101 function setTextLanguage( $lang ) {
1102 $this->mDiffLang
= wfGetLangObj( $lang );
1106 * Maps a revision pair definition as accepted by DifferenceEngine constructor
1107 * to a pair of actual integers representing revision ids.
1109 * @param int $old Revision id, e.g. from URL parameter 'oldid'
1110 * @param int|string $new Revision id or strings 'next' or 'prev', e.g. from URL parameter 'diff'
1111 * @return array Array of two revision ids, older first, later second.
1112 * Zero signifies invalid argument passed.
1113 * false signifies that there is no previous/next revision ($old is the oldest/newest one).
1115 public function mapDiffPrevNext( $old, $new ) {
1116 if ( $new === 'prev' ) {
1117 // Show diff between revision $old and the previous one. Get previous one from DB.
1118 $newid = intval( $old );
1119 $oldid = $this->getTitle()->getPreviousRevisionID( $newid );
1120 } elseif ( $new === 'next' ) {
1121 // Show diff between revision $old and the next one. Get next one from DB.
1122 $oldid = intval( $old );
1123 $newid = $this->getTitle()->getNextRevisionID( $oldid );
1125 $oldid = intval( $old );
1126 $newid = intval( $new );
1129 return array( $oldid, $newid );
1135 private function loadRevisionIds() {
1136 if ( $this->mRevisionsIdsLoaded
) {
1140 $this->mRevisionsIdsLoaded
= true;
1142 $old = $this->mOldid
;
1143 $new = $this->mNewid
;
1145 list( $this->mOldid
, $this->mNewid
) = self
::mapDiffPrevNext( $old, $new );
1146 if ( $new === 'next' && $this->mNewid
=== false ) {
1147 # if no result, NewId points to the newest old revision. The only newer
1148 # revision is cur, which is "0".
1152 wfRunHooks( 'NewDifferenceEngine', array( $this->getTitle(), &$this->mOldid
, &$this->mNewid
, $old, $new ) );
1156 * Load revision metadata for the specified articles. If newid is 0, then compare
1157 * the old article in oldid to the current article; if oldid is 0, then
1158 * compare the current article to the immediately previous one (ignoring the
1161 * If oldid is false, leave the corresponding revision object set
1162 * to false. This is impossible via ordinary user input, and is provided for
1167 function loadRevisionData() {
1168 if ( $this->mRevisionsLoaded
) {
1172 // Whether it succeeds or fails, we don't want to try again
1173 $this->mRevisionsLoaded
= true;
1175 $this->loadRevisionIds();
1177 // Load the new revision object
1178 if ( $this->mNewid
) {
1179 $this->mNewRev
= Revision
::newFromId( $this->mNewid
);
1181 $this->mNewRev
= Revision
::newFromTitle(
1184 Revision
::READ_NORMAL
1188 if ( !$this->mNewRev
instanceof Revision
) {
1192 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1193 $this->mNewid
= $this->mNewRev
->getId();
1194 $this->mNewPage
= $this->mNewRev
->getTitle();
1196 // Load the old revision object
1197 $this->mOldRev
= false;
1198 if ( $this->mOldid
) {
1199 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1200 } elseif ( $this->mOldid
=== 0 ) {
1201 $rev = $this->mNewRev
->getPrevious();
1203 $this->mOldid
= $rev->getId();
1204 $this->mOldRev
= $rev;
1206 // No previous revision; mark to show as first-version only.
1207 $this->mOldid
= false;
1208 $this->mOldRev
= false;
1210 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1212 if ( is_null( $this->mOldRev
) ) {
1216 if ( $this->mOldRev
) {
1217 $this->mOldPage
= $this->mOldRev
->getTitle();
1220 // Load tags information for both revisions
1221 $dbr = wfGetDB( DB_SLAVE
);
1222 if ( $this->mOldid
!== false ) {
1223 $this->mOldTags
= $dbr->selectField(
1226 array( 'ts_rev_id' => $this->mOldid
),
1230 $this->mOldTags
= false;
1232 $this->mNewTags
= $dbr->selectField(
1235 array( 'ts_rev_id' => $this->mNewid
),
1243 * Load the text of the revisions, as well as revision data.
1247 function loadText() {
1248 if ( $this->mTextLoaded
== 2 ) {
1252 // Whether it succeeds or fails, we don't want to try again
1253 $this->mTextLoaded
= 2;
1255 if ( !$this->loadRevisionData() ) {
1259 if ( $this->mOldRev
) {
1260 $this->mOldContent
= $this->mOldRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1261 if ( $this->mOldContent
=== null ) {
1266 if ( $this->mNewRev
) {
1267 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1268 if ( $this->mNewContent
=== null ) {
1277 * Load the text of the new revision, not the old one
1281 function loadNewText() {
1282 if ( $this->mTextLoaded
>= 1 ) {
1286 $this->mTextLoaded
= 1;
1288 if ( !$this->loadRevisionData() ) {
1292 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );