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