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