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