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 '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 );
236 # Carry over 'diffonly' param via navigation links
237 if ( $diffOnly != $user->getBoolOption( 'diffonly' ) ) {
238 $query['diffonly'] = $diffOnly;
240 # Cascade unhide param in links for easy deletion browsing
241 if ( $this->unhide
) {
242 $query['unhide'] = 1;
245 # Check if one of the revisions is deleted/suppressed
246 $deleted = $suppressed = false;
247 $allowed = $this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $user );
249 $revisionTools = array();
251 # mOldRev is false if the difference engine is called with a "vague" query for
252 # a diff between a version V and its previous version V' AND the version V
253 # is the first version of that article. In that case, V' does not exist.
254 if ( $this->mOldRev
=== false ) {
255 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
259 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
261 if ( $this->mNewPage
->equals( $this->mOldPage
) ) {
262 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
265 $out->setPageTitle( $this->msg( 'difference-title-multipage',
266 $this->mOldPage
->getPrefixedText(), $this->mNewPage
->getPrefixedText() ) );
267 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
271 if ( $samePage && $this->mNewPage
->quickUserCan( 'edit', $user ) ) {
272 if ( $this->mNewRev
->isCurrent() && $this->mNewPage
->userCan( 'rollback', $user ) ) {
273 $rollbackLink = Linker
::generateRollback( $this->mNewRev
, $this->getContext() );
274 if ( $rollbackLink ) {
275 $out->preventClickjacking();
276 $rollback = '   ' . $rollbackLink;
280 if ( !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) &&
281 !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
)
283 $undoLink = Html
::element( 'a', array(
284 'href' => $this->mNewPage
->getLocalURL( array(
286 'undoafter' => $this->mOldid
,
287 'undo' => $this->mNewid
) ),
288 'title' => Linker
::titleAttrib( 'undo' )
290 $this->msg( 'editundo' )->text()
292 $revisionTools[] = $undoLink;
296 # Make "previous revision link"
297 if ( $samePage && $this->mOldRev
->getPrevious() ) {
298 $prevlink = Linker
::linkKnown(
300 $this->msg( 'previousdiff' )->escaped(),
301 array( 'id' => 'differences-prevlink' ),
302 array( 'diff' => 'prev', 'oldid' => $this->mOldid
) +
$query
305 $prevlink = ' ';
308 if ( $this->mOldRev
->isMinor() ) {
309 $oldminor = ChangesList
::flag( 'minor' );
314 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
315 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev
, 'complete' );
316 $oldChangeTags = ChangeTags
::formatSummaryRow( $this->mOldTags
, 'diff' );
318 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
319 '<div id="mw-diff-otitle2">' .
320 Linker
::revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
321 '<div id="mw-diff-otitle3">' . $oldminor .
322 Linker
::revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
323 '<div id="mw-diff-otitle5">' . $oldChangeTags[0] . '</div>' .
324 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
326 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
327 $deleted = true; // old revisions text is hidden
328 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
329 $suppressed = true; // also suppressed
333 # Check if this user can see the revisions
334 if ( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $user ) ) {
339 # Make "next revision link"
340 # Skip next link on the top revision
341 if ( $samePage && !$this->mNewRev
->isCurrent() ) {
342 $nextlink = Linker
::linkKnown(
344 $this->msg( 'nextdiff' )->escaped(),
345 array( 'id' => 'differences-nextlink' ),
346 array( 'diff' => 'next', 'oldid' => $this->mNewid
) +
$query
349 $nextlink = ' ';
352 if ( $this->mNewRev
->isMinor() ) {
353 $newminor = ChangesList
::flag( 'minor' );
358 # Handle RevisionDelete links...
359 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
361 # Allow extensions to define their own revision tools
362 wfRunHooks( 'DiffRevisionTools', array( $this->mNewRev
, &$revisionTools ) );
363 $formattedRevisionTools = array();
364 // Put each one in parentheses (poor man's button)
365 foreach ( $revisionTools as $tool ) {
366 $formattedRevisionTools[] = $this->msg( 'parentheses' )->rawParams( $tool )->escaped();
368 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev
, 'complete' ) .
369 ' ' . implode( ' ', $formattedRevisionTools );
370 $newChangeTags = ChangeTags
::formatSummaryRow( $this->mNewTags
, 'diff' );
372 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
373 '<div id="mw-diff-ntitle2">' . Linker
::revUserTools( $this->mNewRev
, !$this->unhide
) .
375 '<div id="mw-diff-ntitle3">' . $newminor .
376 Linker
::revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
377 '<div id="mw-diff-ntitle5">' . $newChangeTags[0] . '</div>' .
378 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
380 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
381 $deleted = true; // new revisions text is hidden
382 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
383 $suppressed = true; // also suppressed
387 # If the diff cannot be shown due to a deleted revision, then output
388 # the diff header and links to unhide (if available)...
389 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
390 $this->showDiffStyle();
391 $multi = $this->getMultiNotice();
392 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
394 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
395 # Give explanation for why revision is not visible
396 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
399 # Give explanation and add a link to view the diff...
400 $query = $this->getRequest()->appendQueryValue( 'unhide', '1', true );
401 $link = $this->getTitle()->getFullURL( $query );
402 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
404 "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
408 # Otherwise, output a regular diff...
410 # Add deletion notice if the user is viewing deleted content
413 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
414 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" .
415 $this->msg( $msg )->parse() .
418 $this->showDiff( $oldHeader, $newHeader, $notice );
420 $this->renderNewRevision();
423 wfProfileOut( __METHOD__
);
427 * Get a link to mark the change as patrolled, or '' if there's either no
428 * revision to patrol or the user is not allowed to to it.
429 * Side effect: When the patrol link is build, this method will call
430 * OutputPage::preventClickjacking() and load mediawiki.page.patrol.ajax.
434 protected function markPatrolledLink() {
435 global $wgUseRCPatrol, $wgEnableAPI, $wgEnableWriteAPI;
436 $user = $this->getUser();
438 if ( $this->mMarkPatrolledLink
=== null ) {
439 // Prepare a change patrol link, if applicable
441 // Is patrolling enabled and the user allowed to?
442 $wgUseRCPatrol && $this->mNewPage
->quickUserCan( 'patrol', $user ) &&
443 // Only do this if the revision isn't more than 6 hours older
444 // than the Max RC age (6h because the RC might not be cleaned out regularly)
445 RecentChange
::isInRCLifespan( $this->mNewRev
->getTimestamp(), 21600 )
447 // Look for an unpatrolled change corresponding to this diff
449 $db = wfGetDB( DB_SLAVE
);
450 $change = RecentChange
::newFromConds(
452 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
453 'rc_this_oldid' => $this->mNewid
,
457 array( 'USE INDEX' => 'rc_timestamp' )
460 if ( $change && $change->getPerformer()->getName() !== $user->getName() ) {
461 $rcid = $change->getAttribute( 'rc_id' );
463 // None found or the page has been created by the current user.
464 // If the user could patrol this it already would be patrolled
469 $this->getOutput()->preventClickjacking();
470 if ( $wgEnableAPI && $wgEnableWriteAPI
471 && $user->isAllowed( 'writeapi' )
473 $this->getOutput()->addModules( 'mediawiki.page.patrol.ajax' );
476 $token = $user->getEditToken( $rcid );
477 $this->mMarkPatrolledLink
= ' <span class="patrollink">[' . Linker
::linkKnown(
479 $this->msg( 'markaspatrolleddiff' )->escaped(),
482 'action' => 'markpatrolled',
488 $this->mMarkPatrolledLink
= '';
491 $this->mMarkPatrolledLink
= '';
495 return $this->mMarkPatrolledLink
;
499 * @param $rev Revision
502 protected function revisionDeleteLink( $rev ) {
503 $link = Linker
::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
504 if ( $link !== '' ) {
505 $link = '   ' . $link . ' ';
511 * Show the new revision of the page.
513 function renderNewRevision() {
514 wfProfileIn( __METHOD__
);
515 $out = $this->getOutput();
516 $revHeader = $this->getRevisionHeader( $this->mNewRev
);
517 # Add "current version as of X" title
518 $out->addHTML( "<hr class='diff-hr' />
519 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
520 # Page content may be handled by a hooked call instead...
521 # @codingStandardsIgnoreStart Ignoring long lines.
522 if ( wfRunHooks( 'ArticleContentOnDiff', array( $this, $out ) ) ) {
523 $this->loadNewText();
524 $out->setRevisionId( $this->mNewid
);
525 $out->setRevisionTimestamp( $this->mNewRev
->getTimestamp() );
526 $out->setArticleFlag( true );
528 // NOTE: only needed for B/C: custom rendering of JS/CSS via hook
529 if ( $this->mNewPage
->isCssJsSubpage() ||
$this->mNewPage
->isCssOrJsPage() ) {
530 // Stolen from Article::view --AG 2007-10-11
531 // Give hooks a chance to customise the output
532 // @todo standardize this crap into one function
533 if ( ContentHandler
::runLegacyHooks( 'ShowRawCssJs', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
534 // NOTE: deprecated hook, B/C only
535 // use the content object's own rendering
536 $cnt = $this->mNewRev
->getContent();
537 $po = $cnt ?
$cnt->getParserOutput( $this->mNewRev
->getTitle(), $this->mNewRev
->getId() ) : null;
538 $txt = $po ?
$po->getText() : '';
539 $out->addHTML( $txt );
541 } elseif ( !wfRunHooks( 'ArticleContentViewCustom', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
542 // Handled by extension
543 } elseif ( !ContentHandler
::runLegacyHooks( 'ArticleViewCustom', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
544 // NOTE: deprecated hook, B/C only
545 // Handled by extension
548 if ( $this->getTitle()->equals( $this->mNewPage
) ) {
549 // If the Title stored in the context is the same as the one
550 // of the new revision, we can use its associated WikiPage
552 $wikiPage = $this->getWikiPage();
554 // Otherwise we need to create our own WikiPage object
555 $wikiPage = WikiPage
::factory( $this->mNewPage
);
558 $parserOutput = $this->getParserOutput( $wikiPage, $this->mNewRev
);
560 # Also try to load it as a redirect
561 $rt = $this->mNewContent ?
$this->mNewContent
->getRedirectTarget() : null;
564 $article = Article
::newFromTitle( $this->mNewPage
, $this->getContext() );
565 $out->addHTML( $article->viewRedirect( $rt ) );
567 # WikiPage::getParserOutput() should not return false, but just in case
568 if ( $parserOutput ) {
569 # Show categories etc.
570 $out->addParserOutputNoText( $parserOutput );
572 } elseif ( $parserOutput ) {
573 $out->addParserOutput( $parserOutput );
577 # @codingStandardsIgnoreEnd
579 # Add redundant patrol link on bottom...
580 $out->addHTML( $this->markPatrolledLink() );
582 wfProfileOut( __METHOD__
);
585 protected function getParserOutput( WikiPage
$page, Revision
$rev ) {
586 $parserOptions = $page->makeParserOptions( $this->getContext() );
588 if ( !$rev->isCurrent() ||
!$rev->getTitle()->quickUserCan( "edit" ) ) {
589 $parserOptions->setEditSection( false );
592 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
593 return $parserOutput;
597 * Get the diff text, send it to the OutputPage object
598 * Returns false if the diff could not be generated, otherwise returns true
600 * @param string|bool $otitle Header for old text or false
601 * @param string|bool $ntitle Header for new text or false
602 * @param string $notice
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.
872 protected function debug( $generator = "internal" ) {
873 global $wgShowHostnames;
874 if ( !$this->enableDebugComment
) {
877 $data = array( $generator );
878 if ( $wgShowHostnames ) {
879 $data[] = wfHostname();
881 $data[] = wfTimestamp( TS_DB
);
882 return "<!-- diff generator: " .
891 * Replace line numbers with the text in the user's language
894 function localiseLineNumbers( $text ) {
895 return preg_replace_callback( '/<!--LINE (\d+)-->/',
896 array( &$this, 'localiseLineNumbersCb' ), $text );
899 function localiseLineNumbersCb( $matches ) {
900 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) {
903 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
907 * If there are revisions between the ones being compared, return a note saying so.
910 function getMultiNotice() {
911 if ( !is_object( $this->mOldRev
) ||
!is_object( $this->mNewRev
) ) {
913 } elseif ( !$this->mOldPage
->equals( $this->mNewPage
) ) {
914 // Comparing two different pages? Count would be meaningless.
918 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
919 $oldRev = $this->mNewRev
; // flip
920 $newRev = $this->mOldRev
; // flip
921 } else { // normal case
922 $oldRev = $this->mOldRev
;
923 $newRev = $this->mNewRev
;
926 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev );
928 $limit = 100; // use diff-multi-manyusers if too many users
929 $numUsers = $this->mNewPage
->countAuthorsBetween( $oldRev, $newRev, $limit );
930 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
932 return ''; // nothing
936 * Get a notice about how many intermediate edits and users there are
937 * @param $numEdits int
938 * @param $numUsers int
942 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
943 if ( $numUsers > $limit ) {
944 $msg = 'diff-multi-manyusers';
949 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
953 * Get a header for a specified revision.
955 * @param $rev Revision
956 * @param string $complete 'complete' to get the header wrapped depending
957 * the visibility of the revision and a link to edit the page.
958 * @return String HTML fragment
960 protected function getRevisionHeader( Revision
$rev, $complete = '' ) {
961 $lang = $this->getLanguage();
962 $user = $this->getUser();
963 $revtimestamp = $rev->getTimestamp();
964 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
965 $dateofrev = $lang->userDate( $revtimestamp, $user );
966 $timeofrev = $lang->userTime( $revtimestamp, $user );
968 $header = $this->msg(
969 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
975 if ( $complete !== 'complete' ) {
979 $title = $rev->getTitle();
981 $header = Linker
::linkKnown( $title, $header, array(),
982 array( 'oldid' => $rev->getID() ) );
984 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
985 $editQuery = array( 'action' => 'edit' );
986 if ( !$rev->isCurrent() ) {
987 $editQuery['oldid'] = $rev->getID();
990 $key = $title->quickUserCan( 'edit', $user ) ?
'editold' : 'viewsourceold';
991 $msg = $this->msg( $key )->escaped();
992 $header .= ' ' . $this->msg( 'parentheses' )->rawParams(
993 Linker
::linkKnown( $title, $msg, array(), $editQuery ) )->plain();
994 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
995 $header = Html
::rawElement(
997 array( 'class' => 'history-deleted' ),
1002 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
1009 * Add the header to a diff body
1013 function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
1014 // shared.css sets diff in interface language/dir, but the actual content
1015 // is often in a different language, mostly the page content language/dir
1016 $tableClass = 'diff diff-contentalign-' . htmlspecialchars( $this->getDiffLang()->alignStart() );
1017 $header = "<table class='$tableClass'>";
1019 if ( !$diff && !$otitle ) {
1021 <tr style='vertical-align: top;'>
1022 <td class='diff-ntitle'>{$ntitle}</td>
1026 if ( $diff ) { // Safari/Chrome show broken output if cols not used
1028 <col class='diff-marker' />
1029 <col class='diff-content' />
1030 <col class='diff-marker' />
1031 <col class='diff-content' />";
1038 if ( $otitle ||
$ntitle ) {
1040 <tr style='vertical-align: top;'>
1041 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
1042 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
1047 if ( $multi != '' ) {
1048 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;' " .
1049 "class='diff-multi'>{$multi}</td></tr>";
1051 if ( $notice != '' ) {
1052 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;'>{$notice}</td></tr>";
1055 return $header . $diff . "</table>";
1059 * Use specified text instead of loading from the database
1060 * @deprecated since 1.21, use setContent() instead.
1062 function setText( $oldText, $newText ) {
1063 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1065 $oldContent = ContentHandler
::makeContent( $oldText, $this->getTitle() );
1066 $newContent = ContentHandler
::makeContent( $newText, $this->getTitle() );
1068 $this->setContent( $oldContent, $newContent );
1072 * Use specified text instead of loading from the database
1075 function setContent( Content
$oldContent, Content
$newContent ) {
1076 $this->mOldContent
= $oldContent;
1077 $this->mNewContent
= $newContent;
1079 $this->mTextLoaded
= 2;
1080 $this->mRevisionsLoaded
= true;
1084 * Set the language in which the diff text is written
1085 * (Defaults to page content language).
1088 function setTextLanguage( $lang ) {
1089 $this->mDiffLang
= wfGetLangObj( $lang );
1093 * Maps a revision pair definition as accepted by DifferenceEngine constructor
1094 * to a pair of actual integers representing revision ids.
1096 * @param int $old Revision id, e.g. from URL parameter 'oldid'
1097 * @param int|string $new Revision id or strings 'next' or 'prev', e.g. from URL parameter 'diff'
1098 * @return array Array of two revision ids, older first, later second.
1099 * Zero signifies invalid argument passed.
1100 * false signifies that there is no previous/next revision ($old is the oldest/newest one).
1102 public function mapDiffPrevNext( $old, $new ) {
1103 if ( $new === 'prev' ) {
1104 // Show diff between revision $old and the previous one. Get previous one from DB.
1105 $newid = intval( $old );
1106 $oldid = $this->getTitle()->getPreviousRevisionID( $newid );
1107 } elseif ( $new === 'next' ) {
1108 // Show diff between revision $old and the next one. Get next one from DB.
1109 $oldid = intval( $old );
1110 $newid = $this->getTitle()->getNextRevisionID( $oldid );
1112 $oldid = intval( $old );
1113 $newid = intval( $new );
1116 return array( $oldid, $newid );
1122 private function loadRevisionIds() {
1123 if ( $this->mRevisionsIdsLoaded
) {
1127 $this->mRevisionsIdsLoaded
= true;
1129 $old = $this->mOldid
;
1130 $new = $this->mNewid
;
1132 list( $this->mOldid
, $this->mNewid
) = self
::mapDiffPrevNext( $old, $new );
1133 if ( $new === 'next' && $this->mNewid
=== false ) {
1134 # if no result, NewId points to the newest old revision. The only newer
1135 # revision is cur, which is "0".
1139 wfRunHooks( 'NewDifferenceEngine', array( $this->getTitle(), &$this->mOldid
, &$this->mNewid
, $old, $new ) );
1143 * Load revision metadata for the specified articles. If newid is 0, then compare
1144 * the old article in oldid to the current article; if oldid is 0, then
1145 * compare the current article to the immediately previous one (ignoring the
1148 * If oldid is false, leave the corresponding revision object set
1149 * to false. This is impossible via ordinary user input, and is provided for
1154 function loadRevisionData() {
1155 if ( $this->mRevisionsLoaded
) {
1159 // Whether it succeeds or fails, we don't want to try again
1160 $this->mRevisionsLoaded
= true;
1162 $this->loadRevisionIds();
1164 // Load the new revision object
1165 if ( $this->mNewid
) {
1166 $this->mNewRev
= Revision
::newFromId( $this->mNewid
);
1168 $this->mNewRev
= Revision
::newFromTitle(
1171 Revision
::READ_NORMAL
1175 if ( !$this->mNewRev
instanceof Revision
) {
1179 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1180 $this->mNewid
= $this->mNewRev
->getId();
1181 $this->mNewPage
= $this->mNewRev
->getTitle();
1183 // Load the old revision object
1184 $this->mOldRev
= false;
1185 if ( $this->mOldid
) {
1186 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1187 } elseif ( $this->mOldid
=== 0 ) {
1188 $rev = $this->mNewRev
->getPrevious();
1190 $this->mOldid
= $rev->getId();
1191 $this->mOldRev
= $rev;
1193 // No previous revision; mark to show as first-version only.
1194 $this->mOldid
= false;
1195 $this->mOldRev
= false;
1197 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1199 if ( is_null( $this->mOldRev
) ) {
1203 if ( $this->mOldRev
) {
1204 $this->mOldPage
= $this->mOldRev
->getTitle();
1207 // Load tags information for both revisions
1208 $dbr = wfGetDB( DB_SLAVE
);
1209 if ( $this->mOldid
!== false ) {
1210 $this->mOldTags
= $dbr->selectField(
1213 array( 'ts_rev_id' => $this->mOldid
),
1217 $this->mOldTags
= false;
1219 $this->mNewTags
= $dbr->selectField(
1222 array( 'ts_rev_id' => $this->mNewid
),
1230 * Load the text of the revisions, as well as revision data.
1234 function loadText() {
1235 if ( $this->mTextLoaded
== 2 ) {
1239 // Whether it succeeds or fails, we don't want to try again
1240 $this->mTextLoaded
= 2;
1242 if ( !$this->loadRevisionData() ) {
1246 if ( $this->mOldRev
) {
1247 $this->mOldContent
= $this->mOldRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1248 if ( $this->mOldContent
=== null ) {
1253 if ( $this->mNewRev
) {
1254 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1255 if ( $this->mNewContent
=== null ) {
1264 * Load the text of the new revision, not the old one
1268 function loadNewText() {
1269 if ( $this->mTextLoaded
>= 1 ) {
1273 $this->mTextLoaded
= 1;
1275 if ( !$this->loadRevisionData() ) {
1279 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );