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