Fixed profiling error
[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 $t = $this->mTitle->getPrefixedText();
226 $d = wfMsgExt( 'missingarticle-diff', array( 'escape' ),
227 $this->deletedIdMarker( $this->mOldid ),
228 $this->deletedIdMarker( $this->mNewid ) );
229 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
230 $wgOut->addWikiMsg( 'missing-article', "<nowiki>$t</nowiki>", "<span class='plainlinks'>$d</span>" );
231 wfProfileOut( __METHOD__ );
232 return;
233 }
234
235 wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev, $this->mNewRev ) );
236
237 if ( $this->mNewRev->isCurrent() ) {
238 $wgOut->setArticleFlag( true );
239 }
240
241 # mOldid is false if the difference engine is called with a "vague" query for
242 # a diff between a version V and its previous version V' AND the version V
243 # is the first version of that article. In that case, V' does not exist.
244 if ( $this->mOldid === false ) {
245 $this->showFirstRevision();
246 $this->renderNewRevision(); // should we respect $diffOnly here or not?
247 wfProfileOut( __METHOD__ );
248 return;
249 }
250
251 $oldTitle = $this->mOldPage->getPrefixedText();
252 $newTitle = $this->mNewPage->getPrefixedText();
253 if ( $oldTitle == $newTitle ) {
254 $wgOut->setPageTitle( $newTitle );
255 } else {
256 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
257 }
258 if ( $this->mNewPage->equals( $this->mOldPage ) ) {
259 $wgOut->setSubtitle( wfMsgExt( 'difference', array( 'parseinline' ) ) );
260 } else {
261 $wgOut->setSubtitle( wfMsgExt( 'difference-multipage', array( 'parseinline' ) ) );
262 }
263 $wgOut->setRobotPolicy( 'noindex,nofollow' );
264
265 if ( !$this->mOldPage->userCanRead() || !$this->mNewPage->userCanRead() ) {
266 $wgOut->loginToUse();
267 $wgOut->output();
268 $wgOut->disable();
269 wfProfileOut( __METHOD__ );
270 return;
271 }
272
273 $sk = $wgUser->getSkin();
274 if ( method_exists( $sk, 'suppressQuickbar' ) ) {
275 $sk->suppressQuickbar();
276 }
277
278 // Check if page is editable
279 $editable = $this->mNewRev->getTitle()->userCan( 'edit' );
280 if ( $editable && $this->mNewRev->isCurrent() && $wgUser->isAllowed( 'rollback' ) ) {
281 $wgOut->preventClickjacking();
282 $rollback = '&#160;&#160;&#160;' . $sk->generateRollback( $this->mNewRev );
283 } else {
284 $rollback = '';
285 }
286
287 // Prepare a change patrol link, if applicable
288 if ( $wgUseRCPatrol && $this->mTitle->userCan( 'patrol' ) ) {
289 // If we've been given an explicit change identifier, use it; saves time
290 if ( $this->mRcidMarkPatrolled ) {
291 $rcid = $this->mRcidMarkPatrolled;
292 $rc = RecentChange::newFromId( $rcid );
293 // Already patrolled?
294 $rcid = is_object( $rc ) && !$rc->getAttribute( 'rc_patrolled' ) ? $rcid : 0;
295 } else {
296 // Look for an unpatrolled change corresponding to this diff
297 $db = wfGetDB( DB_SLAVE );
298 $change = RecentChange::newFromConds(
299 array(
300 // Redundant user,timestamp condition so we can use the existing index
301 'rc_user_text' => $this->mNewRev->getRawUserText(),
302 'rc_timestamp' => $db->timestamp( $this->mNewRev->getTimestamp() ),
303 'rc_this_oldid' => $this->mNewid,
304 'rc_last_oldid' => $this->mOldid,
305 'rc_patrolled' => 0
306 ),
307 __METHOD__
308 );
309 if ( $change instanceof RecentChange ) {
310 $rcid = $change->mAttribs['rc_id'];
311 $this->mRcidMarkPatrolled = $rcid;
312 } else {
313 // None found
314 $rcid = 0;
315 }
316 }
317 // Build the link
318 if ( $rcid ) {
319 $wgOut->preventClickjacking();
320 $token = $wgUser->editToken( $rcid );
321 $patrol = ' <span class="patrollink">[' . $sk->link(
322 $this->mTitle,
323 wfMsgHtml( 'markaspatrolleddiff' ),
324 array(),
325 array(
326 'action' => 'markpatrolled',
327 'rcid' => $rcid,
328 'token' => $token,
329 ),
330 array(
331 'known',
332 'noclasses'
333 )
334 ) . ']</span>';
335 } else {
336 $patrol = '';
337 }
338 } else {
339 $patrol = '';
340 }
341
342 # Carry over 'diffonly' param via navigation links
343 if ( $diffOnly != $wgUser->getBoolOption( 'diffonly' ) ) {
344 $query['diffonly'] = $diffOnly;
345 }
346
347 # Make "previous revision link"
348 $query['diff'] = 'prev';
349 $query['oldid'] = $this->mOldid;
350 # Cascade unhide param in links for easy deletion browsing
351 if ( $this->unhide ) {
352 $query['unhide'] = 1;
353 }
354 if ( !$this->mOldRev->getPrevious() ) {
355 $prevlink = '&#160;';
356 } else {
357 $prevlink = $sk->link(
358 $this->mTitle,
359 wfMsgHtml( 'previousdiff' ),
360 array(
361 'id' => 'differences-prevlink'
362 ),
363 $query,
364 array(
365 'known',
366 'noclasses'
367 )
368 );
369 }
370
371 # Make "next revision link"
372 $query['diff'] = 'next';
373 $query['oldid'] = $this->mNewid;
374 # Skip next link on the top revision
375 if ( $this->mNewRev->isCurrent() ) {
376 $nextlink = '&#160;';
377 } else {
378 $nextlink = $sk->link(
379 $this->mTitle,
380 wfMsgHtml( 'nextdiff' ),
381 array(
382 'id' => 'differences-nextlink'
383 ),
384 $query,
385 array(
386 'known',
387 'noclasses'
388 )
389 );
390 }
391
392 $oldminor = '';
393 $newminor = '';
394
395 if ( $this->mOldRev->isMinor() ) {
396 $oldminor = ChangesList::flag( 'minor' );
397 }
398 if ( $this->mNewRev->isMinor() ) {
399 $newminor = ChangesList::flag( 'minor' );
400 }
401
402 # Handle RevisionDelete links...
403 $ldel = $this->revisionDeleteLink( $this->mOldRev );
404 $rdel = $this->revisionDeleteLink( $this->mNewRev );
405
406 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $this->mOldtitle . '</strong></div>' .
407 '<div id="mw-diff-otitle2">' .
408 $sk->revUserTools( $this->mOldRev, !$this->unhide ) . '</div>' .
409 '<div id="mw-diff-otitle3">' . $oldminor .
410 $sk->revComment( $this->mOldRev, !$diffOnly, !$this->unhide ) . $ldel . '</div>' .
411 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
412 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $this->mNewtitle . '</strong></div>' .
413 '<div id="mw-diff-ntitle2">' . $sk->revUserTools( $this->mNewRev, !$this->unhide ) .
414 " $rollback</div>" .
415 '<div id="mw-diff-ntitle3">' . $newminor .
416 $sk->revComment( $this->mNewRev, !$diffOnly, !$this->unhide ) . $rdel . '</div>' .
417 '<div id="mw-diff-ntitle4">' . $nextlink . $patrol . '</div>';
418
419 # Check if this user can see the revisions
420 $allowed = $this->mOldRev->userCan( Revision::DELETED_TEXT )
421 && $this->mNewRev->userCan( Revision::DELETED_TEXT );
422 # Check if one of the revisions is deleted/suppressed
423 $deleted = $suppressed = false;
424 if ( $this->mOldRev->isDeleted( Revision::DELETED_TEXT ) ) {
425 $deleted = true; // old revisions text is hidden
426 if ( $this->mOldRev->isDeleted( Revision::DELETED_RESTRICTED ) )
427 $suppressed = true; // also suppressed
428 }
429 if ( $this->mNewRev->isDeleted( Revision::DELETED_TEXT ) ) {
430 $deleted = true; // new revisions text is hidden
431 if ( $this->mNewRev->isDeleted( Revision::DELETED_RESTRICTED ) )
432 $suppressed = true; // also suppressed
433 }
434 # If the diff cannot be shown due to a deleted revision, then output
435 # the diff header and links to unhide (if available)...
436 if ( $deleted && ( !$this->unhide || !$allowed ) ) {
437 $this->showDiffStyle();
438 $multi = $this->getMultiNotice();
439 $wgOut->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
440 if ( !$allowed ) {
441 $msg = $suppressed ? 'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
442 # Give explanation for why revision is not visible
443 $wgOut->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
444 array( $msg ) );
445 } else {
446 # Give explanation and add a link to view the diff...
447 $link = $this->mTitle->getFullUrl( array(
448 'diff' => $this->mNewid,
449 'oldid' => $this->mOldid,
450 'unhide' => 1
451 ) );
452 $msg = $suppressed ? 'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
453 $wgOut->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n", array( $msg, $link ) );
454 }
455 # Otherwise, output a regular diff...
456 } else {
457 # Add deletion notice if the user is viewing deleted content
458 $notice = '';
459 if ( $deleted ) {
460 $msg = $suppressed ? 'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
461 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" . wfMsgExt( $msg, 'parseinline' ) . "</div>\n";
462 }
463 $this->showDiff( $oldHeader, $newHeader, $notice );
464 if ( !$diffOnly ) {
465 $this->renderNewRevision();
466 }
467 }
468 wfProfileOut( __METHOD__ );
469 }
470
471 /**
472 * @param $rev Revision
473 * @return String
474 */
475 protected function revisionDeleteLink( $rev ) {
476 global $wgUser;
477 $link = '';
478 $canHide = $wgUser->isAllowed( 'deleterevision' );
479 // Show del/undel link if:
480 // (a) the user can delete revisions, or
481 // (b) the user can view deleted revision *and* this one is deleted
482 if ( $canHide || ( $rev->getVisibility() && $wgUser->isAllowed( 'deletedhistory' ) ) ) {
483 $sk = $wgUser->getSkin();
484 if ( !$rev->userCan( Revision::DELETED_RESTRICTED ) ) {
485 $link = $sk->revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
486 } else {
487 $query = array(
488 'type' => 'revision',
489 'target' => $rev->mTitle->getPrefixedDbkey(),
490 'ids' => $rev->getId()
491 );
492 $link = $sk->revDeleteLink( $query,
493 $rev->isDeleted( Revision::DELETED_RESTRICTED ), $canHide );
494 }
495 $link = '&#160;&#160;&#160;' . $link . ' ';
496 }
497 return $link;
498 }
499
500 /**
501 * Show the new revision of the page.
502 */
503 function renderNewRevision() {
504 global $wgOut, $wgUser;
505 wfProfileIn( __METHOD__ );
506 # Add "current version as of X" title
507 $wgOut->addHTML( "<hr class='diff-hr' />
508 <h2 class='diff-currentversion-title'>{$this->mPagetitle}</h2>\n" );
509 # Page content may be handled by a hooked call instead...
510 if ( wfRunHooks( 'ArticleContentOnDiff', array( $this, $wgOut ) ) ) {
511 # Use the current version parser cache if applicable
512 $pCache = true;
513 if ( !$this->mNewRev->isCurrent() ) {
514 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
515 $pCache = false;
516 }
517
518 $this->loadNewText();
519 $wgOut->setRevisionId( $this->mNewRev->getId() );
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 if ( $this->mNewRev->isCurrent() ) {
592 $wgOut->setArticleFlag( true );
593 }
594
595 # Check if user is allowed to look at this page. If not, bail out.
596 #
597 if ( !$this->mTitle->userCanRead() ) {
598 $wgOut->loginToUse();
599 $wgOut->output();
600 wfProfileOut( __METHOD__ );
601 throw new MWException( "Permission Error: you do not have access to view this page" );
602 }
603
604 # Prepare the header box
605 #
606 $sk = $wgUser->getSkin();
607
608 $next = $this->mTitle->getNextRevisionID( $this->mNewid );
609 if ( !$next ) {
610 $nextlink = '';
611 } else {
612 $nextlink = '<br />' . $sk->link(
613 $this->mTitle,
614 wfMsgHtml( 'nextdiff' ),
615 array(
616 'id' => 'differences-nextlink'
617 ),
618 array(
619 'diff' => 'next',
620 'oldid' => $this->mNewid,
621 ),
622 array(
623 'known',
624 'noclasses'
625 )
626 );
627 }
628 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\">" .
629 $sk->revUserTools( $this->mNewRev ) . "<br />" . $sk->revComment( $this->mNewRev ) . $nextlink . "</div>\n";
630
631 $wgOut->addHTML( $header );
632
633 $wgOut->setSubtitle( wfMsgExt( 'difference', array( 'parseinline' ) ) );
634 $wgOut->setRobotPolicy( 'noindex,nofollow' );
635
636 wfProfileOut( __METHOD__ );
637 }
638
639 /**
640 * Get the diff text, send it to $wgOut
641 * Returns false if the diff could not be generated, otherwise returns true
642 *
643 * @return bool
644 */
645 function showDiff( $otitle, $ntitle, $notice = '' ) {
646 global $wgOut;
647 $diff = $this->getDiff( $otitle, $ntitle, $notice );
648 if ( $diff === false ) {
649 $wgOut->addWikiMsg( 'missing-article', "<nowiki>(fixme, bug)</nowiki>", '' );
650 return false;
651 } else {
652 $this->showDiffStyle();
653 $wgOut->addHTML( $diff );
654 return true;
655 }
656 }
657
658 /**
659 * Add style sheets and supporting JS for diff display.
660 */
661 function showDiffStyle() {
662 global $wgOut;
663 $wgOut->addModuleStyles( 'mediawiki.action.history.diff' );
664 }
665
666 /**
667 * Get complete diff table, including header
668 *
669 * @param $otitle Title: old title
670 * @param $ntitle Title: new title
671 * @param $notice String: HTML between diff header and body
672 * @return mixed
673 */
674 function getDiff( $otitle, $ntitle, $notice = '' ) {
675 $body = $this->getDiffBody();
676 if ( $body === false ) {
677 return false;
678 } else {
679 $multi = $this->getMultiNotice();
680 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
681 }
682 }
683
684 /**
685 * Get the diff table body, without header
686 *
687 * @return mixed (string/false)
688 */
689 public function getDiffBody() {
690 global $wgMemc;
691 wfProfileIn( __METHOD__ );
692 $this->mCacheHit = true;
693 // Check if the diff should be hidden from this user
694 if ( !$this->loadRevisionData() ) {
695 wfProfileOut( __METHOD__ );
696 return false;
697 } elseif ( $this->mOldRev && !$this->mOldRev->userCan( Revision::DELETED_TEXT ) ) {
698 wfProfileOut( __METHOD__ );
699 return false;
700 } elseif ( $this->mNewRev && !$this->mNewRev->userCan( Revision::DELETED_TEXT ) ) {
701 wfProfileOut( __METHOD__ );
702 return false;
703 }
704 // Short-circuit
705 if ( $this->mOldRev && $this->mNewRev
706 && $this->mOldRev->getID() == $this->mNewRev->getID() )
707 {
708 wfProfileOut( __METHOD__ );
709 return '';
710 }
711 // Cacheable?
712 $key = false;
713 if ( $this->mOldid && $this->mNewid ) {
714 $key = wfMemcKey( 'diff', 'version', MW_DIFF_VERSION,
715 'oldid', $this->mOldid, 'newid', $this->mNewid );
716 // Try cache
717 if ( !$this->mRefreshCache ) {
718 $difftext = $wgMemc->get( $key );
719 if ( $difftext ) {
720 wfIncrStats( 'diff_cache_hit' );
721 $difftext = $this->localiseLineNumbers( $difftext );
722 $difftext .= "\n<!-- diff cache key $key -->\n";
723 wfProfileOut( __METHOD__ );
724 return $difftext;
725 }
726 } // don't try to load but save the result
727 }
728 $this->mCacheHit = false;
729
730 // Loadtext is permission safe, this just clears out the diff
731 if ( !$this->loadText() ) {
732 wfProfileOut( __METHOD__ );
733 return false;
734 }
735
736 $difftext = $this->generateDiffBody( $this->mOldtext, $this->mNewtext );
737
738 // Save to cache for 7 days
739 if ( !wfRunHooks( 'AbortDiffCache', array( &$this ) ) ) {
740 wfIncrStats( 'diff_uncacheable' );
741 } elseif ( $key !== false && $difftext !== false ) {
742 wfIncrStats( 'diff_cache_miss' );
743 $wgMemc->set( $key, $difftext, 7 * 86400 );
744 } else {
745 wfIncrStats( 'diff_uncacheable' );
746 }
747 // Replace line numbers with the text in the user's language
748 if ( $difftext !== false ) {
749 $difftext = $this->localiseLineNumbers( $difftext );
750 }
751 wfProfileOut( __METHOD__ );
752 return $difftext;
753 }
754
755 /**
756 * Make sure the proper modules are loaded before we try to
757 * make the diff
758 */
759 private function initDiffEngines() {
760 global $wgExternalDiffEngine;
761 if ( $wgExternalDiffEngine == 'wikidiff' && !function_exists( 'wikidiff_do_diff' ) ) {
762 wfProfileIn( __METHOD__ . '-php_wikidiff.so' );
763 wfDl( 'php_wikidiff' );
764 wfProfileOut( __METHOD__ . '-php_wikidiff.so' );
765 }
766 elseif ( $wgExternalDiffEngine == 'wikidiff2' && !function_exists( 'wikidiff2_do_diff' ) ) {
767 wfProfileIn( __METHOD__ . '-php_wikidiff2.so' );
768 wfDl( 'wikidiff2' );
769 wfProfileOut( __METHOD__ . '-php_wikidiff2.so' );
770 }
771 }
772
773 /**
774 * Generate a diff, no caching
775 *
776 * @param $otext String: old text, must be already segmented
777 * @param $ntext String: new text, must be already segmented
778 */
779 function generateDiffBody( $otext, $ntext ) {
780 global $wgExternalDiffEngine, $wgContLang;
781
782 wfProfileIn( __METHOD__ );
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 function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
939 // shared.css sets diff in interface language/dir,
940 // but the actual content should be in the page language/dir
941 $pageLang = $this->mTitle->getPageLanguage();
942 $tableClass = 'diff diff-contentalign-' . htmlspecialchars( $pageLang->alignStart() );
943 $header = "<table class='$tableClass'>";
944 if ( $diff ) { // Safari/Chrome show broken output if cols not used
945 $header .= "
946 <col class='diff-marker' />
947 <col class='diff-content' />
948 <col class='diff-marker' />
949 <col class='diff-content' />";
950 $colspan = 2;
951 $multiColspan = 4;
952 } else {
953 $colspan = 1;
954 $multiColspan = 2;
955 }
956 $header .= "
957 <tr valign='top'>
958 <td colspan='$colspan' class='diff-otitle'>{$otitle}</td>
959 <td colspan='$colspan' class='diff-ntitle'>{$ntitle}</td>
960 </tr>";
961
962 if ( $multi != '' ) {
963 $header .= "<tr><td colspan='{$multiColspan}' align='center' class='diff-multi'>{$multi}</td></tr>";
964 }
965 if ( $notice != '' ) {
966 $header .= "<tr><td colspan='{$multiColspan}' align='center'>{$notice}</td></tr>";
967 }
968
969 return $header . $diff . "</table>";
970 }
971
972 /**
973 * Use specified text instead of loading from the database
974 */
975 function setText( $oldText, $newText ) {
976 $this->mOldtext = $oldText;
977 $this->mNewtext = $newText;
978 $this->mTextLoaded = 2;
979 $this->mRevisionsLoaded = true;
980 }
981
982 /**
983 * Load revision metadata for the specified articles. If newid is 0, then compare
984 * the old article in oldid to the current article; if oldid is 0, then
985 * compare the current article to the immediately previous one (ignoring the
986 * value of newid).
987 *
988 * If oldid is false, leave the corresponding revision object set
989 * to false. This is impossible via ordinary user input, and is provided for
990 * API convenience.
991 *
992 * @return bool
993 */
994 function loadRevisionData() {
995 global $wgLang, $wgUser;
996 if ( $this->mRevisionsLoaded ) {
997 return true;
998 } else {
999 // Whether it succeeds or fails, we don't want to try again
1000 $this->mRevisionsLoaded = true;
1001 }
1002
1003 // Load the new revision object
1004 $this->mNewRev = $this->mNewid
1005 ? Revision::newFromId( $this->mNewid )
1006 : Revision::newFromTitle( $this->mTitle );
1007 if ( !$this->mNewRev instanceof Revision ) {
1008 return false;
1009 }
1010
1011 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1012 $this->mNewid = $this->mNewRev->getId();
1013
1014 // Check if page is editable
1015 $editable = $this->mNewRev->getTitle()->userCan( 'edit' );
1016
1017 // Set assorted variables
1018 $timestamp = $wgLang->timeanddate( $this->mNewRev->getTimestamp(), true );
1019 $dateofrev = $wgLang->date( $this->mNewRev->getTimestamp(), true );
1020 $timeofrev = $wgLang->time( $this->mNewRev->getTimestamp(), true );
1021 $this->mNewPage = $this->mNewRev->getTitle();
1022 if ( $this->mNewRev->isCurrent() ) {
1023 $newLink = $this->mNewPage->escapeLocalUrl( array(
1024 'oldid' => $this->mNewid
1025 ) );
1026 $this->mPagetitle = htmlspecialchars( wfMsg(
1027 'currentrev-asof',
1028 $timestamp,
1029 $dateofrev,
1030 $timeofrev
1031 ) );
1032 $newEdit = $this->mNewPage->escapeLocalUrl( array(
1033 'action' => 'edit'
1034 ) );
1035
1036 $this->mNewtitle = "<a href='$newLink'>{$this->mPagetitle}</a>";
1037 $this->mNewtitle .= " (<a href='$newEdit'>" . wfMsgHtml( $editable ? 'editold' : 'viewsourceold' ) . "</a>)";
1038 } else {
1039 $newLink = $this->mNewPage->escapeLocalUrl( array(
1040 'oldid' => $this->mNewid
1041 ) );
1042 $newEdit = $this->mNewPage->escapeLocalUrl( array(
1043 'action' => 'edit',
1044 'oldid' => $this->mNewid
1045 ) );
1046 $this->mPagetitle = htmlspecialchars( wfMsg(
1047 'revisionasof',
1048 $timestamp,
1049 $dateofrev,
1050 $timeofrev
1051 ) );
1052
1053 $this->mNewtitle = "<a href='$newLink'>{$this->mPagetitle}</a>";
1054 $this->mNewtitle .= " (<a href='$newEdit'>" . wfMsgHtml( $editable ? 'editold' : 'viewsourceold' ) . "</a>)";
1055 }
1056 if ( !$this->mNewRev->userCan( Revision::DELETED_TEXT ) ) {
1057 $this->mNewtitle = "<span class='history-deleted'>{$this->mPagetitle}</span>";
1058 } elseif ( $this->mNewRev->isDeleted( Revision::DELETED_TEXT ) ) {
1059 $this->mNewtitle = "<span class='history-deleted'>{$this->mNewtitle}</span>";
1060 }
1061
1062 // Load the old revision object
1063 $this->mOldRev = false;
1064 if ( $this->mOldid ) {
1065 $this->mOldRev = Revision::newFromId( $this->mOldid );
1066 } elseif ( $this->mOldid === 0 ) {
1067 $rev = $this->mNewRev->getPrevious();
1068 if ( $rev ) {
1069 $this->mOldid = $rev->getId();
1070 $this->mOldRev = $rev;
1071 } else {
1072 // No previous revision; mark to show as first-version only.
1073 $this->mOldid = false;
1074 $this->mOldRev = false;
1075 }
1076 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1077
1078 if ( is_null( $this->mOldRev ) ) {
1079 return false;
1080 }
1081
1082 if ( $this->mOldRev ) {
1083 $this->mOldPage = $this->mOldRev->getTitle();
1084
1085 $t = $wgLang->timeanddate( $this->mOldRev->getTimestamp(), true );
1086 $dateofrev = $wgLang->date( $this->mOldRev->getTimestamp(), true );
1087 $timeofrev = $wgLang->time( $this->mOldRev->getTimestamp(), true );
1088 $oldLink = $this->mOldPage->escapeLocalUrl( array(
1089 'oldid' => $this->mOldid
1090 ) );
1091 $oldEdit = $this->mOldPage->escapeLocalUrl( array(
1092 'action' => 'edit',
1093 'oldid' => $this->mOldid
1094 ) );
1095 $this->mOldPagetitle = htmlspecialchars( wfMsg( 'revisionasof', $t, $dateofrev, $timeofrev ) );
1096
1097 $this->mOldtitle = "<a href='$oldLink'>{$this->mOldPagetitle}</a>"
1098 . " (<a href='$oldEdit'>" . wfMsgHtml( $editable ? 'editold' : 'viewsourceold' ) . "</a>)";
1099 // Add an "undo" link
1100 if ( $editable && !$this->mOldRev->isDeleted( Revision::DELETED_TEXT ) && !$this->mNewRev->isDeleted( Revision::DELETED_TEXT ) ) {
1101 $undoLink = Html::element( 'a', array(
1102 'href' => $this->mNewPage->getLocalUrl( array(
1103 'action' => 'edit',
1104 'undoafter' => $this->mOldid,
1105 'undo' => $this->mNewid ) ),
1106 'title' => $wgUser->getSkin()->titleAttrib( 'undo' )
1107 ), wfMsg( 'editundo' ) );
1108 $this->mNewtitle .= ' (' . $undoLink . ')';
1109 }
1110
1111 if ( !$this->mOldRev->userCan( Revision::DELETED_TEXT ) ) {
1112 $this->mOldtitle = '<span class="history-deleted">' . $this->mOldPagetitle . '</span>';
1113 } elseif ( $this->mOldRev->isDeleted( Revision::DELETED_TEXT ) ) {
1114 $this->mOldtitle = '<span class="history-deleted">' . $this->mOldtitle . '</span>';
1115 }
1116 }
1117
1118 return true;
1119 }
1120
1121 /**
1122 * Load the text of the revisions, as well as revision data.
1123 *
1124 * @return bool
1125 */
1126 function loadText() {
1127 if ( $this->mTextLoaded == 2 ) {
1128 return true;
1129 } else {
1130 // Whether it succeeds or fails, we don't want to try again
1131 $this->mTextLoaded = 2;
1132 }
1133
1134 if ( !$this->loadRevisionData() ) {
1135 return false;
1136 }
1137 if ( $this->mOldRev ) {
1138 $this->mOldtext = $this->mOldRev->getText( Revision::FOR_THIS_USER );
1139 if ( $this->mOldtext === false ) {
1140 return false;
1141 }
1142 }
1143 if ( $this->mNewRev ) {
1144 $this->mNewtext = $this->mNewRev->getText( Revision::FOR_THIS_USER );
1145 if ( $this->mNewtext === false ) {
1146 return false;
1147 }
1148 }
1149 return true;
1150 }
1151
1152 /**
1153 * Load the text of the new revision, not the old one
1154 *
1155 * @return bool
1156 */
1157 function loadNewText() {
1158 if ( $this->mTextLoaded >= 1 ) {
1159 return true;
1160 } else {
1161 $this->mTextLoaded = 1;
1162 }
1163 if ( !$this->loadRevisionData() ) {
1164 return false;
1165 }
1166 $this->mNewtext = $this->mNewRev->getText( Revision::FOR_THIS_USER );
1167 return true;
1168 }
1169 }