ee918f3785a15d370e1573a569345a39f8c1714c
[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 // This needs to be synchronised with Article::showCssOrJsPage(), which sucks
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 if ( $po ) {
566 $out->addParserOutputContent( $po );
567 }
568 }
569 } elseif ( !wfRunHooks( 'ArticleContentViewCustom', array( $this->mNewContent, $this->mNewPage, $out ) ) ) {
570 // Handled by extension
571 } elseif ( !ContentHandler::runLegacyHooks( 'ArticleViewCustom', array( $this->mNewContent, $this->mNewPage, $out ) ) ) {
572 // NOTE: deprecated hook, B/C only
573 // Handled by extension
574 } else {
575 // Normal page
576 if ( $this->getTitle()->equals( $this->mNewPage ) ) {
577 // If the Title stored in the context is the same as the one
578 // of the new revision, we can use its associated WikiPage
579 // object.
580 $wikiPage = $this->getWikiPage();
581 } else {
582 // Otherwise we need to create our own WikiPage object
583 $wikiPage = WikiPage::factory( $this->mNewPage );
584 }
585
586 $parserOutput = $this->getParserOutput( $wikiPage, $this->mNewRev );
587
588 # WikiPage::getParserOutput() should not return false, but just in case
589 if ( $parserOutput ) {
590 $out->addParserOutput( $parserOutput );
591 }
592 }
593 }
594 # @codingStandardsIgnoreEnd
595
596 # Add redundant patrol link on bottom...
597 $out->addHTML( $this->markPatrolledLink() );
598
599 wfProfileOut( __METHOD__ );
600 }
601
602 protected function getParserOutput( WikiPage $page, Revision $rev ) {
603 $parserOptions = $page->makeParserOptions( $this->getContext() );
604
605 if ( !$rev->isCurrent() || !$rev->getTitle()->quickUserCan( "edit" ) ) {
606 $parserOptions->setEditSection( false );
607 }
608
609 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
610
611 return $parserOutput;
612 }
613
614 /**
615 * Get the diff text, send it to the OutputPage object
616 * Returns false if the diff could not be generated, otherwise returns true
617 *
618 * @param string|bool $otitle Header for old text or false
619 * @param string|bool $ntitle Header for new text or false
620 * @param string $notice HTML between diff header and body
621 *
622 * @return bool
623 */
624 public function showDiff( $otitle, $ntitle, $notice = '' ) {
625 $diff = $this->getDiff( $otitle, $ntitle, $notice );
626 if ( $diff === false ) {
627 $this->showMissingRevision();
628
629 return false;
630 } else {
631 $this->showDiffStyle();
632 $this->getOutput()->addHTML( $diff );
633
634 return true;
635 }
636 }
637
638 /**
639 * Add style sheets and supporting JS for diff display.
640 */
641 public function showDiffStyle() {
642 $this->getOutput()->addModuleStyles( 'mediawiki.action.history.diff' );
643 }
644
645 /**
646 * Get complete diff table, including header
647 *
648 * @param string|bool $otitle Header for old text or false
649 * @param string|bool $ntitle Header for new text or false
650 * @param string $notice HTML between diff header and body
651 *
652 * @return mixed
653 */
654 public function getDiff( $otitle, $ntitle, $notice = '' ) {
655 $body = $this->getDiffBody();
656 if ( $body === false ) {
657 return false;
658 }
659
660 $multi = $this->getMultiNotice();
661 // Display a message when the diff is empty
662 if ( $body === '' ) {
663 $notice .= '<div class="mw-diff-empty">' .
664 $this->msg( 'diff-empty' )->parse() .
665 "</div>\n";
666 }
667
668 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
669 }
670
671 /**
672 * Get the diff table body, without header
673 *
674 * @return mixed (string/false)
675 */
676 public function getDiffBody() {
677 global $wgMemc;
678 wfProfileIn( __METHOD__ );
679 $this->mCacheHit = true;
680 // Check if the diff should be hidden from this user
681 if ( !$this->loadRevisionData() ) {
682 wfProfileOut( __METHOD__ );
683
684 return false;
685 } elseif ( $this->mOldRev &&
686 !$this->mOldRev->userCan( Revision::DELETED_TEXT, $this->getUser() )
687 ) {
688 wfProfileOut( __METHOD__ );
689
690 return false;
691 } elseif ( $this->mNewRev &&
692 !$this->mNewRev->userCan( Revision::DELETED_TEXT, $this->getUser() )
693 ) {
694 wfProfileOut( __METHOD__ );
695
696 return false;
697 }
698 // Short-circuit
699 if ( $this->mOldRev === false || ( $this->mOldRev && $this->mNewRev
700 && $this->mOldRev->getID() == $this->mNewRev->getID() )
701 ) {
702 wfProfileOut( __METHOD__ );
703
704 return '';
705 }
706 // Cacheable?
707 $key = false;
708 if ( $this->mOldid && $this->mNewid ) {
709 $key = $this->getDiffBodyCacheKey();
710
711 // Try cache
712 if ( !$this->mRefreshCache ) {
713 $difftext = $wgMemc->get( $key );
714 if ( $difftext ) {
715 wfIncrStats( 'diff_cache_hit' );
716 $difftext = $this->localiseLineNumbers( $difftext );
717 $difftext .= "\n<!-- diff cache key $key -->\n";
718 wfProfileOut( __METHOD__ );
719
720 return $difftext;
721 }
722 } // don't try to load but save the result
723 }
724 $this->mCacheHit = false;
725
726 // Loadtext is permission safe, this just clears out the diff
727 if ( !$this->loadText() ) {
728 wfProfileOut( __METHOD__ );
729
730 return false;
731 }
732
733 $difftext = $this->generateContentDiffBody( $this->mOldContent, $this->mNewContent );
734
735 // Save to cache for 7 days
736 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
737 wfIncrStats( 'diff_uncacheable' );
738 } elseif ( $key !== false && $difftext !== false ) {
739 wfIncrStats( 'diff_cache_miss' );
740 $wgMemc->set( $key, $difftext, 7 * 86400 );
741 } else {
742 wfIncrStats( 'diff_uncacheable' );
743 }
744 // Replace line numbers with the text in the user's language
745 if ( $difftext !== false ) {
746 $difftext = $this->localiseLineNumbers( $difftext );
747 }
748 wfProfileOut( __METHOD__ );
749
750 return $difftext;
751 }
752
753 /**
754 * Returns the cache key for diff body text or content.
755 *
756 * @since 1.23
757 *
758 * @throws MWException
759 * @return string
760 */
761 protected function getDiffBodyCacheKey() {
762 if ( !$this->mOldid || !$this->mNewid ) {
763 throw new MWException( 'mOldid and mNewid must be set to get diff cache key.' );
764 }
765
766 return wfMemcKey( 'diff', 'version', MW_DIFF_VERSION,
767 'oldid', $this->mOldid, 'newid', $this->mNewid );
768 }
769
770 /**
771 * Generate a diff, no caching.
772 *
773 * This implementation uses generateTextDiffBody() to generate a diff based on the default
774 * serialization of the given Content objects. This will fail if $old or $new are not
775 * instances of TextContent.
776 *
777 * Subclasses may override this to provide a different rendering for the diff,
778 * perhaps taking advantage of the content's native form. This is required for all content
779 * models that are not text based.
780 *
781 * @since 1.21
782 *
783 * @param Content $old Old content
784 * @param Content $new New content
785 *
786 * @throws MWException If old or new content is not an instance of TextContent.
787 * @return bool|string
788 */
789 public function generateContentDiffBody( Content $old, Content $new ) {
790 if ( !( $old instanceof TextContent ) ) {
791 throw new MWException( "Diff not implemented for " . get_class( $old ) . "; " .
792 "override generateContentDiffBody to fix this." );
793 }
794
795 if ( !( $new instanceof TextContent ) ) {
796 throw new MWException( "Diff not implemented for " . get_class( $new ) . "; "
797 . "override generateContentDiffBody to fix this." );
798 }
799
800 $otext = $old->serialize();
801 $ntext = $new->serialize();
802
803 return $this->generateTextDiffBody( $otext, $ntext );
804 }
805
806 /**
807 * Generate a diff, no caching
808 *
809 * @param string $otext Old text, must be already segmented
810 * @param string $ntext New text, must be already segmented
811 *
812 * @return bool|string
813 * @deprecated since 1.21, use generateContentDiffBody() instead!
814 */
815 public function generateDiffBody( $otext, $ntext ) {
816 ContentHandler::deprecated( __METHOD__, "1.21" );
817
818 return $this->generateTextDiffBody( $otext, $ntext );
819 }
820
821 /**
822 * Generate a diff, no caching
823 *
824 * @todo move this to TextDifferenceEngine, make DifferenceEngine abstract. At some point.
825 *
826 * @param string $otext Old text, must be already segmented
827 * @param string $ntext New text, must be already segmented
828 *
829 * @return bool|string
830 */
831 public function generateTextDiffBody( $otext, $ntext ) {
832 global $wgExternalDiffEngine, $wgContLang;
833
834 wfProfileIn( __METHOD__ );
835
836 $otext = str_replace( "\r\n", "\n", $otext );
837 $ntext = str_replace( "\r\n", "\n", $ntext );
838
839 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
840 # For historical reasons, external diff engine expects
841 # input text to be HTML-escaped already
842 $otext = htmlspecialchars( $wgContLang->segmentForDiff( $otext ) );
843 $ntext = htmlspecialchars( $wgContLang->segmentForDiff( $ntext ) );
844 wfProfileOut( __METHOD__ );
845
846 return $wgContLang->unsegmentForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
847 $this->debug( 'wikidiff1' );
848 }
849
850 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
851 # Better external diff engine, the 2 may some day be dropped
852 # This one does the escaping and segmenting itself
853 wfProfileIn( 'wikidiff2_do_diff' );
854 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
855 $text .= $this->debug( 'wikidiff2' );
856 wfProfileOut( 'wikidiff2_do_diff' );
857 wfProfileOut( __METHOD__ );
858
859 return $text;
860 }
861 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
862 # Diff via the shell
863 $tmpDir = wfTempDir();
864 $tempName1 = tempnam( $tmpDir, 'diff_' );
865 $tempName2 = tempnam( $tmpDir, 'diff_' );
866
867 $tempFile1 = fopen( $tempName1, "w" );
868 if ( !$tempFile1 ) {
869 wfProfileOut( __METHOD__ );
870
871 return false;
872 }
873 $tempFile2 = fopen( $tempName2, "w" );
874 if ( !$tempFile2 ) {
875 wfProfileOut( __METHOD__ );
876
877 return false;
878 }
879 fwrite( $tempFile1, $otext );
880 fwrite( $tempFile2, $ntext );
881 fclose( $tempFile1 );
882 fclose( $tempFile2 );
883 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
884 wfProfileIn( __METHOD__ . "-shellexec" );
885 $difftext = wfShellExec( $cmd );
886 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
887 wfProfileOut( __METHOD__ . "-shellexec" );
888 unlink( $tempName1 );
889 unlink( $tempName2 );
890 wfProfileOut( __METHOD__ );
891
892 return $difftext;
893 }
894
895 # Native PHP diff
896 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
897 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
898 $diffs = new Diff( $ota, $nta );
899 $formatter = new TableDiffFormatter();
900 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
901 wfProfileOut( __METHOD__ );
902
903 return $difftext;
904 }
905
906 /**
907 * Generate a debug comment indicating diff generating time,
908 * server node, and generator backend.
909 *
910 * @param string $generator : What diff engine was used
911 *
912 * @return string
913 */
914 protected function debug( $generator = "internal" ) {
915 global $wgShowHostnames;
916 if ( !$this->enableDebugComment ) {
917 return '';
918 }
919 $data = array( $generator );
920 if ( $wgShowHostnames ) {
921 $data[] = wfHostname();
922 }
923 $data[] = wfTimestamp( TS_DB );
924
925 return "<!-- diff generator: " .
926 implode( " ", array_map( "htmlspecialchars", $data ) ) .
927 " -->\n";
928 }
929
930 /**
931 * Replace line numbers with the text in the user's language
932 *
933 * @param string $text
934 *
935 * @return mixed
936 */
937 public function localiseLineNumbers( $text ) {
938 return preg_replace_callback(
939 '/<!--LINE (\d+)-->/',
940 array( &$this, 'localiseLineNumbersCb' ),
941 $text
942 );
943 }
944
945 public function localiseLineNumbersCb( $matches ) {
946 if ( $matches[1] === '1' && $this->mReducedLineNumbers ) {
947 return '';
948 }
949
950 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
951 }
952
953 /**
954 * If there are revisions between the ones being compared, return a note saying so.
955 *
956 * @return string
957 */
958 public function getMultiNotice() {
959 if ( !is_object( $this->mOldRev ) || !is_object( $this->mNewRev ) ) {
960 return '';
961 } elseif ( !$this->mOldPage->equals( $this->mNewPage ) ) {
962 // Comparing two different pages? Count would be meaningless.
963 return '';
964 }
965
966 if ( $this->mOldRev->getTimestamp() > $this->mNewRev->getTimestamp() ) {
967 $oldRev = $this->mNewRev; // flip
968 $newRev = $this->mOldRev; // flip
969 } else { // normal case
970 $oldRev = $this->mOldRev;
971 $newRev = $this->mNewRev;
972 }
973
974 // Sanity: don't show the notice if too many rows must be scanned
975 // @todo show some special message for that case
976 $nEdits = $this->mNewPage->countRevisionsBetween( $oldRev, $newRev, 1000 );
977 if ( $nEdits > 0 && $nEdits <= 1000 ) {
978 $limit = 100; // use diff-multi-manyusers if too many users
979 $users = $this->mNewPage->getAuthorsBetween( $oldRev, $newRev, $limit );
980 $numUsers = count( $users );
981
982 if ( $numUsers == 1 && $users[0] == $newRev->getRawUserText() ) {
983 $numUsers = 0; // special case to say "by the same user" instead of "by one other user"
984 }
985
986 return self::intermediateEditsMsg( $nEdits, $numUsers, $limit );
987 }
988
989 return ''; // nothing
990 }
991
992 /**
993 * Get a notice about how many intermediate edits and users there are
994 *
995 * @param int $numEdits
996 * @param int $numUsers
997 * @param int $limit
998 *
999 * @return string
1000 */
1001 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
1002 if ( $numUsers === 0 ) {
1003 $msg = 'diff-multi-sameuser';
1004 } elseif ( $numUsers > $limit ) {
1005 $msg = 'diff-multi-manyusers';
1006 $numUsers = $limit;
1007 } else {
1008 $msg = 'diff-multi-otherusers';
1009 }
1010
1011 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
1012 }
1013
1014 /**
1015 * Get a header for a specified revision.
1016 *
1017 * @param Revision $rev
1018 * @param string $complete 'complete' to get the header wrapped depending
1019 * the visibility of the revision and a link to edit the page.
1020 *
1021 * @return string HTML fragment
1022 */
1023 protected function getRevisionHeader( Revision $rev, $complete = '' ) {
1024 $lang = $this->getLanguage();
1025 $user = $this->getUser();
1026 $revtimestamp = $rev->getTimestamp();
1027 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
1028 $dateofrev = $lang->userDate( $revtimestamp, $user );
1029 $timeofrev = $lang->userTime( $revtimestamp, $user );
1030
1031 $header = $this->msg(
1032 $rev->isCurrent() ? 'currentrev-asof' : 'revisionasof',
1033 $timestamp,
1034 $dateofrev,
1035 $timeofrev
1036 )->escaped();
1037
1038 if ( $complete !== 'complete' ) {
1039 return $header;
1040 }
1041
1042 $title = $rev->getTitle();
1043
1044 $header = Linker::linkKnown( $title, $header, array(),
1045 array( 'oldid' => $rev->getID() ) );
1046
1047 if ( $rev->userCan( Revision::DELETED_TEXT, $user ) ) {
1048 $editQuery = array( 'action' => 'edit' );
1049 if ( !$rev->isCurrent() ) {
1050 $editQuery['oldid'] = $rev->getID();
1051 }
1052
1053 $key = $title->quickUserCan( 'edit', $user ) ? 'editold' : 'viewsourceold';
1054 $msg = $this->msg( $key )->escaped();
1055 $header .= ' ' . $this->msg( 'parentheses' )->rawParams(
1056 Linker::linkKnown( $title, $msg, array(), $editQuery ) )->plain();
1057 if ( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
1058 $header = Html::rawElement(
1059 'span',
1060 array( 'class' => 'history-deleted' ),
1061 $header
1062 );
1063 }
1064 } else {
1065 $header = Html::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
1066 }
1067
1068 return $header;
1069 }
1070
1071 /**
1072 * Add the header to a diff body
1073 *
1074 * @param string $diff Diff body
1075 * @param string $otitle Old revision header
1076 * @param string $ntitle New revision header
1077 * @param string $multi Notice telling user that there are intermediate
1078 * revisions between the ones being compared
1079 * @param string $notice Other notices, e.g. that user is viewing deleted content
1080 *
1081 * @return string
1082 */
1083 public function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
1084 // shared.css sets diff in interface language/dir, but the actual content
1085 // is often in a different language, mostly the page content language/dir
1086 $tableClass = 'diff diff-contentalign-' . htmlspecialchars( $this->getDiffLang()->alignStart() );
1087 $header = "<table class='$tableClass'>";
1088
1089 if ( !$diff && !$otitle ) {
1090 $header .= "
1091 <tr style='vertical-align: top;'>
1092 <td class='diff-ntitle'>{$ntitle}</td>
1093 </tr>";
1094 $multiColspan = 1;
1095 } else {
1096 if ( $diff ) { // Safari/Chrome show broken output if cols not used
1097 $header .= "
1098 <col class='diff-marker' />
1099 <col class='diff-content' />
1100 <col class='diff-marker' />
1101 <col class='diff-content' />";
1102 $colspan = 2;
1103 $multiColspan = 4;
1104 } else {
1105 $colspan = 1;
1106 $multiColspan = 2;
1107 }
1108 if ( $otitle || $ntitle ) {
1109 $header .= "
1110 <tr style='vertical-align: top;'>
1111 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
1112 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
1113 </tr>";
1114 }
1115 }
1116
1117 if ( $multi != '' ) {
1118 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;' " .
1119 "class='diff-multi'>{$multi}</td></tr>";
1120 }
1121 if ( $notice != '' ) {
1122 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;'>{$notice}</td></tr>";
1123 }
1124
1125 return $header . $diff . "</table>";
1126 }
1127
1128 /**
1129 * Use specified text instead of loading from the database
1130 * @deprecated since 1.21, use setContent() instead.
1131 */
1132 public function setText( $oldText, $newText ) {
1133 ContentHandler::deprecated( __METHOD__, "1.21" );
1134
1135 $oldContent = ContentHandler::makeContent( $oldText, $this->getTitle() );
1136 $newContent = ContentHandler::makeContent( $newText, $this->getTitle() );
1137
1138 $this->setContent( $oldContent, $newContent );
1139 }
1140
1141 /**
1142 * Use specified text instead of loading from the database
1143 * @param Content $oldContent
1144 * @param Content $newContent
1145 * @since 1.21
1146 */
1147 public function setContent( Content $oldContent, Content $newContent ) {
1148 $this->mOldContent = $oldContent;
1149 $this->mNewContent = $newContent;
1150
1151 $this->mTextLoaded = 2;
1152 $this->mRevisionsLoaded = true;
1153 }
1154
1155 /**
1156 * Set the language in which the diff text is written
1157 * (Defaults to page content language).
1158 * @param Language|string $lang
1159 * @since 1.19
1160 */
1161 public function setTextLanguage( $lang ) {
1162 $this->mDiffLang = wfGetLangObj( $lang );
1163 }
1164
1165 /**
1166 * Maps a revision pair definition as accepted by DifferenceEngine constructor
1167 * to a pair of actual integers representing revision ids.
1168 *
1169 * @param int $old Revision id, e.g. from URL parameter 'oldid'
1170 * @param int|string $new Revision id or strings 'next' or 'prev', e.g. from URL parameter 'diff'
1171 *
1172 * @return int[] List of two revision ids, older first, later second.
1173 * Zero signifies invalid argument passed.
1174 * false signifies that there is no previous/next revision ($old is the oldest/newest one).
1175 */
1176 public function mapDiffPrevNext( $old, $new ) {
1177 if ( $new === 'prev' ) {
1178 // Show diff between revision $old and the previous one. Get previous one from DB.
1179 $newid = intval( $old );
1180 $oldid = $this->getTitle()->getPreviousRevisionID( $newid );
1181 } elseif ( $new === 'next' ) {
1182 // Show diff between revision $old and the next one. Get next one from DB.
1183 $oldid = intval( $old );
1184 $newid = $this->getTitle()->getNextRevisionID( $oldid );
1185 } else {
1186 $oldid = intval( $old );
1187 $newid = intval( $new );
1188 }
1189
1190 return array( $oldid, $newid );
1191 }
1192
1193 /**
1194 * Load revision IDs
1195 */
1196 private function loadRevisionIds() {
1197 if ( $this->mRevisionsIdsLoaded ) {
1198 return;
1199 }
1200
1201 $this->mRevisionsIdsLoaded = true;
1202
1203 $old = $this->mOldid;
1204 $new = $this->mNewid;
1205
1206 list( $this->mOldid, $this->mNewid ) = self::mapDiffPrevNext( $old, $new );
1207 if ( $new === 'next' && $this->mNewid === false ) {
1208 # if no result, NewId points to the newest old revision. The only newer
1209 # revision is cur, which is "0".
1210 $this->mNewid = 0;
1211 }
1212
1213 wfRunHooks(
1214 'NewDifferenceEngine',
1215 array( $this->getTitle(), &$this->mOldid, &$this->mNewid, $old, $new )
1216 );
1217 }
1218
1219 /**
1220 * Load revision metadata for the specified articles. If newid is 0, then compare
1221 * the old article in oldid to the current article; if oldid is 0, then
1222 * compare the current article to the immediately previous one (ignoring the
1223 * value of newid).
1224 *
1225 * If oldid is false, leave the corresponding revision object set
1226 * to false. This is impossible via ordinary user input, and is provided for
1227 * API convenience.
1228 *
1229 * @return bool
1230 */
1231 public function loadRevisionData() {
1232 if ( $this->mRevisionsLoaded ) {
1233 return true;
1234 }
1235
1236 // Whether it succeeds or fails, we don't want to try again
1237 $this->mRevisionsLoaded = true;
1238
1239 $this->loadRevisionIds();
1240
1241 // Load the new revision object
1242 if ( $this->mNewid ) {
1243 $this->mNewRev = Revision::newFromId( $this->mNewid );
1244 } else {
1245 $this->mNewRev = Revision::newFromTitle(
1246 $this->getTitle(),
1247 false,
1248 Revision::READ_NORMAL
1249 );
1250 }
1251
1252 if ( !$this->mNewRev instanceof Revision ) {
1253 return false;
1254 }
1255
1256 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1257 $this->mNewid = $this->mNewRev->getId();
1258 $this->mNewPage = $this->mNewRev->getTitle();
1259
1260 // Load the old revision object
1261 $this->mOldRev = false;
1262 if ( $this->mOldid ) {
1263 $this->mOldRev = Revision::newFromId( $this->mOldid );
1264 } elseif ( $this->mOldid === 0 ) {
1265 $rev = $this->mNewRev->getPrevious();
1266 if ( $rev ) {
1267 $this->mOldid = $rev->getId();
1268 $this->mOldRev = $rev;
1269 } else {
1270 // No previous revision; mark to show as first-version only.
1271 $this->mOldid = false;
1272 $this->mOldRev = false;
1273 }
1274 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1275
1276 if ( is_null( $this->mOldRev ) ) {
1277 return false;
1278 }
1279
1280 if ( $this->mOldRev ) {
1281 $this->mOldPage = $this->mOldRev->getTitle();
1282 }
1283
1284 // Load tags information for both revisions
1285 $dbr = wfGetDB( DB_SLAVE );
1286 if ( $this->mOldid !== false ) {
1287 $this->mOldTags = $dbr->selectField(
1288 'tag_summary',
1289 'ts_tags',
1290 array( 'ts_rev_id' => $this->mOldid ),
1291 __METHOD__
1292 );
1293 } else {
1294 $this->mOldTags = false;
1295 }
1296 $this->mNewTags = $dbr->selectField(
1297 'tag_summary',
1298 'ts_tags',
1299 array( 'ts_rev_id' => $this->mNewid ),
1300 __METHOD__
1301 );
1302
1303 return true;
1304 }
1305
1306 /**
1307 * Load the text of the revisions, as well as revision data.
1308 *
1309 * @return bool
1310 */
1311 public function loadText() {
1312 if ( $this->mTextLoaded == 2 ) {
1313 return true;
1314 }
1315
1316 // Whether it succeeds or fails, we don't want to try again
1317 $this->mTextLoaded = 2;
1318
1319 if ( !$this->loadRevisionData() ) {
1320 return false;
1321 }
1322
1323 if ( $this->mOldRev ) {
1324 $this->mOldContent = $this->mOldRev->getContent( Revision::FOR_THIS_USER, $this->getUser() );
1325 if ( $this->mOldContent === null ) {
1326 return false;
1327 }
1328 }
1329
1330 if ( $this->mNewRev ) {
1331 $this->mNewContent = $this->mNewRev->getContent( Revision::FOR_THIS_USER, $this->getUser() );
1332 if ( $this->mNewContent === null ) {
1333 return false;
1334 }
1335 }
1336
1337 return true;
1338 }
1339
1340 /**
1341 * Load the text of the new revision, not the old one
1342 *
1343 * @return bool
1344 */
1345 public function loadNewText() {
1346 if ( $this->mTextLoaded >= 1 ) {
1347 return true;
1348 }
1349
1350 $this->mTextLoaded = 1;
1351
1352 if ( !$this->loadRevisionData() ) {
1353 return false;
1354 }
1355
1356 $this->mNewContent = $this->mNewRev->getContent( Revision::FOR_THIS_USER, $this->getUser() );
1357
1358 return true;
1359 }
1360
1361 }