print is not a function
[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
373 # If the diff cannot be shown due to a deleted revision, then output
374 # the diff header and links to unhide (if available)...
375 if ( $deleted && ( !$this->unhide || !$allowed ) ) {
376 $this->showDiffStyle();
377 $multi = $this->getMultiNotice();
378 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
379 if ( !$allowed ) {
380 $msg = $suppressed ? 'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
381 # Give explanation for why revision is not visible
382 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
383 array( $msg ) );
384 } else {
385 # Give explanation and add a link to view the diff...
386 $link = $this->getTitle()->getFullURL( $this->getRequest()->appendQueryValue( 'unhide', '1', true ) );
387 $msg = $suppressed ? 'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
388 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n", array( $msg, $link ) );
389 }
390 # Otherwise, output a regular diff...
391 } else {
392 # Add deletion notice if the user is viewing deleted content
393 $notice = '';
394 if ( $deleted ) {
395 $msg = $suppressed ? 'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
396 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" . $this->msg( $msg )->parse() . "</div>\n";
397 }
398 $this->showDiff( $oldHeader, $newHeader, $notice );
399 if ( !$diffOnly ) {
400 $this->renderNewRevision();
401 }
402 }
403 wfProfileOut( __METHOD__ );
404 }
405
406 /**
407 * Get a link to mark the change as patrolled, or '' if there's either no
408 * revision to patrol or the user is not allowed to to it.
409 * Side effect: When the patrol link is build, this method will call
410 * OutputPage::preventClickjacking() and load mediawiki.page.patrol.ajax.
411 *
412 * @return String
413 */
414 protected function markPatrolledLink() {
415 global $wgUseRCPatrol;
416
417 if ( $this->mMarkPatrolledLink === null ) {
418 // Prepare a change patrol link, if applicable
419 if ( $wgUseRCPatrol && $this->mNewPage->quickUserCan( 'patrol', $this->getUser() ) ) {
420 // If we've been given an explicit change identifier, use it; saves time
421 if ( $this->mRcidMarkPatrolled ) {
422 $rcid = $this->mRcidMarkPatrolled;
423 $rc = RecentChange::newFromId( $rcid );
424 // Already patrolled?
425 $rcid = is_object( $rc ) && !$rc->getAttribute( 'rc_patrolled' ) ? $rcid : 0;
426 } else {
427 // Look for an unpatrolled change corresponding to this diff
428 $db = wfGetDB( DB_SLAVE );
429 $change = RecentChange::newFromConds(
430 array(
431 // Redundant user,timestamp condition so we can use the existing index
432 'rc_user_text' => $this->mNewRev->getRawUserText(),
433 'rc_timestamp' => $db->timestamp( $this->mNewRev->getTimestamp() ),
434 'rc_this_oldid' => $this->mNewid,
435 'rc_last_oldid' => $this->mOldid,
436 'rc_patrolled' => 0
437 ),
438 __METHOD__
439 );
440 if ( $change instanceof RecentChange ) {
441 $rcid = $change->mAttribs['rc_id'];
442 $this->mRcidMarkPatrolled = $rcid;
443 } else {
444 // None found
445 $rcid = 0;
446 }
447 }
448 // Build the link
449 if ( $rcid ) {
450 $this->getOutput()->preventClickjacking();
451 $this->getOutput()->addModules( 'mediawiki.page.patrol.ajax' );
452
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 // NOTE: only needed for B/C: custom rendering of JS/CSS via hook
505 if ( $this->mNewPage->isCssJsSubpage() || $this->mNewPage->isCssOrJsPage() ) {
506 // Stolen from Article::view --AG 2007-10-11
507 // Give hooks a chance to customise the output
508 // @TODO: standardize this crap into one function
509 if ( ContentHandler::runLegacyHooks( 'ShowRawCssJs', array( $this->mNewContent, $this->mNewPage, $out ) ) ) {
510 // NOTE: deprecated hook, B/C only
511 // use the content object's own rendering
512 $cnt = $this->mNewRev->getContent();
513 $po = $cnt ? $cnt->getParserOutput( $this->mNewRev->getTitle(), $this->mNewRev->getId() ) : null;
514 $txt = $po ? $po->getText() : '';
515 $out->addHTML( $txt );
516 }
517 } elseif ( !wfRunHooks( 'ArticleContentViewCustom', array( $this->mNewContent, $this->mNewPage, $out ) ) ) {
518 // Handled by extension
519 } elseif ( !ContentHandler::runLegacyHooks( 'ArticleViewCustom', array( $this->mNewContent, $this->mNewPage, $out ) ) ) {
520 // NOTE: deprecated hook, B/C only
521 // Handled by extension
522 } else {
523 // Normal page
524 if ( $this->getTitle()->equals( $this->mNewPage ) ) {
525 // If the Title stored in the context is the same as the one
526 // of the new revision, we can use its associated WikiPage
527 // object.
528 $wikiPage = $this->getWikiPage();
529 } else {
530 // Otherwise we need to create our own WikiPage object
531 $wikiPage = WikiPage::factory( $this->mNewPage );
532 }
533
534 $parserOutput = $this->getParserOutput( $wikiPage, $this->mNewRev );
535
536 # Also try to load it as a redirect
537 $rt = $this->mNewContent ? $this->mNewContent->getRedirectTarget() : null;
538
539 if ( $rt ) {
540 $article = Article::newFromTitle( $this->mNewPage, $this->getContext() );
541 $out->addHTML( $article->viewRedirect( $rt ) );
542
543 # WikiPage::getParserOutput() should not return false, but just in case
544 if ( $parserOutput ) {
545 # Show categories etc.
546 $out->addParserOutputNoText( $parserOutput );
547 }
548 } elseif ( $parserOutput ) {
549 $out->addParserOutput( $parserOutput );
550 }
551 }
552 }
553 # Add redundant patrol link on bottom...
554 $out->addHTML( $this->markPatrolledLink() );
555
556 wfProfileOut( __METHOD__ );
557 }
558
559 protected function getParserOutput( WikiPage $page, Revision $rev ) {
560 $parserOptions = $page->makeParserOptions( $this->getContext() );
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 string|bool $otitle Header for old text or false
599 * @param string|bool $ntitle Header for new text or false
600 * @param string $notice 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 * This implementation uses generateTextDiffBody() to generate a diff based on the default
707 * serialization of the given Content objects. This will fail if $old or $new are not
708 * instances of TextContent.
709 *
710 * Subclasses may override this to provide a different rendering for the diff,
711 * perhaps taking advantage of the content's native form. This is required for all content
712 * models that are not text based.
713 *
714 * @param $old Content: old content
715 * @param $new Content: new content
716 *
717 * @return bool|string
718 * @since 1.21
719 * @throws MWException if $old or $new are not instances of TextContent.
720 */
721 function generateContentDiffBody( Content $old, Content $new ) {
722 if ( !( $old instanceof TextContent ) ) {
723 throw new MWException( "Diff not implemented for " . get_class( $old ) . "; "
724 . "override generateContentDiffBody to fix this." );
725 }
726
727 if ( !( $new instanceof TextContent ) ) {
728 throw new MWException( "Diff not implemented for " . get_class( $new ) . "; "
729 . "override generateContentDiffBody to fix this." );
730 }
731
732 $otext = $old->serialize();
733 $ntext = $new->serialize();
734
735 return $this->generateTextDiffBody( $otext, $ntext );
736 }
737
738 /**
739 * Generate a diff, no caching
740 *
741 * @param string $otext old text, must be already segmented
742 * @param string $ntext new text, must be already segmented
743 * @return bool|string
744 * @deprecated since 1.21, use generateContentDiffBody() instead!
745 */
746 function generateDiffBody( $otext, $ntext ) {
747 ContentHandler::deprecated( __METHOD__, "1.21" );
748
749 return $this->generateTextDiffBody( $otext, $ntext );
750 }
751
752 /**
753 * Generate a diff, no caching
754 *
755 * @todo move this to TextDifferenceEngine, make DifferenceEngine abstract. At some point.
756 *
757 * @param string $otext old text, must be already segmented
758 * @param string $ntext new text, must be already segmented
759 * @return bool|string
760 */
761 function generateTextDiffBody( $otext, $ntext ) {
762 global $wgExternalDiffEngine, $wgContLang;
763
764 wfProfileIn( __METHOD__ );
765
766 $otext = str_replace( "\r\n", "\n", $otext );
767 $ntext = str_replace( "\r\n", "\n", $ntext );
768
769 $this->initDiffEngines();
770
771 if ( $wgExternalDiffEngine == 'wikidiff' && function_exists( 'wikidiff_do_diff' ) ) {
772 # For historical reasons, external diff engine expects
773 # input text to be HTML-escaped already
774 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
775 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
776 wfProfileOut( __METHOD__ );
777 return $wgContLang->unsegmentForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ) .
778 $this->debug( 'wikidiff1' );
779 }
780
781 if ( $wgExternalDiffEngine == 'wikidiff2' && function_exists( 'wikidiff2_do_diff' ) ) {
782 # Better external diff engine, the 2 may some day be dropped
783 # This one does the escaping and segmenting itself
784 wfProfileIn( 'wikidiff2_do_diff' );
785 $text = wikidiff2_do_diff( $otext, $ntext, 2 );
786 $text .= $this->debug( 'wikidiff2' );
787 wfProfileOut( 'wikidiff2_do_diff' );
788 wfProfileOut( __METHOD__ );
789 return $text;
790 }
791 if ( $wgExternalDiffEngine != 'wikidiff3' && $wgExternalDiffEngine !== false ) {
792 # Diff via the shell
793 $tmpDir = wfTempDir();
794 $tempName1 = tempnam( $tmpDir, 'diff_' );
795 $tempName2 = tempnam( $tmpDir, 'diff_' );
796
797 $tempFile1 = fopen( $tempName1, "w" );
798 if ( !$tempFile1 ) {
799 wfProfileOut( __METHOD__ );
800 return false;
801 }
802 $tempFile2 = fopen( $tempName2, "w" );
803 if ( !$tempFile2 ) {
804 wfProfileOut( __METHOD__ );
805 return false;
806 }
807 fwrite( $tempFile1, $otext );
808 fwrite( $tempFile2, $ntext );
809 fclose( $tempFile1 );
810 fclose( $tempFile2 );
811 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
812 wfProfileIn( __METHOD__ . "-shellexec" );
813 $difftext = wfShellExec( $cmd );
814 $difftext .= $this->debug( "external $wgExternalDiffEngine" );
815 wfProfileOut( __METHOD__ . "-shellexec" );
816 unlink( $tempName1 );
817 unlink( $tempName2 );
818 wfProfileOut( __METHOD__ );
819 return $difftext;
820 }
821
822 # Native PHP diff
823 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
824 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
825 $diffs = new Diff( $ota, $nta );
826 $formatter = new TableDiffFormatter();
827 $difftext = $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ) .
828 wfProfileOut( __METHOD__ );
829 return $difftext;
830 }
831
832 /**
833 * Generate a debug comment indicating diff generating time,
834 * server node, and generator backend.
835 * @return string
836 */
837 protected function debug( $generator = "internal" ) {
838 global $wgShowHostnames;
839 if ( !$this->enableDebugComment ) {
840 return '';
841 }
842 $data = array( $generator );
843 if ( $wgShowHostnames ) {
844 $data[] = wfHostname();
845 }
846 $data[] = wfTimestamp( TS_DB );
847 return "<!-- diff generator: " .
848 implode( " ",
849 array_map(
850 "htmlspecialchars",
851 $data ) ) .
852 " -->\n";
853 }
854
855 /**
856 * Replace line numbers with the text in the user's language
857 * @return mixed
858 */
859 function localiseLineNumbers( $text ) {
860 return preg_replace_callback( '/<!--LINE (\d+)-->/',
861 array( &$this, 'localiseLineNumbersCb' ), $text );
862 }
863
864 function localiseLineNumbersCb( $matches ) {
865 if ( $matches[1] === '1' && $this->mReducedLineNumbers ) {
866 return '';
867 }
868 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
869 }
870
871 /**
872 * If there are revisions between the ones being compared, return a note saying so.
873 * @return string
874 */
875 function getMultiNotice() {
876 if ( !is_object( $this->mOldRev ) || !is_object( $this->mNewRev ) ) {
877 return '';
878 } elseif ( !$this->mOldPage->equals( $this->mNewPage ) ) {
879 // Comparing two different pages? Count would be meaningless.
880 return '';
881 }
882
883 if ( $this->mOldRev->getTimestamp() > $this->mNewRev->getTimestamp() ) {
884 $oldRev = $this->mNewRev; // flip
885 $newRev = $this->mOldRev; // flip
886 } else { // normal case
887 $oldRev = $this->mOldRev;
888 $newRev = $this->mNewRev;
889 }
890
891 $nEdits = $this->mNewPage->countRevisionsBetween( $oldRev, $newRev );
892 if ( $nEdits > 0 ) {
893 $limit = 100; // use diff-multi-manyusers if too many users
894 $numUsers = $this->mNewPage->countAuthorsBetween( $oldRev, $newRev, $limit );
895 return self::intermediateEditsMsg( $nEdits, $numUsers, $limit );
896 }
897 return ''; // nothing
898 }
899
900 /**
901 * Get a notice about how many intermediate edits and users there are
902 * @param $numEdits int
903 * @param $numUsers int
904 * @param $limit int
905 * @return string
906 */
907 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
908 if ( $numUsers > $limit ) {
909 $msg = 'diff-multi-manyusers';
910 $numUsers = $limit;
911 } else {
912 $msg = 'diff-multi';
913 }
914 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
915 }
916
917 /**
918 * Get a header for a specified revision.
919 *
920 * @param $rev Revision
921 * @param string $complete 'complete' to get the header wrapped depending
922 * the visibility of the revision and a link to edit the page.
923 * @return String HTML fragment
924 */
925 protected function getRevisionHeader( Revision $rev, $complete = '' ) {
926 $lang = $this->getLanguage();
927 $user = $this->getUser();
928 $revtimestamp = $rev->getTimestamp();
929 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
930 $dateofrev = $lang->userDate( $revtimestamp, $user );
931 $timeofrev = $lang->userTime( $revtimestamp, $user );
932
933 $header = $this->msg(
934 $rev->isCurrent() ? 'currentrev-asof' : 'revisionasof',
935 $timestamp,
936 $dateofrev,
937 $timeofrev
938 )->escaped();
939
940 if ( $complete !== 'complete' ) {
941 return $header;
942 }
943
944 $title = $rev->getTitle();
945
946 $header = Linker::linkKnown( $title, $header, array(),
947 array( 'oldid' => $rev->getID() ) );
948
949 if ( $rev->userCan( Revision::DELETED_TEXT, $user ) ) {
950 $editQuery = array( 'action' => 'edit' );
951 if ( !$rev->isCurrent() ) {
952 $editQuery['oldid'] = $rev->getID();
953 }
954
955 $msg = $this->msg( $title->quickUserCan( 'edit', $user ) ? 'editold' : 'viewsourceold' )->escaped();
956 $header .= ' ' . $this->msg( 'parentheses' )->rawParams(
957 Linker::linkKnown( $title, $msg, array(), $editQuery ) )->plain();
958 if ( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
959 $header = Html::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
960 }
961 } else {
962 $header = Html::rawElement( 'span', array( 'class' => 'history-deleted' ), $header );
963 }
964
965 return $header;
966 }
967
968 /**
969 * Add the header to a diff body
970 *
971 * @return string
972 */
973 function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
974 // shared.css sets diff in interface language/dir, but the actual content
975 // is often in a different language, mostly the page content language/dir
976 $tableClass = 'diff diff-contentalign-' . htmlspecialchars( $this->getDiffLang()->alignStart() );
977 $header = "<table class='$tableClass'>";
978
979 if ( !$diff && !$otitle ) {
980 $header .= "
981 <tr style='vertical-align: top;'>
982 <td class='diff-ntitle'>{$ntitle}</td>
983 </tr>";
984 $multiColspan = 1;
985 } else {
986 if ( $diff ) { // Safari/Chrome show broken output if cols not used
987 $header .= "
988 <col class='diff-marker' />
989 <col class='diff-content' />
990 <col class='diff-marker' />
991 <col class='diff-content' />";
992 $colspan = 2;
993 $multiColspan = 4;
994 } else {
995 $colspan = 1;
996 $multiColspan = 2;
997 }
998 $header .= "
999 <tr style='vertical-align: top;'>
1000 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
1001 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
1002 </tr>";
1003 }
1004
1005 if ( $multi != '' ) {
1006 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;' class='diff-multi'>{$multi}</td></tr>";
1007 }
1008 if ( $notice != '' ) {
1009 $header .= "<tr><td colspan='{$multiColspan}' style='text-align: center;'>{$notice}</td></tr>";
1010 }
1011
1012 return $header . $diff . "</table>";
1013 }
1014
1015 /**
1016 * Use specified text instead of loading from the database
1017 * @deprecated since 1.21, use setContent() instead.
1018 */
1019 function setText( $oldText, $newText ) {
1020 ContentHandler::deprecated( __METHOD__, "1.21" );
1021
1022 $oldContent = ContentHandler::makeContent( $oldText, $this->getTitle() );
1023 $newContent = ContentHandler::makeContent( $newText, $this->getTitle() );
1024
1025 $this->setContent( $oldContent, $newContent );
1026 }
1027
1028 /**
1029 * Use specified text instead of loading from the database
1030 * @since 1.21
1031 */
1032 function setContent( Content $oldContent, Content $newContent ) {
1033 $this->mOldContent = $oldContent;
1034 $this->mNewContent = $newContent;
1035
1036 $this->mTextLoaded = 2;
1037 $this->mRevisionsLoaded = true;
1038 }
1039
1040 /**
1041 * Set the language in which the diff text is written
1042 * (Defaults to page content language).
1043 * @since 1.19
1044 */
1045 function setTextLanguage( $lang ) {
1046 $this->mDiffLang = wfGetLangObj( $lang );
1047 }
1048
1049 /**
1050 * Load revision IDs
1051 */
1052 private function loadRevisionIds() {
1053 if ( $this->mRevisionsIdsLoaded ) {
1054 return;
1055 }
1056
1057 $this->mRevisionsIdsLoaded = true;
1058
1059 $old = $this->mOldid;
1060 $new = $this->mNewid;
1061
1062 if ( $new === 'prev' ) {
1063 # Show diff between revision $old and the previous one.
1064 # Get previous one from DB.
1065 $this->mNewid = intval( $old );
1066 $this->mOldid = $this->getTitle()->getPreviousRevisionID( $this->mNewid );
1067 } elseif ( $new === 'next' ) {
1068 # Show diff between revision $old and the next one.
1069 # Get next one from DB.
1070 $this->mOldid = intval( $old );
1071 $this->mNewid = $this->getTitle()->getNextRevisionID( $this->mOldid );
1072 if ( $this->mNewid === false ) {
1073 # if no result, NewId points to the newest old revision. The only newer
1074 # revision is cur, which is "0".
1075 $this->mNewid = 0;
1076 }
1077 } else {
1078 $this->mOldid = intval( $old );
1079 $this->mNewid = intval( $new );
1080 wfRunHooks( 'NewDifferenceEngine', array( $this->getTitle(), &$this->mOldid, &$this->mNewid, $old, $new ) );
1081 }
1082 }
1083
1084 /**
1085 * Load revision metadata for the specified articles. If newid is 0, then compare
1086 * the old article in oldid to the current article; if oldid is 0, then
1087 * compare the current article to the immediately previous one (ignoring the
1088 * value of newid).
1089 *
1090 * If oldid is false, leave the corresponding revision object set
1091 * to false. This is impossible via ordinary user input, and is provided for
1092 * API convenience.
1093 *
1094 * @return bool
1095 */
1096 function loadRevisionData() {
1097 if ( $this->mRevisionsLoaded ) {
1098 return true;
1099 }
1100
1101 // Whether it succeeds or fails, we don't want to try again
1102 $this->mRevisionsLoaded = true;
1103
1104 $this->loadRevisionIds();
1105
1106 // Load the new revision object
1107 $this->mNewRev = $this->mNewid
1108 ? Revision::newFromId( $this->mNewid )
1109 : Revision::newFromTitle( $this->getTitle(), false, Revision::READ_NORMAL );
1110
1111 if ( !$this->mNewRev instanceof Revision ) {
1112 return false;
1113 }
1114
1115 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1116 $this->mNewid = $this->mNewRev->getId();
1117 $this->mNewPage = $this->mNewRev->getTitle();
1118
1119 // Load the old revision object
1120 $this->mOldRev = false;
1121 if ( $this->mOldid ) {
1122 $this->mOldRev = Revision::newFromId( $this->mOldid );
1123 } elseif ( $this->mOldid === 0 ) {
1124 $rev = $this->mNewRev->getPrevious();
1125 if ( $rev ) {
1126 $this->mOldid = $rev->getId();
1127 $this->mOldRev = $rev;
1128 } else {
1129 // No previous revision; mark to show as first-version only.
1130 $this->mOldid = false;
1131 $this->mOldRev = false;
1132 }
1133 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1134
1135 if ( is_null( $this->mOldRev ) ) {
1136 return false;
1137 }
1138
1139 if ( $this->mOldRev ) {
1140 $this->mOldPage = $this->mOldRev->getTitle();
1141 }
1142
1143 return true;
1144 }
1145
1146 /**
1147 * Load the text of the revisions, as well as revision data.
1148 *
1149 * @return bool
1150 */
1151 function loadText() {
1152 if ( $this->mTextLoaded == 2 ) {
1153 return true;
1154 } else {
1155 // Whether it succeeds or fails, we don't want to try again
1156 $this->mTextLoaded = 2;
1157 }
1158
1159 if ( !$this->loadRevisionData() ) {
1160 return false;
1161 }
1162 if ( $this->mOldRev ) {
1163 $this->mOldContent = $this->mOldRev->getContent( Revision::FOR_THIS_USER, $this->getUser() );
1164 if ( $this->mOldContent === null ) {
1165 return false;
1166 }
1167 }
1168 if ( $this->mNewRev ) {
1169 $this->mNewContent = $this->mNewRev->getContent( Revision::FOR_THIS_USER, $this->getUser() );
1170 if ( $this->mNewContent === null ) {
1171 return false;
1172 }
1173 }
1174 return true;
1175 }
1176
1177 /**
1178 * Load the text of the new revision, not the old one
1179 *
1180 * @return bool
1181 */
1182 function loadNewText() {
1183 if ( $this->mTextLoaded >= 1 ) {
1184 return true;
1185 } else {
1186 $this->mTextLoaded = 1;
1187 }
1188 if ( !$this->loadRevisionData() ) {
1189 return false;
1190 }
1191 $this->mNewContent = $this->mNewRev->getContent( Revision::FOR_THIS_USER, $this->getUser() );
1192 return true;
1193 }
1194 }