* (bug 6314) Add user tool links on page histories
[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 * @package MediaWiki
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 * @package MediaWiki
18 */
19
20 class PageHistory {
21 const DIR_PREV = 0;
22 const DIR_NEXT = 1;
23
24 var $mArticle, $mTitle, $mSkin;
25 var $lastdate;
26 var $linesonpage;
27 var $mNotificationTimestamp;
28 var $mLatestId = null;
29
30 /**
31 * Construct a new PageHistory.
32 *
33 * @param Article $article
34 * @returns nothing
35 */
36 function PageHistory($article) {
37 global $wgUser;
38
39 $this->mArticle =& $article;
40 $this->mTitle =& $article->mTitle;
41 $this->mNotificationTimestamp = NULL;
42 $this->mSkin = $wgUser->getSkin();
43
44 $this->defaultLimit = 50;
45 }
46
47 /**
48 * Print the history page for an article.
49 *
50 * @returns nothing
51 */
52 function history() {
53 global $wgOut, $wgRequest, $wgTitle;
54
55 /*
56 * Allow client caching.
57 */
58
59 if( $wgOut->checkLastModified( $this->mArticle->getTimestamp() ) )
60 /* Client cache fresh and headers sent, nothing more to do. */
61 return;
62
63 $fname = 'PageHistory::history';
64 wfProfileIn( $fname );
65
66 /*
67 * Setup page variables.
68 */
69 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
70 $wgOut->setSubtitle( wfMsg( 'revhistory' ) );
71 $wgOut->setArticleFlag( false );
72 $wgOut->setArticleRelated( true );
73 $wgOut->setRobotpolicy( 'noindex,nofollow' );
74 $wgOut->setSyndicated( true );
75
76 $feedType = $wgRequest->getVal( 'feed' );
77 if( $feedType ) {
78 wfProfileOut( $fname );
79 return $this->feed( $feedType );
80 }
81
82 /*
83 * Fail if article doesn't exist.
84 */
85 if( !$this->mTitle->exists() ) {
86 $wgOut->addWikiText( wfMsg( 'nohistory' ) );
87 wfProfileOut( $fname );
88 return;
89 }
90
91 $dbr =& wfGetDB(DB_SLAVE);
92
93 /*
94 * Extract limit, the number of revisions to show, and
95 * offset, the timestamp to begin at, from the URL.
96 */
97 $limit = $wgRequest->getInt('limit', $this->defaultLimit);
98 if ( $limit <= 0 ) {
99 $limit = $this->defaultLimit;
100 } elseif ( $limit > 50000 ) {
101 # Arbitrary maximum
102 # Any more than this and we'll probably get an out of memory error
103 $limit = 50000;
104 }
105
106 $offset = $wgRequest->getText('offset');
107
108 /* Offset must be an integral. */
109 if (!strlen($offset) || !preg_match("/^[0-9]+$/", $offset))
110 $offset = 0;
111 # $offset = $dbr->timestamp($offset);
112 $dboffset = $offset === 0 ? 0 : $dbr->timestamp($offset);
113 /*
114 * "go=last" means to jump to the last history page.
115 */
116 if (($gowhere = $wgRequest->getText("go")) !== NULL) {
117 $gourl = null;
118 switch ($gowhere) {
119 case "first":
120 if (($lastid = $this->getLastOffsetForPaging($this->mTitle->getArticleID(), $limit)) === NULL)
121 break;
122 $gourl = $wgTitle->getLocalURL("action=history&limit={$limit}&offset=".
123 wfTimestamp(TS_MW, $lastid));
124 break;
125 }
126
127 if (!is_null($gourl)) {
128 $wgOut->redirect($gourl);
129 return;
130 }
131 }
132
133 /*
134 * Fetch revisions.
135 *
136 * If the user clicked "previous", we retrieve the revisions backwards,
137 * then reverse them. This is to avoid needing to know the timestamp of
138 * previous revisions when generating the URL.
139 */
140 $direction = $this->getDirection();
141 $revisions = $this->fetchRevisions($limit, $dboffset, $direction);
142 $navbar = $this->makeNavbar($revisions, $offset, $limit, $direction);
143
144 /*
145 * We fetch one more revision than needed to get the timestamp of the
146 * one after this page (and to know if it exists).
147 *
148 * linesonpage stores the actual number of lines.
149 */
150 if (count($revisions) < $limit + 1)
151 $this->linesonpage = count($revisions);
152 else
153 $this->linesonpage = count($revisions) - 1;
154
155 /* Un-reverse revisions */
156 if ($direction == PageHistory::DIR_PREV)
157 $revisions = array_reverse($revisions);
158
159 /*
160 * Print the top navbar.
161 */
162 $s = $navbar;
163 $s .= $this->beginHistoryList();
164 $counter = 1;
165
166 /*
167 * Print each revision, excluding the one-past-the-end, if any.
168 */
169 foreach (array_slice($revisions, 0, $limit) as $i => $line) {
170 $latest = !$i && $offset == 0;
171 $firstInList = !$i;
172 $next = isset( $revisions[$i + 1] ) ? $revisions[$i + 1 ] : null;
173 $s .= $this->historyLine($line, $next, $counter, $this->getNotificationTimestamp(), $latest, $firstInList);
174 $counter++;
175 }
176
177 /*
178 * End navbar.
179 */
180 $s .= $this->endHistoryList();
181 $s .= $navbar;
182
183 $wgOut->addHTML( $s );
184 wfProfileOut( $fname );
185 }
186
187 /** @todo document */
188 function beginHistoryList() {
189 global $wgTitle;
190 $this->lastdate = '';
191 $s = wfMsgExt( 'histlegend', array( 'parse') );
192 $s .= '<form action="' . $wgTitle->escapeLocalURL( '-' ) . '" method="get">';
193 $prefixedkey = htmlspecialchars($wgTitle->getPrefixedDbKey());
194
195 // The following line is SUPPOSED to have double-quotes around the
196 // $prefixedkey variable, because htmlspecialchars() doesn't escape
197 // single-quotes.
198 //
199 // On at least two occasions people have changed it to single-quotes,
200 // which creates invalid HTML and incorrect display of the resulting
201 // link.
202 //
203 // Please do not break this a third time. Thank you for your kind
204 // consideration and cooperation.
205 //
206 $s .= "<input type='hidden' name='title' value=\"{$prefixedkey}\" />\n";
207
208 $s .= $this->submitButton();
209 $s .= '<ul id="pagehistory">' . "\n";
210 return $s;
211 }
212
213 /** @todo document */
214 function endHistoryList() {
215 $s = '</ul>';
216 $s .= $this->submitButton( array( 'id' => 'historysubmit' ) );
217 $s .= '</form>';
218 return $s;
219 }
220
221 /** @todo document */
222 function submitButton( $bits = array() ) {
223 return ( $this->linesonpage > 0 )
224 ? wfElement( 'input', array_merge( $bits,
225 array(
226 'class' => 'historysubmit',
227 'type' => 'submit',
228 'accesskey' => wfMsg( 'accesskey-compareselectedversions' ),
229 'title' => wfMsg( 'tooltip-compareselectedversions' ),
230 'value' => wfMsg( 'compareselectedversions' ),
231 ) ) )
232 : '';
233 }
234
235 /** @todo document */
236 function historyLine( $row, $next, $counter = '', $notificationtimestamp = false, $latest = false, $firstInList = false ) {
237 global $wgUser;
238 $rev = new Revision( $row );
239 $rev->setTitle( $this->mTitle );
240
241 $s = '<li>';
242 $curlink = $this->curLink( $rev, $latest );
243 $lastlink = $this->lastLink( $rev, $next, $counter );
244 $arbitrary = $this->diffButtons( $rev, $firstInList, $counter );
245 $link = $this->revLink( $rev );
246
247 $user = $this->mSkin->userLink( $rev->getUser(), $rev->getUserText() )
248 . $this->mSkin->userToolLinks( $rev->getUser(), $rev->getUserText() );
249
250 $s .= "($curlink) ($lastlink) $arbitrary";
251
252 if( $wgUser->isAllowed( 'deleterevision' ) ) {
253 $revdel = Title::makeTitle( NS_SPECIAL, 'Revisiondelete' );
254 if( $firstInList ) {
255 // We don't currently handle well changing the top revision's settings
256 $del = wfMsgHtml( 'rev-delundel' );
257 } else {
258 $del = $this->mSkin->makeKnownLinkObj( $revdel,
259 wfMsg( 'rev-delundel' ),
260 'target=' . urlencode( $this->mTitle->getPrefixedDbkey() ) .
261 '&oldid=' . urlencode( $rev->getId() ) );
262 }
263 $s .= "(<small>$del</small>) ";
264 }
265
266 $s .= " $link <span class='history-user'>$user</span>";
267
268 if( $row->rev_minor_edit ) {
269 $s .= ' ' . wfElement( 'span', array( 'class' => 'minor' ), wfMsg( 'minoreditletter') );
270 }
271
272 $s .= $this->mSkin->revComment( $rev );
273 if ($notificationtimestamp && ($row->rev_timestamp >= $notificationtimestamp)) {
274 $s .= ' <span class="updatedmarker">' . wfMsgHtml( 'updatedmarker' ) . '</span>';
275 }
276 if( $row->rev_deleted & Revision::DELETED_TEXT ) {
277 $s .= ' ' . wfMsgHtml( 'deletedrev' );
278 }
279 $s .= "</li>\n";
280
281 return $s;
282 }
283
284 /** @todo document */
285 function revLink( $rev ) {
286 global $wgLang;
287 $date = $wgLang->timeanddate( wfTimestamp(TS_MW, $rev->getTimestamp()), true );
288 if( $rev->userCan( Revision::DELETED_TEXT ) ) {
289 $link = $this->mSkin->makeKnownLinkObj(
290 $this->mTitle, $date, "oldid=" . $rev->getId() );
291 } else {
292 $link = $date;
293 }
294 if( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
295 return '<span class="history-deleted">' . $link . '</span>';
296 }
297 return $link;
298 }
299
300 /** @todo document */
301 function curLink( $rev, $latest ) {
302 $cur = wfMsgExt( 'cur', array( 'escape') );
303 if( $latest || !$rev->userCan( Revision::DELETED_TEXT ) ) {
304 return $cur;
305 } else {
306 return $this->mSkin->makeKnownLinkObj(
307 $this->mTitle, $cur,
308 'diff=' . $this->getLatestID() .
309 "&oldid=" . $rev->getId() );
310 }
311 }
312
313 /** @todo document */
314 function lastLink( $rev, $next, $counter ) {
315 $last = wfMsgExt( 'last', array( 'escape' ) );
316 if( is_null( $next ) ) {
317 if( $rev->getTimestamp() == $this->getEarliestOffset() ) {
318 return $last;
319 } else {
320 // Cut off by paging; there are more behind us...
321 return $this->mSkin->makeKnownLinkObj(
322 $this->mTitle,
323 $last,
324 "diff=" . $rev->getId() . "&oldid=prev" );
325 }
326 } elseif( !$rev->userCan( Revision::DELETED_TEXT ) ) {
327 return $last;
328 } else {
329 return $this->mSkin->makeKnownLinkObj(
330 $this->mTitle,
331 $last,
332 "diff=" . $rev->getId() . "&oldid={$next->rev_id}"
333 /*,
334 '',
335 '',
336 "tabindex={$counter}"*/ );
337 }
338 }
339
340 /** @todo document */
341 function diffButtons( $rev, $firstInList, $counter ) {
342 if( $this->linesonpage > 1) {
343 $radio = array(
344 'type' => 'radio',
345 'value' => $rev->getId(),
346 # do we really need to flood this on every item?
347 # 'title' => wfMsgHtml( 'selectolderversionfordiff' )
348 );
349
350 if( !$rev->userCan( Revision::DELETED_TEXT ) ) {
351 $radio['disabled'] = 'disabled';
352 }
353
354 /** @todo: move title texts to javascript */
355 if ( $firstInList ) {
356 $first = wfElement( 'input', array_merge(
357 $radio,
358 array(
359 'style' => 'visibility:hidden',
360 'name' => 'oldid' ) ) );
361 $checkmark = array( 'checked' => 'checked' );
362 } else {
363 if( $counter == 2 ) {
364 $checkmark = array( 'checked' => 'checked' );
365 } else {
366 $checkmark = array();
367 }
368 $first = wfElement( 'input', array_merge(
369 $radio,
370 $checkmark,
371 array( 'name' => 'oldid' ) ) );
372 $checkmark = array();
373 }
374 $second = wfElement( 'input', array_merge(
375 $radio,
376 $checkmark,
377 array( 'name' => 'diff' ) ) );
378 return $first . $second;
379 } else {
380 return '';
381 }
382 }
383
384 /** @todo document */
385 function getLatestOffset( $id = null ) {
386 if ( $id === null) $id = $this->mTitle->getArticleID();
387 return $this->getExtremeOffset( $id, 'max' );
388 }
389
390 /** @todo document */
391 function getEarliestOffset( $id = null ) {
392 if ( $id === null) $id = $this->mTitle->getArticleID();
393 return $this->getExtremeOffset( $id, 'min' );
394 }
395
396 /** @todo document */
397 function getExtremeOffset( $id, $func ) {
398 $db =& wfGetDB(DB_SLAVE);
399 return $db->selectField( 'revision',
400 "$func(rev_timestamp)",
401 array( 'rev_page' => $id ),
402 'PageHistory::getExtremeOffset' );
403 }
404
405 /** @todo document */
406 function getLatestId() {
407 if( is_null( $this->mLatestId ) ) {
408 $id = $this->mTitle->getArticleID();
409 $db =& wfGetDB(DB_SLAVE);
410 $this->mLatestId = $db->selectField( 'revision',
411 "max(rev_id)",
412 array( 'rev_page' => $id ),
413 'PageHistory::getLatestID' );
414 }
415 return $this->mLatestId;
416 }
417
418 /** @todo document */
419 function getLastOffsetForPaging( $id, $step ) {
420 $fname = 'PageHistory::getLastOffsetForPaging';
421
422 $dbr =& wfGetDB(DB_SLAVE);
423 $res = $dbr->select(
424 'revision',
425 'rev_timestamp',
426 "rev_page=$id",
427 $fname,
428 array('ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => $step));
429
430 $n = $dbr->numRows( $res );
431 $last = null;
432 while( $obj = $dbr->fetchObject( $res ) ) {
433 $last = $obj->rev_timestamp;
434 }
435 $dbr->freeResult( $res );
436 return $last;
437 }
438
439 /**
440 * @return returns the direction of browsing watchlist
441 */
442 function getDirection() {
443 global $wgRequest;
444 if ($wgRequest->getText("dir") == "prev")
445 return PageHistory::DIR_PREV;
446 else
447 return PageHistory::DIR_NEXT;
448 }
449
450 /** @todo document */
451 function fetchRevisions($limit, $offset, $direction) {
452 $fname = 'PageHistory::fetchRevisions';
453
454 $dbr =& wfGetDB( DB_SLAVE );
455
456 if ($direction == PageHistory::DIR_PREV)
457 list($dirs, $oper) = array("ASC", ">=");
458 else /* $direction == PageHistory::DIR_NEXT */
459 list($dirs, $oper) = array("DESC", "<=");
460
461 if ($offset)
462 $offsets = array("rev_timestamp $oper '$offset'");
463 else
464 $offsets = array();
465
466 $page_id = $this->mTitle->getArticleID();
467
468 $res = $dbr->select(
469 'revision',
470 array('rev_id', 'rev_page', 'rev_text_id', 'rev_user', 'rev_comment', 'rev_user_text',
471 'rev_timestamp', 'rev_minor_edit', 'rev_deleted'),
472 array_merge(array("rev_page=$page_id"), $offsets),
473 $fname,
474 array('ORDER BY' => "rev_timestamp $dirs",
475 'USE INDEX' => 'page_timestamp', 'LIMIT' => $limit)
476 );
477
478 $result = array();
479 while (($obj = $dbr->fetchObject($res)) != NULL)
480 $result[] = $obj;
481
482 return $result;
483 }
484
485 /** @todo document */
486 function getNotificationTimestamp() {
487 global $wgUser, $wgShowUpdatedMarker;
488 $fname = 'PageHistory::getNotficationTimestamp';
489
490 if ($this->mNotificationTimestamp !== NULL)
491 return $this->mNotificationTimestamp;
492
493 if ($wgUser->isAnon() || !$wgShowUpdatedMarker)
494 return $this->mNotificationTimestamp = false;
495
496 $dbr =& wfGetDB(DB_SLAVE);
497
498 $this->mNotificationTimestamp = $dbr->selectField(
499 'watchlist',
500 'wl_notificationtimestamp',
501 array( 'wl_namespace' => $this->mTitle->getNamespace(),
502 'wl_title' => $this->mTitle->getDBkey(),
503 'wl_user' => $wgUser->getID()
504 ),
505 $fname);
506
507 // Don't use the special value reserved for telling whether the field is filled
508 if ( is_null( $this->mNotificationTimestamp ) ) {
509 $this->mNotificationTimestamp = false;
510 }
511
512 return $this->mNotificationTimestamp;
513 }
514
515 /** @todo document */
516 function makeNavbar($revisions, $offset, $limit, $direction) {
517 global $wgLang;
518
519 $revisions = array_slice($revisions, 0, $limit);
520
521 $latestTimestamp = wfTimestamp(TS_MW, $this->getLatestOffset());
522 $earliestTimestamp = wfTimestamp(TS_MW, $this->getEarliestOffset());
523
524 /*
525 * When we're displaying previous revisions, we need to reverse
526 * the array, because it's queried in reverse order.
527 */
528 if ($direction == PageHistory::DIR_PREV)
529 $revisions = array_reverse($revisions);
530
531 /*
532 * lowts is the timestamp of the first revision on this page.
533 * hights is the timestamp of the last revision.
534 */
535
536 $lowts = $hights = 0;
537
538 if( count( $revisions ) ) {
539 $latestShown = wfTimestamp(TS_MW, $revisions[0]->rev_timestamp);
540 $earliestShown = wfTimestamp(TS_MW, $revisions[count($revisions) - 1]->rev_timestamp);
541 } else {
542 $latestShown = null;
543 $earliestShown = null;
544 }
545
546 /* Don't announce the limit everywhere if it's the default */
547 $usefulLimit = $limit == $this->defaultLimit ? '' : $limit;
548
549 $urls = array();
550 foreach (array(20, 50, 100, 250, 500) as $num) {
551 $urls[] = $this->MakeLink( $wgLang->formatNum($num),
552 array('offset' => $offset == 0 ? '' : wfTimestamp(TS_MW, $offset), 'limit' => $num, ) );
553 }
554
555 $bits = implode($urls, ' | ');
556
557 wfDebug("latestShown=$latestShown latestTimestamp=$latestTimestamp\n");
558 if( $latestShown < $latestTimestamp ) {
559 $prevtext = $this->MakeLink( wfMsgHtml("prevn", $limit),
560 array( 'dir' => 'prev', 'offset' => $latestShown, 'limit' => $usefulLimit ) );
561 $lasttext = $this->MakeLink( wfMsgHtml('histlast'),
562 array( 'limit' => $usefulLimit ) );
563 } else {
564 $prevtext = wfMsgHtml("prevn", $limit);
565 $lasttext = wfMsgHtml('histlast');
566 }
567
568 wfDebug("earliestShown=$earliestShown earliestTimestamp=$earliestTimestamp\n");
569 if( $earliestShown > $earliestTimestamp ) {
570 $nexttext = $this->MakeLink( wfMsgHtml("nextn", $limit),
571 array( 'offset' => $earliestShown, 'limit' => $usefulLimit ) );
572 $firsttext = $this->MakeLink( wfMsgHtml('histfirst'),
573 array( 'go' => 'first', 'limit' => $usefulLimit ) );
574 } else {
575 $nexttext = wfMsgHtml("nextn", $limit);
576 $firsttext = wfMsgHtml('histfirst');
577 }
578
579 $firstlast = "($lasttext | $firsttext)";
580
581 return "$firstlast " . wfMsgHtml("viewprevnext", $prevtext, $nexttext, $bits);
582 }
583
584 function MakeLink($text, $query = NULL) {
585 if ( $query === null ) return $text;
586 return $this->mSkin->makeKnownLinkObj(
587 $this->mTitle, $text,
588 wfArrayToCGI( $query, array( 'action' => 'history' )));
589 }
590
591
592 /**
593 * Output a subscription feed listing recent edits to this page.
594 * @param string $type
595 */
596 function feed( $type ) {
597 require_once 'SpecialRecentchanges.php';
598
599 global $wgFeedClasses;
600 if( !isset( $wgFeedClasses[$type] ) ) {
601 global $wgOut;
602 $wgOut->addWikiText( wfMsg( 'feed-invalid' ) );
603 return;
604 }
605
606 $feed = new $wgFeedClasses[$type](
607 $this->mTitle->getPrefixedText() . ' - ' .
608 wfMsgForContent( 'history-feed-title' ),
609 wfMsgForContent( 'history-feed-description' ),
610 $this->mTitle->getFullUrl( 'action=history' ) );
611
612 $items = $this->fetchRevisions(10, 0, PageHistory::DIR_NEXT);
613 $feed->outHeader();
614 if( $items ) {
615 foreach( $items as $row ) {
616 $feed->outItem( $this->feedItem( $row ) );
617 }
618 } else {
619 $feed->outItem( $this->feedEmpty() );
620 }
621 $feed->outFooter();
622 }
623
624 function feedEmpty() {
625 global $wgOut;
626 return new FeedItem(
627 wfMsgForContent( 'nohistory' ),
628 $wgOut->parse( wfMsgForContent( 'history-feed-empty' ) ),
629 $this->mTitle->getFullUrl(),
630 wfTimestamp( TS_MW ),
631 '',
632 $this->mTitle->getTalkPage()->getFullUrl() );
633 }
634
635 /**
636 * Generate a FeedItem object from a given revision table row
637 * Borrows Recent Changes' feed generation functions for formatting;
638 * includes a diff to the previous revision (if any).
639 *
640 * @param $row
641 * @return FeedItem
642 */
643 function feedItem( $row ) {
644 $rev = new Revision( $row );
645 $rev->setTitle( $this->mTitle );
646 $text = rcFormatDiffRow( $this->mTitle,
647 $this->mTitle->getPreviousRevisionID( $rev->getId() ),
648 $rev->getId(),
649 $rev->getTimestamp(),
650 $rev->getComment() );
651
652 if( $rev->getComment() == '' ) {
653 global $wgContLang;
654 $title = wfMsgForContent( 'history-feed-item-nocomment',
655 $rev->getUserText(),
656 $wgContLang->timeanddate( $rev->getTimestamp() ) );
657 } else {
658 $title = $rev->getUserText() . ": " . $this->stripComment( $rev->getComment() );
659 }
660
661 return new FeedItem(
662 $title,
663 $text,
664 $this->mTitle->getFullUrl( 'diff=' . $rev->getId() . '&oldid=prev' ),
665 $rev->getTimestamp(),
666 $rev->getUserText(),
667 $this->mTitle->getTalkPage()->getFullUrl() );
668 }
669
670 /**
671 * Quickie hack... strip out wikilinks to more legible form from the comment.
672 */
673 function stripComment( $text ) {
674 return preg_replace( '/\[\[([^]]*\|)?([^]]+)\]\]/', '\2', $text );
675 }
676
677
678 }
679
680 ?>