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