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