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