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