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