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