ee918f3785a15d370e1573a569345a39f8c1714c
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 public function __construct( $context = null, $old = 0, $new = 0, $rcid = 0,
109 $refreshCache = false, $unhide = false
111 if ( $context instanceof IContextSource
) {
112 $this->setContext( $context );
115 wfDebug( "DifferenceEngine old '$old' new '$new' rcid '$rcid'\n" );
117 $this->mOldid
= $old;
118 $this->mNewid
= $new;
119 $this->mRefreshCache
= $refreshCache;
120 $this->unhide
= $unhide;
126 public function setReducedLineNumbers( $value = true ) {
127 $this->mReducedLineNumbers
= $value;
133 public function getDiffLang() {
134 if ( $this->mDiffLang
=== null ) {
135 # Default language in which the diff text is written.
136 $this->mDiffLang
= $this->getTitle()->getPageLanguage();
139 return $this->mDiffLang
;
145 public function wasCacheHit() {
146 return $this->mCacheHit
;
152 public function getOldid() {
153 $this->loadRevisionIds();
155 return $this->mOldid
;
161 public function getNewid() {
162 $this->loadRevisionIds();
164 return $this->mNewid
;
168 * Look up a special:Undelete link to the given deleted revision id,
169 * as a workaround for being unable to load deleted diffs in currently.
171 * @param int $id Revision ID
173 * @return mixed URL or false
175 public function deletedLink( $id ) {
176 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
177 $dbr = wfGetDB( DB_SLAVE
);
178 $row = $dbr->selectRow( 'archive', '*',
179 array( 'ar_rev_id' => $id ),
182 $rev = Revision
::newFromArchiveRow( $row );
183 $title = Title
::makeTitleSafe( $row->ar_namespace
, $row->ar_title
);
185 return SpecialPage
::getTitleFor( 'Undelete' )->getFullURL( array(
186 'target' => $title->getPrefixedText(),
187 'timestamp' => $rev->getTimestamp()
196 * Build a wikitext link toward a deleted revision, if viewable.
198 * @param int $id Revision ID
200 * @return string Wikitext fragment
202 public function deletedIdMarker( $id ) {
203 $link = $this->deletedLink( $id );
205 return "[$link $id]";
211 private function showMissingRevision() {
212 $out = $this->getOutput();
215 if ( $this->mOldRev
=== null ||
216 ( $this->mOldRev
&& $this->mOldContent
=== null )
218 $missing[] = $this->deletedIdMarker( $this->mOldid
);
220 if ( $this->mNewRev
=== null ||
221 ( $this->mNewRev
&& $this->mNewContent
=== null )
223 $missing[] = $this->deletedIdMarker( $this->mNewid
);
226 $out->setPageTitle( $this->msg( 'errorpagetitle' ) );
227 $out->addWikiMsg( 'difference-missing-revision',
228 $this->getLanguage()->listToText( $missing ), count( $missing ) );
231 public function showDiffPage( $diffOnly = false ) {
232 wfProfileIn( __METHOD__
);
234 # Allow frames except in certain special cases
235 $out = $this->getOutput();
236 $out->allowClickjacking();
237 $out->setRobotPolicy( 'noindex,nofollow' );
239 if ( !$this->loadRevisionData() ) {
240 $this->showMissingRevision();
241 wfProfileOut( __METHOD__
);
246 $user = $this->getUser();
247 $permErrors = $this->mNewPage
->getUserPermissionsErrors( 'read', $user );
248 if ( $this->mOldPage
) { # mOldPage might not be set, see below.
249 $permErrors = wfMergeErrorArrays( $permErrors,
250 $this->mOldPage
->getUserPermissionsErrors( 'read', $user ) );
252 if ( count( $permErrors ) ) {
253 wfProfileOut( __METHOD__
);
254 throw new PermissionsError( 'read', $permErrors );
260 # Carry over 'diffonly' param via navigation links
261 if ( $diffOnly != $user->getBoolOption( 'diffonly' ) ) {
262 $query['diffonly'] = $diffOnly;
264 # Cascade unhide param in links for easy deletion browsing
265 if ( $this->unhide
) {
266 $query['unhide'] = 1;
269 # Check if one of the revisions is deleted/suppressed
270 $deleted = $suppressed = false;
271 $allowed = $this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $user );
273 $revisionTools = array();
275 # mOldRev is false if the difference engine is called with a "vague" query for
276 # a diff between a version V and its previous version V' AND the version V
277 # is the first version of that article. In that case, V' does not exist.
278 if ( $this->mOldRev
=== false ) {
279 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
283 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev
, $this->mNewRev
) );
285 if ( $this->mNewPage
->equals( $this->mOldPage
) ) {
286 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
289 $out->setPageTitle( $this->msg( 'difference-title-multipage',
290 $this->mOldPage
->getPrefixedText(), $this->mNewPage
->getPrefixedText() ) );
291 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
295 if ( $samePage && $this->mNewPage
->quickUserCan( 'edit', $user ) ) {
296 if ( $this->mNewRev
->isCurrent() && $this->mNewPage
->userCan( 'rollback', $user ) ) {
297 $rollbackLink = Linker
::generateRollback( $this->mNewRev
, $this->getContext() );
298 if ( $rollbackLink ) {
299 $out->preventClickjacking();
300 $rollback = '   ' . $rollbackLink;
304 if ( !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) &&
305 !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
)
307 $undoLink = Html
::element( 'a', array(
308 'href' => $this->mNewPage
->getLocalURL( array(
310 'undoafter' => $this->mOldid
,
311 'undo' => $this->mNewid
313 'title' => Linker
::titleAttrib( 'undo' )
315 $this->msg( 'editundo' )->text()
317 $revisionTools[] = $undoLink;
321 # Make "previous revision link"
322 if ( $samePage && $this->mOldRev
->getPrevious() ) {
323 $prevlink = Linker
::linkKnown(
325 $this->msg( 'previousdiff' )->escaped(),
326 array( 'id' => 'differences-prevlink' ),
327 array( 'diff' => 'prev', 'oldid' => $this->mOldid
) +
$query
330 $prevlink = ' ';
333 if ( $this->mOldRev
->isMinor() ) {
334 $oldminor = ChangesList
::flag( 'minor' );
339 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
340 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev
, 'complete' );
341 $oldChangeTags = ChangeTags
::formatSummaryRow( $this->mOldTags
, 'diff' );
343 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
344 '<div id="mw-diff-otitle2">' .
345 Linker
::revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
346 '<div id="mw-diff-otitle3">' . $oldminor .
347 Linker
::revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
348 '<div id="mw-diff-otitle5">' . $oldChangeTags[0] . '</div>' .
349 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
351 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
352 $deleted = true; // old revisions text is hidden
353 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
354 $suppressed = true; // also suppressed
358 # Check if this user can see the revisions
359 if ( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $user ) ) {
364 # Make "next revision link"
365 # Skip next link on the top revision
366 if ( $samePage && !$this->mNewRev
->isCurrent() ) {
367 $nextlink = Linker
::linkKnown(
369 $this->msg( 'nextdiff' )->escaped(),
370 array( 'id' => 'differences-nextlink' ),
371 array( 'diff' => 'next', 'oldid' => $this->mNewid
) +
$query
374 $nextlink = ' ';
377 if ( $this->mNewRev
->isMinor() ) {
378 $newminor = ChangesList
::flag( 'minor' );
383 # Handle RevisionDelete links...
384 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
386 # Allow extensions to define their own revision tools
387 wfRunHooks( 'DiffRevisionTools', array( $this->mNewRev
, &$revisionTools, $this->mOldRev
) );
388 $formattedRevisionTools = array();
389 // Put each one in parentheses (poor man's button)
390 foreach ( $revisionTools as $tool ) {
391 $formattedRevisionTools[] = $this->msg( 'parentheses' )->rawParams( $tool )->escaped();
393 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev
, 'complete' ) .
394 ' ' . implode( ' ', $formattedRevisionTools );
395 $newChangeTags = ChangeTags
::formatSummaryRow( $this->mNewTags
, 'diff' );
397 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
398 '<div id="mw-diff-ntitle2">' . Linker
::revUserTools( $this->mNewRev
, !$this->unhide
) .
400 '<div id="mw-diff-ntitle3">' . $newminor .
401 Linker
::revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
402 '<div id="mw-diff-ntitle5">' . $newChangeTags[0] . '</div>' .
403 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
405 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
406 $deleted = true; // new revisions text is hidden
407 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
408 $suppressed = true; // also suppressed
412 # If the diff cannot be shown due to a deleted revision, then output
413 # the diff header and links to unhide (if available)...
414 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
415 $this->showDiffStyle();
416 $multi = $this->getMultiNotice();
417 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
419 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
420 # Give explanation for why revision is not visible
421 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
424 # Give explanation and add a link to view the diff...
425 $query = $this->getRequest()->appendQueryValue( 'unhide', '1', true );
426 $link = $this->getTitle()->getFullURL( $query );
427 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
429 "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
433 # Otherwise, output a regular diff...
435 # Add deletion notice if the user is viewing deleted content
438 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
439 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" .
440 $this->msg( $msg )->parse() .
443 $this->showDiff( $oldHeader, $newHeader, $notice );
445 $this->renderNewRevision();
448 wfProfileOut( __METHOD__
);
452 * Get a link to mark the change as patrolled, or '' if there's either no
453 * revision to patrol or the user is not allowed to to it.
454 * Side effect: When the patrol link is build, this method will call
455 * OutputPage::preventClickjacking() and load mediawiki.page.patrol.ajax.
459 protected function markPatrolledLink() {
460 global $wgUseRCPatrol, $wgEnableAPI, $wgEnableWriteAPI;
461 $user = $this->getUser();
463 if ( $this->mMarkPatrolledLink
=== null ) {
464 // Prepare a change patrol link, if applicable
466 // Is patrolling enabled and the user allowed to?
467 $wgUseRCPatrol && $this->mNewPage
->quickUserCan( 'patrol', $user ) &&
468 // Only do this if the revision isn't more than 6 hours older
469 // than the Max RC age (6h because the RC might not be cleaned out regularly)
470 RecentChange
::isInRCLifespan( $this->mNewRev
->getTimestamp(), 21600 )
472 // Look for an unpatrolled change corresponding to this diff
474 $db = wfGetDB( DB_SLAVE
);
475 $change = RecentChange
::newFromConds(
477 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
478 'rc_this_oldid' => $this->mNewid
,
482 array( 'USE INDEX' => 'rc_timestamp' )
485 if ( $change && $change->getPerformer()->getName() !== $user->getName() ) {
486 $rcid = $change->getAttribute( 'rc_id' );
488 // None found or the page has been created by the current user.
489 // If the user could patrol this it already would be patrolled
494 $this->getOutput()->preventClickjacking();
495 if ( $wgEnableAPI && $wgEnableWriteAPI
496 && $user->isAllowed( 'writeapi' )
498 $this->getOutput()->addModules( 'mediawiki.page.patrol.ajax' );
501 $token = $user->getEditToken( $rcid );
502 $this->mMarkPatrolledLink
= ' <span class="patrollink">[' . Linker
::linkKnown(
504 $this->msg( 'markaspatrolleddiff' )->escaped(),
507 'action' => 'markpatrolled',
513 $this->mMarkPatrolledLink
= '';
516 $this->mMarkPatrolledLink
= '';
520 return $this->mMarkPatrolledLink
;
524 * @param Revision $rev
528 protected function revisionDeleteLink( $rev ) {
529 $link = Linker
::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
530 if ( $link !== '' ) {
531 $link = '   ' . $link . ' ';
538 * Show the new revision of the page.
540 public function renderNewRevision() {
541 wfProfileIn( __METHOD__
);
542 $out = $this->getOutput();
543 $revHeader = $this->getRevisionHeader( $this->mNewRev
);
544 # Add "current version as of X" title
545 $out->addHTML( "<hr class='diff-hr' />
546 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
547 # Page content may be handled by a hooked call instead...
548 # @codingStandardsIgnoreStart Ignoring long lines.
549 if ( wfRunHooks( 'ArticleContentOnDiff', array( $this, $out ) ) ) {
550 $this->loadNewText();
551 $out->setRevisionId( $this->mNewid
);
552 $out->setRevisionTimestamp( $this->mNewRev
->getTimestamp() );
553 $out->setArticleFlag( true );
555 // NOTE: only needed for B/C: custom rendering of JS/CSS via hook
556 if ( $this->mNewPage
->isCssJsSubpage() ||
$this->mNewPage
->isCssOrJsPage() ) {
557 // This needs to be synchronised with Article::showCssOrJsPage(), which sucks
558 // Give hooks a chance to customise the output
559 // @todo standardize this crap into one function
560 if ( ContentHandler
::runLegacyHooks( 'ShowRawCssJs', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
561 // NOTE: deprecated hook, B/C only
562 // use the content object's own rendering
563 $cnt = $this->mNewRev
->getContent();
564 $po = $cnt ?
$cnt->getParserOutput( $this->mNewRev
->getTitle(), $this->mNewRev
->getId() ) : null;
566 $out->addParserOutputContent( $po );
569 } elseif ( !wfRunHooks( 'ArticleContentViewCustom', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
570 // Handled by extension
571 } elseif ( !ContentHandler
::runLegacyHooks( 'ArticleViewCustom', array( $this->mNewContent
, $this->mNewPage
, $out ) ) ) {
572 // NOTE: deprecated hook, B/C only
573 // Handled by extension
576 if ( $this->getTitle()->equals( $this->mNewPage
) ) {
577 // If the Title stored in the context is the same as the one
578 // of the new revision, we can use its associated WikiPage
580 $wikiPage = $this->getWikiPage();
582 // Otherwise we need to create our own WikiPage object
583 $wikiPage = WikiPage
::factory( $this->mNewPage
);
586 $parserOutput = $this->getParserOutput( $wikiPage, $this->mNewRev
);
588 # WikiPage::getParserOutput() should not return false, but just in case
589 if ( $parserOutput ) {
590 $out->addParserOutput( $parserOutput );
594 # @codingStandardsIgnoreEnd
596 # Add redundant patrol link on bottom...
597 $out->addHTML( $this->markPatrolledLink() );
599 wfProfileOut( __METHOD__
);
602 protected function getParserOutput( WikiPage
$page, Revision
$rev ) {
603 $parserOptions = $page->makeParserOptions( $this->getContext() );
605 if ( !$rev->isCurrent() ||
!$rev->getTitle()->quickUserCan( "edit" ) ) {
606 $parserOptions->setEditSection( false );
609 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
611 return $parserOutput;
615 * Get the diff text, send it to the OutputPage object
616 * Returns false if the diff could not be generated, otherwise returns true
618 * @param string|bool $otitle Header for old text or false
619 * @param string|bool $ntitle Header for new text or false
620 * @param string $notice HTML between diff header and body
624 public function showDiff( $otitle, $ntitle, $notice = '' ) {
625 $diff = $this->getDiff( $otitle, $ntitle, $notice );
626 if ( $diff === false ) {
627 $this->showMissingRevision();
631 $this->showDiffStyle();
632 $this->getOutput()->addHTML( $diff );
639 * Add style sheets and supporting JS for diff display.
641 public function showDiffStyle() {
642 $this->getOutput()->addModuleStyles( 'mediawiki.action.history.diff' );
646 * Get complete diff table, including header
648 * @param string|bool $otitle Header for old text or false
649 * @param string|bool $ntitle Header for new text or false
650 * @param string $notice HTML between diff header and body
654 public function getDiff( $otitle, $ntitle, $notice = '' ) {
655 $body = $this->getDiffBody();
656 if ( $body === false ) {
660 $multi = $this->getMultiNotice();
661 // Display a message when the diff is empty
662 if ( $body === '' ) {
663 $notice .= '<div class="mw-diff-empty">' .
664 $this->msg( 'diff-empty' )->parse() .
668 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
672 * Get the diff table body, without header
674 * @return mixed (string/false)
676 public function getDiffBody() {
678 wfProfileIn( __METHOD__
);
679 $this->mCacheHit
= true;
680 // Check if the diff should be hidden from this user
681 if ( !$this->loadRevisionData() ) {
682 wfProfileOut( __METHOD__
);
685 } elseif ( $this->mOldRev
&&
686 !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
688 wfProfileOut( __METHOD__
);
691 } elseif ( $this->mNewRev
&&
692 !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
694 wfProfileOut( __METHOD__
);
699 if ( $this->mOldRev
=== false ||
( $this->mOldRev
&& $this->mNewRev
700 && $this->mOldRev
->getID() == $this->mNewRev
->getID() )
702 wfProfileOut( __METHOD__
);
708 if ( $this->mOldid
&& $this->mNewid
) {
709 $key = $this->getDiffBodyCacheKey();
712 if ( !$this->mRefreshCache
) {
713 $difftext = $wgMemc->get( $key );
715 wfIncrStats( 'diff_cache_hit' );
716 $difftext = $this->localiseLineNumbers( $difftext );
717 $difftext .= "\n<!-- diff cache key $key -->\n";
718 wfProfileOut( __METHOD__
);
722 } // don't try to load but save the result
724 $this->mCacheHit
= false;
726 // Loadtext is permission safe, this just clears out the diff
727 if ( !$this->loadText() ) {
728 wfProfileOut( __METHOD__
);
733 $difftext = $this->generateContentDiffBody( $this->mOldContent
, $this->mNewContent
);
735 // Save to cache for 7 days
736 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
737 wfIncrStats( 'diff_uncacheable' );
738 } elseif ( $key !== false && $difftext !== false ) {
739 wfIncrStats( 'diff_cache_miss' );
740 $wgMemc->set( $key, $difftext, 7 * 86400 );
742 wfIncrStats( 'diff_uncacheable' );
744 // Replace line numbers with the text in the user's language
745 if ( $difftext !== false ) {
746 $difftext = $this->localiseLineNumbers( $difftext );
748 wfProfileOut( __METHOD__
);
754 * Returns the cache key for diff body text or content.
758 * @throws MWException
761 protected function getDiffBodyCacheKey() {
762 if ( !$this->mOldid ||
!$this->mNewid
) {
763 throw new MWException( 'mOldid and mNewid must be set to get diff cache key.' );
766 return wfMemcKey( 'diff', 'version', MW_DIFF_VERSION
,
767 'oldid', $this->mOldid
, 'newid', $this->mNewid
);
771 * Generate a diff, no caching.
773 * This implementation uses generateTextDiffBody() to generate a diff based on the default
774 * serialization of the given Content objects. This will fail if $old or $new are not
775 * instances of TextContent.
777 * Subclasses may override this to provide a different rendering for the diff,
778 * perhaps taking advantage of the content's native form. This is required for all content
779 * models that are not text based.
783 * @param Content $old Old content
784 * @param Content $new New content
786 * @throws MWException If old or new content is not an instance of TextContent.
787 * @return bool|string
789 public function generateContentDiffBody( Content
$old, Content
$new ) {
790 if ( !( $old instanceof TextContent
) ) {
791 throw new MWException( "Diff not implemented for " . get_class( $old ) . "; " .
792 "override generateContentDiffBody to fix this." );
795 if ( !( $new instanceof TextContent
) ) {
796 throw new MWException( "Diff not implemented for " . get_class( $new ) . "; "
797 . "override generateContentDiffBody to fix this." );
800 $otext = $old->serialize();
801 $ntext = $new->serialize();
803 return $this->generateTextDiffBody( $otext, $ntext );
807 * Generate a diff, no caching
809 * @param string $otext Old text, must be already segmented
810 * @param string $ntext New text, must be already segmented
812 * @return bool|string
813 * @deprecated since 1.21, use generateContentDiffBody() instead!
815 public function generateDiffBody( $otext, $ntext ) {
816 ContentHandler
::deprecated( __METHOD__
, "1.21" );
818 return $this->generateTextDiffBody( $otext, $ntext );
822 * Generate a diff, no caching
824 * @todo move this to TextDifferenceEngine, make DifferenceEngine abstract. At some point.
826 * @param string $otext Old text, must be already segmented
827 * @param string $ntext New text, must be already segmented
829 * @return bool|string
831 public function generateTextDiffBody( $otext, $ntext ) {
832 global $wgExternalDiffEngine, $wgContLang;
834 wfProfileIn( __METHOD__
);
836 $otext = str_replace( "\r\n", "\n", $otext );
837 $ntext = str_replace( "\r\n", "\n", $ntext );
839 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
840 # For historical reasons, external diff engine expects
841 # input text to be HTML-escaped already
842 $otext = htmlspecialchars( $wgContLang->segmentForDiff( $otext ) );
843 $ntext = htmlspecialchars( $wgContLang->segmentForDiff( $ntext ) );
844 wfProfileOut( __METHOD__
);
846 return $wgContLang->unsegmentForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
847 $this->debug( 'wikidiff1' );
850 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
851 # Better external diff engine, the 2 may some day be dropped
852 # This one does the escaping and segmenting itself
853 wfProfileIn( 'wikidiff2_do_diff' );
854 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
855 $text .= $this->debug( 'wikidiff2' );
856 wfProfileOut( 'wikidiff2_do_diff' );
857 wfProfileOut( __METHOD__
);
861 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
863 $tmpDir = wfTempDir();
864 $tempName1 = tempnam( $tmpDir, 'diff_' );
865 $tempName2 = tempnam( $tmpDir, 'diff_' );
867 $tempFile1 = fopen( $tempName1, "w" );
869 wfProfileOut( __METHOD__
);
873 $tempFile2 = fopen( $tempName2, "w" );
875 wfProfileOut( __METHOD__
);
879 fwrite( $tempFile1, $otext );
880 fwrite( $tempFile2, $ntext );
881 fclose( $tempFile1 );
882 fclose( $tempFile2 );
883 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
884 wfProfileIn( __METHOD__
. "-shellexec" );
885 $difftext = wfShellExec( $cmd );
886 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
887 wfProfileOut( __METHOD__
. "-shellexec" );
888 unlink( $tempName1 );
889 unlink( $tempName2 );
890 wfProfileOut( __METHOD__
);
896 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
897 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
898 $diffs = new Diff( $ota, $nta );
899 $formatter = new TableDiffFormatter();
900 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
901 wfProfileOut( __METHOD__
);
907 * Generate a debug comment indicating diff generating time,
908 * server node, and generator backend.
910 * @param string $generator : What diff engine was used
914 protected function debug( $generator = "internal" ) {
915 global $wgShowHostnames;
916 if ( !$this->enableDebugComment
) {
919 $data = array( $generator );
920 if ( $wgShowHostnames ) {
921 $data[] = wfHostname();
923 $data[] = wfTimestamp( TS_DB
);
925 return "<!-- diff generator: " .
926 implode( " ", array_map( "htmlspecialchars", $data ) ) .
931 * Replace line numbers with the text in the user's language
933 * @param string $text
937 public function localiseLineNumbers( $text ) {
938 return preg_replace_callback(
939 '/<!--LINE (\d+)-->/',
940 array( &$this, 'localiseLineNumbersCb' ),
945 public function localiseLineNumbersCb( $matches ) {
946 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) {
950 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
954 * If there are revisions between the ones being compared, return a note saying so.
958 public function getMultiNotice() {
959 if ( !is_object( $this->mOldRev
) ||
!is_object( $this->mNewRev
) ) {
961 } elseif ( !$this->mOldPage
->equals( $this->mNewPage
) ) {
962 // Comparing two different pages? Count would be meaningless.
966 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
967 $oldRev = $this->mNewRev
; // flip
968 $newRev = $this->mOldRev
; // flip
969 } else { // normal case
970 $oldRev = $this->mOldRev
;
971 $newRev = $this->mNewRev
;
974 // Sanity: don't show the notice if too many rows must be scanned
975 // @todo show some special message for that case
976 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev, 1000 );
977 if ( $nEdits > 0 && $nEdits <= 1000 ) {
978 $limit = 100; // use diff-multi-manyusers if too many users
979 $users = $this->mNewPage
->getAuthorsBetween( $oldRev, $newRev, $limit );
980 $numUsers = count( $users );
982 if ( $numUsers == 1 && $users[0] == $newRev->getRawUserText() ) {
983 $numUsers = 0; // special case to say "by the same user" instead of "by one other user"
986 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
989 return ''; // nothing
993 * Get a notice about how many intermediate edits and users there are
995 * @param int $numEdits
996 * @param int $numUsers
1001 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
1002 if ( $numUsers === 0 ) {
1003 $msg = 'diff-multi-sameuser';
1004 } elseif ( $numUsers > $limit ) {
1005 $msg = 'diff-multi-manyusers';
1008 $msg = 'diff-multi-otherusers';
1011 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
1015 * Get a header for a specified revision.
1017 * @param Revision $rev
1018 * @param string $complete 'complete' to get the header wrapped depending
1019 * the visibility of the revision and a link to edit the page.
1021 * @return string HTML fragment
1023 protected function getRevisionHeader( Revision
$rev, $complete = '' ) {
1024 $lang = $this->getLanguage();
1025 $user = $this->getUser();
1026 $revtimestamp = $rev->getTimestamp();
1027 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
1028 $dateofrev = $lang->userDate( $revtimestamp, $user );
1029 $timeofrev = $lang->userTime( $revtimestamp, $user );
1031 $header = $this->msg(
1032 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
1038 if ( $complete !== 'complete' ) {
1042 $title = $rev->getTitle();
1044 $header = Linker
::linkKnown( $title, $header, array(),
1045 array( 'oldid' => $rev->getID() ) );
1047 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
1048 $editQuery = array( 'action' => 'edit' );
1049 if ( !$rev->isCurrent() ) {
1050 $editQuery['oldid'] = $rev->getID();
1053 $key = $title->quickUserCan( 'edit', $user ) ?
'editold' : 'viewsourceold';
1054 $msg = $this->msg( $key )->escaped();
1055 $header .= ' ' . $this->msg( 'parentheses' )->rawParams(
1056 Linker
::linkKnown( $title, $msg, array(), $editQuery ) )->plain();
1057 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
1058 $header = Html
::rawElement(
1060 array( 'class' => 'history-deleted' ),
1065 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
1072 * Add the header to a diff body
1074 * @param string $diff Diff body
1075 * @param string $otitle Old revision header
1076 * @param string $ntitle New revision header
1077 * @param string $multi Notice telling user that there are intermediate
1078 * revisions between the ones being compared
1079 * @param string $notice Other notices, e.g. that user is viewing deleted content
1083 public function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
1084 // shared.css sets diff in interface language/dir, but the actual content
1085 // is often in a different language, mostly the page content language/dir
1086 $tableClass = 'diff diff-contentalign-' . htmlspecialchars( $this->getDiffLang()->alignStart() );
1087 $header = "<table class='$tableClass'>";
1089 if ( !$diff && !$otitle ) {
1091 <tr style='vertical-align: top;'>
1092 <td class='diff-ntitle'>{$ntitle}</td>
1096 if ( $diff ) { // Safari/Chrome show broken output if cols not used
1098 <col class='diff-marker' />
1099 <col class='diff-content' />
1100 <col class='diff-marker' />
1101 <col class='diff-content' />";
1108 if ( $otitle ||
$ntitle ) {
1110 <tr style='vertical-align: top;'>
1111 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
1112 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
1117 if ( $multi != '' ) {
1118 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;' " .
1119 "class='diff-multi'>{$multi}</td></tr>";
1121 if ( $notice != '' ) {
1122 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;'>{$notice}</td></tr>";
1125 return $header . $diff . "</table>";
1129 * Use specified text instead of loading from the database
1130 * @deprecated since 1.21, use setContent() instead.
1132 public function setText( $oldText, $newText ) {
1133 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1135 $oldContent = ContentHandler
::makeContent( $oldText, $this->getTitle() );
1136 $newContent = ContentHandler
::makeContent( $newText, $this->getTitle() );
1138 $this->setContent( $oldContent, $newContent );
1142 * Use specified text instead of loading from the database
1143 * @param Content $oldContent
1144 * @param Content $newContent
1147 public function setContent( Content
$oldContent, Content
$newContent ) {
1148 $this->mOldContent
= $oldContent;
1149 $this->mNewContent
= $newContent;
1151 $this->mTextLoaded
= 2;
1152 $this->mRevisionsLoaded
= true;
1156 * Set the language in which the diff text is written
1157 * (Defaults to page content language).
1158 * @param Language|string $lang
1161 public function setTextLanguage( $lang ) {
1162 $this->mDiffLang
= wfGetLangObj( $lang );
1166 * Maps a revision pair definition as accepted by DifferenceEngine constructor
1167 * to a pair of actual integers representing revision ids.
1169 * @param int $old Revision id, e.g. from URL parameter 'oldid'
1170 * @param int|string $new Revision id or strings 'next' or 'prev', e.g. from URL parameter 'diff'
1172 * @return int[] List of two revision ids, older first, later second.
1173 * Zero signifies invalid argument passed.
1174 * false signifies that there is no previous/next revision ($old is the oldest/newest one).
1176 public function mapDiffPrevNext( $old, $new ) {
1177 if ( $new === 'prev' ) {
1178 // Show diff between revision $old and the previous one. Get previous one from DB.
1179 $newid = intval( $old );
1180 $oldid = $this->getTitle()->getPreviousRevisionID( $newid );
1181 } elseif ( $new === 'next' ) {
1182 // Show diff between revision $old and the next one. Get next one from DB.
1183 $oldid = intval( $old );
1184 $newid = $this->getTitle()->getNextRevisionID( $oldid );
1186 $oldid = intval( $old );
1187 $newid = intval( $new );
1190 return array( $oldid, $newid );
1196 private function loadRevisionIds() {
1197 if ( $this->mRevisionsIdsLoaded
) {
1201 $this->mRevisionsIdsLoaded
= true;
1203 $old = $this->mOldid
;
1204 $new = $this->mNewid
;
1206 list( $this->mOldid
, $this->mNewid
) = self
::mapDiffPrevNext( $old, $new );
1207 if ( $new === 'next' && $this->mNewid
=== false ) {
1208 # if no result, NewId points to the newest old revision. The only newer
1209 # revision is cur, which is "0".
1214 'NewDifferenceEngine',
1215 array( $this->getTitle(), &$this->mOldid
, &$this->mNewid
, $old, $new )
1220 * Load revision metadata for the specified articles. If newid is 0, then compare
1221 * the old article in oldid to the current article; if oldid is 0, then
1222 * compare the current article to the immediately previous one (ignoring the
1225 * If oldid is false, leave the corresponding revision object set
1226 * to false. This is impossible via ordinary user input, and is provided for
1231 public function loadRevisionData() {
1232 if ( $this->mRevisionsLoaded
) {
1236 // Whether it succeeds or fails, we don't want to try again
1237 $this->mRevisionsLoaded
= true;
1239 $this->loadRevisionIds();
1241 // Load the new revision object
1242 if ( $this->mNewid
) {
1243 $this->mNewRev
= Revision
::newFromId( $this->mNewid
);
1245 $this->mNewRev
= Revision
::newFromTitle(
1248 Revision
::READ_NORMAL
1252 if ( !$this->mNewRev
instanceof Revision
) {
1256 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1257 $this->mNewid
= $this->mNewRev
->getId();
1258 $this->mNewPage
= $this->mNewRev
->getTitle();
1260 // Load the old revision object
1261 $this->mOldRev
= false;
1262 if ( $this->mOldid
) {
1263 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1264 } elseif ( $this->mOldid
=== 0 ) {
1265 $rev = $this->mNewRev
->getPrevious();
1267 $this->mOldid
= $rev->getId();
1268 $this->mOldRev
= $rev;
1270 // No previous revision; mark to show as first-version only.
1271 $this->mOldid
= false;
1272 $this->mOldRev
= false;
1274 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1276 if ( is_null( $this->mOldRev
) ) {
1280 if ( $this->mOldRev
) {
1281 $this->mOldPage
= $this->mOldRev
->getTitle();
1284 // Load tags information for both revisions
1285 $dbr = wfGetDB( DB_SLAVE
);
1286 if ( $this->mOldid
!== false ) {
1287 $this->mOldTags
= $dbr->selectField(
1290 array( 'ts_rev_id' => $this->mOldid
),
1294 $this->mOldTags
= false;
1296 $this->mNewTags
= $dbr->selectField(
1299 array( 'ts_rev_id' => $this->mNewid
),
1307 * Load the text of the revisions, as well as revision data.
1311 public function loadText() {
1312 if ( $this->mTextLoaded
== 2 ) {
1316 // Whether it succeeds or fails, we don't want to try again
1317 $this->mTextLoaded
= 2;
1319 if ( !$this->loadRevisionData() ) {
1323 if ( $this->mOldRev
) {
1324 $this->mOldContent
= $this->mOldRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1325 if ( $this->mOldContent
=== null ) {
1330 if ( $this->mNewRev
) {
1331 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1332 if ( $this->mNewContent
=== null ) {
1341 * Load the text of the new revision, not the old one
1345 public function loadNewText() {
1346 if ( $this->mTextLoaded
>= 1 ) {
1350 $this->mTextLoaded
= 1;
1352 if ( !$this->loadRevisionData() ) {
1356 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );