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