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