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