* Respect feed limits
[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 */
7
8 /**
9 * This class handles printing the history page for an article. In order to
10 * be efficient, it uses timestamps rather than offsets for paging, to avoid
11 * costly LIMIT,offset queries.
12 *
13 * Construct it by passing in an Article, and call $h->history() to print the
14 * history.
15 *
16 */
17 class PageHistory {
18 const DIR_PREV = 0;
19 const DIR_NEXT = 1;
20
21 var $mArticle, $mTitle, $mSkin;
22 var $lastdate;
23 var $linesonpage;
24 var $mNotificationTimestamp;
25 var $mLatestId = null;
26
27 /**
28 * Construct a new PageHistory.
29 *
30 * @param Article $article
31 * @returns nothing
32 */
33 function __construct($article) {
34 global $wgUser;
35
36 $this->mArticle =& $article;
37 $this->mTitle =& $article->mTitle;
38 $this->mNotificationTimestamp = NULL;
39 $this->mSkin = $wgUser->getSkin();
40 $this->preCacheMessages();
41 }
42
43 /**
44 * As we use the same small set of messages in various methods and that
45 * they are called often, we call them once and save them in $this->message
46 */
47 function preCacheMessages() {
48 // Precache various messages
49 if( !isset( $this->message ) ) {
50 foreach( explode(' ', 'cur last rev-delundel' ) as $msg ) {
51 $this->message[$msg] = wfMsgExt( $msg, array( 'escape') );
52 }
53 }
54 }
55
56 /**
57 * Print the history page for an article.
58 *
59 * @returns nothing
60 */
61 function history() {
62 global $wgOut, $wgRequest, $wgTitle;
63
64 /*
65 * Allow client caching.
66 */
67
68 if( $wgOut->checkLastModified( $this->mArticle->getTouched() ) )
69 /* Client cache fresh and headers sent, nothing more to do. */
70 return;
71
72 wfProfileIn( __METHOD__ );
73
74 /*
75 * Setup page variables.
76 */
77 $wgOut->setPageTitle( wfMsg( 'history-title', $this->mTitle->getPrefixedText() ) );
78 $wgOut->setPageTitleActionText( wfMsg( 'history_short' ) );
79 $wgOut->setArticleFlag( false );
80 $wgOut->setArticleRelated( true );
81 $wgOut->setRobotpolicy( 'noindex,nofollow' );
82 $wgOut->setSyndicated( true );
83 $wgOut->setFeedAppendQuery( 'action=history' );
84 $wgOut->addScriptFile( 'history.js' );
85
86 $logPage = SpecialPage::getTitleFor( 'Log' );
87 $logLink = $this->mSkin->makeKnownLinkObj( $logPage, wfMsgHtml( 'viewpagelogs' ), 'page=' . $this->mTitle->getPrefixedUrl() );
88 $wgOut->setSubtitle( $logLink );
89
90 $feedType = $wgRequest->getVal( 'feed' );
91 if( $feedType ) {
92 wfProfileOut( __METHOD__ );
93 return $this->feed( $feedType );
94 }
95
96 /*
97 * Fail if article doesn't exist.
98 */
99 if( !$this->mTitle->exists() ) {
100 $wgOut->addWikiMsg( 'nohistory' );
101 wfProfileOut( __METHOD__ );
102 return;
103 }
104
105 /*
106 * "go=first" means to jump to the last (earliest) history page.
107 * This is deprecated, it no longer appears in the user interface
108 */
109 if ( $wgRequest->getText("go") == 'first' ) {
110 $limit = $wgRequest->getInt( 'limit', 50 );
111 global $wgFeedLimit;
112 if( $limit > $wgFeedLimit ) {
113 $limit = $wgFeedLimit;
114 }
115 $wgOut->redirect( $wgTitle->getLocalURL( "action=history&limit={$limit}&dir=prev" ) );
116 return;
117 }
118
119 wfRunHooks( 'PageHistoryBeforeList', array( &$this->mArticle ) );
120
121 /**
122 * Do the list
123 */
124 $pager = new PageHistoryPager( $this );
125 $this->linesonpage = $pager->getNumRows();
126 $wgOut->addHTML(
127 $pager->getNavigationBar() .
128 $this->beginHistoryList() .
129 $pager->getBody() .
130 $this->endHistoryList() .
131 $pager->getNavigationBar()
132 );
133 wfProfileOut( __METHOD__ );
134 }
135
136 /**
137 * Creates begin of history list with a submit button
138 *
139 * @return string HTML output
140 */
141 function beginHistoryList() {
142 global $wgTitle, $wgScript;
143 $this->lastdate = '';
144 $s = wfMsgExt( 'histlegend', array( 'parse') );
145 $s .= Xml::openElement( 'form', array( 'action' => $wgScript ) );
146 $s .= Xml::hidden( 'title', $wgTitle->getPrefixedDbKey() );
147 $s .= $this->submitButton();
148 $s .= '<ul id="pagehistory">' . "\n";
149 return $s;
150 }
151
152 /**
153 * Creates end of history list with a submit button
154 *
155 * @return string HTML output
156 */
157 function endHistoryList() {
158 $s = '</ul>';
159 $s .= $this->submitButton( array( 'id' => 'historysubmit' ) );
160 $s .= '</form>';
161 return $s;
162 }
163
164 /**
165 * Creates a submit button
166 *
167 * @param array $bits optional CSS ID
168 * @return string HTML output for the submit button
169 */
170 function submitButton( $bits = array() ) {
171 # Disable submit button if history has 1 revision only
172 if ( $this->linesonpage > 1 ) {
173 return Xml::submitButton( wfMsg( 'compareselectedversions' ),
174 $bits + array(
175 'class' => 'historysubmit',
176 'accesskey' => wfMsg( 'accesskey-compareselectedversions' ),
177 'title' => wfMsg( 'tooltip-compareselectedversions' ),
178 )
179 );
180 } else {
181 return '';
182 }
183 }
184
185 /**
186 * Returns a row from the history printout.
187 *
188 * @todo document some more, and maybe clean up the code (some params redundant?)
189 *
190 * @param Row $row The database row corresponding to the previous line.
191 * @param mixed $next The database row corresponding to the next line.
192 * @param int $counter Apparently a counter of what row number we're at, counted from the top row = 1.
193 * @param $notificationtimestamp
194 * @param bool $latest Whether this row corresponds to the page's latest revision.
195 * @param bool $firstInList Whether this row corresponds to the first displayed on this history page.
196 * @return string HTML output for the row
197 */
198 function historyLine( $row, $next, $counter = '', $notificationtimestamp = false, $latest = false, $firstInList = false ) {
199 global $wgUser, $wgLang;
200 $rev = new Revision( $row );
201 $rev->setTitle( $this->mTitle );
202
203 $s = '';
204 $curlink = $this->curLink( $rev, $latest );
205 $lastlink = $this->lastLink( $rev, $next, $counter );
206 $arbitrary = $this->diffButtons( $rev, $firstInList, $counter );
207 $link = $this->revLink( $rev );
208
209 $s .= "($curlink) ($lastlink) $arbitrary";
210
211 if( $wgUser->isAllowed( 'deleterevision' ) ) {
212 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
213 if( $firstInList ) {
214 // We don't currently handle well changing the top revision's settings
215 $del = $this->message['rev-delundel'];
216 } else if( !$rev->userCan( Revision::DELETED_RESTRICTED ) ) {
217 // If revision was hidden from sysops
218 $del = $this->message['rev-delundel'];
219 } else {
220 $del = $this->mSkin->makeKnownLinkObj( $revdel,
221 $this->message['rev-delundel'],
222 'target=' . urlencode( $this->mTitle->getPrefixedDbkey() ) .
223 '&oldid=' . urlencode( $rev->getId() ) );
224 // Bolden oversighted content
225 if( $rev->isDeleted( Revision::DELETED_RESTRICTED ) )
226 $del = "<strong>$del</strong>";
227 }
228 $s .= " <tt>(<small>$del</small>)</tt> ";
229 }
230
231 $s .= " $link";
232 $s .= " <span class='history-user'>" . $this->mSkin->revUserTools( $rev, true ) . "</span>";
233
234 if( $row->rev_minor_edit ) {
235 $s .= ' ' . Xml::element( 'span', array( 'class' => 'minor' ), wfMsg( 'minoreditletter') );
236 }
237
238 if ( !is_null( $size = $rev->getSize() ) && $rev->userCan( Revision::DELETED_TEXT ) ) {
239 if ( $size == 0 )
240 $stxt = wfMsgHtml( 'historyempty' );
241 else
242 $stxt = wfMsgExt( 'historysize', array( 'parsemag' ), $wgLang->formatNum( $size ) );
243 $s .= " <span class=\"history-size\">$stxt</span>";
244 }
245
246 $s .= $this->mSkin->revComment( $rev, false, true );
247
248 if ($notificationtimestamp && ($row->rev_timestamp >= $notificationtimestamp)) {
249 $s .= ' <span class="updatedmarker">' . wfMsgHtml( 'updatedmarker' ) . '</span>';
250 }
251 #add blurb about text having been deleted
252 if( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
253 $s .= ' <tt>' . wfMsgHtml( 'deletedrev' ) . '</tt>';
254 }
255
256 $tools = array();
257
258 if ( !is_null( $next ) && is_object( $next ) ) {
259 if( !$this->mTitle->getUserPermissionsErrors( 'rollback', $wgUser )
260 && !$this->mTitle->getUserPermissionsErrors( 'edit', $wgUser )
261 && $latest ) {
262 $tools[] = '<span class="mw-rollback-link">'
263 . $this->mSkin->buildRollbackLink( $rev )
264 . '</span>';
265 }
266
267 if( $this->mTitle->quickUserCan( 'edit' ) &&
268 !$rev->isDeleted( Revision::DELETED_TEXT ) &&
269 !$next->rev_deleted & Revision::DELETED_TEXT ) {
270 $undolink = $this->mSkin->makeKnownLinkObj(
271 $this->mTitle,
272 wfMsgHtml( 'editundo' ),
273 'action=edit&undoafter=' . $next->rev_id . '&undo=' . $rev->getId()
274 );
275 $tools[] = "<span class=\"mw-history-undo\">{$undolink}</span>";
276 }
277 }
278
279 if( $tools ) {
280 $s .= ' (' . implode( ' | ', $tools ) . ')';
281 }
282
283 wfRunHooks( 'PageHistoryLineEnding', array( &$row , &$s ) );
284
285 return "<li>$s</li>\n";
286 }
287
288 /**
289 * Create a link to view this revision of the page
290 * @param Revision $rev
291 * @returns string
292 */
293 function revLink( $rev ) {
294 global $wgLang;
295 $date = $wgLang->timeanddate( wfTimestamp(TS_MW, $rev->getTimestamp()), true );
296 if( $rev->userCan( Revision::DELETED_TEXT ) ) {
297 $link = $this->mSkin->makeKnownLinkObj(
298 $this->mTitle, $date, "oldid=" . $rev->getId() );
299 } else {
300 $link = $date;
301 }
302 if( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
303 return '<span class="history-deleted">' . $link . '</span>';
304 }
305 return $link;
306 }
307
308 /**
309 * Create a diff-to-current link for this revision for this page
310 * @param Revision $rev
311 * @param Bool $latest, this is the latest revision of the page?
312 * @returns string
313 */
314 function curLink( $rev, $latest ) {
315 $cur = $this->message['cur'];
316 if( $latest || !$rev->userCan( Revision::DELETED_TEXT ) ) {
317 return $cur;
318 } else {
319 return $this->mSkin->makeKnownLinkObj(
320 $this->mTitle, $cur,
321 'diff=' . $this->getLatestID() .
322 "&oldid=" . $rev->getId() );
323 }
324 }
325
326 /**
327 * Create a diff-to-previous link for this revision for this page.
328 * @param Revision $prevRev, the previous revision
329 * @param mixed $next, the newer revision
330 * @param int $counter, what row on the history list this is
331 * @returns string
332 */
333 function lastLink( $prevRev, $next, $counter ) {
334 $last = $this->message['last'];
335 # $next may either be a Row, null, or "unkown"
336 $nextRev = is_object($next) ? new Revision( $next ) : $next;
337 if( is_null($next) ) {
338 # Probably no next row
339 return $last;
340 } elseif( $next === 'unknown' ) {
341 # Next row probably exists but is unknown, use an oldid=prev link
342 return $this->mSkin->makeKnownLinkObj(
343 $this->mTitle,
344 $last,
345 "diff=" . $prevRev->getId() . "&oldid=prev" );
346 } elseif( !$prevRev->userCan(Revision::DELETED_TEXT) || !$nextRev->userCan(Revision::DELETED_TEXT) ) {
347 return $last;
348 } else {
349 return $this->mSkin->makeKnownLinkObj(
350 $this->mTitle,
351 $last,
352 "diff=" . $prevRev->getId() . "&oldid={$next->rev_id}"
353 /*,
354 '',
355 '',
356 "tabindex={$counter}"*/ );
357 }
358 }
359
360 /**
361 * Create radio buttons for page history
362 *
363 * @param object $rev Revision
364 * @param bool $firstInList Is this version the first one?
365 * @param int $counter A counter of what row number we're at, counted from the top row = 1.
366 * @return string HTML output for the radio buttons
367 */
368 function diffButtons( $rev, $firstInList, $counter ) {
369 if( $this->linesonpage > 1) {
370 $radio = array(
371 'type' => 'radio',
372 'value' => $rev->getId(),
373 );
374
375 if( !$rev->userCan( Revision::DELETED_TEXT ) ) {
376 $radio['disabled'] = 'disabled';
377 }
378
379 /** @todo: move title texts to javascript */
380 if ( $firstInList ) {
381 $first = Xml::element( 'input', array_merge(
382 $radio,
383 array(
384 'style' => 'visibility:hidden',
385 'name' => 'oldid' ) ) );
386 $checkmark = array( 'checked' => 'checked' );
387 } else {
388 if( $counter == 2 ) {
389 $checkmark = array( 'checked' => 'checked' );
390 } else {
391 $checkmark = array();
392 }
393 $first = Xml::element( 'input', array_merge(
394 $radio,
395 $checkmark,
396 array( 'name' => 'oldid' ) ) );
397 $checkmark = array();
398 }
399 $second = Xml::element( 'input', array_merge(
400 $radio,
401 $checkmark,
402 array( 'name' => 'diff' ) ) );
403 return $first . $second;
404 } else {
405 return '';
406 }
407 }
408
409 /** @todo document */
410 function getLatestId() {
411 if( is_null( $this->mLatestId ) ) {
412 $id = $this->mTitle->getArticleID();
413 $db = wfGetDB( DB_SLAVE );
414 $this->mLatestId = $db->selectField( 'page',
415 "page_latest",
416 array( 'page_id' => $id ),
417 __METHOD__ );
418 }
419 return $this->mLatestId;
420 }
421
422 /**
423 * Fetch an array of revisions, specified by a given limit, offset and
424 * direction. This is now only used by the feeds. It was previously
425 * used by the main UI but that's now handled by the pager.
426 */
427 function fetchRevisions($limit, $offset, $direction) {
428 $dbr = wfGetDB( DB_SLAVE );
429
430 if ($direction == PageHistory::DIR_PREV)
431 list($dirs, $oper) = array("ASC", ">=");
432 else /* $direction == PageHistory::DIR_NEXT */
433 list($dirs, $oper) = array("DESC", "<=");
434
435 if ($offset)
436 $offsets = array("rev_timestamp $oper '$offset'");
437 else
438 $offsets = array();
439
440 $page_id = $this->mTitle->getArticleID();
441
442 $res = $dbr->select(
443 'revision',
444 Revision::selectFields(),
445 array_merge(array("rev_page=$page_id"), $offsets),
446 __METHOD__,
447 array('ORDER BY' => "rev_timestamp $dirs",
448 'USE INDEX' => 'page_timestamp', 'LIMIT' => $limit)
449 );
450
451 $result = array();
452 while (($obj = $dbr->fetchObject($res)) != NULL)
453 $result[] = $obj;
454
455 return $result;
456 }
457
458 /** @todo document */
459 function getNotificationTimestamp() {
460 global $wgUser, $wgShowUpdatedMarker;
461
462 if ($this->mNotificationTimestamp !== NULL)
463 return $this->mNotificationTimestamp;
464
465 if ($wgUser->isAnon() || !$wgShowUpdatedMarker)
466 return $this->mNotificationTimestamp = false;
467
468 $dbr = wfGetDB(DB_SLAVE);
469
470 $this->mNotificationTimestamp = $dbr->selectField(
471 'watchlist',
472 'wl_notificationtimestamp',
473 array( 'wl_namespace' => $this->mTitle->getNamespace(),
474 'wl_title' => $this->mTitle->getDBkey(),
475 'wl_user' => $wgUser->getID()
476 ),
477 __METHOD__ );
478
479 // Don't use the special value reserved for telling whether the field is filled
480 if ( is_null( $this->mNotificationTimestamp ) ) {
481 $this->mNotificationTimestamp = false;
482 }
483
484 return $this->mNotificationTimestamp;
485 }
486
487 /**
488 * Output a subscription feed listing recent edits to this page.
489 * @param string $type
490 */
491 function feed( $type ) {
492 require_once 'SpecialRecentchanges.php';
493
494 global $wgFeed, $wgFeedClasses;
495
496 if ( !$wgFeed ) {
497 global $wgOut;
498 $wgOut->addWikiMsg( 'feed-unavailable' );
499 return;
500 }
501
502 if( !isset( $wgFeedClasses[$type] ) ) {
503 global $wgOut;
504 $wgOut->addWikiMsg( 'feed-invalid' );
505 return;
506 }
507
508 $feed = new $wgFeedClasses[$type](
509 $this->mTitle->getPrefixedText() . ' - ' .
510 wfMsgForContent( 'history-feed-title' ),
511 wfMsgForContent( 'history-feed-description' ),
512 $this->mTitle->getFullUrl( 'action=history' ) );
513
514 $items = $this->fetchRevisions(10, 0, PageHistory::DIR_NEXT);
515 $feed->outHeader();
516 if( $items ) {
517 foreach( $items as $row ) {
518 $feed->outItem( $this->feedItem( $row ) );
519 }
520 } else {
521 $feed->outItem( $this->feedEmpty() );
522 }
523 $feed->outFooter();
524 }
525
526 function feedEmpty() {
527 global $wgOut;
528 return new FeedItem(
529 wfMsgForContent( 'nohistory' ),
530 $wgOut->parse( wfMsgForContent( 'history-feed-empty' ) ),
531 $this->mTitle->getFullUrl(),
532 wfTimestamp( TS_MW ),
533 '',
534 $this->mTitle->getTalkPage()->getFullUrl() );
535 }
536
537 /**
538 * Generate a FeedItem object from a given revision table row
539 * Borrows Recent Changes' feed generation functions for formatting;
540 * includes a diff to the previous revision (if any).
541 *
542 * @param $row
543 * @return FeedItem
544 */
545 function feedItem( $row ) {
546 $rev = new Revision( $row );
547 $rev->setTitle( $this->mTitle );
548 $text = rcFormatDiffRow( $this->mTitle,
549 $this->mTitle->getPreviousRevisionID( $rev->getId() ),
550 $rev->getId(),
551 $rev->getTimestamp(),
552 $rev->getComment() );
553
554 if( $rev->getComment() == '' ) {
555 global $wgContLang;
556 $title = wfMsgForContent( 'history-feed-item-nocomment',
557 $rev->getUserText(),
558 $wgContLang->timeanddate( $rev->getTimestamp() ) );
559 } else {
560 $title = $rev->getUserText() . ": " . $this->stripComment( $rev->getComment() );
561 }
562
563 return new FeedItem(
564 $title,
565 $text,
566 $this->mTitle->getFullUrl( 'diff=' . $rev->getId() . '&oldid=prev' ),
567 $rev->getTimestamp(),
568 $rev->getUserText(),
569 $this->mTitle->getTalkPage()->getFullUrl() );
570 }
571
572 /**
573 * Quickie hack... strip out wikilinks to more legible form from the comment.
574 */
575 function stripComment( $text ) {
576 return preg_replace( '/\[\[([^]]*\|)?([^]]+)\]\]/', '\2', $text );
577 }
578 }
579
580
581 /**
582 * @addtogroup Pager
583 */
584 class PageHistoryPager extends ReverseChronologicalPager {
585 public $mLastRow = false, $mPageHistory;
586
587 function __construct( $pageHistory ) {
588 parent::__construct();
589 $this->mPageHistory = $pageHistory;
590 }
591
592 function getQueryInfo() {
593 return array(
594 'tables' => 'revision',
595 'fields' => Revision::selectFields(),
596 'conds' => array('rev_page' => $this->mPageHistory->mTitle->getArticleID() ),
597 'options' => array( 'USE INDEX' => 'page_timestamp' )
598 );
599 }
600
601 function getIndexField() {
602 return 'rev_timestamp';
603 }
604
605 function formatRow( $row ) {
606 if ( $this->mLastRow ) {
607 $latest = $this->mCounter == 1 && $this->mIsFirst;
608 $firstInList = $this->mCounter == 1;
609 $s = $this->mPageHistory->historyLine( $this->mLastRow, $row, $this->mCounter++,
610 $this->mPageHistory->getNotificationTimestamp(), $latest, $firstInList );
611 } else {
612 $s = '';
613 }
614 $this->mLastRow = $row;
615 return $s;
616 }
617
618 function getStartBody() {
619 $this->mLastRow = false;
620 $this->mCounter = 1;
621 return '';
622 }
623
624 function getEndBody() {
625 if ( $this->mLastRow ) {
626 $latest = $this->mCounter == 1 && $this->mIsFirst;
627 $firstInList = $this->mCounter == 1;
628 if ( $this->mIsBackwards ) {
629 # Next row is unknown, but for UI reasons, probably exists if an offset has been specified
630 if ( $this->mOffset == '' ) {
631 $next = null;
632 } else {
633 $next = 'unknown';
634 }
635 } else {
636 # The next row is the past-the-end row
637 $next = $this->mPastTheEndRow;
638 }
639 $s = $this->mPageHistory->historyLine( $this->mLastRow, $next, $this->mCounter++,
640 $this->mPageHistory->getNotificationTimestamp(), $latest, $firstInList );
641 } else {
642 $s = '';
643 }
644 return $s;
645 }
646 }