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