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