Use AutoLoader to load classes:
[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 define('DIR_PREV', 0);
10 define('DIR_NEXT', 1);
11
12 /**
13 * This class handles printing the history page for an article. In order to
14 * be efficient, it uses timestamps rather than offsets for paging, to avoid
15 * costly LIMIT,offset queries.
16 *
17 * Construct it by passing in an Article, and call $h->history() to print the
18 * history.
19 *
20 * @package MediaWiki
21 */
22
23 class PageHistory {
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 == 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
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 & 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( 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( 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( 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( 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( 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 DIR_PREV;
436 else
437 return 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 == DIR_PREV)
447 list($dirs, $oper) = array("ASC", ">=");
448 else /* $direction == 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 return $this->mNotificationTimestamp;
498 }
499
500 /** @todo document */
501 function makeNavbar($revisions, $offset, $limit, $direction) {
502 global $wgLang;
503
504 $revisions = array_slice($revisions, 0, $limit);
505
506 $latestTimestamp = wfTimestamp(TS_MW, $this->getLatestOffset());
507 $earliestTimestamp = wfTimestamp(TS_MW, $this->getEarliestOffset());
508
509 /*
510 * When we're displaying previous revisions, we need to reverse
511 * the array, because it's queried in reverse order.
512 */
513 if ($direction == DIR_PREV)
514 $revisions = array_reverse($revisions);
515
516 /*
517 * lowts is the timestamp of the first revision on this page.
518 * hights is the timestamp of the last revision.
519 */
520
521 $lowts = $hights = 0;
522
523 if( count( $revisions ) ) {
524 $latestShown = wfTimestamp(TS_MW, $revisions[0]->rev_timestamp);
525 $earliestShown = wfTimestamp(TS_MW, $revisions[count($revisions) - 1]->rev_timestamp);
526 }
527
528 /* Don't announce the limit everywhere if it's the default */
529 $usefulLimit = $limit == $this->defaultLimit ? '' : $limit;
530
531 $urls = array();
532 foreach (array(20, 50, 100, 250, 500) as $num) {
533 $urls[] = $this->MakeLink( $wgLang->formatNum($num),
534 array('offset' => $offset == 0 ? '' : wfTimestamp(TS_MW, $offset), 'limit' => $num, ) );
535 }
536
537 $bits = implode($urls, ' | ');
538
539 wfDebug("latestShown=$latestShown latestTimestamp=$latestTimestamp\n");
540 if( $latestShown < $latestTimestamp ) {
541 $prevtext = $this->MakeLink( wfMsgHtml("prevn", $limit),
542 array( 'dir' => 'prev', 'offset' => $latestShown, 'limit' => $usefulLimit ) );
543 $lasttext = $this->MakeLink( wfMsgHtml('histlast'),
544 array( 'limit' => $usefulLimit ) );
545 } else {
546 $prevtext = wfMsgHtml("prevn", $limit);
547 $lasttext = wfMsgHtml('histlast');
548 }
549
550 wfDebug("earliestShown=$earliestShown earliestTimestamp=$earliestTimestamp\n");
551 if( $earliestShown > $earliestTimestamp ) {
552 $nexttext = $this->MakeLink( wfMsgHtml("nextn", $limit),
553 array( 'offset' => $earliestShown, 'limit' => $usefulLimit ) );
554 $firsttext = $this->MakeLink( wfMsgHtml('histfirst'),
555 array( 'go' => 'first', 'limit' => $usefulLimit ) );
556 } else {
557 $nexttext = wfMsgHtml("nextn", $limit);
558 $firsttext = wfMsgHtml('histfirst');
559 }
560
561 $firstlast = "($lasttext | $firsttext)";
562
563 return "$firstlast " . wfMsgHtml("viewprevnext", $prevtext, $nexttext, $bits);
564 }
565
566 function MakeLink($text, $query = NULL) {
567 if ( $query === null ) return $text;
568 return $this->mSkin->makeKnownLinkObj(
569 $this->mTitle, $text,
570 wfArrayToCGI( $query, array( 'action' => 'history' )));
571 }
572
573
574 /**
575 * Output a subscription feed listing recent edits to this page.
576 * @param string $type
577 */
578 function feed( $type ) {
579 global $wgFeedClasses;
580 if( !isset( $wgFeedClasses[$type] ) ) {
581 global $wgOut;
582 $wgOut->addWikiText( wfMsg( 'feed-invalid' ) );
583 return;
584 }
585
586 $feed = new $wgFeedClasses[$type](
587 $this->mTitle->getPrefixedText() . ' - ' .
588 wfMsgForContent( 'history-feed-title' ),
589 wfMsgForContent( 'history-feed-description' ),
590 $this->mTitle->getFullUrl( 'action=history' ) );
591
592 $items = $this->fetchRevisions(10, 0, DIR_NEXT);
593 $feed->outHeader();
594 if( $items ) {
595 foreach( $items as $row ) {
596 $feed->outItem( $this->feedItem( $row ) );
597 }
598 } else {
599 $feed->outItem( $this->feedEmpty() );
600 }
601 $feed->outFooter();
602 }
603
604 function feedEmpty() {
605 global $wgOut;
606 return new FeedItem(
607 wfMsgForContent( 'nohistory' ),
608 $wgOut->parse( wfMsgForContent( 'history-feed-empty' ) ),
609 $this->mTitle->getFullUrl(),
610 wfTimestamp( TS_MW ),
611 '',
612 $this->mTitle->getTalkPage()->getFullUrl() );
613 }
614
615 /**
616 * Generate a FeedItem object from a given revision table row
617 * Borrows Recent Changes' feed generation functions for formatting;
618 * includes a diff to the previous revision (if any).
619 *
620 * @param $row
621 * @return FeedItem
622 */
623 function feedItem( $row ) {
624 $rev = new Revision( $row );
625 $text = rcFormatDiffRow( $this->mTitle,
626 $this->mTitle->getPreviousRevisionID( $rev->getId() ),
627 $rev->getId(),
628 $rev->getTimestamp(),
629 $rev->getComment() );
630
631 if( $rev->getComment() == '' ) {
632 global $wgContLang;
633 $title = wfMsgForContent( 'history-feed-item-nocomment',
634 $rev->getUserText(),
635 $wgContLang->timeanddate( $rev->getTimestamp() ) );
636 } else {
637 $title = $rev->getUserText() . ": " . $this->stripComment( $rev->getComment() );
638 }
639
640 return new FeedItem(
641 $title,
642 $text,
643 $this->mTitle->getFullUrl( 'diff=' . $rev->getId() . '&oldid=prev' ),
644 $rev->getTimestamp(),
645 $rev->getUserText(),
646 $this->mTitle->getTalkPage()->getFullUrl() );
647 }
648
649 /**
650 * Quickie hack... strip out wikilinks to more legible form from the comment.
651 */
652 function stripComment( $text ) {
653 return preg_replace( '/\[\[([^]]*\|)?([^]]+)\]\]/', '\2', $text );
654 }
655
656
657 }
658
659 ?>