Merge "ORDER BY/GROUP BY accept arrays"
[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 $mOldtext, $mNewtext;
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->mNewPage->getPrefixedText() );
258 $out->addSubtitle( $this->msg( 'difference' ) );
259 $samePage = true;
260 $oldHeader = '';
261 } else {
262 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev, $this->mNewRev ) );
263
264 $sk = $this->getSkin();
265 if ( method_exists( $sk, 'suppressQuickbar' ) ) {
266 $sk->suppressQuickbar();
267 }
268
269 if ( $this->mNewPage->equals( $this->mOldPage ) ) {
270 $out->setPageTitle( $this->mNewPage->getPrefixedText() );
271 $out->addSubtitle( $this->msg( 'difference' ) );
272 $samePage = true;
273 } else {
274 $out->setPageTitle( $this->mOldPage->getPrefixedText() . ', ' . $this->mNewPage->getPrefixedText() );
275 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
276 $samePage = false;
277 }
278
279 if ( $samePage && $this->mNewPage->quickUserCan( 'edit', $user ) ) {
280 if ( $this->mNewRev->isCurrent() && $this->mNewPage->userCan( 'rollback', $user ) ) {
281 $out->preventClickjacking();
282 $rollback = '&#160;&#160;&#160;' . Linker::generateRollback( $this->mNewRev );
283 }
284 if ( !$this->mOldRev->isDeleted( Revision::DELETED_TEXT ) && !$this->mNewRev->isDeleted( Revision::DELETED_TEXT ) ) {
285 $undoLink = ' ' . $this->msg( 'parentheses' )->rawParams(
286 Html::element( 'a', array(
287 'href' => $this->mNewPage->getLocalUrl( array(
288 'action' => 'edit',
289 'undoafter' => $this->mOldid,
290 'undo' => $this->mNewid ) ),
291 'title' => Linker::titleAttrib( 'undo' )
292 ),
293 $this->msg( 'editundo' )->text()
294 ) )->escaped();
295 }
296 }
297
298 # Make "previous revision link"
299 if ( $samePage && $this->mOldRev->getPrevious() ) {
300 $prevlink = Linker::linkKnown(
301 $this->mOldPage,
302 $this->msg( 'previousdiff' )->escaped(),
303 array( 'id' => 'differences-prevlink' ),
304 array( 'diff' => 'prev', 'oldid' => $this->mOldid ) + $query
305 );
306 } else {
307 $prevlink = '&#160;';
308 }
309
310 if ( $this->mOldRev->isMinor() ) {
311 $oldminor = ChangesList::flag( 'minor' );
312 } else {
313 $oldminor = '';
314 }
315
316 $ldel = $this->revisionDeleteLink( $this->mOldRev );
317 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev, 'complete' );
318
319 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
320 '<div id="mw-diff-otitle2">' .
321 Linker::revUserTools( $this->mOldRev, !$this->unhide ) . '</div>' .
322 '<div id="mw-diff-otitle3">' . $oldminor .
323 Linker::revComment( $this->mOldRev, !$diffOnly, !$this->unhide ) . $ldel . '</div>' .
324 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
325
326 if ( $this->mOldRev->isDeleted( Revision::DELETED_TEXT ) ) {
327 $deleted = true; // old revisions text is hidden
328 if ( $this->mOldRev->isDeleted( Revision::DELETED_RESTRICTED ) ) {
329 $suppressed = true; // also suppressed
330 }
331 }
332
333 # Check if this user can see the revisions
334 if ( !$this->mOldRev->userCan( Revision::DELETED_TEXT, $user ) ) {
335 $allowed = false;
336 }
337 }
338
339 # Make "next revision link"
340 # Skip next link on the top revision
341 if ( $samePage && !$this->mNewRev->isCurrent() ) {
342 $nextlink = Linker::linkKnown(
343 $this->mNewPage,
344 $this->msg( 'nextdiff' )->escaped(),
345 array( 'id' => 'differences-nextlink' ),
346 array( 'diff' => 'next', 'oldid' => $this->mNewid ) + $query
347 );
348 } else {
349 $nextlink = '&#160;';
350 }
351
352 if ( $this->mNewRev->isMinor() ) {
353 $newminor = ChangesList::flag( 'minor' );
354 } else {
355 $newminor = '';
356 }
357
358 # Handle RevisionDelete links...
359 $rdel = $this->revisionDeleteLink( $this->mNewRev );
360 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev, 'complete' ) . $undoLink;
361
362 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
363 '<div id="mw-diff-ntitle2">' . Linker::revUserTools( $this->mNewRev, !$this->unhide ) .
364 " $rollback</div>" .
365 '<div id="mw-diff-ntitle3">' . $newminor .
366 Linker::revComment( $this->mNewRev, !$diffOnly, !$this->unhide ) . $rdel . '</div>' .
367 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
368
369 if ( $this->mNewRev->isDeleted( Revision::DELETED_TEXT ) ) {
370 $deleted = true; // new revisions text is hidden
371 if ( $this->mNewRev->isDeleted( Revision::DELETED_RESTRICTED ) )
372 $suppressed = true; // also suppressed
373 }
374
375 # If the diff cannot be shown due to a deleted revision, then output
376 # the diff header and links to unhide (if available)...
377 if ( $deleted && ( !$this->unhide || !$allowed ) ) {
378 $this->showDiffStyle();
379 $multi = $this->getMultiNotice();
380 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
381 if ( !$allowed ) {
382 $msg = $suppressed ? 'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
383 # Give explanation for why revision is not visible
384 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
385 array( $msg ) );
386 } else {
387 # Give explanation and add a link to view the diff...
388 $link = $this->getTitle()->getFullUrl( $this->getRequest()->appendQueryValue( 'unhide', '1', true ) );
389 $msg = $suppressed ? 'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
390 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n", array( $msg, $link ) );
391 }
392 # Otherwise, output a regular diff...
393 } else {
394 # Add deletion notice if the user is viewing deleted content
395 $notice = '';
396 if ( $deleted ) {
397 $msg = $suppressed ? 'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
398 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" . $this->msg( $msg )->parse() . "</div>\n";
399 }
400 $this->showDiff( $oldHeader, $newHeader, $notice );
401 if ( !$diffOnly ) {
402 $this->renderNewRevision();
403 }
404 }
405 wfProfileOut( __METHOD__ );
406 }
407
408 /**
409 * Get a link to mark the change as patrolled, or '' if there's either no
410 * revision to patrol or the user is not allowed to to it.
411 * Side effect: this method will call OutputPage::preventClickjacking()
412 * when a link is builded.
413 *
414 * @return String
415 */
416 protected function markPatrolledLink() {
417 global $wgUseRCPatrol;
418
419 if ( $this->mMarkPatrolledLink === null ) {
420 // Prepare a change patrol link, if applicable
421 if ( $wgUseRCPatrol && $this->mNewPage->quickUserCan( 'patrol', $this->getUser() ) ) {
422 // If we've been given an explicit change identifier, use it; saves time
423 if ( $this->mRcidMarkPatrolled ) {
424 $rcid = $this->mRcidMarkPatrolled;
425 $rc = RecentChange::newFromId( $rcid );
426 // Already patrolled?
427 $rcid = is_object( $rc ) && !$rc->getAttribute( 'rc_patrolled' ) ? $rcid : 0;
428 } else {
429 // Look for an unpatrolled change corresponding to this diff
430 $db = wfGetDB( DB_SLAVE );
431 $change = RecentChange::newFromConds(
432 array(
433 // Redundant user,timestamp condition so we can use the existing index
434 'rc_user_text' => $this->mNewRev->getRawUserText(),
435 'rc_timestamp' => $db->timestamp( $this->mNewRev->getTimestamp() ),
436 'rc_this_oldid' => $this->mNewid,
437 'rc_last_oldid' => $this->mOldid,
438 'rc_patrolled' => 0
439 ),
440 __METHOD__
441 );
442 if ( $change instanceof RecentChange ) {
443 $rcid = $change->mAttribs['rc_id'];
444 $this->mRcidMarkPatrolled = $rcid;
445 } else {
446 // None found
447 $rcid = 0;
448 }
449 }
450 // Build the link
451 if ( $rcid ) {
452 $this->getOutput()->preventClickjacking();
453 $token = $this->getUser()->getEditToken( $rcid );
454 $this->mMarkPatrolledLink = ' <span class="patrollink">[' . Linker::linkKnown(
455 $this->mNewPage,
456 $this->msg( 'markaspatrolleddiff' )->escaped(),
457 array(),
458 array(
459 'action' => 'markpatrolled',
460 'rcid' => $rcid,
461 'token' => $token,
462 )
463 ) . ']</span>';
464 } else {
465 $this->mMarkPatrolledLink = '';
466 }
467 } else {
468 $this->mMarkPatrolledLink = '';
469 }
470 }
471
472 return $this->mMarkPatrolledLink;
473 }
474
475 /**
476 * @param $rev Revision
477 * @return String
478 */
479 protected function revisionDeleteLink( $rev ) {
480 $link = Linker::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
481 if ( $link !== '' ) {
482 $link = '&#160;&#160;&#160;' . $link . ' ';
483 }
484 return $link;
485 }
486
487 /**
488 * Show the new revision of the page.
489 */
490 function renderNewRevision() {
491 wfProfileIn( __METHOD__ );
492 $out = $this->getOutput();
493 $revHeader = $this->getRevisionHeader( $this->mNewRev );
494 # Add "current version as of X" title
495 $out->addHTML( "<hr class='diff-hr' />
496 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
497 # Page content may be handled by a hooked call instead...
498 if ( wfRunHooks( 'ArticleContentOnDiff', array( $this, $out ) ) ) {
499 $this->loadNewText();
500 $out->setRevisionId( $this->mNewid );
501 $out->setRevisionTimestamp( $this->mNewRev->getTimestamp() );
502 $out->setArticleFlag( true );
503
504 if ( $this->mNewPage->isCssJsSubpage() || $this->mNewPage->isCssOrJsPage() ) {
505 // Stolen from Article::view --AG 2007-10-11
506 // Give hooks a chance to customise the output
507 // @TODO: standardize this crap into one function
508 if ( wfRunHooks( 'ShowRawCssJs', array( $this->mNewtext, $this->mNewPage, $out ) ) ) {
509 // Wrap the whole lot in a <pre> and don't parse
510 $m = array();
511 preg_match( '!\.(css|js)$!u', $this->mNewPage->getText(), $m );
512 $out->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
513 $out->addHTML( htmlspecialchars( $this->mNewtext ) );
514 $out->addHTML( "\n</pre>\n" );
515 }
516 } elseif ( !wfRunHooks( 'ArticleViewCustom', array( $this->mNewtext, $this->mNewPage, $out ) ) ) {
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 $difftext = $this->generateDiffBody( $this->mOldtext, $this->mNewtext );
649
650 // Save to cache for 7 days
651 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
652 wfIncrStats( 'diff_uncacheable' );
653 } elseif ( $key !== false && $difftext !== false ) {
654 wfIncrStats( 'diff_cache_miss' );
655 $wgMemc->set( $key, $difftext, 7 * 86400 );
656 } else {
657 wfIncrStats( 'diff_uncacheable' );
658 }
659 // Replace line numbers with the text in the user's language
660 if ( $difftext !== false ) {
661 $difftext = $this->localiseLineNumbers( $difftext );
662 }
663 wfProfileOut( __METHOD__ );
664 return $difftext;
665 }
666
667 /**
668 * Make sure the proper modules are loaded before we try to
669 * make the diff
670 */
671 private function initDiffEngines() {
672 global $wgExternalDiffEngine;
673 if ( $wgExternalDiffEngine == 'wikidiff' && !function_exists( 'wikidiff_do_diff' ) ) {
674 wfProfileIn( __METHOD__ . '-php_wikidiff.so' );
675 wfDl( 'php_wikidiff' );
676 wfProfileOut( __METHOD__ . '-php_wikidiff.so' );
677 }
678 elseif ( $wgExternalDiffEngine == 'wikidiff2' && !function_exists( 'wikidiff2_do_diff' ) ) {
679 wfProfileIn( __METHOD__ . '-php_wikidiff2.so' );
680 wfDl( 'wikidiff2' );
681 wfProfileOut( __METHOD__ . '-php_wikidiff2.so' );
682 }
683 }
684
685 /**
686 * Generate a diff, no caching
687 *
688 * @param $otext String: old text, must be already segmented
689 * @param $ntext String: new text, must be already segmented
690 * @return bool|string
691 */
692 function generateDiffBody( $otext, $ntext ) {
693 global $wgExternalDiffEngine, $wgContLang;
694
695 wfProfileIn( __METHOD__ );
696
697 $otext = str_replace( "\r\n", "\n", $otext );
698 $ntext = str_replace( "\r\n", "\n", $ntext );
699
700 $this->initDiffEngines();
701
702 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
703 # For historical reasons, external diff engine expects
704 # input text to be HTML-escaped already
705 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
706 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
707 wfProfileOut( __METHOD__ );
708 return $wgContLang->unsegmentForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
709 $this->debug( 'wikidiff1' );
710 }
711
712 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
713 # Better external diff engine, the 2 may some day be dropped
714 # This one does the escaping and segmenting itself
715 wfProfileIn( 'wikidiff2_do_diff' );
716 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
717 $text .= $this->debug( 'wikidiff2' );
718 wfProfileOut( 'wikidiff2_do_diff' );
719 wfProfileOut( __METHOD__ );
720 return $text;
721 }
722 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
723 # Diff via the shell
724 global $wgTmpDirectory;
725 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
726 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
727
728 $tempFile1 = fopen( $tempName1, "w" );
729 if ( !$tempFile1 ) {
730 wfProfileOut( __METHOD__ );
731 return false;
732 }
733 $tempFile2 = fopen( $tempName2, "w" );
734 if ( !$tempFile2 ) {
735 wfProfileOut( __METHOD__ );
736 return false;
737 }
738 fwrite( $tempFile1, $otext );
739 fwrite( $tempFile2, $ntext );
740 fclose( $tempFile1 );
741 fclose( $tempFile2 );
742 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
743 wfProfileIn( __METHOD__ . "-shellexec" );
744 $difftext = wfShellExec( $cmd );
745 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
746 wfProfileOut( __METHOD__ . "-shellexec" );
747 unlink( $tempName1 );
748 unlink( $tempName2 );
749 wfProfileOut( __METHOD__ );
750 return $difftext;
751 }
752
753 # Native PHP diff
754 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
755 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
756 $diffs = new Diff( $ota, $nta );
757 $formatter = new TableDiffFormatter();
758 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
759 wfProfileOut( __METHOD__ );
760 return $difftext;
761 }
762
763 /**
764 * Generate a debug comment indicating diff generating time,
765 * server node, and generator backend.
766 * @return string
767 */
768 protected function debug( $generator = "internal" ) {
769 global $wgShowHostnames;
770 if ( !$this->enableDebugComment ) {
771 return '';
772 }
773 $data = array( $generator );
774 if ( $wgShowHostnames ) {
775 $data[] = wfHostname();
776 }
777 $data[] = wfTimestamp( TS_DB );
778 return "<!-- diff generator: " .
779 implode( " ",
780 array_map(
781 "htmlspecialchars",
782 $data ) ) .
783 " -->\n";
784 }
785
786 /**
787 * Replace line numbers with the text in the user's language
788 * @return mixed
789 */
790 function localiseLineNumbers( $text ) {
791 return preg_replace_callback( '/<!--LINE (\d+)-->/',
792 array( &$this, 'localiseLineNumbersCb' ), $text );
793 }
794
795 function localiseLineNumbersCb( $matches ) {
796 if ( $matches[1] === '1' && $this->mReducedLineNumbers ) return '';
797 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
798 }
799
800
801 /**
802 * If there are revisions between the ones being compared, return a note saying so.
803 * @return string
804 */
805 function getMultiNotice() {
806 if ( !is_object( $this->mOldRev ) || !is_object( $this->mNewRev ) ) {
807 return '';
808 } elseif ( !$this->mOldPage->equals( $this->mNewPage ) ) {
809 // Comparing two different pages? Count would be meaningless.
810 return '';
811 }
812
813 if ( $this->mOldRev->getTimestamp() > $this->mNewRev->getTimestamp() ) {
814 $oldRev = $this->mNewRev; // flip
815 $newRev = $this->mOldRev; // flip
816 } else { // normal case
817 $oldRev = $this->mOldRev;
818 $newRev = $this->mNewRev;
819 }
820
821 $nEdits = $this->mNewPage->countRevisionsBetween( $oldRev, $newRev );
822 if ( $nEdits > 0 ) {
823 $limit = 100; // use diff-multi-manyusers if too many users
824 $numUsers = $this->mNewPage->countAuthorsBetween( $oldRev, $newRev, $limit );
825 return self::intermediateEditsMsg( $nEdits, $numUsers, $limit );
826 }
827 return ''; // nothing
828 }
829
830 /**
831 * Get a notice about how many intermediate edits and users there are
832 * @param $numEdits int
833 * @param $numUsers int
834 * @param $limit int
835 * @return string
836 */
837 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
838 if ( $numUsers > $limit ) {
839 $msg = 'diff-multi-manyusers';
840 $numUsers = $limit;
841 } else {
842 $msg = 'diff-multi';
843 }
844 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
845 }
846
847 /**
848 * Get a header for a specified revision.
849 *
850 * @param $rev Revision
851 * @param $complete String: 'complete' to get the header wrapped depending
852 * the visibility of the revision and a link to edit the page.
853 * @return String HTML fragment
854 */
855 private function getRevisionHeader( Revision $rev, $complete = '' ) {
856 $lang = $this->getLanguage();
857 $user = $this->getUser();
858 $revtimestamp = $rev->getTimestamp();
859 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
860 $dateofrev = $lang->userDate( $revtimestamp, $user );
861 $timeofrev = $lang->userTime( $revtimestamp, $user );
862
863 $header = $this->msg(
864 $rev->isCurrent() ? 'currentrev-asof' : 'revisionasof',
865 $timestamp,
866 $dateofrev,
867 $timeofrev
868 )->escaped();
869
870 if ( $complete !== 'complete' ) {
871 return $header;
872 }
873
874 $title = $rev->getTitle();
875
876 $header = Linker::linkKnown( $title, $header, array(),
877 array( 'oldid' => $rev->getID() ) );
878
879 if ( $rev->userCan( Revision::DELETED_TEXT, $user ) ) {
880 $editQuery = array( 'action' => 'edit' );
881 if ( !$rev->isCurrent() ) {
882 $editQuery['oldid'] = $rev->getID();
883 }
884
885 $msg = $this->msg( $title->quickUserCan( 'edit', $user ) ? 'editold' : 'viewsourceold' )->escaped();
886 $header .= ' (' . Linker::linkKnown( $title, $msg, array(), $editQuery ) . ')';
887 if ( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
888 $header = Html::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
889 }
890 } else {
891 $header = Html::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
892 }
893
894 return $header;
895 }
896
897 /**
898 * Add the header to a diff body
899 *
900 * @return string
901 */
902 function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
903 // shared.css sets diff in interface language/dir, but the actual content
904 // is often in a different language, mostly the page content language/dir
905 $tableClass = 'diff diff-contentalign-' . htmlspecialchars( $this->getDiffLang()->alignStart() );
906 $header = "<table class='$tableClass'>";
907
908 if ( !$diff && !$otitle ) {
909 $header .= "
910 <tr valign='top'>
911 <td class='diff-ntitle'>{$ntitle}</td>
912 </tr>";
913 $multiColspan = 1;
914 } else {
915 if ( $diff ) { // Safari/Chrome show broken output if cols not used
916 $header .= "
917 <col class='diff-marker' />
918 <col class='diff-content' />
919 <col class='diff-marker' />
920 <col class='diff-content' />";
921 $colspan = 2;
922 $multiColspan = 4;
923 } else {
924 $colspan = 1;
925 $multiColspan = 2;
926 }
927 $header .= "
928 <tr valign='top'>
929 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
930 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
931 </tr>";
932 }
933
934 if ( $multi != '' ) {
935 $header .= "<tr><td colspan='{$multiColspan}' align='center' class='diff-multi'>{$multi}</td></tr>";
936 }
937 if ( $notice != '' ) {
938 $header .= "<tr><td colspan='{$multiColspan}' align='center'>{$notice}</td></tr>";
939 }
940
941 return $header . $diff . "</table>";
942 }
943
944 /**
945 * Use specified text instead of loading from the database
946 */
947 function setText( $oldText, $newText ) {
948 $this->mOldtext = $oldText;
949 $this->mNewtext = $newText;
950 $this->mTextLoaded = 2;
951 $this->mRevisionsLoaded = true;
952 }
953
954 /**
955 * Set the language in which the diff text is written
956 * (Defaults to page content language).
957 * @since 1.19
958 */
959 function setTextLanguage( $lang ) {
960 $this->mDiffLang = wfGetLangObj( $lang );
961 }
962
963 /**
964 * Load revision IDs
965 */
966 private function loadRevisionIds() {
967 if ( $this->mRevisionsIdsLoaded ) {
968 return;
969 }
970
971 $this->mRevisionsIdsLoaded = true;
972
973 $old = $this->mOldid;
974 $new = $this->mNewid;
975
976 if ( $new === 'prev' ) {
977 # Show diff between revision $old and the previous one.
978 # Get previous one from DB.
979 $this->mNewid = intval( $old );
980 $this->mOldid = $this->getTitle()->getPreviousRevisionID( $this->mNewid );
981 } elseif ( $new === 'next' ) {
982 # Show diff between revision $old and the next one.
983 # Get next one from DB.
984 $this->mOldid = intval( $old );
985 $this->mNewid = $this->getTitle()->getNextRevisionID( $this->mOldid );
986 if ( $this->mNewid === false ) {
987 # if no result, NewId points to the newest old revision. The only newer
988 # revision is cur, which is "0".
989 $this->mNewid = 0;
990 }
991 } else {
992 $this->mOldid = intval( $old );
993 $this->mNewid = intval( $new );
994 wfRunHooks( 'NewDifferenceEngine', array( $this->getTitle(), &$this->mOldid, &$this->mNewid, $old, $new ) );
995 }
996 }
997
998 /**
999 * Load revision metadata for the specified articles. If newid is 0, then compare
1000 * the old article in oldid to the current article; if oldid is 0, then
1001 * compare the current article to the immediately previous one (ignoring the
1002 * value of newid).
1003 *
1004 * If oldid is false, leave the corresponding revision object set
1005 * to false. This is impossible via ordinary user input, and is provided for
1006 * API convenience.
1007 *
1008 * @return bool
1009 */
1010 function loadRevisionData() {
1011 if ( $this->mRevisionsLoaded ) {
1012 return true;
1013 }
1014
1015 // Whether it succeeds or fails, we don't want to try again
1016 $this->mRevisionsLoaded = true;
1017
1018 $this->loadRevisionIds();
1019
1020 // Load the new revision object
1021 $this->mNewRev = $this->mNewid
1022 ? Revision::newFromId( $this->mNewid )
1023 : Revision::newFromTitle( $this->getTitle() );
1024
1025 if ( !$this->mNewRev instanceof Revision ) {
1026 return false;
1027 }
1028
1029 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1030 $this->mNewid = $this->mNewRev->getId();
1031 $this->mNewPage = $this->mNewRev->getTitle();
1032
1033 // Load the old revision object
1034 $this->mOldRev = false;
1035 if ( $this->mOldid ) {
1036 $this->mOldRev = Revision::newFromId( $this->mOldid );
1037 } elseif ( $this->mOldid === 0 ) {
1038 $rev = $this->mNewRev->getPrevious();
1039 if ( $rev ) {
1040 $this->mOldid = $rev->getId();
1041 $this->mOldRev = $rev;
1042 } else {
1043 // No previous revision; mark to show as first-version only.
1044 $this->mOldid = false;
1045 $this->mOldRev = false;
1046 }
1047 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1048
1049 if ( is_null( $this->mOldRev ) ) {
1050 return false;
1051 }
1052
1053 if ( $this->mOldRev ) {
1054 $this->mOldPage = $this->mOldRev->getTitle();
1055 }
1056
1057 return true;
1058 }
1059
1060 /**
1061 * Load the text of the revisions, as well as revision data.
1062 *
1063 * @return bool
1064 */
1065 function loadText() {
1066 if ( $this->mTextLoaded == 2 ) {
1067 return true;
1068 } else {
1069 // Whether it succeeds or fails, we don't want to try again
1070 $this->mTextLoaded = 2;
1071 }
1072
1073 if ( !$this->loadRevisionData() ) {
1074 return false;
1075 }
1076 if ( $this->mOldRev ) {
1077 $this->mOldtext = $this->mOldRev->getText( Revision::FOR_THIS_USER );
1078 if ( $this->mOldtext === false ) {
1079 return false;
1080 }
1081 }
1082 if ( $this->mNewRev ) {
1083 $this->mNewtext = $this->mNewRev->getText( Revision::FOR_THIS_USER );
1084 if ( $this->mNewtext === false ) {
1085 return false;
1086 }
1087 }
1088 return true;
1089 }
1090
1091 /**
1092 * Load the text of the new revision, not the old one
1093 *
1094 * @return bool
1095 */
1096 function loadNewText() {
1097 if ( $this->mTextLoaded >= 1 ) {
1098 return true;
1099 } else {
1100 $this->mTextLoaded = 1;
1101 }
1102 if ( !$this->loadRevisionData() ) {
1103 return false;
1104 }
1105 $this->mNewtext = $this->mNewRev->getText( Revision::FOR_THIS_USER );
1106 return true;
1107 }
1108 }