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