bounding for the limit parameter
[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 $user = $this->mSkin->revUserLink( $rev );
247
248 $s .= "($curlink) ($lastlink) $arbitrary";
249
250 if( $wgUser->isAllowed( 'deleterevision' ) ) {
251 $revdel = Title::makeTitle( NS_SPECIAL, 'Revisiondelete' );
252 if( $firstInList ) {
253 // We don't currently handle well changing the top revision's settings
254 $del = wfMsgHtml( 'rev-delundel' );
255 } else {
256 $del = $this->mSkin->makeKnownLinkObj( $revdel,
257 wfMsg( 'rev-delundel' ),
258 'target=' . urlencode( $this->mTitle->getPrefixedDbkey() ) .
259 '&oldid=' . urlencode( $rev->getId() ) );
260 }
261 $s .= "(<small>$del</small>) ";
262 }
263
264 $s .= " $link <span class='history-user'>$user</span>";
265
266 if( $row->rev_minor_edit ) {
267 $s .= ' ' . wfElement( 'span', array( 'class' => 'minor' ), wfMsg( 'minoreditletter') );
268 }
269
270 $s .= $this->mSkin->revComment( $rev );
271 if ($notificationtimestamp && ($row->rev_timestamp >= $notificationtimestamp)) {
272 $s .= ' <span class="updatedmarker">' . wfMsgHtml( 'updatedmarker' ) . '</span>';
273 }
274 if( $row->rev_deleted & Revision::DELETED_TEXT ) {
275 $s .= ' ' . wfMsgHtml( 'deletedrev' );
276 }
277 $s .= "</li>\n";
278
279 return $s;
280 }
281
282 /** @todo document */
283 function revLink( $rev ) {
284 global $wgLang;
285 $date = $wgLang->timeanddate( wfTimestamp(TS_MW, $rev->getTimestamp()), true );
286 if( $rev->userCan( Revision::DELETED_TEXT ) ) {
287 $link = $this->mSkin->makeKnownLinkObj(
288 $this->mTitle, $date, "oldid=" . $rev->getId() );
289 } else {
290 $link = $date;
291 }
292 if( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
293 return '<span class="history-deleted">' . $link . '</span>';
294 }
295 return $link;
296 }
297
298 /** @todo document */
299 function curLink( $rev, $latest ) {
300 $cur = wfMsgExt( 'cur', array( 'escape') );
301 if( $latest || !$rev->userCan( Revision::DELETED_TEXT ) ) {
302 return $cur;
303 } else {
304 return $this->mSkin->makeKnownLinkObj(
305 $this->mTitle, $cur,
306 'diff=' . $this->getLatestID() .
307 "&oldid=" . $rev->getId() );
308 }
309 }
310
311 /** @todo document */
312 function lastLink( $rev, $next, $counter ) {
313 $last = wfMsgExt( 'last', array( 'escape' ) );
314 if( is_null( $next ) ) {
315 if( $rev->getTimestamp() == $this->getEarliestOffset() ) {
316 return $last;
317 } else {
318 // Cut off by paging; there are more behind us...
319 return $this->mSkin->makeKnownLinkObj(
320 $this->mTitle,
321 $last,
322 "diff=" . $rev->getId() . "&oldid=prev" );
323 }
324 } elseif( !$rev->userCan( Revision::DELETED_TEXT ) ) {
325 return $last;
326 } else {
327 return $this->mSkin->makeKnownLinkObj(
328 $this->mTitle,
329 $last,
330 "diff=" . $rev->getId() . "&oldid={$next->rev_id}"
331 /*,
332 '',
333 '',
334 "tabindex={$counter}"*/ );
335 }
336 }
337
338 /** @todo document */
339 function diffButtons( $rev, $firstInList, $counter ) {
340 if( $this->linesonpage > 1) {
341 $radio = array(
342 'type' => 'radio',
343 'value' => $rev->getId(),
344 # do we really need to flood this on every item?
345 # 'title' => wfMsgHtml( 'selectolderversionfordiff' )
346 );
347
348 if( !$rev->userCan( Revision::DELETED_TEXT ) ) {
349 $radio['disabled'] = 'disabled';
350 }
351
352 /** @todo: move title texts to javascript */
353 if ( $firstInList ) {
354 $first = wfElement( 'input', array_merge(
355 $radio,
356 array(
357 'style' => 'visibility:hidden',
358 'name' => 'oldid' ) ) );
359 $checkmark = array( 'checked' => 'checked' );
360 } else {
361 if( $counter == 2 ) {
362 $checkmark = array( 'checked' => 'checked' );
363 } else {
364 $checkmark = array();
365 }
366 $first = wfElement( 'input', array_merge(
367 $radio,
368 $checkmark,
369 array( 'name' => 'oldid' ) ) );
370 $checkmark = array();
371 }
372 $second = wfElement( 'input', array_merge(
373 $radio,
374 $checkmark,
375 array( 'name' => 'diff' ) ) );
376 return $first . $second;
377 } else {
378 return '';
379 }
380 }
381
382 /** @todo document */
383 function getLatestOffset( $id = null ) {
384 if ( $id === null) $id = $this->mTitle->getArticleID();
385 return $this->getExtremeOffset( $id, 'max' );
386 }
387
388 /** @todo document */
389 function getEarliestOffset( $id = null ) {
390 if ( $id === null) $id = $this->mTitle->getArticleID();
391 return $this->getExtremeOffset( $id, 'min' );
392 }
393
394 /** @todo document */
395 function getExtremeOffset( $id, $func ) {
396 $db =& wfGetDB(DB_SLAVE);
397 return $db->selectField( 'revision',
398 "$func(rev_timestamp)",
399 array( 'rev_page' => $id ),
400 'PageHistory::getExtremeOffset' );
401 }
402
403 /** @todo document */
404 function getLatestId() {
405 if( is_null( $this->mLatestId ) ) {
406 $id = $this->mTitle->getArticleID();
407 $db =& wfGetDB(DB_SLAVE);
408 $this->mLatestId = $db->selectField( 'revision',
409 "max(rev_id)",
410 array( 'rev_page' => $id ),
411 'PageHistory::getLatestID' );
412 }
413 return $this->mLatestId;
414 }
415
416 /** @todo document */
417 function getLastOffsetForPaging( $id, $step ) {
418 $fname = 'PageHistory::getLastOffsetForPaging';
419
420 $dbr =& wfGetDB(DB_SLAVE);
421 $res = $dbr->select(
422 'revision',
423 'rev_timestamp',
424 "rev_page=$id",
425 $fname,
426 array('ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => $step));
427
428 $n = $dbr->numRows( $res );
429 $last = null;
430 while( $obj = $dbr->fetchObject( $res ) ) {
431 $last = $obj->rev_timestamp;
432 }
433 $dbr->freeResult( $res );
434 return $last;
435 }
436
437 /**
438 * @return returns the direction of browsing watchlist
439 */
440 function getDirection() {
441 global $wgRequest;
442 if ($wgRequest->getText("dir") == "prev")
443 return PageHistory::DIR_PREV;
444 else
445 return PageHistory::DIR_NEXT;
446 }
447
448 /** @todo document */
449 function fetchRevisions($limit, $offset, $direction) {
450 $fname = 'PageHistory::fetchRevisions';
451
452 $dbr =& wfGetDB( DB_SLAVE );
453
454 if ($direction == PageHistory::DIR_PREV)
455 list($dirs, $oper) = array("ASC", ">=");
456 else /* $direction == PageHistory::DIR_NEXT */
457 list($dirs, $oper) = array("DESC", "<=");
458
459 if ($offset)
460 $offsets = array("rev_timestamp $oper '$offset'");
461 else
462 $offsets = array();
463
464 $page_id = $this->mTitle->getArticleID();
465
466 $res = $dbr->select(
467 'revision',
468 array('rev_id', 'rev_page', 'rev_text_id', 'rev_user', 'rev_comment', 'rev_user_text',
469 'rev_timestamp', 'rev_minor_edit', 'rev_deleted'),
470 array_merge(array("rev_page=$page_id"), $offsets),
471 $fname,
472 array('ORDER BY' => "rev_timestamp $dirs",
473 'USE INDEX' => 'page_timestamp', 'LIMIT' => $limit)
474 );
475
476 $result = array();
477 while (($obj = $dbr->fetchObject($res)) != NULL)
478 $result[] = $obj;
479
480 return $result;
481 }
482
483 /** @todo document */
484 function getNotificationTimestamp() {
485 global $wgUser, $wgShowUpdatedMarker;
486 $fname = 'PageHistory::getNotficationTimestamp';
487
488 if ($this->mNotificationTimestamp !== NULL)
489 return $this->mNotificationTimestamp;
490
491 if ($wgUser->isAnon() || !$wgShowUpdatedMarker)
492 return $this->mNotificationTimestamp = false;
493
494 $dbr =& wfGetDB(DB_SLAVE);
495
496 $this->mNotificationTimestamp = $dbr->selectField(
497 'watchlist',
498 'wl_notificationtimestamp',
499 array( 'wl_namespace' => $this->mTitle->getNamespace(),
500 'wl_title' => $this->mTitle->getDBkey(),
501 'wl_user' => $wgUser->getID()
502 ),
503 $fname);
504
505 // Don't use the special value reserved for telling whether the field is filled
506 if ( is_null( $this->mNotificationTimestamp ) ) {
507 $this->mNotificationTimestamp = false;
508 }
509
510 return $this->mNotificationTimestamp;
511 }
512
513 /** @todo document */
514 function makeNavbar($revisions, $offset, $limit, $direction) {
515 global $wgLang;
516
517 $revisions = array_slice($revisions, 0, $limit);
518
519 $latestTimestamp = wfTimestamp(TS_MW, $this->getLatestOffset());
520 $earliestTimestamp = wfTimestamp(TS_MW, $this->getEarliestOffset());
521
522 /*
523 * When we're displaying previous revisions, we need to reverse
524 * the array, because it's queried in reverse order.
525 */
526 if ($direction == PageHistory::DIR_PREV)
527 $revisions = array_reverse($revisions);
528
529 /*
530 * lowts is the timestamp of the first revision on this page.
531 * hights is the timestamp of the last revision.
532 */
533
534 $lowts = $hights = 0;
535
536 if( count( $revisions ) ) {
537 $latestShown = wfTimestamp(TS_MW, $revisions[0]->rev_timestamp);
538 $earliestShown = wfTimestamp(TS_MW, $revisions[count($revisions) - 1]->rev_timestamp);
539 } else {
540 $latestShown = null;
541 $earliestShown = null;
542 }
543
544 /* Don't announce the limit everywhere if it's the default */
545 $usefulLimit = $limit == $this->defaultLimit ? '' : $limit;
546
547 $urls = array();
548 foreach (array(20, 50, 100, 250, 500) as $num) {
549 $urls[] = $this->MakeLink( $wgLang->formatNum($num),
550 array('offset' => $offset == 0 ? '' : wfTimestamp(TS_MW, $offset), 'limit' => $num, ) );
551 }
552
553 $bits = implode($urls, ' | ');
554
555 wfDebug("latestShown=$latestShown latestTimestamp=$latestTimestamp\n");
556 if( $latestShown < $latestTimestamp ) {
557 $prevtext = $this->MakeLink( wfMsgHtml("prevn", $limit),
558 array( 'dir' => 'prev', 'offset' => $latestShown, 'limit' => $usefulLimit ) );
559 $lasttext = $this->MakeLink( wfMsgHtml('histlast'),
560 array( 'limit' => $usefulLimit ) );
561 } else {
562 $prevtext = wfMsgHtml("prevn", $limit);
563 $lasttext = wfMsgHtml('histlast');
564 }
565
566 wfDebug("earliestShown=$earliestShown earliestTimestamp=$earliestTimestamp\n");
567 if( $earliestShown > $earliestTimestamp ) {
568 $nexttext = $this->MakeLink( wfMsgHtml("nextn", $limit),
569 array( 'offset' => $earliestShown, 'limit' => $usefulLimit ) );
570 $firsttext = $this->MakeLink( wfMsgHtml('histfirst'),
571 array( 'go' => 'first', 'limit' => $usefulLimit ) );
572 } else {
573 $nexttext = wfMsgHtml("nextn", $limit);
574 $firsttext = wfMsgHtml('histfirst');
575 }
576
577 $firstlast = "($lasttext | $firsttext)";
578
579 return "$firstlast " . wfMsgHtml("viewprevnext", $prevtext, $nexttext, $bits);
580 }
581
582 function MakeLink($text, $query = NULL) {
583 if ( $query === null ) return $text;
584 return $this->mSkin->makeKnownLinkObj(
585 $this->mTitle, $text,
586 wfArrayToCGI( $query, array( 'action' => 'history' )));
587 }
588
589
590 /**
591 * Output a subscription feed listing recent edits to this page.
592 * @param string $type
593 */
594 function feed( $type ) {
595 require_once 'SpecialRecentchanges.php';
596
597 global $wgFeedClasses;
598 if( !isset( $wgFeedClasses[$type] ) ) {
599 global $wgOut;
600 $wgOut->addWikiText( wfMsg( 'feed-invalid' ) );
601 return;
602 }
603
604 $feed = new $wgFeedClasses[$type](
605 $this->mTitle->getPrefixedText() . ' - ' .
606 wfMsgForContent( 'history-feed-title' ),
607 wfMsgForContent( 'history-feed-description' ),
608 $this->mTitle->getFullUrl( 'action=history' ) );
609
610 $items = $this->fetchRevisions(10, 0, PageHistory::DIR_NEXT);
611 $feed->outHeader();
612 if( $items ) {
613 foreach( $items as $row ) {
614 $feed->outItem( $this->feedItem( $row ) );
615 }
616 } else {
617 $feed->outItem( $this->feedEmpty() );
618 }
619 $feed->outFooter();
620 }
621
622 function feedEmpty() {
623 global $wgOut;
624 return new FeedItem(
625 wfMsgForContent( 'nohistory' ),
626 $wgOut->parse( wfMsgForContent( 'history-feed-empty' ) ),
627 $this->mTitle->getFullUrl(),
628 wfTimestamp( TS_MW ),
629 '',
630 $this->mTitle->getTalkPage()->getFullUrl() );
631 }
632
633 /**
634 * Generate a FeedItem object from a given revision table row
635 * Borrows Recent Changes' feed generation functions for formatting;
636 * includes a diff to the previous revision (if any).
637 *
638 * @param $row
639 * @return FeedItem
640 */
641 function feedItem( $row ) {
642 $rev = new Revision( $row );
643 $rev->setTitle( $this->mTitle );
644 $text = rcFormatDiffRow( $this->mTitle,
645 $this->mTitle->getPreviousRevisionID( $rev->getId() ),
646 $rev->getId(),
647 $rev->getTimestamp(),
648 $rev->getComment() );
649
650 if( $rev->getComment() == '' ) {
651 global $wgContLang;
652 $title = wfMsgForContent( 'history-feed-item-nocomment',
653 $rev->getUserText(),
654 $wgContLang->timeanddate( $rev->getTimestamp() ) );
655 } else {
656 $title = $rev->getUserText() . ": " . $this->stripComment( $rev->getComment() );
657 }
658
659 return new FeedItem(
660 $title,
661 $text,
662 $this->mTitle->getFullUrl( 'diff=' . $rev->getId() . '&oldid=prev' ),
663 $rev->getTimestamp(),
664 $rev->getUserText(),
665 $this->mTitle->getTalkPage()->getFullUrl() );
666 }
667
668 /**
669 * Quickie hack... strip out wikilinks to more legible form from the comment.
670 */
671 function stripComment( $text ) {
672 return preg_replace( '/\[\[([^]]*\|)?([^]]+)\]\]/', '\2', $text );
673 }
674
675
676 }
677
678 ?>