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