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