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