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