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
{
68 /** @var bool Have the revisions IDs been loaded */
69 private $mRevisionsIdsLoaded = false;
71 /** @var bool Have the revisions been loaded */
72 public $mRevisionsLoaded = false;
74 /** @var int How many text blobs have been loaded, 0, 1 or 2? */
75 public $mTextLoaded = 0;
77 /** @var bool Was the diff fetched from cache? */
78 public $mCacheHit = false;
81 * Set this to true to add debug info to the HTML output.
82 * Warning: this may cause RSS readers to spuriously mark articles as "new"
85 public $enableDebugComment = false;
87 /** @var bool If true, line X is not displayed when X is 1, for example
88 * to increase readability and conserve space with many small diffs.
90 protected $mReducedLineNumbers = false;
92 /** @var string Link to action=markpatrolled */
93 protected $mMarkPatrolledLink = null;
95 /** @var bool Show rev_deleted content if allowed */
96 protected $unhide = false;
101 * @param IContextSource $context context to use, anything else will be ignored
102 * @param int $old old ID we want to show and diff with.
103 * @param string|int $new either revision ID or 'prev' or 'next'. Default: 0.
104 * @param int $rcid Deprecated, no longer used!
105 * @param bool $refreshCache If set, refreshes the diff cache
106 * @param bool $unhide If set, allow viewing deleted revs
108 function __construct( $context = null, $old = 0, $new = 0, $rcid = 0,
109 $refreshCache = false, $unhide = false ) {
110 if ( $context instanceof IContextSource
) {
111 $this->setContext( $context );
114 wfDebug( "DifferenceEngine old '$old' new '$new' rcid '$rcid'\n" );
116 $this->mOldid
= $old;
117 $this->mNewid
= $new;
118 $this->mRefreshCache
= $refreshCache;
119 $this->unhide
= $unhide;
125 function setReducedLineNumbers( $value = true ) {
126 $this->mReducedLineNumbers
= $value;
132 function getDiffLang() {
133 if ( $this->mDiffLang
=== null ) {
134 # Default language in which the diff text is written.
135 $this->mDiffLang
= $this->getTitle()->getPageLanguage();
138 return $this->mDiffLang
;
144 function wasCacheHit() {
145 return $this->mCacheHit
;
151 function getOldid() {
152 $this->loadRevisionIds();
154 return $this->mOldid
;
160 function getNewid() {
161 $this->loadRevisionIds();
163 return $this->mNewid
;
167 * Look up a special:Undelete link to the given deleted revision id,
168 * as a workaround for being unable to load deleted diffs in currently.
170 * @param int $id Revision ID
172 * @return mixed URL or false
174 function deletedLink( $id ) {
175 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
176 $dbr = wfGetDB( DB_SLAVE
);
177 $row = $dbr->selectRow( 'archive', '*',
178 array( 'ar_rev_id' => $id ),
181 $rev = Revision
::newFromArchiveRow( $row );
182 $title = Title
::makeTitleSafe( $row->ar_namespace
, $row->ar_title
);
184 return SpecialPage
::getTitleFor( 'Undelete' )->getFullURL( array(
185 'target' => $title->getPrefixedText(),
186 'timestamp' => $rev->getTimestamp()
195 * Build a wikitext link toward a deleted revision, if viewable.
197 * @param int $id Revision ID
199 * @return string Wikitext fragment
201 function deletedIdMarker( $id ) {
202 $link = $this->deletedLink( $id );
204 return "[$link $id]";
210 private function showMissingRevision() {
211 $out = $this->getOutput();
214 if ( $this->mOldRev
=== null ||
215 ( $this->mOldRev
&& $this->mOldContent
=== null )
217 $missing[] = $this->deletedIdMarker( $this->mOldid
);
219 if ( $this->mNewRev
=== null ||
220 ( $this->mNewRev
&& $this->mNewContent
=== null )
222 $missing[] = $this->deletedIdMarker( $this->mNewid
);
225 $out->setPageTitle( $this->msg( 'errorpagetitle' ) );
226 $out->addWikiMsg( 'difference-missing-revision',
227 $this->getLanguage()->listToText( $missing ), count( $missing ) );
230 function showDiffPage( $diffOnly = false ) {
231 wfProfileIn( __METHOD__
);
233 # Allow frames except in certain special cases
234 $out = $this->getOutput();
235 $out->allowClickjacking();
236 $out->setRobotPolicy( 'noindex,nofollow' );
238 if ( !$this->loadRevisionData() ) {
239 $this->showMissingRevision();
240 wfProfileOut( __METHOD__
);
245 $user = $this->getUser();
246 $permErrors = $this->mNewPage
->getUserPermissionsErrors( 'read', $user );
247 if ( $this->mOldPage
) { # mOldPage might not be set, see below.
248 $permErrors = wfMergeErrorArrays( $permErrors,
249 $this->mOldPage
->getUserPermissionsErrors( 'read', $user ) );
251 if ( count( $permErrors ) ) {
252 wfProfileOut( __METHOD__
);
253 throw new PermissionsError( 'read', $permErrors );
259 # Carry over 'diffonly' param via navigation links
260 if ( $diffOnly != $user->getBoolOption( 'diffonly' ) ) {
261 $query['diffonly'] = $diffOnly;
263 # Cascade unhide param in links for easy deletion browsing
264 if ( $this->unhide
) {
265 $query['unhide'] = 1;
268 # Check if one of the revisions is deleted/suppressed
269 $deleted = $suppressed = false;
270 $allowed = $this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $user );
272 $revisionTools = array();
274 # mOldRev is false if the difference engine is called with a "vague" query for
275 # a diff between a version V and its previous version V' AND the version V
276 # is the first version of that article. In that case, V' does not exist.
277 if ( $this->mOldRev
=== false ) {
278 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
282 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
284 if ( $this->mNewPage
->equals( $this->mOldPage
) ) {
285 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
288 $out->setPageTitle( $this->msg( 'difference-title-multipage',
289 $this->mOldPage
->getPrefixedText(), $this->mNewPage
->getPrefixedText() ) );
290 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
294 if ( $samePage && $this->mNewPage
->quickUserCan( 'edit', $user ) ) {
295 if ( $this->mNewRev
->isCurrent() && $this->mNewPage
->userCan( 'rollback', $user ) ) {
296 $rollbackLink = Linker
::generateRollback( $this->mNewRev
, $this->getContext() );
297 if ( $rollbackLink ) {
298 $out->preventClickjacking();
299 $rollback = '   ' . $rollbackLink;
303 if ( !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) &&
304 !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
)
306 $undoLink = Html
::element( 'a', array(
307 'href' => $this->mNewPage
->getLocalURL( array(
309 'undoafter' => $this->mOldid
,
310 'undo' => $this->mNewid
312 'title' => Linker
::titleAttrib( 'undo' )
314 $this->msg( 'editundo' )->text()
316 $revisionTools[] = $undoLink;
320 # Make "previous revision link"
321 if ( $samePage && $this->mOldRev
->getPrevious() ) {
322 $prevlink = Linker
::linkKnown(
324 $this->msg( 'previousdiff' )->escaped(),
325 array( 'id' => 'differences-prevlink' ),
326 array( 'diff' => 'prev', 'oldid' => $this->mOldid
) +
$query
329 $prevlink = ' ';
332 if ( $this->mOldRev
->isMinor() ) {
333 $oldminor = ChangesList
::flag( 'minor' );
338 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
339 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev
, 'complete' );
340 $oldChangeTags = ChangeTags
::formatSummaryRow( $this->mOldTags
, 'diff' );
342 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
343 '<div id="mw-diff-otitle2">' .
344 Linker
::revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
345 '<div id="mw-diff-otitle3">' . $oldminor .
346 Linker
::revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
347 '<div id="mw-diff-otitle5">' . $oldChangeTags[0] . '</div>' .
348 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
350 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
351 $deleted = true; // old revisions text is hidden
352 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
353 $suppressed = true; // also suppressed
357 # Check if this user can see the revisions
358 if ( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $user ) ) {
363 # Make "next revision link"
364 # Skip next link on the top revision
365 if ( $samePage && !$this->mNewRev
->isCurrent() ) {
366 $nextlink = Linker
::linkKnown(
368 $this->msg( 'nextdiff' )->escaped(),
369 array( 'id' => 'differences-nextlink' ),
370 array( 'diff' => 'next', 'oldid' => $this->mNewid
) +
$query
373 $nextlink = ' ';
376 if ( $this->mNewRev
->isMinor() ) {
377 $newminor = ChangesList
::flag( 'minor' );
382 # Handle RevisionDelete links...
383 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
385 # Allow extensions to define their own revision tools
386 wfRunHooks( 'DiffRevisionTools', array( $this->mNewRev
, &$revisionTools, $this->mOldRev
) );
387 $formattedRevisionTools = array();
388 // Put each one in parentheses (poor man's button)
389 foreach ( $revisionTools as $tool ) {
390 $formattedRevisionTools[] = $this->msg( 'parentheses' )->rawParams( $tool )->escaped();
392 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev
, 'complete' ) .
393 ' ' . implode( ' ', $formattedRevisionTools );
394 $newChangeTags = ChangeTags
::formatSummaryRow( $this->mNewTags
, 'diff' );
396 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
397 '<div id="mw-diff-ntitle2">' . Linker
::revUserTools( $this->mNewRev
, !$this->unhide
) .
399 '<div id="mw-diff-ntitle3">' . $newminor .
400 Linker
::revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
401 '<div id="mw-diff-ntitle5">' . $newChangeTags[0] . '</div>' .
402 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
404 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
405 $deleted = true; // new revisions text is hidden
406 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
407 $suppressed = true; // also suppressed
411 # If the diff cannot be shown due to a deleted revision, then output
412 # the diff header and links to unhide (if available)...
413 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
414 $this->showDiffStyle();
415 $multi = $this->getMultiNotice();
416 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
418 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
419 # Give explanation for why revision is not visible
420 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
423 # Give explanation and add a link to view the diff...
424 $query = $this->getRequest()->appendQueryValue( 'unhide', '1', true );
425 $link = $this->getTitle()->getFullURL( $query );
426 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
428 "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
432 # Otherwise, output a regular diff...
434 # Add deletion notice if the user is viewing deleted content
437 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
438 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" .
439 $this->msg( $msg )->parse() .
442 $this->showDiff( $oldHeader, $newHeader, $notice );
444 $this->renderNewRevision();
447 wfProfileOut( __METHOD__
);
451 * Get a link to mark the change as patrolled, or '' if there's either no
452 * revision to patrol or the user is not allowed to to it.
453 * Side effect: When the patrol link is build, this method will call
454 * OutputPage::preventClickjacking() and load mediawiki.page.patrol.ajax.
458 protected function markPatrolledLink() {
459 global $wgUseRCPatrol, $wgEnableAPI, $wgEnableWriteAPI;
460 $user = $this->getUser();
462 if ( $this->mMarkPatrolledLink
=== null ) {
463 // Prepare a change patrol link, if applicable
465 // Is patrolling enabled and the user allowed to?
466 $wgUseRCPatrol && $this->mNewPage
->quickUserCan( 'patrol', $user ) &&
467 // Only do this if the revision isn't more than 6 hours older
468 // than the Max RC age (6h because the RC might not be cleaned out regularly)
469 RecentChange
::isInRCLifespan( $this->mNewRev
->getTimestamp(), 21600 )
471 // Look for an unpatrolled change corresponding to this diff
473 $db = wfGetDB( DB_SLAVE
);
474 $change = RecentChange
::newFromConds(
476 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
477 'rc_this_oldid' => $this->mNewid
,
481 array( 'USE INDEX' => 'rc_timestamp' )
484 if ( $change && $change->getPerformer()->getName() !== $user->getName() ) {
485 $rcid = $change->getAttribute( 'rc_id' );
487 // None found or the page has been created by the current user.
488 // If the user could patrol this it already would be patrolled
493 $this->getOutput()->preventClickjacking();
494 if ( $wgEnableAPI && $wgEnableWriteAPI
495 && $user->isAllowed( 'writeapi' )
497 $this->getOutput()->addModules( 'mediawiki.page.patrol.ajax' );
500 $token = $user->getEditToken( $rcid );
501 $this->mMarkPatrolledLink
= ' <span class="patrollink">[' . Linker
::linkKnown(
503 $this->msg( 'markaspatrolleddiff' )->escaped(),
506 'action' => 'markpatrolled',
512 $this->mMarkPatrolledLink
= '';
515 $this->mMarkPatrolledLink
= '';
519 return $this->mMarkPatrolledLink
;
523 * @param Revision $rev
527 protected function revisionDeleteLink( $rev ) {
528 $link = Linker
::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
529 if ( $link !== '' ) {
530 $link = '   ' . $link . ' ';
537 * Show the new revision of the page.
539 function renderNewRevision() {
540 wfProfileIn( __METHOD__
);
541 $out = $this->getOutput();
542 $revHeader = $this->getRevisionHeader( $this->mNewRev
);
543 # Add "current version as of X" title
544 $out->addHTML( "<hr class='diff-hr' />
545 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
546 # Page content may be handled by a hooked call instead...
547 # @codingStandardsIgnoreStart Ignoring long lines.
548 if ( wfRunHooks( 'ArticleContentOnDiff', array( $this, $out ) ) ) {
549 $this->loadNewText();
550 $out->setRevisionId( $this->mNewid
);
551 $out->setRevisionTimestamp( $this->mNewRev
->getTimestamp() );
552 $out->setArticleFlag( true );
554 // NOTE: only needed for B/C: custom rendering of JS/CSS via hook
555 if ( $this->mNewPage
->isCssJsSubpage() ||
$this->mNewPage
->isCssOrJsPage() ) {
556 // Stolen from Article::view --AG 2007-10-11
557 // Give hooks a chance to customise the output
558 // @todo standardize this crap into one function
559 if ( ContentHandler
::runLegacyHooks( 'ShowRawCssJs', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
560 // NOTE: deprecated hook, B/C only
561 // use the content object's own rendering
562 $cnt = $this->mNewRev
->getContent();
563 $po = $cnt ?
$cnt->getParserOutput( $this->mNewRev
->getTitle(), $this->mNewRev
->getId() ) : null;
564 $txt = $po ?
$po->getText() : '';
565 $out->addHTML( $txt );
567 } elseif ( !wfRunHooks( 'ArticleContentViewCustom', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
568 // Handled by extension
569 } elseif ( !ContentHandler
::runLegacyHooks( 'ArticleViewCustom', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
570 // NOTE: deprecated hook, B/C only
571 // Handled by extension
574 if ( $this->getTitle()->equals( $this->mNewPage
) ) {
575 // If the Title stored in the context is the same as the one
576 // of the new revision, we can use its associated WikiPage
578 $wikiPage = $this->getWikiPage();
580 // Otherwise we need to create our own WikiPage object
581 $wikiPage = WikiPage
::factory( $this->mNewPage
);
584 $parserOutput = $this->getParserOutput( $wikiPage, $this->mNewRev
);
586 # WikiPage::getParserOutput() should not return false, but just in case
587 if ( $parserOutput ) {
588 $out->addParserOutput( $parserOutput );
592 # @codingStandardsIgnoreEnd
594 # Add redundant patrol link on bottom...
595 $out->addHTML( $this->markPatrolledLink() );
597 wfProfileOut( __METHOD__
);
600 protected function getParserOutput( WikiPage
$page, Revision
$rev ) {
601 $parserOptions = $page->makeParserOptions( $this->getContext() );
603 if ( !$rev->isCurrent() ||
!$rev->getTitle()->quickUserCan( "edit" ) ) {
604 $parserOptions->setEditSection( false );
607 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
609 return $parserOutput;
613 * Get the diff text, send it to the OutputPage object
614 * Returns false if the diff could not be generated, otherwise returns true
616 * @param string|bool $otitle Header for old text or false
617 * @param string|bool $ntitle Header for new text or false
618 * @param string $notice HTML between diff header and body
622 function showDiff( $otitle, $ntitle, $notice = '' ) {
623 $diff = $this->getDiff( $otitle, $ntitle, $notice );
624 if ( $diff === false ) {
625 $this->showMissingRevision();
629 $this->showDiffStyle();
630 $this->getOutput()->addHTML( $diff );
637 * Add style sheets and supporting JS for diff display.
639 function showDiffStyle() {
640 $this->getOutput()->addModuleStyles( 'mediawiki.action.history.diff' );
644 * Get complete diff table, including header
646 * @param string|bool $otitle Header for old text or false
647 * @param string|bool $ntitle Header for new text or false
648 * @param string $notice HTML between diff header and body
652 function getDiff( $otitle, $ntitle, $notice = '' ) {
653 $body = $this->getDiffBody();
654 if ( $body === false ) {
658 $multi = $this->getMultiNotice();
659 // Display a message when the diff is empty
660 if ( $body === '' ) {
661 $notice .= '<div class="mw-diff-empty">' .
662 $this->msg( 'diff-empty' )->parse() .
666 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
670 * Get the diff table body, without header
672 * @return mixed (string/false)
674 public function getDiffBody() {
676 wfProfileIn( __METHOD__
);
677 $this->mCacheHit
= true;
678 // Check if the diff should be hidden from this user
679 if ( !$this->loadRevisionData() ) {
680 wfProfileOut( __METHOD__
);
683 } elseif ( $this->mOldRev
&&
684 !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
686 wfProfileOut( __METHOD__
);
689 } elseif ( $this->mNewRev
&&
690 !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
692 wfProfileOut( __METHOD__
);
697 if ( $this->mOldRev
=== false ||
( $this->mOldRev
&& $this->mNewRev
698 && $this->mOldRev
->getID() == $this->mNewRev
->getID() )
700 wfProfileOut( __METHOD__
);
706 if ( $this->mOldid
&& $this->mNewid
) {
707 $key = $this->getDiffBodyCacheKey();
710 if ( !$this->mRefreshCache
) {
711 $difftext = $wgMemc->get( $key );
713 wfIncrStats( 'diff_cache_hit' );
714 $difftext = $this->localiseLineNumbers( $difftext );
715 $difftext .= "\n<!-- diff cache key $key -->\n";
716 wfProfileOut( __METHOD__
);
720 } // don't try to load but save the result
722 $this->mCacheHit
= false;
724 // Loadtext is permission safe, this just clears out the diff
725 if ( !$this->loadText() ) {
726 wfProfileOut( __METHOD__
);
731 $difftext = $this->generateContentDiffBody( $this->mOldContent
, $this->mNewContent
);
733 // Save to cache for 7 days
734 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
735 wfIncrStats( 'diff_uncacheable' );
736 } elseif ( $key !== false && $difftext !== false ) {
737 wfIncrStats( 'diff_cache_miss' );
738 $wgMemc->set( $key, $difftext, 7 * 86400 );
740 wfIncrStats( 'diff_uncacheable' );
742 // Replace line numbers with the text in the user's language
743 if ( $difftext !== false ) {
744 $difftext = $this->localiseLineNumbers( $difftext );
746 wfProfileOut( __METHOD__
);
752 * Returns the cache key for diff body text or content.
756 * @throws MWException
759 protected function getDiffBodyCacheKey() {
760 if ( !$this->mOldid ||
!$this->mNewid
) {
761 throw new MWException( 'mOldid and mNewid must be set to get diff cache key.' );
764 return wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
,
765 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
769 * Generate a diff, no caching.
771 * This implementation uses generateTextDiffBody() to generate a diff based on the default
772 * serialization of the given Content objects. This will fail if $old or $new are not
773 * instances of TextContent.
775 * Subclasses may override this to provide a different rendering for the diff,
776 * perhaps taking advantage of the content's native form. This is required for all content
777 * models that are not text based.
781 * @param Content $old Old content
782 * @param Content $new New content
784 * @throws MWException If old or new content is not an instance of TextContent.
785 * @return bool|string
787 function generateContentDiffBody( Content
$old, Content
$new ) {
788 if ( !( $old instanceof TextContent
) ) {
789 throw new MWException( "Diff not implemented for " . get_class( $old ) . "; " .
790 "override generateContentDiffBody to fix this." );
793 if ( !( $new instanceof TextContent
) ) {
794 throw new MWException( "Diff not implemented for " . get_class( $new ) . "; "
795 . "override generateContentDiffBody to fix this." );
798 $otext = $old->serialize();
799 $ntext = $new->serialize();
801 return $this->generateTextDiffBody( $otext, $ntext );
805 * Generate a diff, no caching
807 * @param string $otext Old text, must be already segmented
808 * @param string $ntext New text, must be already segmented
810 * @return bool|string
811 * @deprecated since 1.21, use generateContentDiffBody() instead!
813 function generateDiffBody( $otext, $ntext ) {
814 ContentHandler
::deprecated( __METHOD__
, "1.21" );
816 return $this->generateTextDiffBody( $otext, $ntext );
820 * Generate a diff, no caching
822 * @todo move this to TextDifferenceEngine, make DifferenceEngine abstract. At some point.
824 * @param string $otext old text, must be already segmented
825 * @param string $ntext new text, must be already segmented
827 * @return bool|string
829 function generateTextDiffBody( $otext, $ntext ) {
830 global $wgExternalDiffEngine, $wgContLang;
832 wfProfileIn( __METHOD__
);
834 $otext = str_replace( "\r\n", "\n", $otext );
835 $ntext = str_replace( "\r\n", "\n", $ntext );
837 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
838 # For historical reasons, external diff engine expects
839 # input text to be HTML-escaped already
840 $otext = htmlspecialchars( $wgContLang->segmentForDiff( $otext ) );
841 $ntext = htmlspecialchars( $wgContLang->segmentForDiff( $ntext ) );
842 wfProfileOut( __METHOD__
);
844 return $wgContLang->unsegmentForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
845 $this->debug( 'wikidiff1' );
848 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
849 # Better external diff engine, the 2 may some day be dropped
850 # This one does the escaping and segmenting itself
851 wfProfileIn( 'wikidiff2_do_diff' );
852 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
853 $text .= $this->debug( 'wikidiff2' );
854 wfProfileOut( 'wikidiff2_do_diff' );
855 wfProfileOut( __METHOD__
);
859 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
861 $tmpDir = wfTempDir();
862 $tempName1 = tempnam( $tmpDir, 'diff_' );
863 $tempName2 = tempnam( $tmpDir, 'diff_' );
865 $tempFile1 = fopen( $tempName1, "w" );
867 wfProfileOut( __METHOD__
);
871 $tempFile2 = fopen( $tempName2, "w" );
873 wfProfileOut( __METHOD__
);
877 fwrite( $tempFile1, $otext );
878 fwrite( $tempFile2, $ntext );
879 fclose( $tempFile1 );
880 fclose( $tempFile2 );
881 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
882 wfProfileIn( __METHOD__
. "-shellexec" );
883 $difftext = wfShellExec( $cmd );
884 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
885 wfProfileOut( __METHOD__
. "-shellexec" );
886 unlink( $tempName1 );
887 unlink( $tempName2 );
888 wfProfileOut( __METHOD__
);
894 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
895 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
896 $diffs = new Diff( $ota, $nta );
897 $formatter = new TableDiffFormatter();
898 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
899 wfProfileOut( __METHOD__
);
905 * Generate a debug comment indicating diff generating time,
906 * server node, and generator backend.
908 * @param string $generator : What diff engine was used
912 protected function debug( $generator = "internal" ) {
913 global $wgShowHostnames;
914 if ( !$this->enableDebugComment
) {
917 $data = array( $generator );
918 if ( $wgShowHostnames ) {
919 $data[] = wfHostname();
921 $data[] = wfTimestamp( TS_DB
);
923 return "<!-- diff generator: " .
924 implode( " ", array_map( "htmlspecialchars", $data ) ) .
929 * Replace line numbers with the text in the user's language
931 * @param string $text
935 function localiseLineNumbers( $text ) {
936 return preg_replace_callback(
937 '/<!--LINE (\d+)-->/',
938 array( &$this, 'localiseLineNumbersCb' ),
943 function localiseLineNumbersCb( $matches ) {
944 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) {
948 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
952 * If there are revisions between the ones being compared, return a note saying so.
956 function getMultiNotice() {
957 if ( !is_object( $this->mOldRev
) ||
!is_object( $this->mNewRev
) ) {
959 } elseif ( !$this->mOldPage
->equals( $this->mNewPage
) ) {
960 // Comparing two different pages? Count would be meaningless.
964 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
965 $oldRev = $this->mNewRev
; // flip
966 $newRev = $this->mOldRev
; // flip
967 } else { // normal case
968 $oldRev = $this->mOldRev
;
969 $newRev = $this->mNewRev
;
972 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev );
974 $limit = 100; // use diff-multi-manyusers if too many users
975 $users = $this->mNewPage
->getAuthorsBetween( $oldRev, $newRev, $limit );
976 $numUsers = count( $users );
978 if ( $numUsers == 1 && $users[0] == $newRev->getRawUserText() ) {
979 $numUsers = 0; // special case to say "by the same user" instead of "by one other user"
982 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
985 return ''; // nothing
989 * Get a notice about how many intermediate edits and users there are
991 * @param int $numEdits
992 * @param int $numUsers
997 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
998 if ( $numUsers === 0 ) {
999 $msg = 'diff-multi-sameuser';
1000 } elseif ( $numUsers > $limit ) {
1001 $msg = 'diff-multi-manyusers';
1004 $msg = 'diff-multi-otherusers';
1007 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
1011 * Get a header for a specified revision.
1013 * @param Revision $rev
1014 * @param string $complete 'complete' to get the header wrapped depending
1015 * the visibility of the revision and a link to edit the page.
1017 * @return string HTML fragment
1019 protected function getRevisionHeader( Revision
$rev, $complete = '' ) {
1020 $lang = $this->getLanguage();
1021 $user = $this->getUser();
1022 $revtimestamp = $rev->getTimestamp();
1023 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
1024 $dateofrev = $lang->userDate( $revtimestamp, $user );
1025 $timeofrev = $lang->userTime( $revtimestamp, $user );
1027 $header = $this->msg(
1028 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
1034 if ( $complete !== 'complete' ) {
1038 $title = $rev->getTitle();
1040 $header = Linker
::linkKnown( $title, $header, array(),
1041 array( 'oldid' => $rev->getID() ) );
1043 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
1044 $editQuery = array( 'action' => 'edit' );
1045 if ( !$rev->isCurrent() ) {
1046 $editQuery['oldid'] = $rev->getID();
1049 $key = $title->quickUserCan( 'edit', $user ) ?
'editold' : 'viewsourceold';
1050 $msg = $this->msg( $key )->escaped();
1051 $header .= ' ' . $this->msg( 'parentheses' )->rawParams(
1052 Linker
::linkKnown( $title, $msg, array(), $editQuery ) )->plain();
1053 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
1054 $header = Html
::rawElement(
1056 array( 'class' => 'history-deleted' ),
1061 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
1068 * Add the header to a diff body
1070 * @param string $diff Diff body
1071 * @param string $otitle Old revision header
1072 * @param string $ntitle New revision header
1073 * @param string $multi Notice telling user that there are intermediate
1074 * revisions between the ones being compared
1075 * @param string $notice Other notices, e.g. that user is viewing deleted content
1079 function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
1080 // shared.css sets diff in interface language/dir, but the actual content
1081 // is often in a different language, mostly the page content language/dir
1082 $tableClass = 'diff diff-contentalign-' . htmlspecialchars( $this->getDiffLang()->alignStart() );
1083 $header = "<table class='$tableClass'>";
1085 if ( !$diff && !$otitle ) {
1087 <tr style='vertical-align: top;'>
1088 <td class='diff-ntitle'>{$ntitle}</td>
1092 if ( $diff ) { // Safari/Chrome show broken output if cols not used
1094 <col class='diff-marker' />
1095 <col class='diff-content' />
1096 <col class='diff-marker' />
1097 <col class='diff-content' />";
1104 if ( $otitle ||
$ntitle ) {
1106 <tr style='vertical-align: top;'>
1107 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
1108 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
1113 if ( $multi != '' ) {
1114 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;' " .
1115 "class='diff-multi'>{$multi}</td></tr>";
1117 if ( $notice != '' ) {
1118 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;'>{$notice}</td></tr>";
1121 return $header . $diff . "</table>";
1125 * Use specified text instead of loading from the database
1126 * @deprecated since 1.21, use setContent() instead.
1128 function setText( $oldText, $newText ) {
1129 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1131 $oldContent = ContentHandler
::makeContent( $oldText, $this->getTitle() );
1132 $newContent = ContentHandler
::makeContent( $newText, $this->getTitle() );
1134 $this->setContent( $oldContent, $newContent );
1138 * Use specified text instead of loading from the database
1141 function setContent( Content
$oldContent, Content
$newContent ) {
1142 $this->mOldContent
= $oldContent;
1143 $this->mNewContent
= $newContent;
1145 $this->mTextLoaded
= 2;
1146 $this->mRevisionsLoaded
= true;
1150 * Set the language in which the diff text is written
1151 * (Defaults to page content language).
1154 function setTextLanguage( $lang ) {
1155 $this->mDiffLang
= wfGetLangObj( $lang );
1159 * Maps a revision pair definition as accepted by DifferenceEngine constructor
1160 * to a pair of actual integers representing revision ids.
1162 * @param int $old Revision id, e.g. from URL parameter 'oldid'
1163 * @param int|string $new Revision id or strings 'next' or 'prev', e.g. from URL parameter 'diff'
1165 * @return int[] List of two revision ids, older first, later second.
1166 * Zero signifies invalid argument passed.
1167 * false signifies that there is no previous/next revision ($old is the oldest/newest one).
1169 public function mapDiffPrevNext( $old, $new ) {
1170 if ( $new === 'prev' ) {
1171 // Show diff between revision $old and the previous one. Get previous one from DB.
1172 $newid = intval( $old );
1173 $oldid = $this->getTitle()->getPreviousRevisionID( $newid );
1174 } elseif ( $new === 'next' ) {
1175 // Show diff between revision $old and the next one. Get next one from DB.
1176 $oldid = intval( $old );
1177 $newid = $this->getTitle()->getNextRevisionID( $oldid );
1179 $oldid = intval( $old );
1180 $newid = intval( $new );
1183 return array( $oldid, $newid );
1189 private function loadRevisionIds() {
1190 if ( $this->mRevisionsIdsLoaded
) {
1194 $this->mRevisionsIdsLoaded
= true;
1196 $old = $this->mOldid
;
1197 $new = $this->mNewid
;
1199 list( $this->mOldid
, $this->mNewid
) = self
::mapDiffPrevNext( $old, $new );
1200 if ( $new === 'next' && $this->mNewid
=== false ) {
1201 # if no result, NewId points to the newest old revision. The only newer
1202 # revision is cur, which is "0".
1207 'NewDifferenceEngine',
1208 array( $this->getTitle(), &$this->mOldid
, &$this->mNewid
, $old, $new )
1213 * Load revision metadata for the specified articles. If newid is 0, then compare
1214 * the old article in oldid to the current article; if oldid is 0, then
1215 * compare the current article to the immediately previous one (ignoring the
1218 * If oldid is false, leave the corresponding revision object set
1219 * to false. This is impossible via ordinary user input, and is provided for
1224 function loadRevisionData() {
1225 if ( $this->mRevisionsLoaded
) {
1229 // Whether it succeeds or fails, we don't want to try again
1230 $this->mRevisionsLoaded
= true;
1232 $this->loadRevisionIds();
1234 // Load the new revision object
1235 if ( $this->mNewid
) {
1236 $this->mNewRev
= Revision
::newFromId( $this->mNewid
);
1238 $this->mNewRev
= Revision
::newFromTitle(
1241 Revision
::READ_NORMAL
1245 if ( !$this->mNewRev
instanceof Revision
) {
1249 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1250 $this->mNewid
= $this->mNewRev
->getId();
1251 $this->mNewPage
= $this->mNewRev
->getTitle();
1253 // Load the old revision object
1254 $this->mOldRev
= false;
1255 if ( $this->mOldid
) {
1256 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1257 } elseif ( $this->mOldid
=== 0 ) {
1258 $rev = $this->mNewRev
->getPrevious();
1260 $this->mOldid
= $rev->getId();
1261 $this->mOldRev
= $rev;
1263 // No previous revision; mark to show as first-version only.
1264 $this->mOldid
= false;
1265 $this->mOldRev
= false;
1267 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1269 if ( is_null( $this->mOldRev
) ) {
1273 if ( $this->mOldRev
) {
1274 $this->mOldPage
= $this->mOldRev
->getTitle();
1277 // Load tags information for both revisions
1278 $dbr = wfGetDB( DB_SLAVE
);
1279 if ( $this->mOldid
!== false ) {
1280 $this->mOldTags
= $dbr->selectField(
1283 array( 'ts_rev_id' => $this->mOldid
),
1287 $this->mOldTags
= false;
1289 $this->mNewTags
= $dbr->selectField(
1292 array( 'ts_rev_id' => $this->mNewid
),
1300 * Load the text of the revisions, as well as revision data.
1304 function loadText() {
1305 if ( $this->mTextLoaded
== 2 ) {
1309 // Whether it succeeds or fails, we don't want to try again
1310 $this->mTextLoaded
= 2;
1312 if ( !$this->loadRevisionData() ) {
1316 if ( $this->mOldRev
) {
1317 $this->mOldContent
= $this->mOldRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1318 if ( $this->mOldContent
=== null ) {
1323 if ( $this->mNewRev
) {
1324 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1325 if ( $this->mNewContent
=== null ) {
1334 * Load the text of the new revision, not the old one
1338 function loadNewText() {
1339 if ( $this->mTextLoaded
>= 1 ) {
1343 $this->mTextLoaded
= 1;
1345 if ( !$this->loadRevisionData() ) {
1349 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );