* Made OuputPage::showPermissionsErrorPage() show a different messages for 'read...
[lhc/web/wiklou.git] / includes / diff / DifferenceEngine.php
1 <?php
2 /**
3 * User interface for the difference engine
4 *
5 * @file
6 * @ingroup DifferenceEngine
7 */
8
9 /**
10 * Constant to indicate diff cache compatibility.
11 * Bump this when changing the diff formatting in a way that
12 * fixes important bugs or such to force cached diff views to
13 * clear.
14 */
15 define( 'MW_DIFF_VERSION', '1.11a' );
16
17 /**
18 * @todo document
19 * @ingroup DifferenceEngine
20 */
21 class DifferenceEngine {
22 /**#@+
23 * @private
24 */
25 var $mOldid, $mNewid;
26 var $mOldtext, $mNewtext;
27 protected $mDiffLang;
28
29 /**
30 * @var Title
31 */
32 var $mOldPage, $mNewPage, $mTitle;
33 var $mRcidMarkPatrolled;
34
35 /**
36 * @var Revision
37 */
38 var $mOldRev, $mNewRev;
39 private $mRevisionsIdsLoaded = false; // Have the revisions IDs been loaded
40 var $mRevisionsLoaded = false; // Have the revisions been loaded
41 var $mTextLoaded = 0; // How many text blobs have been loaded, 0, 1 or 2?
42 var $mCacheHit = false; // Was the diff fetched from cache?
43
44 /**
45 * Set this to true to add debug info to the HTML output.
46 * Warning: this may cause RSS readers to spuriously mark articles as "new"
47 * (bug 20601)
48 */
49 var $enableDebugComment = false;
50
51 // If true, line X is not displayed when X is 1, for example to increase
52 // readability and conserve space with many small diffs.
53 protected $mReducedLineNumbers = false;
54
55 // Link to action=markpatrolled
56 protected $mMarkPatrolledLink = null;
57
58 protected $unhide = false; # show rev_deleted content if allowed
59 /**#@-*/
60
61 /**
62 * Constructor
63 * @param $titleObj Title object that the diff is associated with
64 * @param $old Integer old ID we want to show and diff with.
65 * @param $new String either 'prev' or 'next'.
66 * @param $rcid Integer ??? FIXME (default 0)
67 * @param $refreshCache boolean If set, refreshes the diff cache
68 * @param $unhide boolean If set, allow viewing deleted revs
69 */
70 function __construct( $titleObj = null, $old = 0, $new = 0, $rcid = 0,
71 $refreshCache = false, $unhide = false )
72 {
73 if ( $titleObj ) {
74 $this->mTitle = $titleObj;
75 } else {
76 global $wgTitle;
77 $this->mTitle = $wgTitle; // @TODO: get rid of this
78 }
79 wfDebug( "DifferenceEngine old '$old' new '$new' rcid '$rcid'\n" );
80
81 $this->mOldid = $old;
82 $this->mNewid = $new;
83 $this->mRcidMarkPatrolled = intval( $rcid ); # force it to be an integer
84 $this->mRefreshCache = $refreshCache;
85 $this->unhide = $unhide;
86 }
87
88 /**
89 * @param $value bool
90 */
91 function setReducedLineNumbers( $value = true ) {
92 $this->mReducedLineNumbers = $value;
93 }
94
95 /**
96 * @return Language
97 */
98 function getDiffLang() {
99 if ( $this->mDiffLang === null ) {
100 # Default language in which the diff text is written.
101 $this->mDiffLang = $this->mTitle->getPageLanguage();
102 }
103 return $this->mDiffLang;
104 }
105
106 /**
107 * @return Title
108 */
109 function getTitle() {
110 return $this->mTitle;
111 }
112
113 /**
114 * @return bool
115 */
116 function wasCacheHit() {
117 return $this->mCacheHit;
118 }
119
120 /**
121 * @return int
122 */
123 function getOldid() {
124 $this->loadRevisionIds();
125 return $this->mOldid;
126 }
127
128 /**
129 * @return Bool|int
130 */
131 function getNewid() {
132 $this->loadRevisionIds();
133 return $this->mNewid;
134 }
135
136 /**
137 * Look up a special:Undelete link to the given deleted revision id,
138 * as a workaround for being unable to load deleted diffs in currently.
139 *
140 * @param int $id revision ID
141 * @return mixed URL or false
142 */
143 function deletedLink( $id ) {
144 global $wgUser;
145 if ( $wgUser->isAllowed( 'deletedhistory' ) ) {
146 $dbr = wfGetDB( DB_SLAVE );
147 $row = $dbr->selectRow('archive', '*',
148 array( 'ar_rev_id' => $id ),
149 __METHOD__ );
150 if ( $row ) {
151 $rev = Revision::newFromArchiveRow( $row );
152 $title = Title::makeTitleSafe( $row->ar_namespace, $row->ar_title );
153 return SpecialPage::getTitleFor( 'Undelete' )->getFullURL( array(
154 'target' => $title->getPrefixedText(),
155 'timestamp' => $rev->getTimestamp()
156 ));
157 }
158 }
159 return false;
160 }
161
162 /**
163 * Build a wikitext link toward a deleted revision, if viewable.
164 *
165 * @param int $id revision ID
166 * @return string wikitext fragment
167 */
168 function deletedIdMarker( $id ) {
169 $link = $this->deletedLink( $id );
170 if ( $link ) {
171 return "[$link $id]";
172 } else {
173 return $id;
174 }
175 }
176
177 function showDiffPage( $diffOnly = false ) {
178 global $wgUser, $wgOut, $wgRequest, $wgUseExternalEditor;
179 wfProfileIn( __METHOD__ );
180
181 # Allow frames except in certain special cases
182 $wgOut->allowClickjacking();
183 $wgOut->setRobotPolicy( 'noindex,nofollow' );
184
185 if ( !$this->loadRevisionData() ) {
186 // Sounds like a deleted revision... Let's see what we can do.
187 $t = $this->mTitle->getPrefixedText();
188 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ),
189 $this->deletedIdMarker( $this->mOldid ),
190 $this->deletedIdMarker( $this->mNewid ) );
191 $wgOut->setPageTitle( wfMessage( 'errorpagetitle' ) );
192 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", "<span class='plainlinks'>$d</span>" );
193 wfProfileOut( __METHOD__ );
194 return;
195 }
196
197 # mOldPage might not be set, see below.
198 if ( !$this->mNewPage->userCanRead() || ( $this->mOldPage && !$this->mOldPage->userCanRead() ) ) {
199 wfProfileOut( __METHOD__ );
200 throw new PermissionsError( 'read' );
201 }
202
203 # If external diffs are enabled both globally and for the user,
204 # we'll use the application/x-external-editor interface to call
205 # an external diff tool like kompare, kdiff3, etc.
206 if ( $wgUseExternalEditor && $wgUser->getOption( 'externaldiff' ) ) {
207 global $wgCanonicalServer, $wgScript, $wgLang;
208 $wgOut->disable();
209 header ( "Content-type: application/x-external-editor; charset=UTF-8" );
210 # This should be mOldPage, but it may not be set, see below.
211 $url1 = $this->mNewPage->getCanonicalURL( array(
212 'action' => 'raw',
213 'oldid' => $this->mOldid
214 ) );
215 $url2 = $this->mNewPage->getCanonicalURL( array(
216 'action' => 'raw',
217 'oldid' => $this->mNewid
218 ) );
219 $special = $wgLang->getNsText( NS_SPECIAL );
220 $control = <<<CONTROL
221 [Process]
222 Type=Diff text
223 Engine=MediaWiki
224 Script={$wgCanonicalServer}{$wgScript}
225 Special namespace={$special}
226
227 [File]
228 Extension=wiki
229 URL=$url1
230
231 [File 2]
232 Extension=wiki
233 URL=$url2
234 CONTROL;
235 echo( $control );
236
237 wfProfileOut( __METHOD__ );
238 return;
239 }
240
241 $rollback = '';
242 $undoLink = '';
243
244 $query = array();
245 # Carry over 'diffonly' param via navigation links
246 if ( $diffOnly != $wgUser->getBoolOption( 'diffonly' ) ) {
247 $query['diffonly'] = $diffOnly;
248 }
249 # Cascade unhide param in links for easy deletion browsing
250 if ( $this->unhide ) {
251 $query['unhide'] = 1;
252 }
253
254 # Check if one of the revisions is deleted/suppressed
255 $deleted = $suppressed = false;
256 $allowed = $this->mNewRev->userCan( Revision::DELETED_TEXT );
257
258 # mOldRev is false if the difference engine is called with a "vague" query for
259 # a diff between a version V and its previous version V' AND the version V
260 # is the first version of that article. In that case, V' does not exist.
261 if ( $this->mOldRev === false ) {
262 $wgOut->setPageTitle( $this->mNewPage->getPrefixedText() );
263 $wgOut->setSubtitle( wfMsgExt( 'difference', array( 'parseinline' ) ) );
264 $samePage = true;
265 $oldHeader = '';
266 } else {
267 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev, $this->mNewRev ) );
268
269 $sk = $wgUser->getSkin();
270 if ( method_exists( $sk, 'suppressQuickbar' ) ) {
271 $sk->suppressQuickbar();
272 }
273
274 if ( $this->mNewPage->equals( $this->mOldPage ) ) {
275 $wgOut->setPageTitle( $this->mNewPage->getPrefixedText() );
276 $wgOut->setSubtitle( wfMsgExt( 'difference', array( 'parseinline' ) ) );
277 $samePage = true;
278 } else {
279 $wgOut->setPageTitle( $this->mOldPage->getPrefixedText() . ', ' . $this->mNewPage->getPrefixedText() );
280 $wgOut->setSubtitle( wfMsgExt( 'difference-multipage', array( 'parseinline' ) ) );
281 $samePage = false;
282 }
283
284 if ( $samePage && $this->mNewPage->userCan( 'edit' ) ) {
285 if ( $this->mNewRev->isCurrent() && $this->mNewPage->userCan( 'rollback' ) ) {
286 $wgOut->preventClickjacking();
287 $rollback = '&#160;&#160;&#160;' . Linker::generateRollback( $this->mNewRev );
288 }
289 if ( !$this->mOldRev->isDeleted( Revision::DELETED_TEXT ) && !$this->mNewRev->isDeleted( Revision::DELETED_TEXT ) ) {
290 $undoLink = ' ' . wfMsgHtml( 'parentheses', Html::element( 'a', array(
291 'href' => $this->mNewPage->getLocalUrl( array(
292 'action' => 'edit',
293 'undoafter' => $this->mOldid,
294 'undo' => $this->mNewid ) ),
295 'title' => Linker::titleAttrib( 'undo' )
296 ), wfMsg( 'editundo' ) ) );
297 }
298 }
299
300 # Make "previous revision link"
301 if ( $samePage && $this->mOldRev->getPrevious() ) {
302 $prevlink = Linker::linkKnown(
303 $this->mOldPage,
304 wfMsgHtml( 'previousdiff' ),
305 array( 'id' => 'differences-prevlink' ),
306 array( 'diff' => 'prev', 'oldid' => $this->mOldid ) + $query
307 );
308 } else {
309 $prevlink = '&#160;';
310 }
311
312 if ( $this->mOldRev->isMinor() ) {
313 $oldminor = ChangesList::flag( 'minor' );
314 } else {
315 $oldminor = '';
316 }
317
318 $ldel = $this->revisionDeleteLink( $this->mOldRev );
319 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev, 'complete' );
320
321 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
322 '<div id="mw-diff-otitle2">' .
323 Linker::revUserTools( $this->mOldRev, !$this->unhide ) . '</div>' .
324 '<div id="mw-diff-otitle3">' . $oldminor .
325 Linker::revComment( $this->mOldRev, !$diffOnly, !$this->unhide ) . $ldel . '</div>' .
326 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
327
328 if ( $this->mOldRev->isDeleted( Revision::DELETED_TEXT ) ) {
329 $deleted = true; // old revisions text is hidden
330 if ( $this->mOldRev->isDeleted( Revision::DELETED_RESTRICTED ) ) {
331 $suppressed = true; // also suppressed
332 }
333 }
334
335 # Check if this user can see the revisions
336 if ( !$this->mOldRev->userCan( Revision::DELETED_TEXT ) ) {
337 $allowed = false;
338 }
339 }
340
341 # Make "next revision link"
342 # Skip next link on the top revision
343 if ( $samePage && !$this->mNewRev->isCurrent() ) {
344 $nextlink = Linker::linkKnown(
345 $this->mNewPage,
346 wfMsgHtml( 'nextdiff' ),
347 array( 'id' => 'differences-nextlink' ),
348 array( 'diff' => 'next', 'oldid' => $this->mNewid ) + $query
349 );
350 } else {
351 $nextlink = '&#160;';
352 }
353
354 if ( $this->mNewRev->isMinor() ) {
355 $newminor = ChangesList::flag( 'minor' );
356 } else {
357 $newminor = '';
358 }
359
360 # Handle RevisionDelete links...
361 $rdel = $this->revisionDeleteLink( $this->mNewRev );
362 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev, 'complete' ) . $undoLink;
363
364 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
365 '<div id="mw-diff-ntitle2">' . Linker::revUserTools( $this->mNewRev, !$this->unhide ) .
366 " $rollback</div>" .
367 '<div id="mw-diff-ntitle3">' . $newminor .
368 Linker::revComment( $this->mNewRev, !$diffOnly, !$this->unhide ) . $rdel . '</div>' .
369 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
370
371 if ( $this->mNewRev->isDeleted( Revision::DELETED_TEXT ) ) {
372 $deleted = true; // new revisions text is hidden
373 if ( $this->mNewRev->isDeleted( Revision::DELETED_RESTRICTED ) )
374 $suppressed = true; // also suppressed
375 }
376
377 # If the diff cannot be shown due to a deleted revision, then output
378 # the diff header and links to unhide (if available)...
379 if ( $deleted && ( !$this->unhide || !$allowed ) ) {
380 $this->showDiffStyle();
381 $multi = $this->getMultiNotice();
382 $wgOut->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
383 if ( !$allowed ) {
384 $msg = $suppressed ? 'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
385 # Give explanation for why revision is not visible
386 $wgOut->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
387 array( $msg ) );
388 } else {
389 # Give explanation and add a link to view the diff...
390 $link = $this->mTitle->getFullUrl( $wgRequest->appendQueryValue( 'unhide', '1', true ) );
391 $msg = $suppressed ? 'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
392 $wgOut->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</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 id='mw-$msg' 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 * Get a link to mark the change as patrolled, or '' if there's either no
412 * revision to patrol or the user is not allowed to to it.
413 * Side effect: this method will call OutputPage::preventClickjacking()
414 * when a link is builded.
415 *
416 * @return String
417 */
418 protected function markPatrolledLink() {
419 global $wgUseRCPatrol, $wgUser, $wgOut;
420
421 if ( $this->mMarkPatrolledLink === null ) {
422 // Prepare a change patrol link, if applicable
423 if ( $wgUseRCPatrol && $this->mNewPage->userCan( 'patrol' ) ) {
424 // If we've been given an explicit change identifier, use it; saves time
425 if ( $this->mRcidMarkPatrolled ) {
426 $rcid = $this->mRcidMarkPatrolled;
427 $rc = RecentChange::newFromId( $rcid );
428 // Already patrolled?
429 $rcid = is_object( $rc ) && !$rc->getAttribute( 'rc_patrolled' ) ? $rcid : 0;
430 } else {
431 // Look for an unpatrolled change corresponding to this diff
432 $db = wfGetDB( DB_SLAVE );
433 $change = RecentChange::newFromConds(
434 array(
435 // Redundant user,timestamp condition so we can use the existing index
436 'rc_user_text' => $this->mNewRev->getRawUserText(),
437 'rc_timestamp' => $db->timestamp( $this->mNewRev->getTimestamp() ),
438 'rc_this_oldid' => $this->mNewid,
439 'rc_last_oldid' => $this->mOldid,
440 'rc_patrolled' => 0
441 ),
442 __METHOD__
443 );
444 if ( $change instanceof RecentChange ) {
445 $rcid = $change->mAttribs['rc_id'];
446 $this->mRcidMarkPatrolled = $rcid;
447 } else {
448 // None found
449 $rcid = 0;
450 }
451 }
452 // Build the link
453 if ( $rcid ) {
454 $wgOut->preventClickjacking();
455 $token = $wgUser->editToken( $rcid );
456 $this->mMarkPatrolledLink = ' <span class="patrollink">[' . Linker::linkKnown(
457 $this->mNewPage,
458 wfMsgHtml( 'markaspatrolleddiff' ),
459 array(),
460 array(
461 'action' => 'markpatrolled',
462 'rcid' => $rcid,
463 'token' => $token,
464 )
465 ) . ']</span>';
466 } else {
467 $this->mMarkPatrolledLink = '';
468 }
469 } else {
470 $this->mMarkPatrolledLink = '';
471 }
472 }
473
474 return $this->mMarkPatrolledLink;
475 }
476
477 /**
478 * @param $rev Revision
479 * @return String
480 */
481 protected function revisionDeleteLink( $rev ) {
482 global $wgUser;
483 $link = '';
484 $canHide = $wgUser->isAllowed( 'deleterevision' );
485 // Show del/undel link if:
486 // (a) the user can delete revisions, or
487 // (b) the user can view deleted revision *and* this one is deleted
488 if ( $canHide || ( $rev->getVisibility() && $wgUser->isAllowed( 'deletedhistory' ) ) ) {
489 if ( !$rev->userCan( Revision::DELETED_RESTRICTED ) ) {
490 $link = Linker::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
491 } else {
492 $query = array(
493 'type' => 'revision',
494 'target' => $rev->getTitle()->getPrefixedDBkey(),
495 'ids' => $rev->getId()
496 );
497 $link = Linker::revDeleteLink( $query,
498 $rev->isDeleted( Revision::DELETED_RESTRICTED ), $canHide );
499 }
500 $link = '&#160;&#160;&#160;' . $link . ' ';
501 }
502 return $link;
503 }
504
505 /**
506 * Show the new revision of the page.
507 */
508 function renderNewRevision() {
509 global $wgOut;
510 wfProfileIn( __METHOD__ );
511 $revHeader = $this->getRevisionHeader( $this->mNewRev );
512 # Add "current version as of X" title
513 $wgOut->addHTML( "<hr class='diff-hr' />
514 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
515 # Page content may be handled by a hooked call instead...
516 if ( wfRunHooks( 'ArticleContentOnDiff', array( $this, $wgOut ) ) ) {
517 # Use the current version parser cache if applicable
518 $pCache = true;
519 if ( !$this->mNewRev->isCurrent() ) {
520 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
521 $pCache = false;
522 }
523
524 $this->loadNewText();
525 $wgOut->setRevisionId( $this->mNewRev->getId() );
526 $wgOut->setArticleFlag( true );
527
528 if ( $this->mNewPage->isCssJsSubpage() || $this->mNewPage->isCssOrJsPage() ) {
529 // Stolen from Article::view --AG 2007-10-11
530 // Give hooks a chance to customise the output
531 // @TODO: standardize this crap into one function
532 if ( wfRunHooks( 'ShowRawCssJs', array( $this->mNewtext, $this->mNewPage, $wgOut ) ) ) {
533 // Wrap the whole lot in a <pre> and don't parse
534 $m = array();
535 preg_match( '!\.(css|js)$!u', $this->mNewPage->getText(), $m );
536 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
537 $wgOut->addHTML( htmlspecialchars( $this->mNewtext ) );
538 $wgOut->addHTML( "\n</pre>\n" );
539 }
540 } elseif ( $pCache ) {
541 $article = new Article( $this->mNewPage, 0 );
542 $pOutput = ParserCache::singleton()->get( $article, $wgOut->parserOptions() );
543 if( $pOutput ) {
544 $wgOut->addParserOutput( $pOutput );
545 } else {
546 $article->doViewParse();
547 }
548 } else {
549 $wgOut->addWikiTextTidy( $this->mNewtext );
550 }
551
552 if ( !$this->mNewRev->isCurrent() ) {
553 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
554 }
555 }
556 # Add redundant patrol link on bottom...
557 $wgOut->addHTML( $this->markPatrolledLink() );
558
559 wfProfileOut( __METHOD__ );
560 }
561
562 /**
563 * Get the diff text, send it to $wgOut
564 * Returns false if the diff could not be generated, otherwise returns true
565 *
566 * @return bool
567 */
568 function showDiff( $otitle, $ntitle, $notice = '' ) {
569 global $wgOut;
570 $diff = $this->getDiff( $otitle, $ntitle, $notice );
571 if ( $diff === false ) {
572 $wgOut->addWikiMsg( 'missing-article', "<nowiki>(fixme, bug)</nowiki>", '' );
573 return false;
574 } else {
575 $this->showDiffStyle();
576 $wgOut->addHTML( $diff );
577 return true;
578 }
579 }
580
581 /**
582 * Add style sheets and supporting JS for diff display.
583 */
584 function showDiffStyle() {
585 global $wgOut;
586 $wgOut->addModuleStyles( 'mediawiki.action.history.diff' );
587 }
588
589 /**
590 * Get complete diff table, including header
591 *
592 * @param $otitle Title: old title
593 * @param $ntitle Title: new title
594 * @param $notice String: HTML between diff header and body
595 * @return mixed
596 */
597 function getDiff( $otitle, $ntitle, $notice = '' ) {
598 $body = $this->getDiffBody();
599 if ( $body === false ) {
600 return false;
601 } else {
602 $multi = $this->getMultiNotice();
603 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
604 }
605 }
606
607 /**
608 * Get the diff table body, without header
609 *
610 * @return mixed (string/false)
611 */
612 public function getDiffBody() {
613 global $wgMemc;
614 wfProfileIn( __METHOD__ );
615 $this->mCacheHit = true;
616 // Check if the diff should be hidden from this user
617 if ( !$this->loadRevisionData() ) {
618 wfProfileOut( __METHOD__ );
619 return false;
620 } elseif ( $this->mOldRev && !$this->mOldRev->userCan( Revision::DELETED_TEXT ) ) {
621 wfProfileOut( __METHOD__ );
622 return false;
623 } elseif ( $this->mNewRev && !$this->mNewRev->userCan( Revision::DELETED_TEXT ) ) {
624 wfProfileOut( __METHOD__ );
625 return false;
626 }
627 // Short-circuit
628 // If mOldRev is false, it means that the
629 if ( $this->mOldRev === false || ( $this->mOldRev && $this->mNewRev
630 && $this->mOldRev->getID() == $this->mNewRev->getID() ) )
631 {
632 wfProfileOut( __METHOD__ );
633 return '';
634 }
635 // Cacheable?
636 $key = false;
637 if ( $this->mOldid && $this->mNewid ) {
638 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION,
639 'oldid', $this->mOldid, 'newid', $this->mNewid );
640 // Try cache
641 if ( !$this->mRefreshCache ) {
642 $difftext = $wgMemc->get( $key );
643 if ( $difftext ) {
644 wfIncrStats( 'diff_cache_hit' );
645 $difftext = $this->localiseLineNumbers( $difftext );
646 $difftext .= "\n<!-- diff cache key $key -->\n";
647 wfProfileOut( __METHOD__ );
648 return $difftext;
649 }
650 } // don't try to load but save the result
651 }
652 $this->mCacheHit = false;
653
654 // Loadtext is permission safe, this just clears out the diff
655 if ( !$this->loadText() ) {
656 wfProfileOut( __METHOD__ );
657 return false;
658 }
659
660 $difftext = $this->generateDiffBody( $this->mOldtext, $this->mNewtext );
661
662 // Save to cache for 7 days
663 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
664 wfIncrStats( 'diff_uncacheable' );
665 } elseif ( $key !== false && $difftext !== false ) {
666 wfIncrStats( 'diff_cache_miss' );
667 $wgMemc->set( $key, $difftext, 7 * 86400 );
668 } else {
669 wfIncrStats( 'diff_uncacheable' );
670 }
671 // Replace line numbers with the text in the user's language
672 if ( $difftext !== false ) {
673 $difftext = $this->localiseLineNumbers( $difftext );
674 }
675 wfProfileOut( __METHOD__ );
676 return $difftext;
677 }
678
679 /**
680 * Make sure the proper modules are loaded before we try to
681 * make the diff
682 */
683 private function initDiffEngines() {
684 global $wgExternalDiffEngine;
685 if ( $wgExternalDiffEngine == 'wikidiff' && !function_exists( 'wikidiff_do_diff' ) ) {
686 wfProfileIn( __METHOD__ . '-php_wikidiff.so' );
687 wfDl( 'php_wikidiff' );
688 wfProfileOut( __METHOD__ . '-php_wikidiff.so' );
689 }
690 elseif ( $wgExternalDiffEngine == 'wikidiff2' && !function_exists( 'wikidiff2_do_diff' ) ) {
691 wfProfileIn( __METHOD__ . '-php_wikidiff2.so' );
692 wfDl( 'wikidiff2' );
693 wfProfileOut( __METHOD__ . '-php_wikidiff2.so' );
694 }
695 }
696
697 /**
698 * Generate a diff, no caching
699 *
700 * @param $otext String: old text, must be already segmented
701 * @param $ntext String: new text, must be already segmented
702 */
703 function generateDiffBody( $otext, $ntext ) {
704 global $wgExternalDiffEngine, $wgContLang;
705
706 wfProfileIn( __METHOD__ );
707
708 $otext = str_replace( "\r\n", "\n", $otext );
709 $ntext = str_replace( "\r\n", "\n", $ntext );
710
711 $this->initDiffEngines();
712
713 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
714 # For historical reasons, external diff engine expects
715 # input text to be HTML-escaped already
716 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
717 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
718 wfProfileOut( __METHOD__ );
719 return $wgContLang->unsegmentForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
720 $this->debug( 'wikidiff1' );
721 }
722
723 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
724 # Better external diff engine, the 2 may some day be dropped
725 # This one does the escaping and segmenting itself
726 wfProfileIn( 'wikidiff2_do_diff' );
727 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
728 $text .= $this->debug( 'wikidiff2' );
729 wfProfileOut( 'wikidiff2_do_diff' );
730 wfProfileOut( __METHOD__ );
731 return $text;
732 }
733 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
734 # Diff via the shell
735 global $wgTmpDirectory;
736 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
737 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
738
739 $tempFile1 = fopen( $tempName1, "w" );
740 if ( !$tempFile1 ) {
741 wfProfileOut( __METHOD__ );
742 return false;
743 }
744 $tempFile2 = fopen( $tempName2, "w" );
745 if ( !$tempFile2 ) {
746 wfProfileOut( __METHOD__ );
747 return false;
748 }
749 fwrite( $tempFile1, $otext );
750 fwrite( $tempFile2, $ntext );
751 fclose( $tempFile1 );
752 fclose( $tempFile2 );
753 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
754 wfProfileIn( __METHOD__ . "-shellexec" );
755 $difftext = wfShellExec( $cmd );
756 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
757 wfProfileOut( __METHOD__ . "-shellexec" );
758 unlink( $tempName1 );
759 unlink( $tempName2 );
760 wfProfileOut( __METHOD__ );
761 return $difftext;
762 }
763
764 # Native PHP diff
765 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
766 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
767 $diffs = new Diff( $ota, $nta );
768 $formatter = new TableDiffFormatter();
769 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
770 wfProfileOut( __METHOD__ );
771 return $difftext;
772 }
773
774 /**
775 * Generate a debug comment indicating diff generating time,
776 * server node, and generator backend.
777 */
778 protected function debug( $generator = "internal" ) {
779 global $wgShowHostnames;
780 if ( !$this->enableDebugComment ) {
781 return '';
782 }
783 $data = array( $generator );
784 if ( $wgShowHostnames ) {
785 $data[] = wfHostname();
786 }
787 $data[] = wfTimestamp( TS_DB );
788 return "<!-- diff generator: " .
789 implode( " ",
790 array_map(
791 "htmlspecialchars",
792 $data ) ) .
793 " -->\n";
794 }
795
796 /**
797 * Replace line numbers with the text in the user's language
798 */
799 function localiseLineNumbers( $text ) {
800 return preg_replace_callback( '/<!--LINE (\d+)-->/',
801 array( &$this, 'localiseLineNumbersCb' ), $text );
802 }
803
804 function localiseLineNumbersCb( $matches ) {
805 global $wgLang;
806 if ( $matches[1] === '1' && $this->mReducedLineNumbers ) return '';
807 return wfMsgExt( 'lineno', 'escape', $wgLang->formatNum( $matches[1] ) );
808 }
809
810
811 /**
812 * If there are revisions between the ones being compared, return a note saying so.
813 * @return string
814 */
815 function getMultiNotice() {
816 if ( !is_object( $this->mOldRev ) || !is_object( $this->mNewRev ) ) {
817 return '';
818 } elseif ( !$this->mOldPage->equals( $this->mNewPage ) ) {
819 // Comparing two different pages? Count would be meaningless.
820 return '';
821 }
822
823 if ( $this->mOldRev->getTimestamp() > $this->mNewRev->getTimestamp() ) {
824 $oldRev = $this->mNewRev; // flip
825 $newRev = $this->mOldRev; // flip
826 } else { // normal case
827 $oldRev = $this->mOldRev;
828 $newRev = $this->mNewRev;
829 }
830
831 $nEdits = $this->mNewPage->countRevisionsBetween( $oldRev, $newRev );
832 if ( $nEdits > 0 ) {
833 $limit = 100; // use diff-multi-manyusers if too many users
834 $numUsers = $this->mNewPage->countAuthorsBetween( $oldRev, $newRev, $limit );
835 return self::intermediateEditsMsg( $nEdits, $numUsers, $limit );
836 }
837 return ''; // nothing
838 }
839
840 /**
841 * Get a notice about how many intermediate edits and users there are
842 * @param $numEdits int
843 * @param $numUsers int
844 * @param $limit int
845 * @return string
846 */
847 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
848 global $wgLang;
849 if ( $numUsers > $limit ) {
850 $msg = 'diff-multi-manyusers';
851 $numUsers = $limit;
852 } else {
853 $msg = 'diff-multi';
854 }
855 return wfMsgExt( $msg, 'parseinline',
856 $wgLang->formatnum( $numEdits ), $wgLang->formatnum( $numUsers ) );
857 }
858
859 /**
860 * Get a header for a specified revision.
861 *
862 * @param $rev Revision
863 * @param $complete String: 'complete' to get the header wrapped depending
864 * the visibility of the revision and a link to edit the page.
865 * @return String HTML fragment
866 */
867 private function getRevisionHeader( Revision $rev, $complete = '' ) {
868 global $wgLang;
869
870 $revtimestamp = $rev->getTimestamp();
871 $timestamp = $wgLang->timeanddate( $revtimestamp, true );
872 $dateofrev = $wgLang->date( $revtimestamp, true );
873 $timeofrev = $wgLang->time( $revtimestamp, true );
874
875 $header = htmlspecialchars( wfMsg(
876 $rev->isCurrent() ? 'currentrev-asof' : 'revisionasof',
877 $timestamp,
878 $dateofrev,
879 $timeofrev
880 ) );
881
882 if ( $complete !== 'complete' ) {
883 return $header;
884 }
885
886 $title = $rev->getTitle();
887
888 $header = Linker::linkKnown( $title, $header, array(),
889 array( 'oldid' => $rev->getID() ) );
890
891 if ( $rev->userCan( Revision::DELETED_TEXT ) ) {
892 $editQuery = array( 'action' => 'edit' );
893 if ( !$rev->isCurrent() ) {
894 $editQuery['oldid'] = $rev->getID();
895 }
896
897 $msg = wfMsgHtml( $title->userCan( 'edit' ) ? 'editold' : 'viewsourceold' );
898 $header .= ' (' . Linker::linkKnown( $title, $msg, array(), $editQuery ) . ')';
899 if ( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
900 $header = Html::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
901 }
902 } else {
903 $header = Html::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
904 }
905
906 return $header;
907 }
908
909 /**
910 * Add the header to a diff body
911 *
912 * @return string
913 */
914 function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
915 // shared.css sets diff in interface language/dir, but the actual content
916 // is often in a different language, mostly the page content language/dir
917 $tableClass = 'diff diff-contentalign-' . htmlspecialchars( $this->getDiffLang()->alignStart() );
918 $header = "<table class='$tableClass'>";
919
920 if ( !$diff && !$otitle ) {
921 $header .= "
922 <tr valign='top'>
923 <td class='diff-ntitle'>{$ntitle}</td>
924 </tr>";
925 $multiColspan = 1;
926 } else {
927 if ( $diff ) { // Safari/Chrome show broken output if cols not used
928 $header .= "
929 <col class='diff-marker' />
930 <col class='diff-content' />
931 <col class='diff-marker' />
932 <col class='diff-content' />";
933 $colspan = 2;
934 $multiColspan = 4;
935 } else {
936 $colspan = 1;
937 $multiColspan = 2;
938 }
939 $header .= "
940 <tr valign='top'>
941 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
942 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
943 </tr>";
944 }
945
946 if ( $multi != '' ) {
947 $header .= "<tr><td colspan='{$multiColspan}' align='center' class='diff-multi'>{$multi}</td></tr>";
948 }
949 if ( $notice != '' ) {
950 $header .= "<tr><td colspan='{$multiColspan}' align='center'>{$notice}</td></tr>";
951 }
952
953 return $header . $diff . "</table>";
954 }
955
956 /**
957 * Use specified text instead of loading from the database
958 */
959 function setText( $oldText, $newText ) {
960 $this->mOldtext = $oldText;
961 $this->mNewtext = $newText;
962 $this->mTextLoaded = 2;
963 $this->mRevisionsLoaded = true;
964 }
965
966 /**
967 * Set the language in which the diff text is written
968 * (Defaults to page content language).
969 * @since 1.19
970 */
971 function setTextLanguage( $lang ) {
972 $this->mDiffLang = wfGetLangObj( $lang );
973 }
974
975 /**
976 * Load revision IDs
977 */
978 private function loadRevisionIds() {
979 if ( $this->mRevisionsIdsLoaded ) {
980 return;
981 }
982
983 $this->mRevisionsIdsLoaded = true;
984
985 $old = $this->mOldid;
986 $new = $this->mNewid;
987
988 if ( $new === 'prev' ) {
989 # Show diff between revision $old and the previous one.
990 # Get previous one from DB.
991 $this->mNewid = intval( $old );
992 $this->mOldid = $this->mTitle->getPreviousRevisionID( $this->mNewid );
993 } elseif ( $new === 'next' ) {
994 # Show diff between revision $old and the next one.
995 # Get next one from DB.
996 $this->mOldid = intval( $old );
997 $this->mNewid = $this->mTitle->getNextRevisionID( $this->mOldid );
998 if ( $this->mNewid === false ) {
999 # if no result, NewId points to the newest old revision. The only newer
1000 # revision is cur, which is "0".
1001 $this->mNewid = 0;
1002 }
1003 } else {
1004 $this->mOldid = intval( $old );
1005 $this->mNewid = intval( $new );
1006 wfRunHooks( 'NewDifferenceEngine', array( &$this->mTitle, &$this->mOldid, &$this->mNewid, $old, $new ) );
1007 }
1008 }
1009
1010 /**
1011 * Load revision metadata for the specified articles. If newid is 0, then compare
1012 * the old article in oldid to the current article; if oldid is 0, then
1013 * compare the current article to the immediately previous one (ignoring the
1014 * value of newid).
1015 *
1016 * If oldid is false, leave the corresponding revision object set
1017 * to false. This is impossible via ordinary user input, and is provided for
1018 * API convenience.
1019 *
1020 * @return bool
1021 */
1022 function loadRevisionData() {
1023 if ( $this->mRevisionsLoaded ) {
1024 return true;
1025 }
1026
1027 // Whether it succeeds or fails, we don't want to try again
1028 $this->mRevisionsLoaded = true;
1029
1030 $this->loadRevisionIds();
1031
1032 // Load the new revision object
1033 $this->mNewRev = $this->mNewid
1034 ? Revision::newFromId( $this->mNewid )
1035 : Revision::newFromTitle( $this->mTitle );
1036
1037 if ( !$this->mNewRev instanceof Revision ) {
1038 return false;
1039 }
1040
1041 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1042 $this->mNewid = $this->mNewRev->getId();
1043 $this->mNewPage = $this->mNewRev->getTitle();
1044
1045 // Load the old revision object
1046 $this->mOldRev = false;
1047 if ( $this->mOldid ) {
1048 $this->mOldRev = Revision::newFromId( $this->mOldid );
1049 } elseif ( $this->mOldid === 0 ) {
1050 $rev = $this->mNewRev->getPrevious();
1051 if ( $rev ) {
1052 $this->mOldid = $rev->getId();
1053 $this->mOldRev = $rev;
1054 } else {
1055 // No previous revision; mark to show as first-version only.
1056 $this->mOldid = false;
1057 $this->mOldRev = false;
1058 }
1059 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1060
1061 if ( is_null( $this->mOldRev ) ) {
1062 return false;
1063 }
1064
1065 if ( $this->mOldRev ) {
1066 $this->mOldPage = $this->mOldRev->getTitle();
1067 }
1068
1069 return true;
1070 }
1071
1072 /**
1073 * Load the text of the revisions, as well as revision data.
1074 *
1075 * @return bool
1076 */
1077 function loadText() {
1078 if ( $this->mTextLoaded == 2 ) {
1079 return true;
1080 } else {
1081 // Whether it succeeds or fails, we don't want to try again
1082 $this->mTextLoaded = 2;
1083 }
1084
1085 if ( !$this->loadRevisionData() ) {
1086 return false;
1087 }
1088 if ( $this->mOldRev ) {
1089 $this->mOldtext = $this->mOldRev->getText( Revision::FOR_THIS_USER );
1090 if ( $this->mOldtext === false ) {
1091 return false;
1092 }
1093 }
1094 if ( $this->mNewRev ) {
1095 $this->mNewtext = $this->mNewRev->getText( Revision::FOR_THIS_USER );
1096 if ( $this->mNewtext === false ) {
1097 return false;
1098 }
1099 }
1100 return true;
1101 }
1102
1103 /**
1104 * Load the text of the new revision, not the old one
1105 *
1106 * @return bool
1107 */
1108 function loadNewText() {
1109 if ( $this->mTextLoaded >= 1 ) {
1110 return true;
1111 } else {
1112 $this->mTextLoaded = 1;
1113 }
1114 if ( !$this->loadRevisionData() ) {
1115 return false;
1116 }
1117 $this->mNewtext = $this->mNewRev->getText( Revision::FOR_THIS_USER );
1118 return true;
1119 }
1120 }