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