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