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