Don't show rollback or undo buttons for deleted revisions or revivions whose next...
[lhc/web/wiklou.git] / includes / PageHistory.php
1 <?php
2 /**
3 * Page history
4 *
5 * Split off from Article.php and Skin.php, 2003-12-22
6 */
7
8 /**
9 * This class handles printing the history page for an article. In order to
10 * be efficient, it uses timestamps rather than offsets for paging, to avoid
11 * costly LIMIT,offset queries.
12 *
13 * Construct it by passing in an Article, and call $h->history() to print the
14 * history.
15 *
16 */
17 class PageHistory {
18 const DIR_PREV = 0;
19 const DIR_NEXT = 1;
20
21 var $mArticle, $mTitle, $mSkin;
22 var $lastdate;
23 var $linesonpage;
24 var $mNotificationTimestamp;
25 var $mLatestId = null;
26
27 /**
28 * Construct a new PageHistory.
29 *
30 * @param Article $article
31 * @returns nothing
32 */
33 function __construct($article) {
34 global $wgUser;
35
36 $this->mArticle =& $article;
37 $this->mTitle =& $article->mTitle;
38 $this->mNotificationTimestamp = NULL;
39 $this->mSkin = $wgUser->getSkin();
40 $this->preCacheMessages();
41 }
42
43 /**
44 * As we use the same small set of messages in various methods and that
45 * they are called often, we call them once and save them in $this->message
46 */
47 function preCacheMessages() {
48 // Precache various messages
49 if( !isset( $this->message ) ) {
50 foreach( explode(' ', 'cur last rev-delundel' ) as $msg ) {
51 $this->message[$msg] = wfMsgExt( $msg, array( 'escape') );
52 }
53 }
54 }
55
56 /**
57 * Print the history page for an article.
58 *
59 * @returns nothing
60 */
61 function history() {
62 global $wgOut, $wgRequest, $wgTitle;
63
64 /*
65 * Allow client caching.
66 */
67
68 if( $wgOut->checkLastModified( $this->mArticle->getTouched() ) )
69 /* Client cache fresh and headers sent, nothing more to do. */
70 return;
71
72 wfProfileIn( __METHOD__ );
73
74 /*
75 * Setup page variables.
76 */
77 $wgOut->setPageTitle( wfMsg( 'history-title', $this->mTitle->getPrefixedText() ) );
78 $wgOut->setPageTitleActionText( wfMsg( 'history_short' ) );
79 $wgOut->setArticleFlag( false );
80 $wgOut->setArticleRelated( true );
81 $wgOut->setRobotpolicy( 'noindex,nofollow' );
82 $wgOut->setSyndicated( true );
83 $wgOut->setFeedAppendQuery( 'action=history' );
84
85 $logPage = SpecialPage::getTitleFor( 'Log' );
86 $logLink = $this->mSkin->makeKnownLinkObj( $logPage, wfMsgHtml( 'viewpagelogs' ), 'page=' . $this->mTitle->getPrefixedUrl() );
87 $wgOut->setSubtitle( $logLink );
88
89 $feedType = $wgRequest->getVal( 'feed' );
90 if( $feedType ) {
91 wfProfileOut( __METHOD__ );
92 return $this->feed( $feedType );
93 }
94
95 /*
96 * Fail if article doesn't exist.
97 */
98 if( !$this->mTitle->exists() ) {
99 $wgOut->addWikiMsg( 'nohistory' );
100 wfProfileOut( __METHOD__ );
101 return;
102 }
103
104 /*
105 * "go=first" means to jump to the last (earliest) history page.
106 * This is deprecated, it no longer appears in the user interface
107 */
108 if ( $wgRequest->getText("go") == 'first' ) {
109 $limit = $wgRequest->getInt( 'limit', 50 );
110 $wgOut->redirect( $wgTitle->getLocalURL( "action=history&limit={$limit}&dir=prev" ) );
111 return;
112 }
113
114 wfRunHooks( 'PageHistoryBeforeList', array( &$this->mArticle ) );
115
116 /**
117 * Do the list
118 */
119 $pager = new PageHistoryPager( $this );
120 $this->linesonpage = $pager->getNumRows();
121 $wgOut->addHTML(
122 $pager->getNavigationBar() .
123 $this->beginHistoryList() .
124 $pager->getBody() .
125 $this->endHistoryList() .
126 $pager->getNavigationBar()
127 );
128 wfProfileOut( __METHOD__ );
129 }
130
131 /**
132 * Creates begin of history list with a submit button
133 *
134 * @return string HTML output
135 */
136 function beginHistoryList() {
137 global $wgTitle;
138 $this->lastdate = '';
139 $s = wfMsgExt( 'histlegend', array( 'parse') );
140 $s .= '<form action="' . $wgTitle->escapeLocalURL( '-' ) . '" method="get">';
141 $prefixedkey = htmlspecialchars($wgTitle->getPrefixedDbKey());
142
143 // The following line is SUPPOSED to have double-quotes around the
144 // $prefixedkey variable, because htmlspecialchars() doesn't escape
145 // single-quotes.
146 //
147 // On at least two occasions people have changed it to single-quotes,
148 // which creates invalid HTML and incorrect display of the resulting
149 // link.
150 //
151 // Please do not break this a third time. Thank you for your kind
152 // consideration and cooperation.
153 //
154 $s .= "<input type='hidden' name='title' value=\"{$prefixedkey}\" />\n";
155
156 $s .= $this->submitButton();
157 $s .= '<ul id="pagehistory">' . "\n";
158 return $s;
159 }
160
161 /**
162 * Creates end of history list with a submit button
163 *
164 * @return string HTML output
165 */
166 function endHistoryList() {
167 $s = '</ul>';
168 $s .= $this->submitButton( array( 'id' => 'historysubmit' ) );
169 $s .= '</form>';
170 return $s;
171 }
172
173 /**
174 * Creates a submit button
175 *
176 * @param array $bits optional CSS ID
177 * @return string HTML output for the submit button
178 */
179 function submitButton( $bits = array() ) {
180 # Disable submit button if history has 1 revision only
181 if ( $this->linesonpage > 1 ) {
182 return Xml::submitButton( wfMsg( 'compareselectedversions' ),
183 $bits + array(
184 'class' => 'historysubmit',
185 'accesskey' => wfMsg( 'accesskey-compareselectedversions' ),
186 'title' => wfMsg( 'tooltip-compareselectedversions' ),
187 )
188 );
189 } else {
190 return '';
191 }
192 }
193
194 /**
195 * Returns a row from the history printout.
196 *
197 * @todo document some more, and maybe clean up the code (some params redundant?)
198 *
199 * @param Row $row The database row corresponding to the previous line.
200 * @param mixed $next The database row corresponding to the next line.
201 * @param int $counter Apparently a counter of what row number we're at, counted from the top row = 1.
202 * @param $notificationtimestamp
203 * @param bool $latest Whether this row corresponds to the page's latest revision.
204 * @param bool $firstInList Whether this row corresponds to the first displayed on this history page.
205 * @return string HTML output for the row
206 */
207 function historyLine( $row, $next, $counter = '', $notificationtimestamp = false, $latest = false, $firstInList = false ) {
208 global $wgUser, $wgLang;
209 $rev = new Revision( $row );
210 $rev->setTitle( $this->mTitle );
211
212 $s = '';
213 $curlink = $this->curLink( $rev, $latest );
214 $lastlink = $this->lastLink( $rev, $next, $counter );
215 $arbitrary = $this->diffButtons( $rev, $firstInList, $counter );
216 $link = $this->revLink( $rev );
217
218 $s .= "($curlink) ($lastlink) $arbitrary";
219
220 if( $wgUser->isAllowed( 'deleterevision' ) ) {
221 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
222 if( $firstInList ) {
223 // We don't currently handle well changing the top revision's settings
224 $del = $this->message['rev-delundel'];
225 } else if( !$rev->userCan( Revision::DELETED_RESTRICTED ) ) {
226 // If revision was hidden from sysops
227 $del = $this->message['rev-delundel'];
228 } else {
229 $del = $this->mSkin->makeKnownLinkObj( $revdel,
230 $this->message['rev-delundel'],
231 'target=' . urlencode( $this->mTitle->getPrefixedDbkey() ) .
232 '&oldid=' . urlencode( $rev->getId() ) );
233 // Bolden oversighted content
234 if( $rev->isDeleted( Revision::DELETED_RESTRICTED ) )
235 $del = "<strong>$del</strong>";
236 }
237 $s .= " <tt>(<small>$del</small>)</tt> ";
238 }
239
240 $s .= " $link";
241 $s .= " <span class='history-user'>" . $this->mSkin->revUserTools( $rev, true ) . "</span>";
242
243 if( $row->rev_minor_edit ) {
244 $s .= ' ' . Xml::element( 'span', array( 'class' => 'minor' ), wfMsg( 'minoreditletter') );
245 }
246
247 if ( !is_null( $size = $rev->getSize() ) && $rev->userCan( Revision::DELETED_TEXT ) ) {
248 if ( $size == 0 )
249 $stxt = wfMsgHtml( 'historyempty' );
250 else
251 $stxt = wfMsgExt( 'historysize', array( 'parsemag' ), $wgLang->formatNum( $size ) );
252 $s .= " <span class=\"history-size\">$stxt</span>";
253 }
254
255 $s .= $this->mSkin->revComment( $rev, false, true );
256
257 if ($notificationtimestamp && ($row->rev_timestamp >= $notificationtimestamp)) {
258 $s .= ' <span class="updatedmarker">' . wfMsgHtml( 'updatedmarker' ) . '</span>';
259 }
260 #add blurb about text having been deleted
261 if( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
262 $s .= ' <tt>' . wfMsgHtml( 'deletedrev' ) . '</tt>';
263 }
264
265 $tools = array();
266
267 if ( !is_null( $next ) && is_object( $next ) &&
268 !$rev->isDeleted( Revision::DELETED_TEXT ) &&
269 !$next->rev_deleted & Revision::DELETED_TEXT ) {
270 if( !$this->mTitle->getUserPermissionsErrors( 'rollback', $wgUser )
271 && !$this->mTitle->getUserPermissionsErrors( 'edit', $wgUser )
272 && $latest ) {
273 $tools[] = '<span class="mw-rollback-link">'
274 . $this->mSkin->buildRollbackLink( $rev )
275 . '</span>';
276 }
277
278 if( $this->mTitle->quickUserCan( 'edit' ) ) {
279 $undolink = $this->mSkin->makeKnownLinkObj(
280 $this->mTitle,
281 wfMsgHtml( 'editundo' ),
282 'action=edit&undoafter=' . $next->rev_id . '&undo=' . $rev->getId()
283 );
284 $tools[] = "<span class=\"mw-history-undo\">{$undolink}</span>";
285 }
286 }
287
288 if( $tools ) {
289 $s .= ' (' . implode( ' | ', $tools ) . ')';
290 }
291
292 wfRunHooks( 'PageHistoryLineEnding', array( &$row , &$s ) );
293
294 return "<li>$s</li>\n";
295 }
296
297 /**
298 * Create a link to view this revision of the page
299 * @param Revision $rev
300 * @returns string
301 */
302 function revLink( $rev ) {
303 global $wgLang;
304 $date = $wgLang->timeanddate( wfTimestamp(TS_MW, $rev->getTimestamp()), true );
305 if( $rev->userCan( Revision::DELETED_TEXT ) ) {
306 $link = $this->mSkin->makeKnownLinkObj(
307 $this->mTitle, $date, "oldid=" . $rev->getId() );
308 } else {
309 $link = $date;
310 }
311 if( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
312 return '<span class="history-deleted">' . $link . '</span>';
313 }
314 return $link;
315 }
316
317 /**
318 * Create a diff-to-current link for this revision for this page
319 * @param Revision $rev
320 * @param Bool $latest, this is the latest revision of the page?
321 * @returns string
322 */
323 function curLink( $rev, $latest ) {
324 $cur = $this->message['cur'];
325 if( $latest || !$rev->userCan( Revision::DELETED_TEXT ) ) {
326 return $cur;
327 } else {
328 return $this->mSkin->makeKnownLinkObj(
329 $this->mTitle, $cur,
330 'diff=' . $this->getLatestID() .
331 "&oldid=" . $rev->getId() );
332 }
333 }
334
335 /**
336 * Create a diff-to-previous link for this revision for this page.
337 * @param Revision $prevRev, the previous revision
338 * @param mixed $next, the newer revision
339 * @param int $counter, what row on the history list this is
340 * @returns string
341 */
342 function lastLink( $prevRev, $next, $counter ) {
343 $last = $this->message['last'];
344 # $next may either be a Row, null, or "unkown"
345 $nextRev = is_object($next) ? new Revision( $next ) : $next;
346 if( is_null($next) ) {
347 # Probably no next row
348 return $last;
349 } elseif( $next === 'unknown' ) {
350 # Next row probably exists but is unknown, use an oldid=prev link
351 return $this->mSkin->makeKnownLinkObj(
352 $this->mTitle,
353 $last,
354 "diff=" . $prevRev->getId() . "&oldid=prev" );
355 } elseif( !$prevRev->userCan(Revision::DELETED_TEXT) || !$nextRev->userCan(Revision::DELETED_TEXT) ) {
356 return $last;
357 } else {
358 return $this->mSkin->makeKnownLinkObj(
359 $this->mTitle,
360 $last,
361 "diff=" . $prevRev->getId() . "&oldid={$next->rev_id}"
362 /*,
363 '',
364 '',
365 "tabindex={$counter}"*/ );
366 }
367 }
368
369 /**
370 * Create radio buttons for page history
371 *
372 * @param object $rev Revision
373 * @param bool $firstInList Is this version the first one?
374 * @param int $counter A counter of what row number we're at, counted from the top row = 1.
375 * @return string HTML output for the radio buttons
376 */
377 function diffButtons( $rev, $firstInList, $counter ) {
378 if( $this->linesonpage > 1) {
379 $radio = array(
380 'type' => 'radio',
381 'value' => $rev->getId(),
382 );
383
384 if( !$rev->userCan( Revision::DELETED_TEXT ) ) {
385 $radio['disabled'] = 'disabled';
386 }
387
388 /** @todo: move title texts to javascript */
389 if ( $firstInList ) {
390 $first = Xml::element( 'input', array_merge(
391 $radio,
392 array(
393 'style' => 'visibility:hidden',
394 'name' => 'oldid' ) ) );
395 $checkmark = array( 'checked' => 'checked' );
396 } else {
397 if( $counter == 2 ) {
398 $checkmark = array( 'checked' => 'checked' );
399 } else {
400 $checkmark = array();
401 }
402 $first = Xml::element( 'input', array_merge(
403 $radio,
404 $checkmark,
405 array( 'name' => 'oldid' ) ) );
406 $checkmark = array();
407 }
408 $second = Xml::element( 'input', array_merge(
409 $radio,
410 $checkmark,
411 array( 'name' => 'diff' ) ) );
412 return $first . $second;
413 } else {
414 return '';
415 }
416 }
417
418 /** @todo document */
419 function getLatestId() {
420 if( is_null( $this->mLatestId ) ) {
421 $id = $this->mTitle->getArticleID();
422 $db = wfGetDB( DB_SLAVE );
423 $this->mLatestId = $db->selectField( 'page',
424 "page_latest",
425 array( 'page_id' => $id ),
426 __METHOD__ );
427 }
428 return $this->mLatestId;
429 }
430
431 /**
432 * Fetch an array of revisions, specified by a given limit, offset and
433 * direction. This is now only used by the feeds. It was previously
434 * used by the main UI but that's now handled by the pager.
435 */
436 function fetchRevisions($limit, $offset, $direction) {
437 $dbr = wfGetDB( DB_SLAVE );
438
439 if ($direction == PageHistory::DIR_PREV)
440 list($dirs, $oper) = array("ASC", ">=");
441 else /* $direction == PageHistory::DIR_NEXT */
442 list($dirs, $oper) = array("DESC", "<=");
443
444 if ($offset)
445 $offsets = array("rev_timestamp $oper '$offset'");
446 else
447 $offsets = array();
448
449 $page_id = $this->mTitle->getArticleID();
450
451 $res = $dbr->select(
452 'revision',
453 Revision::selectFields(),
454 array_merge(array("rev_page=$page_id"), $offsets),
455 __METHOD__,
456 array('ORDER BY' => "rev_timestamp $dirs",
457 'USE INDEX' => 'page_timestamp', 'LIMIT' => $limit)
458 );
459
460 $result = array();
461 while (($obj = $dbr->fetchObject($res)) != NULL)
462 $result[] = $obj;
463
464 return $result;
465 }
466
467 /** @todo document */
468 function getNotificationTimestamp() {
469 global $wgUser, $wgShowUpdatedMarker;
470
471 if ($this->mNotificationTimestamp !== NULL)
472 return $this->mNotificationTimestamp;
473
474 if ($wgUser->isAnon() || !$wgShowUpdatedMarker)
475 return $this->mNotificationTimestamp = false;
476
477 $dbr = wfGetDB(DB_SLAVE);
478
479 $this->mNotificationTimestamp = $dbr->selectField(
480 'watchlist',
481 'wl_notificationtimestamp',
482 array( 'wl_namespace' => $this->mTitle->getNamespace(),
483 'wl_title' => $this->mTitle->getDBkey(),
484 'wl_user' => $wgUser->getID()
485 ),
486 __METHOD__ );
487
488 // Don't use the special value reserved for telling whether the field is filled
489 if ( is_null( $this->mNotificationTimestamp ) ) {
490 $this->mNotificationTimestamp = false;
491 }
492
493 return $this->mNotificationTimestamp;
494 }
495
496 /**
497 * Output a subscription feed listing recent edits to this page.
498 * @param string $type
499 */
500 function feed( $type ) {
501 require_once 'SpecialRecentchanges.php';
502
503 global $wgFeed, $wgFeedClasses;
504
505 if ( !$wgFeed ) {
506 global $wgOut;
507 $wgOut->addWikiMsg( 'feed-unavailable' );
508 return;
509 }
510
511 if( !isset( $wgFeedClasses[$type] ) ) {
512 global $wgOut;
513 $wgOut->addWikiMsg( 'feed-invalid' );
514 return;
515 }
516
517 $feed = new $wgFeedClasses[$type](
518 $this->mTitle->getPrefixedText() . ' - ' .
519 wfMsgForContent( 'history-feed-title' ),
520 wfMsgForContent( 'history-feed-description' ),
521 $this->mTitle->getFullUrl( 'action=history' ) );
522
523 $items = $this->fetchRevisions(10, 0, PageHistory::DIR_NEXT);
524 $feed->outHeader();
525 if( $items ) {
526 foreach( $items as $row ) {
527 $feed->outItem( $this->feedItem( $row ) );
528 }
529 } else {
530 $feed->outItem( $this->feedEmpty() );
531 }
532 $feed->outFooter();
533 }
534
535 function feedEmpty() {
536 global $wgOut;
537 return new FeedItem(
538 wfMsgForContent( 'nohistory' ),
539 $wgOut->parse( wfMsgForContent( 'history-feed-empty' ) ),
540 $this->mTitle->getFullUrl(),
541 wfTimestamp( TS_MW ),
542 '',
543 $this->mTitle->getTalkPage()->getFullUrl() );
544 }
545
546 /**
547 * Generate a FeedItem object from a given revision table row
548 * Borrows Recent Changes' feed generation functions for formatting;
549 * includes a diff to the previous revision (if any).
550 *
551 * @param $row
552 * @return FeedItem
553 */
554 function feedItem( $row ) {
555 $rev = new Revision( $row );
556 $rev->setTitle( $this->mTitle );
557 $text = rcFormatDiffRow( $this->mTitle,
558 $this->mTitle->getPreviousRevisionID( $rev->getId() ),
559 $rev->getId(),
560 $rev->getTimestamp(),
561 $rev->getComment() );
562
563 if( $rev->getComment() == '' ) {
564 global $wgContLang;
565 $title = wfMsgForContent( 'history-feed-item-nocomment',
566 $rev->getUserText(),
567 $wgContLang->timeanddate( $rev->getTimestamp() ) );
568 } else {
569 $title = $rev->getUserText() . ": " . $this->stripComment( $rev->getComment() );
570 }
571
572 return new FeedItem(
573 $title,
574 $text,
575 $this->mTitle->getFullUrl( 'diff=' . $rev->getId() . '&oldid=prev' ),
576 $rev->getTimestamp(),
577 $rev->getUserText(),
578 $this->mTitle->getTalkPage()->getFullUrl() );
579 }
580
581 /**
582 * Quickie hack... strip out wikilinks to more legible form from the comment.
583 */
584 function stripComment( $text ) {
585 return preg_replace( '/\[\[([^]]*\|)?([^]]+)\]\]/', '\2', $text );
586 }
587 }
588
589
590 /**
591 * @addtogroup Pager
592 */
593 class PageHistoryPager extends ReverseChronologicalPager {
594 public $mLastRow = false, $mPageHistory;
595
596 function __construct( $pageHistory ) {
597 parent::__construct();
598 $this->mPageHistory = $pageHistory;
599 }
600
601 function getQueryInfo() {
602 return array(
603 'tables' => 'revision',
604 'fields' => Revision::selectFields(),
605 'conds' => array('rev_page' => $this->mPageHistory->mTitle->getArticleID() ),
606 'options' => array( 'USE INDEX' => 'page_timestamp' )
607 );
608 }
609
610 function getIndexField() {
611 return 'rev_timestamp';
612 }
613
614 function formatRow( $row ) {
615 if ( $this->mLastRow ) {
616 $latest = $this->mCounter == 1 && $this->mIsFirst;
617 $firstInList = $this->mCounter == 1;
618 $s = $this->mPageHistory->historyLine( $this->mLastRow, $row, $this->mCounter++,
619 $this->mPageHistory->getNotificationTimestamp(), $latest, $firstInList );
620 } else {
621 $s = '';
622 }
623 $this->mLastRow = $row;
624 return $s;
625 }
626
627 function getStartBody() {
628 $this->mLastRow = false;
629 $this->mCounter = 1;
630 return '';
631 }
632
633 function getEndBody() {
634 if ( $this->mLastRow ) {
635 $latest = $this->mCounter == 1 && $this->mIsFirst;
636 $firstInList = $this->mCounter == 1;
637 if ( $this->mIsBackwards ) {
638 # Next row is unknown, but for UI reasons, probably exists if an offset has been specified
639 if ( $this->mOffset == '' ) {
640 $next = null;
641 } else {
642 $next = 'unknown';
643 }
644 } else {
645 # The next row is the past-the-end row
646 $next = $this->mPastTheEndRow;
647 }
648 $s = $this->mPageHistory->historyLine( $this->mLastRow, $next, $this->mCounter++,
649 $this->mPageHistory->getNotificationTimestamp(), $latest, $firstInList );
650 } else {
651 $s = '';
652 }
653 return $s;
654 }
655 }