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
26 * @ingroup DifferenceEngine
28 class DifferenceEngine
extends ContextSource
{
30 * Constant to indicate diff cache compatibility.
31 * Bump this when changing the diff formatting in a way that
32 * fixes important bugs or such to force cached diff views to
35 const CACHE_VERSION
='1.11a';
71 private $revisionsIdsLoaded = false; // Have the revisions IDs been loaded
72 public $revisionsLoaded = false; // Have the revisions been loaded
73 public $textLoaded = 0; // How many text blobs have been loaded, 0, 1 or 2?
74 public $cacheHit = false; // Was the diff fetched from cache?
77 * Set this to true to add debug info to the HTML output.
78 * Warning: this may cause RSS readers to spuriously mark articles as "new"
81 public $enableDebugComment = false;
83 // If true, line X is not displayed when X is 1, for example to increase
84 // readability and conserve space with many small diffs.
85 protected $reducedLineNumbers = false;
87 // Link to action=markpatrolled
88 protected $markPatrolledLink = null;
90 protected $unhide = false; # show rev_deleted content if allowed
91 private $refreshCache;
96 * @param $context IContextSource context to use, anything else will be ignored
97 * @param $old Integer old ID we want to show and diff with.
98 * @param $new String|int either revision ID or 'prev' or 'next'. Default: 0.
99 * @param $rcid Integer Deprecated, no longer used!
100 * @param $refreshCache boolean If set, refreshes the diff cache
101 * @param $unhide boolean If set, allow viewing deleted revs
103 function __construct( $context = null, $old = 0, $new = 0, $rcid = 0,
104 $refreshCache = false, $unhide = false
106 if ( $context instanceof IContextSource
) {
107 $this->setContext( $context );
110 wfDebug( "DifferenceEngine old '$old' new '$new' rcid '$rcid'\n" );
114 $this->refreshCache
= $refreshCache;
115 $this->unhide
= $unhide;
121 function setReducedLineNumbers( $value = true ) {
122 $this->reducedLineNumbers
= $value;
128 function getDiffLang() {
129 if ( $this->diffLang
=== null ) {
130 # Default language in which the diff text is written.
131 $this->diffLang
= $this->getTitle()->getPageLanguage();
133 return $this->diffLang
;
139 function wasCacheHit() {
140 return $this->cacheHit
;
146 function getOldid() {
147 $this->loadRevisionIds();
154 function getNewid() {
155 $this->loadRevisionIds();
160 * Look up a special:Undelete link to the given deleted revision id,
161 * as a workaround for being unable to load deleted diffs in currently.
163 * @param int $id revision ID
164 * @return mixed URL or false
166 function deletedLink( $id ) {
167 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
168 $dbr = wfGetDB( DB_SLAVE
);
169 $row = $dbr->selectRow( 'archive', '*',
170 array( 'ar_rev_id' => $id ),
173 $rev = Revision
::newFromArchiveRow( $row );
174 $title = Title
::makeTitleSafe( $row->ar_namespace
, $row->ar_title
);
175 return SpecialPage
::getTitleFor( 'Undelete' )->getFullURL( array(
176 'target' => $title->getPrefixedText(),
177 'timestamp' => $rev->getTimestamp()
185 * Build a wikitext link toward a deleted revision, if viewable.
187 * @param int $id revision ID
188 * @return string wikitext fragment
190 function deletedIdMarker( $id ) {
191 $link = $this->deletedLink( $id );
193 return "[$link $id]";
199 private function showMissingRevision() {
200 $out = $this->getOutput();
203 if ( $this->oldRev
=== null ||
204 ( $this->oldRev
&& $this->oldContent
=== null )
206 $missing[] = $this->deletedIdMarker( $this->oldId
);
208 if ( $this->newRev
=== null ||
209 ( $this->newRev
&& $this->newContent
=== null )
211 $missing[] = $this->deletedIdMarker( $this->newId
);
214 $out->setPageTitle( $this->msg( 'errorpagetitle' ) );
215 $out->addWikiMsg( 'difference-missing-revision',
216 $this->getLanguage()->listToText( $missing ), count( $missing ) );
219 function showDiffPage( $diffOnly = false ) {
220 wfProfileIn( __METHOD__
);
222 # Allow frames except in certain special cases
223 $out = $this->getOutput();
224 $out->allowClickjacking();
225 $out->setRobotPolicy( 'noindex,nofollow' );
227 if ( !$this->loadRevisionData() ) {
228 $this->showMissingRevision();
229 wfProfileOut( __METHOD__
);
233 $user = $this->getUser();
234 $permErrors = $this->newPage
->getUserPermissionsErrors( 'read', $user );
235 if ( $this->oldPage
) { # oldPage might not be set, see below.
236 $permErrors = wfMergeErrorArrays( $permErrors,
237 $this->oldPage
->getUserPermissionsErrors( 'read', $user ) );
239 if ( count( $permErrors ) ) {
240 wfProfileOut( __METHOD__
);
241 throw new PermissionsError( 'read', $permErrors );
247 # Carry over 'diffonly' param via navigation links
248 if ( $diffOnly != $user->getBoolOption( 'diffonly' ) ) {
249 $query['diffonly'] = $diffOnly;
251 # Cascade unhide param in links for easy deletion browsing
252 if ( $this->unhide
) {
253 $query['unhide'] = 1;
256 # Check if one of the revisions is deleted/suppressed
257 $deleted = $suppressed = false;
258 $allowed = $this->newRev
->userCan( Revision
::DELETED_TEXT
, $user );
260 $revisionTools = array();
262 # oldRev is false if the difference engine is called with a "vague" query for
263 # a diff between a version V and its previous version V' AND the version V
264 # is the first version of that article. In that case, V' does not exist.
265 if ( $this->oldRev
=== false ) {
266 $out->setPageTitle( $this->msg( 'difference-title', $this->newPage
->getPrefixedText() ) );
270 wfRunHooks( 'DiffViewHeader', array( $this, $this->oldRev
, $this->newRev
) );
272 if ( $this->newPage
->equals( $this->oldPage
) ) {
273 $out->setPageTitle( $this->msg( 'difference-title', $this->newPage
->getPrefixedText() ) );
276 $out->setPageTitle( $this->msg( 'difference-title-multipage',
277 $this->oldPage
->getPrefixedText(), $this->newPage
->getPrefixedText() ) );
278 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
282 if ( $samePage && $this->newPage
->quickUserCan( 'edit', $user ) ) {
283 if ( $this->newRev
->isCurrent() && $this->newPage
->userCan( 'rollback', $user ) ) {
284 $rollbackLink = Linker
::generateRollback( $this->newRev
, $this->getContext() );
285 if ( $rollbackLink ) {
286 $out->preventClickjacking();
287 $rollback = '   ' . $rollbackLink;
291 if ( !$this->oldRev
->isDeleted( Revision
::DELETED_TEXT
) &&
292 !$this->newRev
->isDeleted( Revision
::DELETED_TEXT
)
294 $undoLink = Html
::element( 'a', array(
295 'href' => $this->newPage
->getLocalURL( array(
297 'undoafter' => $this->oldId
,
298 'undo' => $this->newId
) ),
299 'title' => Linker
::titleAttrib( 'undo' )
301 $this->msg( 'editundo' )->text()
303 $revisionTools[] = $undoLink;
307 # Make "previous revision link"
308 if ( $samePage && $this->oldRev
->getPrevious() ) {
309 $prevlink = Linker
::linkKnown(
311 $this->msg( 'previousdiff' )->escaped(),
312 array( 'id' => 'differences-prevlink' ),
313 array( 'diff' => 'prev', 'oldid' => $this->oldId
) +
$query
316 $prevlink = ' ';
319 if ( $this->oldRev
->isMinor() ) {
320 $oldminor = ChangesList
::flag( 'minor' );
325 $ldel = $this->revisionDeleteLink( $this->oldRev
);
326 $oldRevisionHeader = $this->getRevisionHeader( $this->oldRev
, 'complete' );
327 $oldChangeTags = ChangeTags
::formatSummaryRow( $this->oldTags
, 'diff' );
329 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
330 '<div id="mw-diff-otitle2">' .
331 Linker
::revUserTools( $this->oldRev
, !$this->unhide
) . '</div>' .
332 '<div id="mw-diff-otitle3">' . $oldminor .
333 Linker
::revComment( $this->oldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
334 '<div id="mw-diff-otitle5">' . $oldChangeTags[0] . '</div>' .
335 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
337 if ( $this->oldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
338 $deleted = true; // old revisions text is hidden
339 if ( $this->oldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
340 $suppressed = true; // also suppressed
344 # Check if this user can see the revisions
345 if ( !$this->oldRev
->userCan( Revision
::DELETED_TEXT
, $user ) ) {
350 # Make "next revision link"
351 # Skip next link on the top revision
352 if ( $samePage && !$this->newRev
->isCurrent() ) {
353 $nextlink = Linker
::linkKnown(
355 $this->msg( 'nextdiff' )->escaped(),
356 array( 'id' => 'differences-nextlink' ),
357 array( 'diff' => 'next', 'oldid' => $this->newId
) +
$query
360 $nextlink = ' ';
363 if ( $this->newRev
->isMinor() ) {
364 $newminor = ChangesList
::flag( 'minor' );
369 # Handle RevisionDelete links...
370 $rdel = $this->revisionDeleteLink( $this->newRev
);
372 # Allow extensions to define their own revision tools
373 wfRunHooks( 'DiffRevisionTools', array( $this->newRev
, &$revisionTools ) );
374 $formattedRevisionTools = array();
375 // Put each one in parentheses (poor man's button)
376 foreach ( $revisionTools as $tool ) {
377 $formattedRevisionTools[] = $this->msg( 'parentheses' )->rawParams( $tool )->escaped();
379 $newRevisionHeader = $this->getRevisionHeader( $this->newRev
, 'complete' ) .
380 ' ' . implode( ' ', $formattedRevisionTools );
381 $newChangeTags = ChangeTags
::formatSummaryRow( $this->newTags
, 'diff' );
383 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
384 '<div id="mw-diff-ntitle2">' . Linker
::revUserTools( $this->newRev
, !$this->unhide
) .
386 '<div id="mw-diff-ntitle3">' . $newminor .
387 Linker
::revComment( $this->newRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
388 '<div id="mw-diff-ntitle5">' . $newChangeTags[0] . '</div>' .
389 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
391 if ( $this->newRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
392 $deleted = true; // new revisions text is hidden
393 if ( $this->newRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
394 $suppressed = true; // also suppressed
398 # If the diff cannot be shown due to a deleted revision, then output
399 # the diff header and links to unhide (if available)...
400 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
401 $this->showDiffStyle();
402 $multi = $this->getMultiNotice();
403 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
405 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
406 # Give explanation for why revision is not visible
407 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
410 # Give explanation and add a link to view the diff...
411 $query = $this->getRequest()->appendQueryValue( 'unhide', '1', true );
412 $link = $this->getTitle()->getFullURL( $query );
413 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
415 "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
419 # Otherwise, output a regular diff...
421 # Add deletion notice if the user is viewing deleted content
424 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
425 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" .
426 $this->msg( $msg )->parse() .
429 $this->showDiff( $oldHeader, $newHeader, $notice );
431 $this->renderNewRevision();
434 wfProfileOut( __METHOD__
);
438 * Get a link to mark the change as patrolled, or '' if there's either no
439 * revision to patrol or the user is not allowed to to it.
440 * Side effect: When the patrol link is build, this method will call
441 * OutputPage::preventClickjacking() and load mediawiki.page.patrol.ajax.
445 protected function markPatrolledLink() {
446 global $wgUseRCPatrol, $wgEnableAPI, $wgEnableWriteAPI;
447 $user = $this->getUser();
449 if ( $this->markPatrolledLink
=== null ) {
450 // Prepare a change patrol link, if applicable
452 // Is patrolling enabled and the user allowed to?
453 $wgUseRCPatrol && $this->newPage
->quickUserCan( 'patrol', $user ) &&
454 // Only do this if the revision isn't more than 6 hours older
455 // than the Max RC age (6h because the RC might not be cleaned out regularly)
456 RecentChange
::isInRCLifespan( $this->newRev
->getTimestamp(), 21600 )
458 // Look for an unpatrolled change corresponding to this diff
460 $db = wfGetDB( DB_SLAVE
);
461 $change = RecentChange
::newFromConds(
463 'rc_timestamp' => $db->timestamp( $this->newRev
->getTimestamp() ),
464 'rc_this_oldid' => $this->newId
,
468 array( 'USE INDEX' => 'rc_timestamp' )
471 if ( $change && $change->getPerformer()->getName() !== $user->getName() ) {
472 $rcid = $change->getAttribute( 'rc_id' );
474 // None found or the page has been created by the current user.
475 // If the user could patrol this it already would be patrolled
480 $this->getOutput()->preventClickjacking();
481 if ( $wgEnableAPI && $wgEnableWriteAPI
482 && $user->isAllowed( 'writeapi' )
484 $this->getOutput()->addModules( 'mediawiki.page.patrol.ajax' );
487 $token = $user->getEditToken( $rcid );
488 $this->markPatrolledLink
= ' <span class="patrollink">[' . Linker
::linkKnown(
490 $this->msg( 'markaspatrolleddiff' )->escaped(),
493 'action' => 'markpatrolled',
499 $this->markPatrolledLink
= '';
502 $this->markPatrolledLink
= '';
506 return $this->markPatrolledLink
;
510 * @param $rev Revision
513 protected function revisionDeleteLink( $rev ) {
514 $link = Linker
::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
515 if ( $link !== '' ) {
516 $link = '   ' . $link . ' ';
522 * Show the new revision of the page.
524 function renderNewRevision() {
525 wfProfileIn( __METHOD__
);
526 $out = $this->getOutput();
527 $revHeader = $this->getRevisionHeader( $this->newRev
);
528 # Add "current version as of X" title
529 $out->addHTML( "<hr class='diff-hr' />
530 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
531 # Page content may be handled by a hooked call instead...
532 # @codingStandardsIgnoreStart Ignoring long lines.
533 if ( wfRunHooks( 'ArticleContentOnDiff', array( $this, $out ) ) ) {
534 $this->loadNewText();
535 $out->setRevisionId( $this->newId
);
536 $out->setRevisionTimestamp( $this->newRev
->getTimestamp() );
537 $out->setArticleFlag( true );
539 // NOTE: only needed for B/C: custom rendering of JS/CSS via hook
540 if ( $this->newPage
->isCssJsSubpage() ||
$this->newPage
->isCssOrJsPage() ) {
541 // Stolen from Article::view --AG 2007-10-11
542 // Give hooks a chance to customise the output
543 // @todo standardize this crap into one function
544 if ( ContentHandler
::runLegacyHooks( 'ShowRawCssJs', array( $this->newContent
, $this->newPage
, $out ) ) ) {
545 // NOTE: deprecated hook, B/C only
546 // use the content object's own rendering
547 $cnt = $this->newRev
->getContent();
548 $po = $cnt ?
$cnt->getParserOutput( $this->newRev
->getTitle(), $this->newRev
->getId() ) : null;
549 $txt = $po ?
$po->getText() : '';
550 $out->addHTML( $txt );
552 } elseif ( !wfRunHooks( 'ArticleContentViewCustom', array( $this->newContent
, $this->newPage
, $out ) ) ) {
553 // Handled by extension
554 } elseif ( !ContentHandler
::runLegacyHooks( 'ArticleViewCustom', array( $this->newContent
, $this->newPage
, $out ) ) ) {
555 // NOTE: deprecated hook, B/C only
556 // Handled by extension
559 if ( $this->getTitle()->equals( $this->newPage
) ) {
560 // If the Title stored in the context is the same as the one
561 // of the new revision, we can use its associated WikiPage
563 $wikiPage = $this->getWikiPage();
565 // Otherwise we need to create our own WikiPage object
566 $wikiPage = WikiPage
::factory( $this->newPage
);
569 $parserOutput = $this->getParserOutput( $wikiPage, $this->newRev
);
571 # Also try to load it as a redirect
572 $rt = $this->newContent ?
$this->newContent
->getRedirectTarget() : null;
575 $article = Article
::newFromTitle( $this->newPage
, $this->getContext() );
576 $out->addHTML( $article->viewRedirect( $rt ) );
578 # WikiPage::getParserOutput() should not return false, but just in case
579 if ( $parserOutput ) {
580 # Show categories etc.
581 $out->addParserOutputNoText( $parserOutput );
583 } elseif ( $parserOutput ) {
584 $out->addParserOutput( $parserOutput );
588 # @codingStandardsIgnoreEnd
590 # Add redundant patrol link on bottom...
591 $out->addHTML( $this->markPatrolledLink() );
593 wfProfileOut( __METHOD__
);
596 protected function getParserOutput( WikiPage
$page, Revision
$rev ) {
597 $parserOptions = $page->makeParserOptions( $this->getContext() );
599 if ( !$rev->isCurrent() ||
!$rev->getTitle()->quickUserCan( "edit" ) ) {
600 $parserOptions->setEditSection( false );
603 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
604 return $parserOutput;
608 * Get the diff text, send it to the OutputPage object
609 * Returns false if the diff could not be generated, otherwise returns true
611 * @param string|bool $otitle Header for old text or false
612 * @param string|bool $ntitle Header for new text or false
613 * @param string $notice HTML between diff header and body
617 function showDiff( $otitle, $ntitle, $notice = '' ) {
618 $diff = $this->getDiff( $otitle, $ntitle, $notice );
619 if ( $diff === false ) {
620 $this->showMissingRevision();
623 $this->showDiffStyle();
624 $this->getOutput()->addHTML( $diff );
630 * Add style sheets and supporting JS for diff display.
632 function showDiffStyle() {
633 $this->getOutput()->addModuleStyles( 'mediawiki.action.history.diff' );
637 * Get complete diff table, including header
639 * @param string|bool $otitle Header for old text or false
640 * @param string|bool $ntitle Header for new text or false
641 * @param string $notice HTML between diff header and body
644 function getDiff( $otitle, $ntitle, $notice = '' ) {
645 $body = $this->getDiffBody();
646 if ( $body === false ) {
650 $multi = $this->getMultiNotice();
651 // Display a message when the diff is empty
652 if ( $body === '' ) {
653 $notice .= '<div class="mw-diff-empty">' .
654 $this->msg( 'diff-empty' )->parse() .
658 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
662 * Get the diff table body, without header
664 * @return mixed (string/false)
666 public function getDiffBody() {
668 wfProfileIn( __METHOD__
);
669 $this->cacheHit
= true;
670 // Check if the diff should be hidden from this user
671 if ( !$this->loadRevisionData() ) {
672 wfProfileOut( __METHOD__
);
674 } elseif ( $this->oldRev
&&
675 !$this->oldRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
677 wfProfileOut( __METHOD__
);
679 } elseif ( $this->newRev
&&
680 !$this->newRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
682 wfProfileOut( __METHOD__
);
686 if ( $this->oldRev
=== false ||
( $this->oldRev
&& $this->newRev
687 && $this->oldRev
->getID() == $this->newRev
->getID() ) )
689 wfProfileOut( __METHOD__
);
694 if ( $this->oldId
&& $this->newId
) {
695 $key = $this->getDiffBodyCacheKey();
698 if ( !$this->refreshCache
) {
699 $difftext = $wgMemc->get( $key );
701 wfIncrStats( 'diff_cache_hit' );
702 $difftext = $this->localiseLineNumbers( $difftext );
703 $difftext .= "\n<!-- diff cache key $key -->\n";
704 wfProfileOut( __METHOD__
);
707 } // don't try to load but save the result
709 $this->cacheHit
= false;
711 // Loadtext is permission safe, this just clears out the diff
712 if ( !$this->loadText() ) {
713 wfProfileOut( __METHOD__
);
717 $difftext = $this->generateContentDiffBody( $this->oldContent
, $this->newContent
);
719 // Save to cache for 7 days
720 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
721 wfIncrStats( 'diff_uncacheable' );
722 } elseif ( $key !== false && $difftext !== false ) {
723 wfIncrStats( 'diff_cache_miss' );
724 $wgMemc->set( $key, $difftext, 7 * 86400 );
726 wfIncrStats( 'diff_uncacheable' );
728 // Replace line numbers with the text in the user's language
729 if ( $difftext !== false ) {
730 $difftext = $this->localiseLineNumbers( $difftext );
732 wfProfileOut( __METHOD__
);
737 * Returns the cache key for diff body text or content.
741 * @throws MWException
743 protected function getDiffBodyCacheKey() {
744 if ( !$this->oldId ||
!$this->newId
) {
745 throw new MWException( 'oldId and newId must be set to get diff cache key.' );
748 return wfMemcKey( 'diff', 'version', self
::CACHE_VERSION
,
749 'oldid', $this->oldId
, 'newid', $this->newId
);
753 * Generate a diff, no caching.
755 * This implementation uses generateTextDiffBody() to generate a diff based on the default
756 * serialization of the given Content objects. This will fail if $old or $new are not
757 * instances of TextContent.
759 * Subclasses may override this to provide a different rendering for the diff,
760 * perhaps taking advantage of the content's native form. This is required for all content
761 * models that are not text based.
763 * @param $old Content: old content
764 * @param $new Content: new content
766 * @return bool|string
768 * @throws MWException if $old or $new are not instances of TextContent.
770 function generateContentDiffBody( Content
$old, Content
$new ) {
771 if ( !( $old instanceof TextContent
) ) {
772 throw new MWException( "Diff not implemented for " . get_class( $old ) . "; "
773 . "override generateContentDiffBody to fix this." );
776 if ( !( $new instanceof TextContent
) ) {
777 throw new MWException( "Diff not implemented for " . get_class( $new ) . "; "
778 . "override generateContentDiffBody to fix this." );
781 $otext = $old->serialize();
782 $ntext = $new->serialize();
784 return $this->generateTextDiffBody( $otext, $ntext );
788 * Generate a diff, no caching
790 * @param string $otext old text, must be already segmented
791 * @param string $ntext new text, must be already segmented
792 * @return bool|string
793 * @deprecated since 1.21, use generateContentDiffBody() instead!
795 function generateDiffBody( $otext, $ntext ) {
796 ContentHandler
::deprecated( __METHOD__
, "1.21" );
798 return $this->generateTextDiffBody( $otext, $ntext );
802 * Generate a diff, no caching
804 * @todo move this to TextDifferenceEngine, make DifferenceEngine abstract. At some point.
806 * @param string $otext old text, must be already segmented
807 * @param string $ntext new text, must be already segmented
808 * @return bool|string
810 function generateTextDiffBody( $otext, $ntext ) {
811 global $wgExternalDiffEngine, $wgContLang;
813 wfProfileIn( __METHOD__
);
815 $otext = str_replace( "\r\n", "\n", $otext );
816 $ntext = str_replace( "\r\n", "\n", $ntext );
818 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
819 # For historical reasons, external diff engine expects
820 # input text to be HTML-escaped already
821 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
822 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
823 wfProfileOut( __METHOD__
);
824 return $wgContLang->unsegmentForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
825 $this->debug( 'wikidiff1' );
828 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
829 # Better external diff engine, the 2 may some day be dropped
830 # This one does the escaping and segmenting itself
831 wfProfileIn( 'wikidiff2_do_diff' );
832 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
833 $text .= $this->debug( 'wikidiff2' );
834 wfProfileOut( 'wikidiff2_do_diff' );
835 wfProfileOut( __METHOD__
);
838 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
840 $tmpDir = wfTempDir();
841 $tempName1 = tempnam( $tmpDir, 'diff_' );
842 $tempName2 = tempnam( $tmpDir, 'diff_' );
844 $tempFile1 = fopen( $tempName1, "w" );
846 wfProfileOut( __METHOD__
);
849 $tempFile2 = fopen( $tempName2, "w" );
851 wfProfileOut( __METHOD__
);
854 fwrite( $tempFile1, $otext );
855 fwrite( $tempFile2, $ntext );
856 fclose( $tempFile1 );
857 fclose( $tempFile2 );
858 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
859 wfProfileIn( __METHOD__
. "-shellexec" );
860 $difftext = wfShellExec( $cmd );
861 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
862 wfProfileOut( __METHOD__
. "-shellexec" );
863 unlink( $tempName1 );
864 unlink( $tempName2 );
865 wfProfileOut( __METHOD__
);
870 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
871 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
872 $diffs = new Diff( $ota, $nta );
873 $formatter = new TableDiffFormatter();
874 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
875 wfProfileOut( __METHOD__
);
880 * Generate a debug comment indicating diff generating time,
881 * server node, and generator backend.
883 * @param String $generator: What diff engine was used
887 protected function debug( $generator = "internal" ) {
888 global $wgShowHostnames;
889 if ( !$this->enableDebugComment
) {
892 $data = array( $generator );
893 if ( $wgShowHostnames ) {
894 $data[] = wfHostname();
896 $data[] = wfTimestamp( TS_DB
);
897 return "<!-- diff generator: "
907 * Replace line numbers with the text in the user's language
909 * @param String $text
913 function localiseLineNumbers( $text ) {
914 return preg_replace_callback( '/<!--LINE (\d+)-->/',
915 array( &$this, 'localiseLineNumbersCb' ), $text );
918 function localiseLineNumbersCb( $matches ) {
919 if ( $matches[1] === '1' && $this->reducedLineNumbers
) {
922 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
926 * If there are revisions between the ones being compared, return a note saying so.
929 function getMultiNotice() {
930 if ( !is_object( $this->oldRev
) ||
!is_object( $this->newRev
) ) {
932 } elseif ( !$this->oldPage
->equals( $this->newPage
) ) {
933 // Comparing two different pages? Count would be meaningless.
937 if ( $this->oldRev
->getTimestamp() > $this->newRev
->getTimestamp() ) {
938 $oldRev = $this->newRev
; // flip
939 $newRev = $this->oldRev
; // flip
940 } else { // normal case
941 $oldRev = $this->oldRev
;
942 $newRev = $this->newRev
;
945 $nEdits = $this->newPage
->countRevisionsBetween( $oldRev, $newRev );
947 $limit = 100; // use diff-multi-manyusers if too many users
948 $numUsers = $this->newPage
->countAuthorsBetween( $oldRev, $newRev, $limit );
949 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
951 return ''; // nothing
955 * Get a notice about how many intermediate edits and users there are
956 * @param $numEdits int
957 * @param $numUsers int
961 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
962 if ( $numUsers > $limit ) {
963 $msg = 'diff-multi-manyusers';
968 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
972 * Get a header for a specified revision.
974 * @param $rev Revision
975 * @param string $complete 'complete' to get the header wrapped depending
976 * the visibility of the revision and a link to edit the page.
977 * @return String HTML fragment
979 protected function getRevisionHeader( Revision
$rev, $complete = '' ) {
980 $lang = $this->getLanguage();
981 $user = $this->getUser();
982 $revtimestamp = $rev->getTimestamp();
983 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
984 $dateofrev = $lang->userDate( $revtimestamp, $user );
985 $timeofrev = $lang->userTime( $revtimestamp, $user );
987 $header = $this->msg(
988 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
994 if ( $complete !== 'complete' ) {
998 $title = $rev->getTitle();
1000 $header = Linker
::linkKnown( $title, $header, array(),
1001 array( 'oldid' => $rev->getID() ) );
1003 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
1004 $editQuery = array( 'action' => 'edit' );
1005 if ( !$rev->isCurrent() ) {
1006 $editQuery['oldid'] = $rev->getID();
1009 $key = $title->quickUserCan( 'edit', $user ) ?
'editold' : 'viewsourceold';
1010 $msg = $this->msg( $key )->escaped();
1011 $header .= ' ' . $this->msg( 'parentheses' )->rawParams(
1012 Linker
::linkKnown( $title, $msg, array(), $editQuery ) )->plain();
1013 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
1014 $header = Html
::rawElement(
1016 array( 'class' => 'history-deleted' ),
1021 $header = Html
::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
1028 * Add the header to a diff body
1030 * @param String $diff: Diff body
1031 * @param String $otitle: Old revision header
1032 * @param String $ntitle: New revision header
1033 * @param String $multi: Notice telling user that there are intermediate revisions between the ones being compared
1034 * @param String $notice: Other notices, e.g. that user is viewing deleted content
1038 function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
1039 // shared.css sets diff in interface language/dir, but the actual content
1040 // is often in a different language, mostly the page content language/dir
1041 $tableClass = 'diff diff-contentalign-' . htmlspecialchars( $this->getDiffLang()->alignStart() );
1042 $header = "<table class='$tableClass'>";
1044 if ( !$diff && !$otitle ) {
1046 <tr style='vertical-align: top;'>
1047 <td class='diff-ntitle'>{$ntitle}</td>
1051 if ( $diff ) { // Safari/Chrome show broken output if cols not used
1053 <col class='diff-marker' />
1054 <col class='diff-content' />
1055 <col class='diff-marker' />
1056 <col class='diff-content' />";
1063 if ( $otitle ||
$ntitle ) {
1065 <tr style='vertical-align: top;'>
1066 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
1067 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
1072 if ( $multi != '' ) {
1073 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;' " .
1074 "class='diff-multi'>{$multi}</td></tr>";
1076 if ( $notice != '' ) {
1077 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;'>{$notice}</td></tr>";
1080 return $header . $diff . "</table>";
1084 * Use specified text instead of loading from the database
1085 * @deprecated since 1.21, use setContent() instead.
1087 function setText( $oldText, $newText ) {
1088 ContentHandler
::deprecated( __METHOD__
, "1.21" );
1090 $oldContent = ContentHandler
::makeContent( $oldText, $this->getTitle() );
1091 $newContent = ContentHandler
::makeContent( $newText, $this->getTitle() );
1093 $this->setContent( $oldContent, $newContent );
1097 * Use specified text instead of loading from the database
1100 function setContent( Content
$oldContent, Content
$newContent ) {
1101 $this->oldContent
= $oldContent;
1102 $this->newContent
= $newContent;
1104 $this->textLoaded
= 2;
1105 $this->revisionsLoaded
= true;
1109 * Set the language in which the diff text is written
1110 * (Defaults to page content language).
1113 function setTextLanguage( $lang ) {
1114 $this->diffLang
= wfGetLangObj( $lang );
1118 * Maps a revision pair definition as accepted by DifferenceEngine constructor
1119 * to a pair of actual integers representing revision ids.
1121 * @param int $old Revision id, e.g. from URL parameter 'oldid'
1122 * @param int|string $new Revision id or strings 'next' or 'prev', e.g. from URL parameter 'diff'
1123 * @return array Array of two revision ids, older first, later second.
1124 * Zero signifies invalid argument passed.
1125 * false signifies that there is no previous/next revision ($old is the oldest/newest one).
1127 public function mapDiffPrevNext( $old, $new ) {
1128 if ( $new === 'prev' ) {
1129 // Show diff between revision $old and the previous one. Get previous one from DB.
1130 $newid = intval( $old );
1131 $oldid = $this->getTitle()->getPreviousRevisionID( $newid );
1132 } elseif ( $new === 'next' ) {
1133 // Show diff between revision $old and the next one. Get next one from DB.
1134 $oldid = intval( $old );
1135 $newid = $this->getTitle()->getNextRevisionID( $oldid );
1137 $oldid = intval( $old );
1138 $newid = intval( $new );
1141 return array( $oldid, $newid );
1147 private function loadRevisionIds() {
1148 if ( $this->revisionsIdsLoaded
) {
1152 $this->revisionsIdsLoaded
= true;
1154 $old = $this->oldId
;
1155 $new = $this->newId
;
1157 list( $this->oldId
, $this->newId
) = self
::mapDiffPrevNext( $old, $new );
1158 if ( $new === 'next' && $this->newId
=== false ) {
1159 # if no result, NewId points to the newest old revision. The only newer
1160 # revision is cur, which is "0".
1164 wfRunHooks( 'NewDifferenceEngine', array( $this->getTitle(), &$this->oldId
, &$this->newId
, $old, $new ) );
1168 * Load revision metadata for the specified articles. If newid is 0, then compare
1169 * the old article in oldid to the current article; if oldid is 0, then
1170 * compare the current article to the immediately previous one (ignoring the
1173 * If oldid is false, leave the corresponding revision object set
1174 * to false. This is impossible via ordinary user input, and is provided for
1179 function loadRevisionData() {
1180 if ( $this->revisionsLoaded
) {
1184 // Whether it succeeds or fails, we don't want to try again
1185 $this->revisionsLoaded
= true;
1187 $this->loadRevisionIds();
1189 // Load the new revision object
1190 if ( $this->newId
) {
1191 $this->newRev
= Revision
::newFromId( $this->newId
);
1193 $this->newRev
= Revision
::newFromTitle(
1196 Revision
::READ_NORMAL
1200 if ( !$this->newRev
instanceof Revision
) {
1204 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1205 $this->newId
= $this->newRev
->getId();
1206 $this->newPage
= $this->newRev
->getTitle();
1208 // Load the old revision object
1209 $this->oldRev
= false;
1210 if ( $this->oldId
) {
1211 $this->oldRev
= Revision
::newFromId( $this->oldId
);
1212 } elseif ( $this->oldId
=== 0 ) {
1213 $rev = $this->newRev
->getPrevious();
1215 $this->oldId
= $rev->getId();
1216 $this->oldRev
= $rev;
1218 // No previous revision; mark to show as first-version only.
1219 $this->oldId
= false;
1220 $this->oldRev
= false;
1222 } /* elseif ( $this->oldId === false ) leave oldRev false; */
1224 if ( is_null( $this->oldRev
) ) {
1228 if ( $this->oldRev
) {
1229 $this->oldPage
= $this->oldRev
->getTitle();
1232 // Load tags information for both revisions
1233 $dbr = wfGetDB( DB_SLAVE
);
1234 if ( $this->oldId
!== false ) {
1235 $this->oldTags
= $dbr->selectField(
1238 array( 'ts_rev_id' => $this->oldId
),
1242 $this->oldTags
= false;
1244 $this->newTags
= $dbr->selectField(
1247 array( 'ts_rev_id' => $this->newId
),
1255 * Load the text of the revisions, as well as revision data.
1259 function loadText() {
1260 if ( $this->textLoaded
== 2 ) {
1264 // Whether it succeeds or fails, we don't want to try again
1265 $this->textLoaded
= 2;
1267 if ( !$this->loadRevisionData() ) {
1271 if ( $this->oldRev
) {
1272 $this->oldContent
= $this->oldRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1273 if ( $this->oldContent
=== null ) {
1278 if ( $this->newRev
) {
1279 $this->newContent
= $this->newRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1280 if ( $this->newContent
=== null ) {
1289 * Load the text of the new revision, not the old one
1293 function loadNewText() {
1294 if ( $this->textLoaded
>= 1 ) {
1298 $this->textLoaded
= 1;
1300 if ( !$this->loadRevisionData() ) {
1304 $this->newContent
= $this->newRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );