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