Made DifferenceEngine use a context instead of global variables and updaters calls...
[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->mNewPage->getPrefixedText() );
243 $out->addSubtitle( $this->msg( 'difference' ) );
244 $samePage = true;
245 $oldHeader = '';
246 } else {
247 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev, $this->mNewRev ) );
248
249 $sk = $this->getSkin();
250 if ( method_exists( $sk, 'suppressQuickbar' ) ) {
251 $sk->suppressQuickbar();
252 }
253
254 if ( $this->mNewPage->equals( $this->mOldPage ) ) {
255 $out->setPageTitle( $this->mNewPage->getPrefixedText() );
256 $out->addSubtitle( $this->msg( 'difference' ) );
257 $samePage = true;
258 } else {
259 $out->setPageTitle( $this->mOldPage->getPrefixedText() . ', ' . $this->mNewPage->getPrefixedText() );
260 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
261 $samePage = false;
262 }
263
264 if ( $samePage && $this->mNewPage->userCan( 'edit', $user ) ) {
265 if ( $this->mNewRev->isCurrent() && $this->mNewPage->userCan( 'rollback', $user ) ) {
266 $out->preventClickjacking();
267 $rollback = '&#160;&#160;&#160;' . Linker::generateRollback( $this->mNewRev );
268 }
269 if ( !$this->mOldRev->isDeleted( Revision::DELETED_TEXT ) && !$this->mNewRev->isDeleted( Revision::DELETED_TEXT ) ) {
270 $undoLink = ' ' . $this->msg( 'parentheses' )->rawParams(
271 Html::element( 'a', array(
272 'href' => $this->mNewPage->getLocalUrl( array(
273 'action' => 'edit',
274 'undoafter' => $this->mOldid,
275 'undo' => $this->mNewid ) ),
276 'title' => Linker::titleAttrib( 'undo' )
277 ),
278 $this->msg( 'editundo' )->text()
279 ) )->escaped();
280 }
281 }
282
283 # Make "previous revision link"
284 if ( $samePage && $this->mOldRev->getPrevious() ) {
285 $prevlink = Linker::linkKnown(
286 $this->mOldPage,
287 $this->msg( 'previousdiff' )->escaped(),
288 array( 'id' => 'differences-prevlink' ),
289 array( 'diff' => 'prev', 'oldid' => $this->mOldid ) + $query
290 );
291 } else {
292 $prevlink = '&#160;';
293 }
294
295 if ( $this->mOldRev->isMinor() ) {
296 $oldminor = ChangesList::flag( 'minor' );
297 } else {
298 $oldminor = '';
299 }
300
301 $ldel = $this->revisionDeleteLink( $this->mOldRev );
302 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev, 'complete' );
303
304 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
305 '<div id="mw-diff-otitle2">' .
306 Linker::revUserTools( $this->mOldRev, !$this->unhide ) . '</div>' .
307 '<div id="mw-diff-otitle3">' . $oldminor .
308 Linker::revComment( $this->mOldRev, !$diffOnly, !$this->unhide ) . $ldel . '</div>' .
309 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
310
311 if ( $this->mOldRev->isDeleted( Revision::DELETED_TEXT ) ) {
312 $deleted = true; // old revisions text is hidden
313 if ( $this->mOldRev->isDeleted( Revision::DELETED_RESTRICTED ) ) {
314 $suppressed = true; // also suppressed
315 }
316 }
317
318 # Check if this user can see the revisions
319 if ( !$this->mOldRev->userCan( Revision::DELETED_TEXT, $user ) ) {
320 $allowed = false;
321 }
322 }
323
324 # Make "next revision link"
325 # Skip next link on the top revision
326 if ( $samePage && !$this->mNewRev->isCurrent() ) {
327 $nextlink = Linker::linkKnown(
328 $this->mNewPage,
329 $this->msg( 'nextdiff' )->escaped(),
330 array( 'id' => 'differences-nextlink' ),
331 array( 'diff' => 'next', 'oldid' => $this->mNewid ) + $query
332 );
333 } else {
334 $nextlink = '&#160;';
335 }
336
337 if ( $this->mNewRev->isMinor() ) {
338 $newminor = ChangesList::flag( 'minor' );
339 } else {
340 $newminor = '';
341 }
342
343 # Handle RevisionDelete links...
344 $rdel = $this->revisionDeleteLink( $this->mNewRev );
345 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev, 'complete' ) . $undoLink;
346
347 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
348 '<div id="mw-diff-ntitle2">' . Linker::revUserTools( $this->mNewRev, !$this->unhide ) .
349 " $rollback</div>" .
350 '<div id="mw-diff-ntitle3">' . $newminor .
351 Linker::revComment( $this->mNewRev, !$diffOnly, !$this->unhide ) . $rdel . '</div>' .
352 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
353
354 if ( $this->mNewRev->isDeleted( Revision::DELETED_TEXT ) ) {
355 $deleted = true; // new revisions text is hidden
356 if ( $this->mNewRev->isDeleted( Revision::DELETED_RESTRICTED ) )
357 $suppressed = true; // also suppressed
358 }
359
360 # If the diff cannot be shown due to a deleted revision, then output
361 # the diff header and links to unhide (if available)...
362 if ( $deleted && ( !$this->unhide || !$allowed ) ) {
363 $this->showDiffStyle();
364 $multi = $this->getMultiNotice();
365 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
366 if ( !$allowed ) {
367 $msg = $suppressed ? 'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
368 # Give explanation for why revision is not visible
369 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
370 array( $msg ) );
371 } else {
372 # Give explanation and add a link to view the diff...
373 $link = $this->getTitle()->getFullUrl( $this->getRequest()->appendQueryValue( 'unhide', '1', true ) );
374 $msg = $suppressed ? 'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
375 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n", array( $msg, $link ) );
376 }
377 # Otherwise, output a regular diff...
378 } else {
379 # Add deletion notice if the user is viewing deleted content
380 $notice = '';
381 if ( $deleted ) {
382 $msg = $suppressed ? 'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
383 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" . $this->msg( $msg )->parse() . "</div>\n";
384 }
385 $this->showDiff( $oldHeader, $newHeader, $notice );
386 if ( !$diffOnly ) {
387 $this->renderNewRevision();
388 }
389 }
390 wfProfileOut( __METHOD__ );
391 }
392
393 /**
394 * Get a link to mark the change as patrolled, or '' if there's either no
395 * revision to patrol or the user is not allowed to to it.
396 * Side effect: this method will call OutputPage::preventClickjacking()
397 * when a link is builded.
398 *
399 * @return String
400 */
401 protected function markPatrolledLink() {
402 global $wgUseRCPatrol;
403
404 if ( $this->mMarkPatrolledLink === null ) {
405 // Prepare a change patrol link, if applicable
406 if ( $wgUseRCPatrol && $this->mNewPage->userCan( 'patrol', $this->getUser() ) ) {
407 // If we've been given an explicit change identifier, use it; saves time
408 if ( $this->mRcidMarkPatrolled ) {
409 $rcid = $this->mRcidMarkPatrolled;
410 $rc = RecentChange::newFromId( $rcid );
411 // Already patrolled?
412 $rcid = is_object( $rc ) && !$rc->getAttribute( 'rc_patrolled' ) ? $rcid : 0;
413 } else {
414 // Look for an unpatrolled change corresponding to this diff
415 $db = wfGetDB( DB_SLAVE );
416 $change = RecentChange::newFromConds(
417 array(
418 // Redundant user,timestamp condition so we can use the existing index
419 'rc_user_text' => $this->mNewRev->getRawUserText(),
420 'rc_timestamp' => $db->timestamp( $this->mNewRev->getTimestamp() ),
421 'rc_this_oldid' => $this->mNewid,
422 'rc_last_oldid' => $this->mOldid,
423 'rc_patrolled' => 0
424 ),
425 __METHOD__
426 );
427 if ( $change instanceof RecentChange ) {
428 $rcid = $change->mAttribs['rc_id'];
429 $this->mRcidMarkPatrolled = $rcid;
430 } else {
431 // None found
432 $rcid = 0;
433 }
434 }
435 // Build the link
436 if ( $rcid ) {
437 $this->getOutput()->preventClickjacking();
438 $token = $this->getUser()->editToken( $rcid );
439 $this->mMarkPatrolledLink = ' <span class="patrollink">[' . Linker::linkKnown(
440 $this->mNewPage,
441 $this->msg( 'markaspatrolleddiff' )->escaped(),
442 array(),
443 array(
444 'action' => 'markpatrolled',
445 'rcid' => $rcid,
446 'token' => $token,
447 )
448 ) . ']</span>';
449 } else {
450 $this->mMarkPatrolledLink = '';
451 }
452 } else {
453 $this->mMarkPatrolledLink = '';
454 }
455 }
456
457 return $this->mMarkPatrolledLink;
458 }
459
460 /**
461 * @param $rev Revision
462 * @return String
463 */
464 protected function revisionDeleteLink( $rev ) {
465 $link = '';
466 $user = $this->getUser();
467 $canHide = $user->isAllowed( 'deleterevision' );
468 // Show del/undel link if:
469 // (a) the user can delete revisions, or
470 // (b) the user can view deleted revision *and* this one is deleted
471 if ( $canHide || ( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) ) {
472 if ( !$rev->userCan( Revision::DELETED_RESTRICTED, $user ) ) {
473 $link = Linker::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
474 } else {
475 $query = array(
476 'type' => 'revision',
477 'target' => $rev->getTitle()->getPrefixedDBkey(),
478 'ids' => $rev->getId()
479 );
480 $link = Linker::revDeleteLink( $query,
481 $rev->isDeleted( Revision::DELETED_RESTRICTED ), $canHide );
482 }
483 $link = '&#160;&#160;&#160;' . $link . ' ';
484 }
485 return $link;
486 }
487
488 /**
489 * Show the new revision of the page.
490 */
491 function renderNewRevision() {
492 wfProfileIn( __METHOD__ );
493 $out = $this->getOutput();
494 $revHeader = $this->getRevisionHeader( $this->mNewRev );
495 # Add "current version as of X" title
496 $out->addHTML( "<hr class='diff-hr' />
497 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
498 # Page content may be handled by a hooked call instead...
499 if ( wfRunHooks( 'ArticleContentOnDiff', array( $this, $out ) ) ) {
500 # Use the current version parser cache if applicable
501 $pCache = true;
502 if ( !$this->mNewRev->isCurrent() ) {
503 $oldEditSectionSetting = $out->parserOptions()->setEditSection( false );
504 $pCache = false;
505 }
506
507 $this->loadNewText();
508 $out->setRevisionId( $this->mNewRev->getId() );
509 $out->setArticleFlag( true );
510
511 if ( $this->mNewPage->isCssJsSubpage() || $this->mNewPage->isCssOrJsPage() ) {
512 // Stolen from Article::view --AG 2007-10-11
513 // Give hooks a chance to customise the output
514 // @TODO: standardize this crap into one function
515 if ( wfRunHooks( 'ShowRawCssJs', array( $this->mNewtext, $this->mNewPage, $out ) ) ) {
516 // Wrap the whole lot in a <pre> and don't parse
517 $m = array();
518 preg_match( '!\.(css|js)$!u', $this->mNewPage->getText(), $m );
519 $out->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
520 $out->addHTML( htmlspecialchars( $this->mNewtext ) );
521 $out->addHTML( "\n</pre>\n" );
522 }
523 } elseif ( $pCache ) {
524 $wikipage = WikiPage::factory( $this->mNewPage );
525 $pOutput = ParserCache::singleton()->get( $wikipage, $out->parserOptions() );
526 if( $pOutput ) {
527 $out->addParserOutput( $pOutput );
528 } else {
529 $out->addWikiTextTidy( $this->mNewtext );
530 }
531 } else {
532 $out->addWikiTextTidy( $this->mNewtext );
533 }
534
535 if ( !$this->mNewRev->isCurrent() ) {
536 $out->parserOptions()->setEditSection( $oldEditSectionSetting );
537 }
538 }
539 # Add redundant patrol link on bottom...
540 $out->addHTML( $this->markPatrolledLink() );
541
542 wfProfileOut( __METHOD__ );
543 }
544
545 /**
546 * Get the diff text, send it to the OutputPage object
547 * Returns false if the diff could not be generated, otherwise returns true
548 *
549 * @return bool
550 */
551 function showDiff( $otitle, $ntitle, $notice = '' ) {
552 $diff = $this->getDiff( $otitle, $ntitle, $notice );
553 if ( $diff === false ) {
554 $this->getOutput()->addWikiMsg( 'missing-article', "<nowiki>(fixme, bug)</nowiki>", '' );
555 return false;
556 } else {
557 $this->showDiffStyle();
558 $this->getOutput()->addHTML( $diff );
559 return true;
560 }
561 }
562
563 /**
564 * Add style sheets and supporting JS for diff display.
565 */
566 function showDiffStyle() {
567 $this->getOutput()->addModuleStyles( 'mediawiki.action.history.diff' );
568 }
569
570 /**
571 * Get complete diff table, including header
572 *
573 * @param $otitle Title: old title
574 * @param $ntitle Title: new title
575 * @param $notice String: HTML between diff header and body
576 * @return mixed
577 */
578 function getDiff( $otitle, $ntitle, $notice = '' ) {
579 $body = $this->getDiffBody();
580 if ( $body === false ) {
581 return false;
582 } else {
583 $multi = $this->getMultiNotice();
584 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
585 }
586 }
587
588 /**
589 * Get the diff table body, without header
590 *
591 * @return mixed (string/false)
592 */
593 public function getDiffBody() {
594 global $wgMemc;
595 wfProfileIn( __METHOD__ );
596 $this->mCacheHit = true;
597 // Check if the diff should be hidden from this user
598 if ( !$this->loadRevisionData() ) {
599 wfProfileOut( __METHOD__ );
600 return false;
601 } elseif ( $this->mOldRev && !$this->mOldRev->userCan( Revision::DELETED_TEXT, $this->getUser() ) ) {
602 wfProfileOut( __METHOD__ );
603 return false;
604 } elseif ( $this->mNewRev && !$this->mNewRev->userCan( Revision::DELETED_TEXT, $this->getUser() ) ) {
605 wfProfileOut( __METHOD__ );
606 return false;
607 }
608 // Short-circuit
609 // If mOldRev is false, it means that the
610 if ( $this->mOldRev === false || ( $this->mOldRev && $this->mNewRev
611 && $this->mOldRev->getID() == $this->mNewRev->getID() ) )
612 {
613 wfProfileOut( __METHOD__ );
614 return '';
615 }
616 // Cacheable?
617 $key = false;
618 if ( $this->mOldid && $this->mNewid ) {
619 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION,
620 'oldid', $this->mOldid, 'newid', $this->mNewid );
621 // Try cache
622 if ( !$this->mRefreshCache ) {
623 $difftext = $wgMemc->get( $key );
624 if ( $difftext ) {
625 wfIncrStats( 'diff_cache_hit' );
626 $difftext = $this->localiseLineNumbers( $difftext );
627 $difftext .= "\n<!-- diff cache key $key -->\n";
628 wfProfileOut( __METHOD__ );
629 return $difftext;
630 }
631 } // don't try to load but save the result
632 }
633 $this->mCacheHit = false;
634
635 // Loadtext is permission safe, this just clears out the diff
636 if ( !$this->loadText() ) {
637 wfProfileOut( __METHOD__ );
638 return false;
639 }
640
641 $difftext = $this->generateDiffBody( $this->mOldtext, $this->mNewtext );
642
643 // Save to cache for 7 days
644 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
645 wfIncrStats( 'diff_uncacheable' );
646 } elseif ( $key !== false && $difftext !== false ) {
647 wfIncrStats( 'diff_cache_miss' );
648 $wgMemc->set( $key, $difftext, 7 * 86400 );
649 } else {
650 wfIncrStats( 'diff_uncacheable' );
651 }
652 // Replace line numbers with the text in the user's language
653 if ( $difftext !== false ) {
654 $difftext = $this->localiseLineNumbers( $difftext );
655 }
656 wfProfileOut( __METHOD__ );
657 return $difftext;
658 }
659
660 /**
661 * Make sure the proper modules are loaded before we try to
662 * make the diff
663 */
664 private function initDiffEngines() {
665 global $wgExternalDiffEngine;
666 if ( $wgExternalDiffEngine == 'wikidiff' && !function_exists( 'wikidiff_do_diff' ) ) {
667 wfProfileIn( __METHOD__ . '-php_wikidiff.so' );
668 wfDl( 'php_wikidiff' );
669 wfProfileOut( __METHOD__ . '-php_wikidiff.so' );
670 }
671 elseif ( $wgExternalDiffEngine == 'wikidiff2' && !function_exists( 'wikidiff2_do_diff' ) ) {
672 wfProfileIn( __METHOD__ . '-php_wikidiff2.so' );
673 wfDl( 'wikidiff2' );
674 wfProfileOut( __METHOD__ . '-php_wikidiff2.so' );
675 }
676 }
677
678 /**
679 * Generate a diff, no caching
680 *
681 * @param $otext String: old text, must be already segmented
682 * @param $ntext String: new text, must be already segmented
683 */
684 function generateDiffBody( $otext, $ntext ) {
685 global $wgExternalDiffEngine, $wgContLang;
686
687 wfProfileIn( __METHOD__ );
688
689 $otext = str_replace( "\r\n", "\n", $otext );
690 $ntext = str_replace( "\r\n", "\n", $ntext );
691
692 $this->initDiffEngines();
693
694 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
695 # For historical reasons, external diff engine expects
696 # input text to be HTML-escaped already
697 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
698 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
699 wfProfileOut( __METHOD__ );
700 return $wgContLang->unsegmentForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
701 $this->debug( 'wikidiff1' );
702 }
703
704 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
705 # Better external diff engine, the 2 may some day be dropped
706 # This one does the escaping and segmenting itself
707 wfProfileIn( 'wikidiff2_do_diff' );
708 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
709 $text .= $this->debug( 'wikidiff2' );
710 wfProfileOut( 'wikidiff2_do_diff' );
711 wfProfileOut( __METHOD__ );
712 return $text;
713 }
714 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
715 # Diff via the shell
716 global $wgTmpDirectory;
717 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
718 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
719
720 $tempFile1 = fopen( $tempName1, "w" );
721 if ( !$tempFile1 ) {
722 wfProfileOut( __METHOD__ );
723 return false;
724 }
725 $tempFile2 = fopen( $tempName2, "w" );
726 if ( !$tempFile2 ) {
727 wfProfileOut( __METHOD__ );
728 return false;
729 }
730 fwrite( $tempFile1, $otext );
731 fwrite( $tempFile2, $ntext );
732 fclose( $tempFile1 );
733 fclose( $tempFile2 );
734 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
735 wfProfileIn( __METHOD__ . "-shellexec" );
736 $difftext = wfShellExec( $cmd );
737 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
738 wfProfileOut( __METHOD__ . "-shellexec" );
739 unlink( $tempName1 );
740 unlink( $tempName2 );
741 wfProfileOut( __METHOD__ );
742 return $difftext;
743 }
744
745 # Native PHP diff
746 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
747 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
748 $diffs = new Diff( $ota, $nta );
749 $formatter = new TableDiffFormatter();
750 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
751 wfProfileOut( __METHOD__ );
752 return $difftext;
753 }
754
755 /**
756 * Generate a debug comment indicating diff generating time,
757 * server node, and generator backend.
758 */
759 protected function debug( $generator = "internal" ) {
760 global $wgShowHostnames;
761 if ( !$this->enableDebugComment ) {
762 return '';
763 }
764 $data = array( $generator );
765 if ( $wgShowHostnames ) {
766 $data[] = wfHostname();
767 }
768 $data[] = wfTimestamp( TS_DB );
769 return "<!-- diff generator: " .
770 implode( " ",
771 array_map(
772 "htmlspecialchars",
773 $data ) ) .
774 " -->\n";
775 }
776
777 /**
778 * Replace line numbers with the text in the user's language
779 */
780 function localiseLineNumbers( $text ) {
781 return preg_replace_callback( '/<!--LINE (\d+)-->/',
782 array( &$this, 'localiseLineNumbersCb' ), $text );
783 }
784
785 function localiseLineNumbersCb( $matches ) {
786 if ( $matches[1] === '1' && $this->mReducedLineNumbers ) return '';
787 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
788 }
789
790
791 /**
792 * If there are revisions between the ones being compared, return a note saying so.
793 * @return string
794 */
795 function getMultiNotice() {
796 if ( !is_object( $this->mOldRev ) || !is_object( $this->mNewRev ) ) {
797 return '';
798 } elseif ( !$this->mOldPage->equals( $this->mNewPage ) ) {
799 // Comparing two different pages? Count would be meaningless.
800 return '';
801 }
802
803 if ( $this->mOldRev->getTimestamp() > $this->mNewRev->getTimestamp() ) {
804 $oldRev = $this->mNewRev; // flip
805 $newRev = $this->mOldRev; // flip
806 } else { // normal case
807 $oldRev = $this->mOldRev;
808 $newRev = $this->mNewRev;
809 }
810
811 $nEdits = $this->mNewPage->countRevisionsBetween( $oldRev, $newRev );
812 if ( $nEdits > 0 ) {
813 $limit = 100; // use diff-multi-manyusers if too many users
814 $numUsers = $this->mNewPage->countAuthorsBetween( $oldRev, $newRev, $limit );
815 return self::intermediateEditsMsg( $nEdits, $numUsers, $limit );
816 }
817 return ''; // nothing
818 }
819
820 /**
821 * Get a notice about how many intermediate edits and users there are
822 * @param $numEdits int
823 * @param $numUsers int
824 * @param $limit int
825 * @return string
826 */
827 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
828 if ( $numUsers > $limit ) {
829 $msg = 'diff-multi-manyusers';
830 $numUsers = $limit;
831 } else {
832 $msg = 'diff-multi';
833 }
834 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
835 }
836
837 /**
838 * Get a header for a specified revision.
839 *
840 * @param $rev Revision
841 * @param $complete String: 'complete' to get the header wrapped depending
842 * the visibility of the revision and a link to edit the page.
843 * @return String HTML fragment
844 */
845 private function getRevisionHeader( Revision $rev, $complete = '' ) {
846 $lang = $this->getLang();
847 $user = $this->getUser();
848 $revtimestamp = $rev->getTimestamp();
849 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
850 $dateofrev = $lang->userDate( $revtimestamp, $user );
851 $timeofrev = $lang->userTime( $revtimestamp, $user );
852
853 $header = $this->msg(
854 $rev->isCurrent() ? 'currentrev-asof' : 'revisionasof',
855 $timestamp,
856 $dateofrev,
857 $timeofrev
858 )->escaped();
859
860 if ( $complete !== 'complete' ) {
861 return $header;
862 }
863
864 $title = $rev->getTitle();
865
866 $header = Linker::linkKnown( $title, $header, array(),
867 array( 'oldid' => $rev->getID() ) );
868
869 if ( $rev->userCan( Revision::DELETED_TEXT, $user ) ) {
870 $editQuery = array( 'action' => 'edit' );
871 if ( !$rev->isCurrent() ) {
872 $editQuery['oldid'] = $rev->getID();
873 }
874
875 $msg = $this->msg( $title->userCan( 'edit', $user ) ? 'editold' : 'viewsourceold' )->escaped();
876 $header .= ' (' . Linker::linkKnown( $title, $msg, array(), $editQuery ) . ')';
877 if ( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
878 $header = Html::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
879 }
880 } else {
881 $header = Html::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
882 }
883
884 return $header;
885 }
886
887 /**
888 * Add the header to a diff body
889 *
890 * @return string
891 */
892 function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
893 // shared.css sets diff in interface language/dir, but the actual content
894 // is often in a different language, mostly the page content language/dir
895 $tableClass = 'diff diff-contentalign-' . htmlspecialchars( $this->getDiffLang()->alignStart() );
896 $header = "<table class='$tableClass'>";
897
898 if ( !$diff && !$otitle ) {
899 $header .= "
900 <tr valign='top'>
901 <td class='diff-ntitle'>{$ntitle}</td>
902 </tr>";
903 $multiColspan = 1;
904 } else {
905 if ( $diff ) { // Safari/Chrome show broken output if cols not used
906 $header .= "
907 <col class='diff-marker' />
908 <col class='diff-content' />
909 <col class='diff-marker' />
910 <col class='diff-content' />";
911 $colspan = 2;
912 $multiColspan = 4;
913 } else {
914 $colspan = 1;
915 $multiColspan = 2;
916 }
917 $header .= "
918 <tr valign='top'>
919 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
920 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
921 </tr>";
922 }
923
924 if ( $multi != '' ) {
925 $header .= "<tr><td colspan='{$multiColspan}' align='center' class='diff-multi'>{$multi}</td></tr>";
926 }
927 if ( $notice != '' ) {
928 $header .= "<tr><td colspan='{$multiColspan}' align='center'>{$notice}</td></tr>";
929 }
930
931 return $header . $diff . "</table>";
932 }
933
934 /**
935 * Use specified text instead of loading from the database
936 */
937 function setText( $oldText, $newText ) {
938 $this->mOldtext = $oldText;
939 $this->mNewtext = $newText;
940 $this->mTextLoaded = 2;
941 $this->mRevisionsLoaded = true;
942 }
943
944 /**
945 * Set the language in which the diff text is written
946 * (Defaults to page content language).
947 * @since 1.19
948 */
949 function setTextLanguage( $lang ) {
950 $this->mDiffLang = wfGetLangObj( $lang );
951 }
952
953 /**
954 * Load revision IDs
955 */
956 private function loadRevisionIds() {
957 if ( $this->mRevisionsIdsLoaded ) {
958 return;
959 }
960
961 $this->mRevisionsIdsLoaded = true;
962
963 $old = $this->mOldid;
964 $new = $this->mNewid;
965
966 if ( $new === 'prev' ) {
967 # Show diff between revision $old and the previous one.
968 # Get previous one from DB.
969 $this->mNewid = intval( $old );
970 $this->mOldid = $this->getTitle()->getPreviousRevisionID( $this->mNewid );
971 } elseif ( $new === 'next' ) {
972 # Show diff between revision $old and the next one.
973 # Get next one from DB.
974 $this->mOldid = intval( $old );
975 $this->mNewid = $this->getTitle()->getNextRevisionID( $this->mOldid );
976 if ( $this->mNewid === false ) {
977 # if no result, NewId points to the newest old revision. The only newer
978 # revision is cur, which is "0".
979 $this->mNewid = 0;
980 }
981 } else {
982 $this->mOldid = intval( $old );
983 $this->mNewid = intval( $new );
984 wfRunHooks( 'NewDifferenceEngine', array( $this->getTitle(), &$this->mOldid, &$this->mNewid, $old, $new ) );
985 }
986 }
987
988 /**
989 * Load revision metadata for the specified articles. If newid is 0, then compare
990 * the old article in oldid to the current article; if oldid is 0, then
991 * compare the current article to the immediately previous one (ignoring the
992 * value of newid).
993 *
994 * If oldid is false, leave the corresponding revision object set
995 * to false. This is impossible via ordinary user input, and is provided for
996 * API convenience.
997 *
998 * @return bool
999 */
1000 function loadRevisionData() {
1001 if ( $this->mRevisionsLoaded ) {
1002 return true;
1003 }
1004
1005 // Whether it succeeds or fails, we don't want to try again
1006 $this->mRevisionsLoaded = true;
1007
1008 $this->loadRevisionIds();
1009
1010 // Load the new revision object
1011 $this->mNewRev = $this->mNewid
1012 ? Revision::newFromId( $this->mNewid )
1013 : Revision::newFromTitle( $this->getTitle() );
1014
1015 if ( !$this->mNewRev instanceof Revision ) {
1016 return false;
1017 }
1018
1019 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1020 $this->mNewid = $this->mNewRev->getId();
1021 $this->mNewPage = $this->mNewRev->getTitle();
1022
1023 // Load the old revision object
1024 $this->mOldRev = false;
1025 if ( $this->mOldid ) {
1026 $this->mOldRev = Revision::newFromId( $this->mOldid );
1027 } elseif ( $this->mOldid === 0 ) {
1028 $rev = $this->mNewRev->getPrevious();
1029 if ( $rev ) {
1030 $this->mOldid = $rev->getId();
1031 $this->mOldRev = $rev;
1032 } else {
1033 // No previous revision; mark to show as first-version only.
1034 $this->mOldid = false;
1035 $this->mOldRev = false;
1036 }
1037 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1038
1039 if ( is_null( $this->mOldRev ) ) {
1040 return false;
1041 }
1042
1043 if ( $this->mOldRev ) {
1044 $this->mOldPage = $this->mOldRev->getTitle();
1045 }
1046
1047 return true;
1048 }
1049
1050 /**
1051 * Load the text of the revisions, as well as revision data.
1052 *
1053 * @return bool
1054 */
1055 function loadText() {
1056 if ( $this->mTextLoaded == 2 ) {
1057 return true;
1058 } else {
1059 // Whether it succeeds or fails, we don't want to try again
1060 $this->mTextLoaded = 2;
1061 }
1062
1063 if ( !$this->loadRevisionData() ) {
1064 return false;
1065 }
1066 if ( $this->mOldRev ) {
1067 $this->mOldtext = $this->mOldRev->getText( Revision::FOR_THIS_USER );
1068 if ( $this->mOldtext === false ) {
1069 return false;
1070 }
1071 }
1072 if ( $this->mNewRev ) {
1073 $this->mNewtext = $this->mNewRev->getText( Revision::FOR_THIS_USER );
1074 if ( $this->mNewtext === false ) {
1075 return false;
1076 }
1077 }
1078 return true;
1079 }
1080
1081 /**
1082 * Load the text of the new revision, not the old one
1083 *
1084 * @return bool
1085 */
1086 function loadNewText() {
1087 if ( $this->mTextLoaded >= 1 ) {
1088 return true;
1089 } else {
1090 $this->mTextLoaded = 1;
1091 }
1092 if ( !$this->loadRevisionData() ) {
1093 return false;
1094 }
1095 $this->mNewtext = $this->mNewRev->getText( Revision::FOR_THIS_USER );
1096 return true;
1097 }
1098 }