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