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