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