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