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