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