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