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