28f8889cd4e1162998e684bf7ea351034b267377
[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 * @todo document
26 * @ingroup DifferenceEngine
27 */
28 class DifferenceEngine extends ContextSource {
29 /**
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
33 * clear.
34 */
35 const CACHE_VERSION ='1.11a';
36
37 /**#@+
38 * @private
39 */
40 public $oldId;
41 public $newId;
42 private $oldTags;
43 private $newTags;
44 /**
45 * @var Content
46 */
47 public $oldContent;
48 /**
49 * @var Content
50 */
51 public $newContent;
52 protected $diffLang;
53
54 /**
55 * @var Title
56 */
57 public $oldPage;
58 /**
59 * @var Title
60 */
61 public $newPage;
62
63 /**
64 * @var Revision
65 */
66 public $oldRev;
67 /**
68 * @var Revision
69 */
70 public $newRev;
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?
75
76 /**
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"
79 * (bug 20601)
80 */
81 public $enableDebugComment = false;
82
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;
86
87 // Link to action=markpatrolled
88 protected $markPatrolledLink = null;
89
90 protected $unhide = false; # show rev_deleted content if allowed
91 private $refreshCache;
92 /**#@-*/
93
94 /**
95 * Constructor
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
102 */
103 function __construct( $context = null, $old = 0, $new = 0, $rcid = 0,
104 $refreshCache = false, $unhide = false
105 ) {
106 if ( $context instanceof IContextSource ) {
107 $this->setContext( $context );
108 }
109
110 wfDebug( "DifferenceEngine old '$old' new '$new' rcid '$rcid'\n" );
111
112 $this->oldId = $old;
113 $this->newId = $new;
114 $this->refreshCache = $refreshCache;
115 $this->unhide = $unhide;
116 }
117
118 /**
119 * @param $value bool
120 */
121 function setReducedLineNumbers( $value = true ) {
122 $this->reducedLineNumbers = $value;
123 }
124
125 /**
126 * @return Language
127 */
128 function getDiffLang() {
129 if ( $this->diffLang === null ) {
130 # Default language in which the diff text is written.
131 $this->diffLang = $this->getTitle()->getPageLanguage();
132 }
133 return $this->diffLang;
134 }
135
136 /**
137 * @return bool
138 */
139 function wasCacheHit() {
140 return $this->cacheHit;
141 }
142
143 /**
144 * @return int
145 */
146 function getOldid() {
147 $this->loadRevisionIds();
148 return $this->oldId;
149 }
150
151 /**
152 * @return Bool|int
153 */
154 function getNewid() {
155 $this->loadRevisionIds();
156 return $this->newId;
157 }
158
159 /**
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.
162 *
163 * @param int $id revision ID
164 * @return mixed URL or false
165 */
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 ),
171 __METHOD__ );
172 if ( $row ) {
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()
178 ));
179 }
180 }
181 return false;
182 }
183
184 /**
185 * Build a wikitext link toward a deleted revision, if viewable.
186 *
187 * @param int $id revision ID
188 * @return string wikitext fragment
189 */
190 function deletedIdMarker( $id ) {
191 $link = $this->deletedLink( $id );
192 if ( $link ) {
193 return "[$link $id]";
194 } else {
195 return $id;
196 }
197 }
198
199 private function showMissingRevision() {
200 $out = $this->getOutput();
201
202 $missing = array();
203 if ( $this->oldRev === null ||
204 ( $this->oldRev && $this->oldContent === null )
205 ) {
206 $missing[] = $this->deletedIdMarker( $this->oldId );
207 }
208 if ( $this->newRev === null ||
209 ( $this->newRev && $this->newContent === null )
210 ) {
211 $missing[] = $this->deletedIdMarker( $this->newId );
212 }
213
214 $out->setPageTitle( $this->msg( 'errorpagetitle' ) );
215 $out->addWikiMsg( 'difference-missing-revision',
216 $this->getLanguage()->listToText( $missing ), count( $missing ) );
217 }
218
219 function showDiffPage( $diffOnly = false ) {
220 wfProfileIn( __METHOD__ );
221
222 # Allow frames except in certain special cases
223 $out = $this->getOutput();
224 $out->allowClickjacking();
225 $out->setRobotPolicy( 'noindex,nofollow' );
226
227 if ( !$this->loadRevisionData() ) {
228 $this->showMissingRevision();
229 wfProfileOut( __METHOD__ );
230 return;
231 }
232
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 ) );
238 }
239 if ( count( $permErrors ) ) {
240 wfProfileOut( __METHOD__ );
241 throw new PermissionsError( 'read', $permErrors );
242 }
243
244 $rollback = '';
245
246 $query = array();
247 # Carry over 'diffonly' param via navigation links
248 if ( $diffOnly != $user->getBoolOption( 'diffonly' ) ) {
249 $query['diffonly'] = $diffOnly;
250 }
251 # Cascade unhide param in links for easy deletion browsing
252 if ( $this->unhide ) {
253 $query['unhide'] = 1;
254 }
255
256 # Check if one of the revisions is deleted/suppressed
257 $deleted = $suppressed = false;
258 $allowed = $this->newRev->userCan( Revision::DELETED_TEXT, $user );
259
260 $revisionTools = array();
261
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() ) );
267 $samePage = true;
268 $oldHeader = '';
269 } else {
270 wfRunHooks( 'DiffViewHeader', array( $this, $this->oldRev, $this->newRev ) );
271
272 if ( $this->newPage->equals( $this->oldPage ) ) {
273 $out->setPageTitle( $this->msg( 'difference-title', $this->newPage->getPrefixedText() ) );
274 $samePage = true;
275 } else {
276 $out->setPageTitle( $this->msg( 'difference-title-multipage',
277 $this->oldPage->getPrefixedText(), $this->newPage->getPrefixedText() ) );
278 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
279 $samePage = false;
280 }
281
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 = '&#160;&#160;&#160;' . $rollbackLink;
288 }
289 }
290
291 if ( !$this->oldRev->isDeleted( Revision::DELETED_TEXT ) &&
292 !$this->newRev->isDeleted( Revision::DELETED_TEXT )
293 ) {
294 $undoLink = Html::element( 'a', array(
295 'href' => $this->newPage->getLocalURL( array(
296 'action' => 'edit',
297 'undoafter' => $this->oldId,
298 'undo' => $this->newId ) ),
299 'title' => Linker::titleAttrib( 'undo' )
300 ),
301 $this->msg( 'editundo' )->text()
302 );
303 $revisionTools[] = $undoLink;
304 }
305 }
306
307 # Make "previous revision link"
308 if ( $samePage && $this->oldRev->getPrevious() ) {
309 $prevlink = Linker::linkKnown(
310 $this->oldPage,
311 $this->msg( 'previousdiff' )->escaped(),
312 array( 'id' => 'differences-prevlink' ),
313 array( 'diff' => 'prev', 'oldid' => $this->oldId ) + $query
314 );
315 } else {
316 $prevlink = '&#160;';
317 }
318
319 if ( $this->oldRev->isMinor() ) {
320 $oldminor = ChangesList::flag( 'minor' );
321 } else {
322 $oldminor = '';
323 }
324
325 $ldel = $this->revisionDeleteLink( $this->oldRev );
326 $oldRevisionHeader = $this->getRevisionHeader( $this->oldRev, 'complete' );
327 $oldChangeTags = ChangeTags::formatSummaryRow( $this->oldTags, 'diff' );
328
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>';
336
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
341 }
342 }
343
344 # Check if this user can see the revisions
345 if ( !$this->oldRev->userCan( Revision::DELETED_TEXT, $user ) ) {
346 $allowed = false;
347 }
348 }
349
350 # Make "next revision link"
351 # Skip next link on the top revision
352 if ( $samePage && !$this->newRev->isCurrent() ) {
353 $nextlink = Linker::linkKnown(
354 $this->newPage,
355 $this->msg( 'nextdiff' )->escaped(),
356 array( 'id' => 'differences-nextlink' ),
357 array( 'diff' => 'next', 'oldid' => $this->newId ) + $query
358 );
359 } else {
360 $nextlink = '&#160;';
361 }
362
363 if ( $this->newRev->isMinor() ) {
364 $newminor = ChangesList::flag( 'minor' );
365 } else {
366 $newminor = '';
367 }
368
369 # Handle RevisionDelete links...
370 $rdel = $this->revisionDeleteLink( $this->newRev );
371
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();
378 }
379 $newRevisionHeader = $this->getRevisionHeader( $this->newRev, 'complete' ) .
380 ' ' . implode( ' ', $formattedRevisionTools );
381 $newChangeTags = ChangeTags::formatSummaryRow( $this->newTags, 'diff' );
382
383 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
384 '<div id="mw-diff-ntitle2">' . Linker::revUserTools( $this->newRev, !$this->unhide ) .
385 " $rollback</div>" .
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>';
390
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
395 }
396 }
397
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 ) );
404 if ( !$allowed ) {
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",
408 array( $msg ) );
409 } else {
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';
414 $out->wrapWikiMsg(
415 "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
416 array( $msg, $link )
417 );
418 }
419 # Otherwise, output a regular diff...
420 } else {
421 # Add deletion notice if the user is viewing deleted content
422 $notice = '';
423 if ( $deleted ) {
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() .
427 "</div>\n";
428 }
429 $this->showDiff( $oldHeader, $newHeader, $notice );
430 if ( !$diffOnly ) {
431 $this->renderNewRevision();
432 }
433 }
434 wfProfileOut( __METHOD__ );
435 }
436
437 /**
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.
442 *
443 * @return String
444 */
445 protected function markPatrolledLink() {
446 global $wgUseRCPatrol, $wgEnableAPI, $wgEnableWriteAPI;
447 $user = $this->getUser();
448
449 if ( $this->markPatrolledLink === null ) {
450 // Prepare a change patrol link, if applicable
451 if (
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 )
457 ) {
458 // Look for an unpatrolled change corresponding to this diff
459
460 $db = wfGetDB( DB_SLAVE );
461 $change = RecentChange::newFromConds(
462 array(
463 'rc_timestamp' => $db->timestamp( $this->newRev->getTimestamp() ),
464 'rc_this_oldid' => $this->newId,
465 'rc_patrolled' => 0
466 ),
467 __METHOD__,
468 array( 'USE INDEX' => 'rc_timestamp' )
469 );
470
471 if ( $change && $change->getPerformer()->getName() !== $user->getName() ) {
472 $rcid = $change->getAttribute( 'rc_id' );
473 } else {
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
476 $rcid = 0;
477 }
478 // Build the link
479 if ( $rcid ) {
480 $this->getOutput()->preventClickjacking();
481 if ( $wgEnableAPI && $wgEnableWriteAPI
482 && $user->isAllowed( 'writeapi' )
483 ) {
484 $this->getOutput()->addModules( 'mediawiki.page.patrol.ajax' );
485 }
486
487 $token = $user->getEditToken( $rcid );
488 $this->markPatrolledLink = ' <span class="patrollink">[' . Linker::linkKnown(
489 $this->newPage,
490 $this->msg( 'markaspatrolleddiff' )->escaped(),
491 array(),
492 array(
493 'action' => 'markpatrolled',
494 'rcid' => $rcid,
495 'token' => $token,
496 )
497 ) . ']</span>';
498 } else {
499 $this->markPatrolledLink = '';
500 }
501 } else {
502 $this->markPatrolledLink = '';
503 }
504 }
505
506 return $this->markPatrolledLink;
507 }
508
509 /**
510 * @param $rev Revision
511 * @return String
512 */
513 protected function revisionDeleteLink( $rev ) {
514 $link = Linker::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
515 if ( $link !== '' ) {
516 $link = '&#160;&#160;&#160;' . $link . ' ';
517 }
518 return $link;
519 }
520
521 /**
522 * Show the new revision of the page.
523 */
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 );
538
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 );
551 }
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
557 } else {
558 // Normal page
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
562 // object.
563 $wikiPage = $this->getWikiPage();
564 } else {
565 // Otherwise we need to create our own WikiPage object
566 $wikiPage = WikiPage::factory( $this->newPage );
567 }
568
569 $parserOutput = $this->getParserOutput( $wikiPage, $this->newRev );
570
571 # Also try to load it as a redirect
572 $rt = $this->newContent ? $this->newContent->getRedirectTarget() : null;
573
574 if ( $rt ) {
575 $article = Article::newFromTitle( $this->newPage, $this->getContext() );
576 $out->addHTML( $article->viewRedirect( $rt ) );
577
578 # WikiPage::getParserOutput() should not return false, but just in case
579 if ( $parserOutput ) {
580 # Show categories etc.
581 $out->addParserOutputNoText( $parserOutput );
582 }
583 } elseif ( $parserOutput ) {
584 $out->addParserOutput( $parserOutput );
585 }
586 }
587 }
588 # @codingStandardsIgnoreEnd
589
590 # Add redundant patrol link on bottom...
591 $out->addHTML( $this->markPatrolledLink() );
592
593 wfProfileOut( __METHOD__ );
594 }
595
596 protected function getParserOutput( WikiPage $page, Revision $rev ) {
597 $parserOptions = $page->makeParserOptions( $this->getContext() );
598
599 if ( !$rev->isCurrent() || !$rev->getTitle()->quickUserCan( "edit" ) ) {
600 $parserOptions->setEditSection( false );
601 }
602
603 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
604 return $parserOutput;
605 }
606
607 /**
608 * Get the diff text, send it to the OutputPage object
609 * Returns false if the diff could not be generated, otherwise returns true
610 *
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
614 *
615 * @return bool
616 */
617 function showDiff( $otitle, $ntitle, $notice = '' ) {
618 $diff = $this->getDiff( $otitle, $ntitle, $notice );
619 if ( $diff === false ) {
620 $this->showMissingRevision();
621 return false;
622 } else {
623 $this->showDiffStyle();
624 $this->getOutput()->addHTML( $diff );
625 return true;
626 }
627 }
628
629 /**
630 * Add style sheets and supporting JS for diff display.
631 */
632 function showDiffStyle() {
633 $this->getOutput()->addModuleStyles( 'mediawiki.action.history.diff' );
634 }
635
636 /**
637 * Get complete diff table, including header
638 *
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
642 * @return mixed
643 */
644 function getDiff( $otitle, $ntitle, $notice = '' ) {
645 $body = $this->getDiffBody();
646 if ( $body === false ) {
647 return false;
648 }
649
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() .
655 "</div>\n";
656 }
657
658 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
659 }
660
661 /**
662 * Get the diff table body, without header
663 *
664 * @return mixed (string/false)
665 */
666 public function getDiffBody() {
667 global $wgMemc;
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__ );
673 return false;
674 } elseif ( $this->oldRev &&
675 !$this->oldRev->userCan( Revision::DELETED_TEXT, $this->getUser() )
676 ) {
677 wfProfileOut( __METHOD__ );
678 return false;
679 } elseif ( $this->newRev &&
680 !$this->newRev->userCan( Revision::DELETED_TEXT, $this->getUser() )
681 ) {
682 wfProfileOut( __METHOD__ );
683 return false;
684 }
685 // Short-circuit
686 if ( $this->oldRev === false || ( $this->oldRev && $this->newRev
687 && $this->oldRev->getID() == $this->newRev->getID() ) )
688 {
689 wfProfileOut( __METHOD__ );
690 return '';
691 }
692 // Cacheable?
693 $key = false;
694 if ( $this->oldId && $this->newId ) {
695 $key = $this->getDiffBodyCacheKey();
696
697 // Try cache
698 if ( !$this->refreshCache ) {
699 $difftext = $wgMemc->get( $key );
700 if ( $difftext ) {
701 wfIncrStats( 'diff_cache_hit' );
702 $difftext = $this->localiseLineNumbers( $difftext );
703 $difftext .= "\n<!-- diff cache key $key -->\n";
704 wfProfileOut( __METHOD__ );
705 return $difftext;
706 }
707 } // don't try to load but save the result
708 }
709 $this->cacheHit = false;
710
711 // Loadtext is permission safe, this just clears out the diff
712 if ( !$this->loadText() ) {
713 wfProfileOut( __METHOD__ );
714 return false;
715 }
716
717 $difftext = $this->generateContentDiffBody( $this->oldContent, $this->newContent );
718
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 );
725 } else {
726 wfIncrStats( 'diff_uncacheable' );
727 }
728 // Replace line numbers with the text in the user's language
729 if ( $difftext !== false ) {
730 $difftext = $this->localiseLineNumbers( $difftext );
731 }
732 wfProfileOut( __METHOD__ );
733 return $difftext;
734 }
735
736 /**
737 * Returns the cache key for diff body text or content.
738 *
739 * @return string
740 * @since 1.23
741 * @throws MWException
742 */
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.' );
746 }
747
748 return wfMemcKey( 'diff', 'version', self::CACHE_VERSION,
749 'oldid', $this->oldId, 'newid', $this->newId );
750 }
751
752 /**
753 * Generate a diff, no caching.
754 *
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.
758 *
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.
762 *
763 * @param $old Content: old content
764 * @param $new Content: new content
765 *
766 * @return bool|string
767 * @since 1.21
768 * @throws MWException if $old or $new are not instances of TextContent.
769 */
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." );
774 }
775
776 if ( !( $new instanceof TextContent ) ) {
777 throw new MWException( "Diff not implemented for " . get_class( $new ) . "; "
778 . "override generateContentDiffBody to fix this." );
779 }
780
781 $otext = $old->serialize();
782 $ntext = $new->serialize();
783
784 return $this->generateTextDiffBody( $otext, $ntext );
785 }
786
787 /**
788 * Generate a diff, no caching
789 *
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!
794 */
795 function generateDiffBody( $otext, $ntext ) {
796 ContentHandler::deprecated( __METHOD__, "1.21" );
797
798 return $this->generateTextDiffBody( $otext, $ntext );
799 }
800
801 /**
802 * Generate a diff, no caching
803 *
804 * @todo move this to TextDifferenceEngine, make DifferenceEngine abstract. At some point.
805 *
806 * @param string $otext old text, must be already segmented
807 * @param string $ntext new text, must be already segmented
808 * @return bool|string
809 */
810 function generateTextDiffBody( $otext, $ntext ) {
811 global $wgExternalDiffEngine, $wgContLang;
812
813 wfProfileIn( __METHOD__ );
814
815 $otext = str_replace( "\r\n", "\n", $otext );
816 $ntext = str_replace( "\r\n", "\n", $ntext );
817
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' );
826 }
827
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__ );
836 return $text;
837 }
838 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
839 # Diff via the shell
840 $tmpDir = wfTempDir();
841 $tempName1 = tempnam( $tmpDir, 'diff_' );
842 $tempName2 = tempnam( $tmpDir, 'diff_' );
843
844 $tempFile1 = fopen( $tempName1, "w" );
845 if ( !$tempFile1 ) {
846 wfProfileOut( __METHOD__ );
847 return false;
848 }
849 $tempFile2 = fopen( $tempName2, "w" );
850 if ( !$tempFile2 ) {
851 wfProfileOut( __METHOD__ );
852 return false;
853 }
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__ );
866 return $difftext;
867 }
868
869 # Native PHP diff
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__ );
876 return $difftext;
877 }
878
879 /**
880 * Generate a debug comment indicating diff generating time,
881 * server node, and generator backend.
882 *
883 * @param String $generator: What diff engine was used
884 *
885 * @return string
886 */
887 protected function debug( $generator = "internal" ) {
888 global $wgShowHostnames;
889 if ( !$this->enableDebugComment ) {
890 return '';
891 }
892 $data = array( $generator );
893 if ( $wgShowHostnames ) {
894 $data[] = wfHostname();
895 }
896 $data[] = wfTimestamp( TS_DB );
897 return "<!-- diff generator: "
898 . implode( " ",
899 array_map(
900 "htmlspecialchars",
901 $data )
902 )
903 . " -->\n";
904 }
905
906 /**
907 * Replace line numbers with the text in the user's language
908 *
909 * @param String $text
910 *
911 * @return mixed
912 */
913 function localiseLineNumbers( $text ) {
914 return preg_replace_callback( '/<!--LINE (\d+)-->/',
915 array( &$this, 'localiseLineNumbersCb' ), $text );
916 }
917
918 function localiseLineNumbersCb( $matches ) {
919 if ( $matches[1] === '1' && $this->reducedLineNumbers ) {
920 return '';
921 }
922 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
923 }
924
925 /**
926 * If there are revisions between the ones being compared, return a note saying so.
927 * @return string
928 */
929 function getMultiNotice() {
930 if ( !is_object( $this->oldRev ) || !is_object( $this->newRev ) ) {
931 return '';
932 } elseif ( !$this->oldPage->equals( $this->newPage ) ) {
933 // Comparing two different pages? Count would be meaningless.
934 return '';
935 }
936
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;
943 }
944
945 $nEdits = $this->newPage->countRevisionsBetween( $oldRev, $newRev );
946 if ( $nEdits > 0 ) {
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 );
950 }
951 return ''; // nothing
952 }
953
954 /**
955 * Get a notice about how many intermediate edits and users there are
956 * @param $numEdits int
957 * @param $numUsers int
958 * @param $limit int
959 * @return string
960 */
961 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
962 if ( $numUsers > $limit ) {
963 $msg = 'diff-multi-manyusers';
964 $numUsers = $limit;
965 } else {
966 $msg = 'diff-multi';
967 }
968 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
969 }
970
971 /**
972 * Get a header for a specified revision.
973 *
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
978 */
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 );
986
987 $header = $this->msg(
988 $rev->isCurrent() ? 'currentrev-asof' : 'revisionasof',
989 $timestamp,
990 $dateofrev,
991 $timeofrev
992 )->escaped();
993
994 if ( $complete !== 'complete' ) {
995 return $header;
996 }
997
998 $title = $rev->getTitle();
999
1000 $header = Linker::linkKnown( $title, $header, array(),
1001 array( 'oldid' => $rev->getID() ) );
1002
1003 if ( $rev->userCan( Revision::DELETED_TEXT, $user ) ) {
1004 $editQuery = array( 'action' => 'edit' );
1005 if ( !$rev->isCurrent() ) {
1006 $editQuery['oldid'] = $rev->getID();
1007 }
1008
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(
1015 'span',
1016 array( 'class' => 'history-deleted' ),
1017 $header
1018 );
1019 }
1020 } else {
1021 $header = Html::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
1022 }
1023
1024 return $header;
1025 }
1026
1027 /**
1028 * Add the header to a diff body
1029 *
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
1035 *
1036 * @return string
1037 */
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'>";
1043
1044 if ( !$diff && !$otitle ) {
1045 $header .= "
1046 <tr style='vertical-align: top;'>
1047 <td class='diff-ntitle'>{$ntitle}</td>
1048 </tr>";
1049 $multiColspan = 1;
1050 } else {
1051 if ( $diff ) { // Safari/Chrome show broken output if cols not used
1052 $header .= "
1053 <col class='diff-marker' />
1054 <col class='diff-content' />
1055 <col class='diff-marker' />
1056 <col class='diff-content' />";
1057 $colspan = 2;
1058 $multiColspan = 4;
1059 } else {
1060 $colspan = 1;
1061 $multiColspan = 2;
1062 }
1063 if ( $otitle || $ntitle ) {
1064 $header .= "
1065 <tr style='vertical-align: top;'>
1066 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
1067 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
1068 </tr>";
1069 }
1070 }
1071
1072 if ( $multi != '' ) {
1073 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;' " .
1074 "class='diff-multi'>{$multi}</td></tr>";
1075 }
1076 if ( $notice != '' ) {
1077 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;'>{$notice}</td></tr>";
1078 }
1079
1080 return $header . $diff . "</table>";
1081 }
1082
1083 /**
1084 * Use specified text instead of loading from the database
1085 * @deprecated since 1.21, use setContent() instead.
1086 */
1087 function setText( $oldText, $newText ) {
1088 ContentHandler::deprecated( __METHOD__, "1.21" );
1089
1090 $oldContent = ContentHandler::makeContent( $oldText, $this->getTitle() );
1091 $newContent = ContentHandler::makeContent( $newText, $this->getTitle() );
1092
1093 $this->setContent( $oldContent, $newContent );
1094 }
1095
1096 /**
1097 * Use specified text instead of loading from the database
1098 * @since 1.21
1099 */
1100 function setContent( Content $oldContent, Content $newContent ) {
1101 $this->oldContent = $oldContent;
1102 $this->newContent = $newContent;
1103
1104 $this->textLoaded = 2;
1105 $this->revisionsLoaded = true;
1106 }
1107
1108 /**
1109 * Set the language in which the diff text is written
1110 * (Defaults to page content language).
1111 * @since 1.19
1112 */
1113 function setTextLanguage( $lang ) {
1114 $this->diffLang = wfGetLangObj( $lang );
1115 }
1116
1117 /**
1118 * Maps a revision pair definition as accepted by DifferenceEngine constructor
1119 * to a pair of actual integers representing revision ids.
1120 *
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).
1126 */
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 );
1136 } else {
1137 $oldid = intval( $old );
1138 $newid = intval( $new );
1139 }
1140
1141 return array( $oldid, $newid );
1142 }
1143
1144 /**
1145 * Load revision IDs
1146 */
1147 private function loadRevisionIds() {
1148 if ( $this->revisionsIdsLoaded ) {
1149 return;
1150 }
1151
1152 $this->revisionsIdsLoaded = true;
1153
1154 $old = $this->oldId;
1155 $new = $this->newId;
1156
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".
1161 $this->newId = 0;
1162 }
1163
1164 wfRunHooks( 'NewDifferenceEngine', array( $this->getTitle(), &$this->oldId, &$this->newId, $old, $new ) );
1165 }
1166
1167 /**
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
1171 * value of newid).
1172 *
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
1175 * API convenience.
1176 *
1177 * @return bool
1178 */
1179 function loadRevisionData() {
1180 if ( $this->revisionsLoaded ) {
1181 return true;
1182 }
1183
1184 // Whether it succeeds or fails, we don't want to try again
1185 $this->revisionsLoaded = true;
1186
1187 $this->loadRevisionIds();
1188
1189 // Load the new revision object
1190 if ( $this->newId ) {
1191 $this->newRev = Revision::newFromId( $this->newId );
1192 } else {
1193 $this->newRev = Revision::newFromTitle(
1194 $this->getTitle(),
1195 false,
1196 Revision::READ_NORMAL
1197 );
1198 }
1199
1200 if ( !$this->newRev instanceof Revision ) {
1201 return false;
1202 }
1203
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();
1207
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();
1214 if ( $rev ) {
1215 $this->oldId = $rev->getId();
1216 $this->oldRev = $rev;
1217 } else {
1218 // No previous revision; mark to show as first-version only.
1219 $this->oldId = false;
1220 $this->oldRev = false;
1221 }
1222 } /* elseif ( $this->oldId === false ) leave oldRev false; */
1223
1224 if ( is_null( $this->oldRev ) ) {
1225 return false;
1226 }
1227
1228 if ( $this->oldRev ) {
1229 $this->oldPage = $this->oldRev->getTitle();
1230 }
1231
1232 // Load tags information for both revisions
1233 $dbr = wfGetDB( DB_SLAVE );
1234 if ( $this->oldId !== false ) {
1235 $this->oldTags = $dbr->selectField(
1236 'tag_summary',
1237 'ts_tags',
1238 array( 'ts_rev_id' => $this->oldId ),
1239 __METHOD__
1240 );
1241 } else {
1242 $this->oldTags = false;
1243 }
1244 $this->newTags = $dbr->selectField(
1245 'tag_summary',
1246 'ts_tags',
1247 array( 'ts_rev_id' => $this->newId ),
1248 __METHOD__
1249 );
1250
1251 return true;
1252 }
1253
1254 /**
1255 * Load the text of the revisions, as well as revision data.
1256 *
1257 * @return bool
1258 */
1259 function loadText() {
1260 if ( $this->textLoaded == 2 ) {
1261 return true;
1262 }
1263
1264 // Whether it succeeds or fails, we don't want to try again
1265 $this->textLoaded = 2;
1266
1267 if ( !$this->loadRevisionData() ) {
1268 return false;
1269 }
1270
1271 if ( $this->oldRev ) {
1272 $this->oldContent = $this->oldRev->getContent( Revision::FOR_THIS_USER, $this->getUser() );
1273 if ( $this->oldContent === null ) {
1274 return false;
1275 }
1276 }
1277
1278 if ( $this->newRev ) {
1279 $this->newContent = $this->newRev->getContent( Revision::FOR_THIS_USER, $this->getUser() );
1280 if ( $this->newContent === null ) {
1281 return false;
1282 }
1283 }
1284
1285 return true;
1286 }
1287
1288 /**
1289 * Load the text of the new revision, not the old one
1290 *
1291 * @return bool
1292 */
1293 function loadNewText() {
1294 if ( $this->textLoaded >= 1 ) {
1295 return true;
1296 }
1297
1298 $this->textLoaded = 1;
1299
1300 if ( !$this->loadRevisionData() ) {
1301 return false;
1302 }
1303
1304 $this->newContent = $this->newRev->getContent( Revision::FOR_THIS_USER, $this->getUser() );
1305
1306 return true;
1307 }
1308 }