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