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