Merge "Show the revision ID on error message when content is missing on difference...
[lhc/web/wiklou.git] / includes / diff / DifferenceEngine.php
1 <?php
2 /**
3 * User interface for the difference engine.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup DifferenceEngine
22 */
23
24 /**
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
28 * clear.
29 */
30 define( 'MW_DIFF_VERSION', '1.11a' );
31
32 /**
33 * @todo document
34 * @ingroup DifferenceEngine
35 */
36 class DifferenceEngine extends ContextSource {
37 /**#@+
38 * @private
39 */
40 var $mOldid, $mNewid;
41 var $mOldTags, $mNewTags;
42 /**
43 * @var Content
44 */
45 var $mOldContent, $mNewContent;
46 protected $mDiffLang;
47
48 /**
49 * @var Title
50 */
51 var $mOldPage, $mNewPage;
52
53 /**
54 * @var Revision
55 */
56 var $mOldRev, $mNewRev;
57 private $mRevisionsIdsLoaded = false; // Have the revisions IDs been loaded
58 var $mRevisionsLoaded = false; // Have the revisions been loaded
59 var $mTextLoaded = 0; // How many text blobs have been loaded, 0, 1 or 2?
60 var $mCacheHit = false; // Was the diff fetched from cache?
61
62 /**
63 * Set this to true to add debug info to the HTML output.
64 * Warning: this may cause RSS readers to spuriously mark articles as "new"
65 * (bug 20601)
66 */
67 var $enableDebugComment = false;
68
69 // If true, line X is not displayed when X is 1, for example to increase
70 // readability and conserve space with many small diffs.
71 protected $mReducedLineNumbers = false;
72
73 // Link to action=markpatrolled
74 protected $mMarkPatrolledLink = null;
75
76 protected $unhide = false; # show rev_deleted content if allowed
77 /**#@-*/
78
79 /**
80 * Constructor
81 * @param $context IContextSource context to use, anything else will be ignored
82 * @param $old Integer old ID we want to show and diff with.
83 * @param $new String either 'prev' or 'next'.
84 * @param $rcid Integer Deprecated, no longer used!
85 * @param $refreshCache boolean If set, refreshes the diff cache
86 * @param $unhide boolean If set, allow viewing deleted revs
87 */
88 function __construct( $context = null, $old = 0, $new = 0, $rcid = 0,
89 $refreshCache = false, $unhide = false )
90 {
91 if ( $context instanceof IContextSource ) {
92 $this->setContext( $context );
93 }
94
95 wfDebug( "DifferenceEngine old '$old' new '$new' rcid '$rcid'\n" );
96
97 $this->mOldid = $old;
98 $this->mNewid = $new;
99 $this->mRefreshCache = $refreshCache;
100 $this->unhide = $unhide;
101 }
102
103 /**
104 * @param $value bool
105 */
106 function setReducedLineNumbers( $value = true ) {
107 $this->mReducedLineNumbers = $value;
108 }
109
110 /**
111 * @return Language
112 */
113 function getDiffLang() {
114 if ( $this->mDiffLang === null ) {
115 # Default language in which the diff text is written.
116 $this->mDiffLang = $this->getTitle()->getPageLanguage();
117 }
118 return $this->mDiffLang;
119 }
120
121 /**
122 * @return bool
123 */
124 function wasCacheHit() {
125 return $this->mCacheHit;
126 }
127
128 /**
129 * @return int
130 */
131 function getOldid() {
132 $this->loadRevisionIds();
133 return $this->mOldid;
134 }
135
136 /**
137 * @return Bool|int
138 */
139 function getNewid() {
140 $this->loadRevisionIds();
141 return $this->mNewid;
142 }
143
144 /**
145 * Look up a special:Undelete link to the given deleted revision id,
146 * as a workaround for being unable to load deleted diffs in currently.
147 *
148 * @param int $id revision ID
149 * @return mixed URL or false
150 */
151 function deletedLink( $id ) {
152 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
153 $dbr = wfGetDB( DB_SLAVE );
154 $row = $dbr->selectRow( 'archive', '*',
155 array( 'ar_rev_id' => $id ),
156 __METHOD__ );
157 if ( $row ) {
158 $rev = Revision::newFromArchiveRow( $row );
159 $title = Title::makeTitleSafe( $row->ar_namespace, $row->ar_title );
160 return SpecialPage::getTitleFor( 'Undelete' )->getFullURL( array(
161 'target' => $title->getPrefixedText(),
162 'timestamp' => $rev->getTimestamp()
163 ));
164 }
165 }
166 return false;
167 }
168
169 /**
170 * Build a wikitext link toward a deleted revision, if viewable.
171 *
172 * @param int $id revision ID
173 * @return string wikitext fragment
174 */
175 function deletedIdMarker( $id ) {
176 $link = $this->deletedLink( $id );
177 if ( $link ) {
178 return "[$link $id]";
179 } else {
180 return $id;
181 }
182 }
183
184 private function showMissingRevision() {
185 $out = $this->getOutput();
186
187 $missing = array();
188 if ( $this->mOldRev === null ||
189 ( $this->mOldRev && $this->mOldContent === null )
190 ) {
191 $missing[] = $this->deletedIdMarker( $this->mOldid );
192 }
193 if ( $this->mNewRev === null ||
194 ( $this->mNewRev && $this->mNewContent === null )
195 ) {
196 $missing[] = $this->deletedIdMarker( $this->mNewid );
197 }
198
199 $out->setPageTitle( $this->msg( 'errorpagetitle' ) );
200 $out->addWikiMsg( 'difference-missing-revision',
201 $this->getLanguage()->listToText( $missing ), count( $missing ) );
202 }
203
204 function showDiffPage( $diffOnly = false ) {
205 wfProfileIn( __METHOD__ );
206
207 # Allow frames except in certain special cases
208 $out = $this->getOutput();
209 $out->allowClickjacking();
210 $out->setRobotPolicy( 'noindex,nofollow' );
211
212 if ( !$this->loadRevisionData() ) {
213 $this->showMissingRevision();
214 wfProfileOut( __METHOD__ );
215 return;
216 }
217
218 $user = $this->getUser();
219 $permErrors = $this->mNewPage->getUserPermissionsErrors( 'read', $user );
220 if ( $this->mOldPage ) { # mOldPage might not be set, see below.
221 $permErrors = wfMergeErrorArrays( $permErrors,
222 $this->mOldPage->getUserPermissionsErrors( 'read', $user ) );
223 }
224 if ( count( $permErrors ) ) {
225 wfProfileOut( __METHOD__ );
226 throw new PermissionsError( 'read', $permErrors );
227 }
228
229 $rollback = '';
230 $undoLink = '';
231
232 $query = array();
233 # Carry over 'diffonly' param via navigation links
234 if ( $diffOnly != $user->getBoolOption( 'diffonly' ) ) {
235 $query['diffonly'] = $diffOnly;
236 }
237 # Cascade unhide param in links for easy deletion browsing
238 if ( $this->unhide ) {
239 $query['unhide'] = 1;
240 }
241
242 # Check if one of the revisions is deleted/suppressed
243 $deleted = $suppressed = false;
244 $allowed = $this->mNewRev->userCan( Revision::DELETED_TEXT, $user );
245
246 $revisionTools = array();
247
248 # mOldRev is false if the difference engine is called with a "vague" query for
249 # a diff between a version V and its previous version V' AND the version V
250 # is the first version of that article. In that case, V' does not exist.
251 if ( $this->mOldRev === false ) {
252 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage->getPrefixedText() ) );
253 $samePage = true;
254 $oldHeader = '';
255 } else {
256 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev, $this->mNewRev ) );
257
258 if ( $this->mNewPage->equals( $this->mOldPage ) ) {
259 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage->getPrefixedText() ) );
260 $samePage = true;
261 } else {
262 $out->setPageTitle( $this->msg( 'difference-title-multipage', $this->mOldPage->getPrefixedText(),
263 $this->mNewPage->getPrefixedText() ) );
264 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
265 $samePage = false;
266 }
267
268 if ( $samePage && $this->mNewPage->quickUserCan( 'edit', $user ) ) {
269 if ( $this->mNewRev->isCurrent() && $this->mNewPage->userCan( 'rollback', $user ) ) {
270 $rollbackLink = Linker::generateRollback( $this->mNewRev, $this->getContext() );
271 if ( $rollbackLink ) {
272 $out->preventClickjacking();
273 $rollback = '&#160;&#160;&#160;' . $rollbackLink;
274 }
275 }
276 if ( !$this->mOldRev->isDeleted( Revision::DELETED_TEXT ) && !$this->mNewRev->isDeleted( Revision::DELETED_TEXT ) ) {
277 $undoLink = Html::element( 'a', array(
278 'href' => $this->mNewPage->getLocalURL( array(
279 'action' => 'edit',
280 'undoafter' => $this->mOldid,
281 'undo' => $this->mNewid ) ),
282 'title' => Linker::titleAttrib( 'undo' )
283 ),
284 $this->msg( 'editundo' )->text()
285 );
286 $revisionTools[] = $undoLink;
287 }
288 }
289
290 # Make "previous revision link"
291 if ( $samePage && $this->mOldRev->getPrevious() ) {
292 $prevlink = Linker::linkKnown(
293 $this->mOldPage,
294 $this->msg( 'previousdiff' )->escaped(),
295 array( 'id' => 'differences-prevlink' ),
296 array( 'diff' => 'prev', 'oldid' => $this->mOldid ) + $query
297 );
298 } else {
299 $prevlink = '&#160;';
300 }
301
302 if ( $this->mOldRev->isMinor() ) {
303 $oldminor = ChangesList::flag( 'minor' );
304 } else {
305 $oldminor = '';
306 }
307
308 $ldel = $this->revisionDeleteLink( $this->mOldRev );
309 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev, 'complete' );
310 $oldChangeTags = ChangeTags::formatSummaryRow( $this->mOldTags, 'diff' );
311
312 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
313 '<div id="mw-diff-otitle2">' .
314 Linker::revUserTools( $this->mOldRev, !$this->unhide ) . '</div>' .
315 '<div id="mw-diff-otitle3">' . $oldminor .
316 Linker::revComment( $this->mOldRev, !$diffOnly, !$this->unhide ) . $ldel . '</div>' .
317 '<div id="mw-diff-otitle5">' . $oldChangeTags[0] . '</div>' .
318 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
319
320 if ( $this->mOldRev->isDeleted( Revision::DELETED_TEXT ) ) {
321 $deleted = true; // old revisions text is hidden
322 if ( $this->mOldRev->isDeleted( Revision::DELETED_RESTRICTED ) ) {
323 $suppressed = true; // also suppressed
324 }
325 }
326
327 # Check if this user can see the revisions
328 if ( !$this->mOldRev->userCan( Revision::DELETED_TEXT, $user ) ) {
329 $allowed = false;
330 }
331 }
332
333 # Make "next revision link"
334 # Skip next link on the top revision
335 if ( $samePage && !$this->mNewRev->isCurrent() ) {
336 $nextlink = Linker::linkKnown(
337 $this->mNewPage,
338 $this->msg( 'nextdiff' )->escaped(),
339 array( 'id' => 'differences-nextlink' ),
340 array( 'diff' => 'next', 'oldid' => $this->mNewid ) + $query
341 );
342 } else {
343 $nextlink = '&#160;';
344 }
345
346 if ( $this->mNewRev->isMinor() ) {
347 $newminor = ChangesList::flag( 'minor' );
348 } else {
349 $newminor = '';
350 }
351
352 # Handle RevisionDelete links...
353 $rdel = $this->revisionDeleteLink( $this->mNewRev );
354
355 # Allow extensions to define their own revision tools
356 wfRunHooks( 'DiffRevisionTools', array( $this->mNewRev, &$revisionTools ) );
357 $formattedRevisionTools = array();
358 // Put each one in parentheses (poor man's button)
359 foreach ( $revisionTools as $tool ) {
360 $formattedRevisionTools[] = $this->msg( 'parentheses' )->rawParams( $tool )->escaped();
361 }
362 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev, 'complete' ) . ' ' . implode( ' ', $formattedRevisionTools );
363 $newChangeTags = ChangeTags::formatSummaryRow( $this->mNewTags, 'diff' );
364
365 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
366 '<div id="mw-diff-ntitle2">' . Linker::revUserTools( $this->mNewRev, !$this->unhide ) .
367 " $rollback</div>" .
368 '<div id="mw-diff-ntitle3">' . $newminor .
369 Linker::revComment( $this->mNewRev, !$diffOnly, !$this->unhide ) . $rdel . '</div>' .
370 '<div id="mw-diff-ntitle5">' . $newChangeTags[0] . '</div>' .
371 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
372
373 if ( $this->mNewRev->isDeleted( Revision::DELETED_TEXT ) ) {
374 $deleted = true; // new revisions text is hidden
375 if ( $this->mNewRev->isDeleted( Revision::DELETED_RESTRICTED ) ) {
376 $suppressed = true; // also suppressed
377 }
378 }
379
380 # If the diff cannot be shown due to a deleted revision, then output
381 # the diff header and links to unhide (if available)...
382 if ( $deleted && ( !$this->unhide || !$allowed ) ) {
383 $this->showDiffStyle();
384 $multi = $this->getMultiNotice();
385 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
386 if ( !$allowed ) {
387 $msg = $suppressed ? 'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
388 # Give explanation for why revision is not visible
389 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
390 array( $msg ) );
391 } else {
392 # Give explanation and add a link to view the diff...
393 $link = $this->getTitle()->getFullURL( $this->getRequest()->appendQueryValue( 'unhide', '1', true ) );
394 $msg = $suppressed ? 'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
395 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n", array( $msg, $link ) );
396 }
397 # Otherwise, output a regular diff...
398 } else {
399 # Add deletion notice if the user is viewing deleted content
400 $notice = '';
401 if ( $deleted ) {
402 $msg = $suppressed ? 'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
403 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" . $this->msg( $msg )->parse() . "</div>\n";
404 }
405 $this->showDiff( $oldHeader, $newHeader, $notice );
406 if ( !$diffOnly ) {
407 $this->renderNewRevision();
408 }
409 }
410 wfProfileOut( __METHOD__ );
411 }
412
413 /**
414 * Get a link to mark the change as patrolled, or '' if there's either no
415 * revision to patrol or the user is not allowed to to it.
416 * Side effect: When the patrol link is build, this method will call
417 * OutputPage::preventClickjacking() and load mediawiki.page.patrol.ajax.
418 *
419 * @return String
420 */
421 protected function markPatrolledLink() {
422 global $wgUseRCPatrol, $wgEnableAPI, $wgEnableWriteAPI;
423 $user = $this->getUser();
424
425 if ( $this->mMarkPatrolledLink === null ) {
426 // Prepare a change patrol link, if applicable
427 if (
428 // Is patrolling enabled and the user allowed to?
429 $wgUseRCPatrol && $this->mNewPage->quickUserCan( 'patrol', $user ) &&
430 // Only do this if the revision isn't more than 6 hours older
431 // than the Max RC age (6h because the RC might not be cleaned out regularly)
432 RecentChange::isInRCLifespan( $this->mNewRev->getTimestamp(), 21600 )
433 ) {
434 // Look for an unpatrolled change corresponding to this diff
435
436 $db = wfGetDB( DB_SLAVE );
437 $change = RecentChange::newFromConds(
438 array(
439 'rc_timestamp' => $db->timestamp( $this->mNewRev->getTimestamp() ),
440 'rc_this_oldid' => $this->mNewid,
441 'rc_patrolled' => 0
442 ),
443 __METHOD__,
444 array( 'USE INDEX' => 'rc_timestamp' )
445 );
446
447 if ( $change && $change->getPerformer()->getName() !== $user->getName() ) {
448 $rcid = $change->getAttribute( 'rc_id' );
449 } else {
450 // None found or the page has been created by the current user.
451 // If the user could patrol this it already would be patrolled
452 $rcid = 0;
453 }
454 // Build the link
455 if ( $rcid ) {
456 $this->getOutput()->preventClickjacking();
457 if ( $wgEnableAPI && $wgEnableWriteAPI
458 && $user->isAllowed( 'writeapi' )
459 ) {
460 $this->getOutput()->addModules( 'mediawiki.page.patrol.ajax' );
461 }
462
463 $token = $user->getEditToken( $rcid );
464 $this->mMarkPatrolledLink = ' <span class="patrollink">[' . Linker::linkKnown(
465 $this->mNewPage,
466 $this->msg( 'markaspatrolleddiff' )->escaped(),
467 array(),
468 array(
469 'action' => 'markpatrolled',
470 'rcid' => $rcid,
471 'token' => $token,
472 )
473 ) . ']</span>';
474 } else {
475 $this->mMarkPatrolledLink = '';
476 }
477 } else {
478 $this->mMarkPatrolledLink = '';
479 }
480 }
481
482 return $this->mMarkPatrolledLink;
483 }
484
485 /**
486 * @param $rev Revision
487 * @return String
488 */
489 protected function revisionDeleteLink( $rev ) {
490 $link = Linker::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
491 if ( $link !== '' ) {
492 $link = '&#160;&#160;&#160;' . $link . ' ';
493 }
494 return $link;
495 }
496
497 /**
498 * Show the new revision of the page.
499 */
500 function renderNewRevision() {
501 wfProfileIn( __METHOD__ );
502 $out = $this->getOutput();
503 $revHeader = $this->getRevisionHeader( $this->mNewRev );
504 # Add "current version as of X" title
505 $out->addHTML( "<hr class='diff-hr' />
506 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
507 # Page content may be handled by a hooked call instead...
508 if ( wfRunHooks( 'ArticleContentOnDiff', array( $this, $out ) ) ) {
509 $this->loadNewText();
510 $out->setRevisionId( $this->mNewid );
511 $out->setRevisionTimestamp( $this->mNewRev->getTimestamp() );
512 $out->setArticleFlag( true );
513
514 // NOTE: only needed for B/C: custom rendering of JS/CSS via hook
515 if ( $this->mNewPage->isCssJsSubpage() || $this->mNewPage->isCssOrJsPage() ) {
516 // Stolen from Article::view --AG 2007-10-11
517 // Give hooks a chance to customise the output
518 // @todo standardize this crap into one function
519 if ( ContentHandler::runLegacyHooks( 'ShowRawCssJs', array( $this->mNewContent, $this->mNewPage, $out ) ) ) {
520 // NOTE: deprecated hook, B/C only
521 // use the content object's own rendering
522 $cnt = $this->mNewRev->getContent();
523 $po = $cnt ? $cnt->getParserOutput( $this->mNewRev->getTitle(), $this->mNewRev->getId() ) : null;
524 $txt = $po ? $po->getText() : '';
525 $out->addHTML( $txt );
526 }
527 } elseif ( !wfRunHooks( 'ArticleContentViewCustom', array( $this->mNewContent, $this->mNewPage, $out ) ) ) {
528 // Handled by extension
529 } elseif ( !ContentHandler::runLegacyHooks( 'ArticleViewCustom', array( $this->mNewContent, $this->mNewPage, $out ) ) ) {
530 // NOTE: deprecated hook, B/C only
531 // Handled by extension
532 } else {
533 // Normal page
534 if ( $this->getTitle()->equals( $this->mNewPage ) ) {
535 // If the Title stored in the context is the same as the one
536 // of the new revision, we can use its associated WikiPage
537 // object.
538 $wikiPage = $this->getWikiPage();
539 } else {
540 // Otherwise we need to create our own WikiPage object
541 $wikiPage = WikiPage::factory( $this->mNewPage );
542 }
543
544 $parserOutput = $this->getParserOutput( $wikiPage, $this->mNewRev );
545
546 # Also try to load it as a redirect
547 $rt = $this->mNewContent ? $this->mNewContent->getRedirectTarget() : null;
548
549 if ( $rt ) {
550 $article = Article::newFromTitle( $this->mNewPage, $this->getContext() );
551 $out->addHTML( $article->viewRedirect( $rt ) );
552
553 # WikiPage::getParserOutput() should not return false, but just in case
554 if ( $parserOutput ) {
555 # Show categories etc.
556 $out->addParserOutputNoText( $parserOutput );
557 }
558 } elseif ( $parserOutput ) {
559 $out->addParserOutput( $parserOutput );
560 }
561 }
562 }
563 # Add redundant patrol link on bottom...
564 $out->addHTML( $this->markPatrolledLink() );
565
566 wfProfileOut( __METHOD__ );
567 }
568
569 protected function getParserOutput( WikiPage $page, Revision $rev ) {
570 $parserOptions = $page->makeParserOptions( $this->getContext() );
571
572 if ( !$rev->isCurrent() || !$rev->getTitle()->quickUserCan( "edit" ) ) {
573 $parserOptions->setEditSection( false );
574 }
575
576 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
577 return $parserOutput;
578 }
579
580 /**
581 * Get the diff text, send it to the OutputPage object
582 * Returns false if the diff could not be generated, otherwise returns true
583 *
584 * @return bool
585 */
586 function showDiff( $otitle, $ntitle, $notice = '' ) {
587 $diff = $this->getDiff( $otitle, $ntitle, $notice );
588 if ( $diff === false ) {
589 $this->showMissingRevision();
590 return false;
591 } else {
592 $this->showDiffStyle();
593 $this->getOutput()->addHTML( $diff );
594 return true;
595 }
596 }
597
598 /**
599 * Add style sheets and supporting JS for diff display.
600 */
601 function showDiffStyle() {
602 $this->getOutput()->addModuleStyles( 'mediawiki.action.history.diff' );
603 }
604
605 /**
606 * Get complete diff table, including header
607 *
608 * @param string|bool $otitle Header for old text or false
609 * @param string|bool $ntitle Header for new text or false
610 * @param string $notice HTML between diff header and body
611 * @return mixed
612 */
613 function getDiff( $otitle, $ntitle, $notice = '' ) {
614 $body = $this->getDiffBody();
615 if ( $body === false ) {
616 return false;
617 } else {
618 $multi = $this->getMultiNotice();
619 // Display a message when the diff is empty
620 if ( $body === '' ) {
621 $notice .= '<div class="mw-diff-empty">' . $this->msg( 'diff-empty' )->parse() . "</div>\n";
622 }
623 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
624 }
625 }
626
627 /**
628 * Get the diff table body, without header
629 *
630 * @return mixed (string/false)
631 */
632 public function getDiffBody() {
633 global $wgMemc;
634 wfProfileIn( __METHOD__ );
635 $this->mCacheHit = true;
636 // Check if the diff should be hidden from this user
637 if ( !$this->loadRevisionData() ) {
638 wfProfileOut( __METHOD__ );
639 return false;
640 } elseif ( $this->mOldRev && !$this->mOldRev->userCan( Revision::DELETED_TEXT, $this->getUser() ) ) {
641 wfProfileOut( __METHOD__ );
642 return false;
643 } elseif ( $this->mNewRev && !$this->mNewRev->userCan( Revision::DELETED_TEXT, $this->getUser() ) ) {
644 wfProfileOut( __METHOD__ );
645 return false;
646 }
647 // Short-circuit
648 if ( $this->mOldRev === false || ( $this->mOldRev && $this->mNewRev
649 && $this->mOldRev->getID() == $this->mNewRev->getID() ) )
650 {
651 wfProfileOut( __METHOD__ );
652 return '';
653 }
654 // Cacheable?
655 $key = false;
656 if ( $this->mOldid && $this->mNewid ) {
657 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION,
658 'oldid', $this->mOldid, 'newid', $this->mNewid );
659 // Try cache
660 if ( !$this->mRefreshCache ) {
661 $difftext = $wgMemc->get( $key );
662 if ( $difftext ) {
663 wfIncrStats( 'diff_cache_hit' );
664 $difftext = $this->localiseLineNumbers( $difftext );
665 $difftext .= "\n<!-- diff cache key $key -->\n";
666 wfProfileOut( __METHOD__ );
667 return $difftext;
668 }
669 } // don't try to load but save the result
670 }
671 $this->mCacheHit = false;
672
673 // Loadtext is permission safe, this just clears out the diff
674 if ( !$this->loadText() ) {
675 wfProfileOut( __METHOD__ );
676 return false;
677 }
678
679 $difftext = $this->generateContentDiffBody( $this->mOldContent, $this->mNewContent );
680
681 // Save to cache for 7 days
682 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
683 wfIncrStats( 'diff_uncacheable' );
684 } elseif ( $key !== false && $difftext !== false ) {
685 wfIncrStats( 'diff_cache_miss' );
686 $wgMemc->set( $key, $difftext, 7 * 86400 );
687 } else {
688 wfIncrStats( 'diff_uncacheable' );
689 }
690 // Replace line numbers with the text in the user's language
691 if ( $difftext !== false ) {
692 $difftext = $this->localiseLineNumbers( $difftext );
693 }
694 wfProfileOut( __METHOD__ );
695 return $difftext;
696 }
697
698 /**
699 * Make sure the proper modules are loaded before we try to
700 * make the diff
701 */
702 private function initDiffEngines() {
703 global $wgExternalDiffEngine;
704 if ( $wgExternalDiffEngine == 'wikidiff' && !function_exists( 'wikidiff_do_diff' ) ) {
705 wfProfileIn( __METHOD__ . '-php_wikidiff.so' );
706 wfDl( 'php_wikidiff' );
707 wfProfileOut( __METHOD__ . '-php_wikidiff.so' );
708 }
709 elseif ( $wgExternalDiffEngine == 'wikidiff2' && !function_exists( 'wikidiff2_do_diff' ) ) {
710 wfProfileIn( __METHOD__ . '-php_wikidiff2.so' );
711 wfDl( 'wikidiff2' );
712 wfProfileOut( __METHOD__ . '-php_wikidiff2.so' );
713 }
714 }
715
716 /**
717 * Generate a diff, no caching.
718 *
719 * This implementation uses generateTextDiffBody() to generate a diff based on the default
720 * serialization of the given Content objects. This will fail if $old or $new are not
721 * instances of TextContent.
722 *
723 * Subclasses may override this to provide a different rendering for the diff,
724 * perhaps taking advantage of the content's native form. This is required for all content
725 * models that are not text based.
726 *
727 * @param $old Content: old content
728 * @param $new Content: new content
729 *
730 * @return bool|string
731 * @since 1.21
732 * @throws MWException if $old or $new are not instances of TextContent.
733 */
734 function generateContentDiffBody( Content $old, Content $new ) {
735 if ( !( $old instanceof TextContent ) ) {
736 throw new MWException( "Diff not implemented for " . get_class( $old ) . "; "
737 . "override generateContentDiffBody to fix this." );
738 }
739
740 if ( !( $new instanceof TextContent ) ) {
741 throw new MWException( "Diff not implemented for " . get_class( $new ) . "; "
742 . "override generateContentDiffBody to fix this." );
743 }
744
745 $otext = $old->serialize();
746 $ntext = $new->serialize();
747
748 return $this->generateTextDiffBody( $otext, $ntext );
749 }
750
751 /**
752 * Generate a diff, no caching
753 *
754 * @param string $otext old text, must be already segmented
755 * @param string $ntext new text, must be already segmented
756 * @return bool|string
757 * @deprecated since 1.21, use generateContentDiffBody() instead!
758 */
759 function generateDiffBody( $otext, $ntext ) {
760 ContentHandler::deprecated( __METHOD__, "1.21" );
761
762 return $this->generateTextDiffBody( $otext, $ntext );
763 }
764
765 /**
766 * Generate a diff, no caching
767 *
768 * @todo move this to TextDifferenceEngine, make DifferenceEngine abstract. At some point.
769 *
770 * @param string $otext old text, must be already segmented
771 * @param string $ntext new text, must be already segmented
772 * @return bool|string
773 */
774 function generateTextDiffBody( $otext, $ntext ) {
775 global $wgExternalDiffEngine, $wgContLang;
776
777 wfProfileIn( __METHOD__ );
778
779 $otext = str_replace( "\r\n", "\n", $otext );
780 $ntext = str_replace( "\r\n", "\n", $ntext );
781
782 $this->initDiffEngines();
783
784 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
785 # For historical reasons, external diff engine expects
786 # input text to be HTML-escaped already
787 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
788 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
789 wfProfileOut( __METHOD__ );
790 return $wgContLang->unsegmentForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
791 $this->debug( 'wikidiff1' );
792 }
793
794 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
795 # Better external diff engine, the 2 may some day be dropped
796 # This one does the escaping and segmenting itself
797 wfProfileIn( 'wikidiff2_do_diff' );
798 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
799 $text .= $this->debug( 'wikidiff2' );
800 wfProfileOut( 'wikidiff2_do_diff' );
801 wfProfileOut( __METHOD__ );
802 return $text;
803 }
804 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
805 # Diff via the shell
806 $tmpDir = wfTempDir();
807 $tempName1 = tempnam( $tmpDir, 'diff_' );
808 $tempName2 = tempnam( $tmpDir, 'diff_' );
809
810 $tempFile1 = fopen( $tempName1, "w" );
811 if ( !$tempFile1 ) {
812 wfProfileOut( __METHOD__ );
813 return false;
814 }
815 $tempFile2 = fopen( $tempName2, "w" );
816 if ( !$tempFile2 ) {
817 wfProfileOut( __METHOD__ );
818 return false;
819 }
820 fwrite( $tempFile1, $otext );
821 fwrite( $tempFile2, $ntext );
822 fclose( $tempFile1 );
823 fclose( $tempFile2 );
824 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
825 wfProfileIn( __METHOD__ . "-shellexec" );
826 $difftext = wfShellExec( $cmd );
827 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
828 wfProfileOut( __METHOD__ . "-shellexec" );
829 unlink( $tempName1 );
830 unlink( $tempName2 );
831 wfProfileOut( __METHOD__ );
832 return $difftext;
833 }
834
835 # Native PHP diff
836 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
837 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
838 $diffs = new Diff( $ota, $nta );
839 $formatter = new TableDiffFormatter();
840 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
841 wfProfileOut( __METHOD__ );
842 return $difftext;
843 }
844
845 /**
846 * Generate a debug comment indicating diff generating time,
847 * server node, and generator backend.
848 * @return string
849 */
850 protected function debug( $generator = "internal" ) {
851 global $wgShowHostnames;
852 if ( !$this->enableDebugComment ) {
853 return '';
854 }
855 $data = array( $generator );
856 if ( $wgShowHostnames ) {
857 $data[] = wfHostname();
858 }
859 $data[] = wfTimestamp( TS_DB );
860 return "<!-- diff generator: " .
861 implode( " ",
862 array_map(
863 "htmlspecialchars",
864 $data ) ) .
865 " -->\n";
866 }
867
868 /**
869 * Replace line numbers with the text in the user's language
870 * @return mixed
871 */
872 function localiseLineNumbers( $text ) {
873 return preg_replace_callback( '/<!--LINE (\d+)-->/',
874 array( &$this, 'localiseLineNumbersCb' ), $text );
875 }
876
877 function localiseLineNumbersCb( $matches ) {
878 if ( $matches[1] === '1' && $this->mReducedLineNumbers ) {
879 return '';
880 }
881 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
882 }
883
884 /**
885 * If there are revisions between the ones being compared, return a note saying so.
886 * @return string
887 */
888 function getMultiNotice() {
889 if ( !is_object( $this->mOldRev ) || !is_object( $this->mNewRev ) ) {
890 return '';
891 } elseif ( !$this->mOldPage->equals( $this->mNewPage ) ) {
892 // Comparing two different pages? Count would be meaningless.
893 return '';
894 }
895
896 if ( $this->mOldRev->getTimestamp() > $this->mNewRev->getTimestamp() ) {
897 $oldRev = $this->mNewRev; // flip
898 $newRev = $this->mOldRev; // flip
899 } else { // normal case
900 $oldRev = $this->mOldRev;
901 $newRev = $this->mNewRev;
902 }
903
904 $nEdits = $this->mNewPage->countRevisionsBetween( $oldRev, $newRev );
905 if ( $nEdits > 0 ) {
906 $limit = 100; // use diff-multi-manyusers if too many users
907 $numUsers = $this->mNewPage->countAuthorsBetween( $oldRev, $newRev, $limit );
908 return self::intermediateEditsMsg( $nEdits, $numUsers, $limit );
909 }
910 return ''; // nothing
911 }
912
913 /**
914 * Get a notice about how many intermediate edits and users there are
915 * @param $numEdits int
916 * @param $numUsers int
917 * @param $limit int
918 * @return string
919 */
920 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
921 if ( $numUsers > $limit ) {
922 $msg = 'diff-multi-manyusers';
923 $numUsers = $limit;
924 } else {
925 $msg = 'diff-multi';
926 }
927 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
928 }
929
930 /**
931 * Get a header for a specified revision.
932 *
933 * @param $rev Revision
934 * @param string $complete 'complete' to get the header wrapped depending
935 * the visibility of the revision and a link to edit the page.
936 * @return String HTML fragment
937 */
938 protected function getRevisionHeader( Revision $rev, $complete = '' ) {
939 $lang = $this->getLanguage();
940 $user = $this->getUser();
941 $revtimestamp = $rev->getTimestamp();
942 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
943 $dateofrev = $lang->userDate( $revtimestamp, $user );
944 $timeofrev = $lang->userTime( $revtimestamp, $user );
945
946 $header = $this->msg(
947 $rev->isCurrent() ? 'currentrev-asof' : 'revisionasof',
948 $timestamp,
949 $dateofrev,
950 $timeofrev
951 )->escaped();
952
953 if ( $complete !== 'complete' ) {
954 return $header;
955 }
956
957 $title = $rev->getTitle();
958
959 $header = Linker::linkKnown( $title, $header, array(),
960 array( 'oldid' => $rev->getID() ) );
961
962 if ( $rev->userCan( Revision::DELETED_TEXT, $user ) ) {
963 $editQuery = array( 'action' => 'edit' );
964 if ( !$rev->isCurrent() ) {
965 $editQuery['oldid'] = $rev->getID();
966 }
967
968 $msg = $this->msg( $title->quickUserCan( 'edit', $user ) ? 'editold' : 'viewsourceold' )->escaped();
969 $header .= ' ' . $this->msg( 'parentheses' )->rawParams(
970 Linker::linkKnown( $title, $msg, array(), $editQuery ) )->plain();
971 if ( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
972 $header = Html::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
973 }
974 } else {
975 $header = Html::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
976 }
977
978 return $header;
979 }
980
981 /**
982 * Add the header to a diff body
983 *
984 * @return string
985 */
986 function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
987 // shared.css sets diff in interface language/dir, but the actual content
988 // is often in a different language, mostly the page content language/dir
989 $tableClass = 'diff diff-contentalign-' . htmlspecialchars( $this->getDiffLang()->alignStart() );
990 $header = "<table class='$tableClass'>";
991
992 if ( !$diff && !$otitle ) {
993 $header .= "
994 <tr style='vertical-align: top;'>
995 <td class='diff-ntitle'>{$ntitle}</td>
996 </tr>";
997 $multiColspan = 1;
998 } else {
999 if ( $diff ) { // Safari/Chrome show broken output if cols not used
1000 $header .= "
1001 <col class='diff-marker' />
1002 <col class='diff-content' />
1003 <col class='diff-marker' />
1004 <col class='diff-content' />";
1005 $colspan = 2;
1006 $multiColspan = 4;
1007 } else {
1008 $colspan = 1;
1009 $multiColspan = 2;
1010 }
1011 if ( $otitle || $ntitle ) {
1012 $header .= "
1013 <tr style='vertical-align: top;'>
1014 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
1015 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
1016 </tr>";
1017 }
1018 }
1019
1020 if ( $multi != '' ) {
1021 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;' class='diff-multi'>{$multi}</td></tr>";
1022 }
1023 if ( $notice != '' ) {
1024 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;'>{$notice}</td></tr>";
1025 }
1026
1027 return $header . $diff . "</table>";
1028 }
1029
1030 /**
1031 * Use specified text instead of loading from the database
1032 * @deprecated since 1.21, use setContent() instead.
1033 */
1034 function setText( $oldText, $newText ) {
1035 ContentHandler::deprecated( __METHOD__, "1.21" );
1036
1037 $oldContent = ContentHandler::makeContent( $oldText, $this->getTitle() );
1038 $newContent = ContentHandler::makeContent( $newText, $this->getTitle() );
1039
1040 $this->setContent( $oldContent, $newContent );
1041 }
1042
1043 /**
1044 * Use specified text instead of loading from the database
1045 * @since 1.21
1046 */
1047 function setContent( Content $oldContent, Content $newContent ) {
1048 $this->mOldContent = $oldContent;
1049 $this->mNewContent = $newContent;
1050
1051 $this->mTextLoaded = 2;
1052 $this->mRevisionsLoaded = true;
1053 }
1054
1055 /**
1056 * Set the language in which the diff text is written
1057 * (Defaults to page content language).
1058 * @since 1.19
1059 */
1060 function setTextLanguage( $lang ) {
1061 $this->mDiffLang = wfGetLangObj( $lang );
1062 }
1063
1064 /**
1065 * Load revision IDs
1066 */
1067 private function loadRevisionIds() {
1068 if ( $this->mRevisionsIdsLoaded ) {
1069 return;
1070 }
1071
1072 $this->mRevisionsIdsLoaded = true;
1073
1074 $old = $this->mOldid;
1075 $new = $this->mNewid;
1076
1077 if ( $new === 'prev' ) {
1078 # Show diff between revision $old and the previous one.
1079 # Get previous one from DB.
1080 $this->mNewid = intval( $old );
1081 $this->mOldid = $this->getTitle()->getPreviousRevisionID( $this->mNewid );
1082 } elseif ( $new === 'next' ) {
1083 # Show diff between revision $old and the next one.
1084 # Get next one from DB.
1085 $this->mOldid = intval( $old );
1086 $this->mNewid = $this->getTitle()->getNextRevisionID( $this->mOldid );
1087 if ( $this->mNewid === false ) {
1088 # if no result, NewId points to the newest old revision. The only newer
1089 # revision is cur, which is "0".
1090 $this->mNewid = 0;
1091 }
1092 } else {
1093 $this->mOldid = intval( $old );
1094 $this->mNewid = intval( $new );
1095 wfRunHooks( 'NewDifferenceEngine', array( $this->getTitle(), &$this->mOldid, &$this->mNewid, $old, $new ) );
1096 }
1097 }
1098
1099 /**
1100 * Load revision metadata for the specified articles. If newid is 0, then compare
1101 * the old article in oldid to the current article; if oldid is 0, then
1102 * compare the current article to the immediately previous one (ignoring the
1103 * value of newid).
1104 *
1105 * If oldid is false, leave the corresponding revision object set
1106 * to false. This is impossible via ordinary user input, and is provided for
1107 * API convenience.
1108 *
1109 * @return bool
1110 */
1111 function loadRevisionData() {
1112 if ( $this->mRevisionsLoaded ) {
1113 return true;
1114 }
1115
1116 // Whether it succeeds or fails, we don't want to try again
1117 $this->mRevisionsLoaded = true;
1118
1119 $this->loadRevisionIds();
1120
1121 // Load the new revision object
1122 $this->mNewRev = $this->mNewid
1123 ? Revision::newFromId( $this->mNewid )
1124 : Revision::newFromTitle( $this->getTitle(), false, Revision::READ_NORMAL );
1125
1126 if ( !$this->mNewRev instanceof Revision ) {
1127 return false;
1128 }
1129
1130 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1131 $this->mNewid = $this->mNewRev->getId();
1132 $this->mNewPage = $this->mNewRev->getTitle();
1133
1134 // Load the old revision object
1135 $this->mOldRev = false;
1136 if ( $this->mOldid ) {
1137 $this->mOldRev = Revision::newFromId( $this->mOldid );
1138 } elseif ( $this->mOldid === 0 ) {
1139 $rev = $this->mNewRev->getPrevious();
1140 if ( $rev ) {
1141 $this->mOldid = $rev->getId();
1142 $this->mOldRev = $rev;
1143 } else {
1144 // No previous revision; mark to show as first-version only.
1145 $this->mOldid = false;
1146 $this->mOldRev = false;
1147 }
1148 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1149
1150 if ( is_null( $this->mOldRev ) ) {
1151 return false;
1152 }
1153
1154 if ( $this->mOldRev ) {
1155 $this->mOldPage = $this->mOldRev->getTitle();
1156 }
1157
1158 // Load tags information for both revisions
1159 $dbr = wfGetDB( DB_SLAVE );
1160 if ( $this->mOldid !== false ) {
1161 $this->mOldTags = $dbr->selectField(
1162 'tag_summary',
1163 'ts_tags',
1164 array( 'ts_rev_id' => $this->mOldid ),
1165 __METHOD__
1166 );
1167 } else {
1168 $this->mOldTags = false;
1169 }
1170 $this->mNewTags = $dbr->selectField(
1171 'tag_summary',
1172 'ts_tags',
1173 array( 'ts_rev_id' => $this->mNewid ),
1174 __METHOD__
1175 );
1176
1177 return true;
1178 }
1179
1180 /**
1181 * Load the text of the revisions, as well as revision data.
1182 *
1183 * @return bool
1184 */
1185 function loadText() {
1186 if ( $this->mTextLoaded == 2 ) {
1187 return true;
1188 }
1189
1190 // Whether it succeeds or fails, we don't want to try again
1191 $this->mTextLoaded = 2;
1192
1193 if ( !$this->loadRevisionData() ) {
1194 return false;
1195 }
1196
1197 if ( $this->mOldRev ) {
1198 $this->mOldContent = $this->mOldRev->getContent( Revision::FOR_THIS_USER, $this->getUser() );
1199 if ( $this->mOldContent === null ) {
1200 return false;
1201 }
1202 }
1203
1204 if ( $this->mNewRev ) {
1205 $this->mNewContent = $this->mNewRev->getContent( Revision::FOR_THIS_USER, $this->getUser() );
1206 if ( $this->mNewContent === null ) {
1207 return false;
1208 }
1209 }
1210
1211 return true;
1212 }
1213
1214 /**
1215 * Load the text of the new revision, not the old one
1216 *
1217 * @return bool
1218 */
1219 function loadNewText() {
1220 if ( $this->mTextLoaded >= 1 ) {
1221 return true;
1222 }
1223
1224 $this->mTextLoaded = 1;
1225
1226 if ( !$this->loadRevisionData() ) {
1227 return false;
1228 }
1229
1230 $this->mNewContent = $this->mNewRev->getContent( Revision::FOR_THIS_USER, $this->getUser() );
1231
1232 return true;
1233 }
1234 }