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