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