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