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