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