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