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