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