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