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