* Fix some misuse of message functions
[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 = wfMsg( 'historyempty' );
250 } else {
251 $stxt = wfMsg( 'nbytes', $wgLang->formatNum( $size ) );
252 $stxt = "($stxt)";
253 }
254 $stxt = htmlspecialchars( $stxt );
255 $s .= " <span class=\"history-size\">$stxt</span>";
256 }
257
258 $s .= $this->mSkin->revComment( $rev, false, true );
259
260 if ($notificationtimestamp && ($row->rev_timestamp >= $notificationtimestamp)) {
261 $s .= ' <span class="updatedmarker">' . wfMsgHtml( 'updatedmarker' ) . '</span>';
262 }
263 #add blurb about text having been deleted
264 if( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
265 $s .= ' <tt>' . wfMsgHtml( 'deletedrev' ) . '</tt>';
266 }
267
268 $tools = array();
269
270 if ( !is_null( $next ) && is_object( $next ) ) {
271 if( !$this->mTitle->getUserPermissionsErrors( 'rollback', $wgUser )
272 && !$this->mTitle->getUserPermissionsErrors( 'edit', $wgUser )
273 && $latest ) {
274 $tools[] = '<span class="mw-rollback-link">'
275 . $this->mSkin->buildRollbackLink( $rev )
276 . '</span>';
277 }
278
279 if( $this->mTitle->quickUserCan( 'edit' ) &&
280 !$rev->isDeleted( Revision::DELETED_TEXT ) &&
281 !$next->rev_deleted & Revision::DELETED_TEXT ) {
282 $undolink = $this->mSkin->makeKnownLinkObj(
283 $this->mTitle,
284 wfMsgHtml( 'editundo' ),
285 'action=edit&undoafter=' . $next->rev_id . '&undo=' . $rev->getId()
286 );
287 $tools[] = "<span class=\"mw-history-undo\">{$undolink}</span>";
288 }
289 }
290
291 if( $tools ) {
292 $s .= ' (' . implode( ' | ', $tools ) . ')';
293 }
294
295 wfRunHooks( 'PageHistoryLineEnding', array( $this, &$row , &$s ) );
296
297 return "<li>$s</li>\n";
298 }
299
300 /**
301 * Create a link to view this revision of the page
302 * @param Revision $rev
303 * @returns string
304 */
305 function revLink( $rev ) {
306 global $wgLang;
307 $date = $wgLang->timeanddate( wfTimestamp(TS_MW, $rev->getTimestamp()), true );
308 if( $rev->userCan( Revision::DELETED_TEXT ) ) {
309 $link = $this->mSkin->makeKnownLinkObj(
310 $this->mTitle, $date, "oldid=" . $rev->getId() );
311 } else {
312 $link = $date;
313 }
314 if( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
315 return '<span class="history-deleted">' . $link . '</span>';
316 }
317 return $link;
318 }
319
320 /**
321 * Create a diff-to-current link for this revision for this page
322 * @param Revision $rev
323 * @param Bool $latest, this is the latest revision of the page?
324 * @returns string
325 */
326 function curLink( $rev, $latest ) {
327 $cur = $this->message['cur'];
328 if( $latest || !$rev->userCan( Revision::DELETED_TEXT ) ) {
329 return $cur;
330 } else {
331 return $this->mSkin->makeKnownLinkObj(
332 $this->mTitle, $cur,
333 'diff=' . $this->getLatestID() .
334 "&oldid=" . $rev->getId() );
335 }
336 }
337
338 /**
339 * Create a diff-to-previous link for this revision for this page.
340 * @param Revision $prevRev, the previous revision
341 * @param mixed $next, the newer revision
342 * @param int $counter, what row on the history list this is
343 * @returns string
344 */
345 function lastLink( $prevRev, $next, $counter ) {
346 $last = $this->message['last'];
347 # $next may either be a Row, null, or "unkown"
348 $nextRev = is_object($next) ? new Revision( $next ) : $next;
349 if( is_null($next) ) {
350 # Probably no next row
351 return $last;
352 } elseif( $next === 'unknown' ) {
353 # Next row probably exists but is unknown, use an oldid=prev link
354 return $this->mSkin->makeKnownLinkObj(
355 $this->mTitle,
356 $last,
357 "diff=" . $prevRev->getId() . "&oldid=prev" );
358 } elseif( !$prevRev->userCan(Revision::DELETED_TEXT) || !$nextRev->userCan(Revision::DELETED_TEXT) ) {
359 return $last;
360 } else {
361 return $this->mSkin->makeKnownLinkObj(
362 $this->mTitle,
363 $last,
364 "diff=" . $prevRev->getId() . "&oldid={$next->rev_id}"
365 /*,
366 '',
367 '',
368 "tabindex={$counter}"*/ );
369 }
370 }
371
372 /**
373 * Create radio buttons for page history
374 *
375 * @param object $rev Revision
376 * @param bool $firstInList Is this version the first one?
377 * @param int $counter A counter of what row number we're at, counted from the top row = 1.
378 * @return string HTML output for the radio buttons
379 */
380 function diffButtons( $rev, $firstInList, $counter ) {
381 if( $this->linesonpage > 1) {
382 $radio = array(
383 'type' => 'radio',
384 'value' => $rev->getId(),
385 );
386
387 if( !$rev->userCan( Revision::DELETED_TEXT ) ) {
388 $radio['disabled'] = 'disabled';
389 }
390
391 /** @todo: move title texts to javascript */
392 if ( $firstInList ) {
393 $first = Xml::element( 'input', array_merge(
394 $radio,
395 array(
396 'style' => 'visibility:hidden',
397 'name' => 'oldid' ) ) );
398 $checkmark = array( 'checked' => 'checked' );
399 } else {
400 if( $counter == 2 ) {
401 $checkmark = array( 'checked' => 'checked' );
402 } else {
403 $checkmark = array();
404 }
405 $first = Xml::element( 'input', array_merge(
406 $radio,
407 $checkmark,
408 array( 'name' => 'oldid' ) ) );
409 $checkmark = array();
410 }
411 $second = Xml::element( 'input', array_merge(
412 $radio,
413 $checkmark,
414 array( 'name' => 'diff' ) ) );
415 return $first . $second;
416 } else {
417 return '';
418 }
419 }
420
421 /** @todo document */
422 function getLatestId() {
423 if( is_null( $this->mLatestId ) ) {
424 $id = $this->mTitle->getArticleID();
425 $db = wfGetDB( DB_SLAVE );
426 $this->mLatestId = $db->selectField( 'page',
427 "page_latest",
428 array( 'page_id' => $id ),
429 __METHOD__ );
430 }
431 return $this->mLatestId;
432 }
433
434 /**
435 * Fetch an array of revisions, specified by a given limit, offset and
436 * direction. This is now only used by the feeds. It was previously
437 * used by the main UI but that's now handled by the pager.
438 */
439 function fetchRevisions($limit, $offset, $direction) {
440 $dbr = wfGetDB( DB_SLAVE );
441
442 if ($direction == PageHistory::DIR_PREV)
443 list($dirs, $oper) = array("ASC", ">=");
444 else /* $direction == PageHistory::DIR_NEXT */
445 list($dirs, $oper) = array("DESC", "<=");
446
447 if ($offset)
448 $offsets = array("rev_timestamp $oper '$offset'");
449 else
450 $offsets = array();
451
452 $page_id = $this->mTitle->getArticleID();
453
454 $res = $dbr->select(
455 'revision',
456 Revision::selectFields(),
457 array_merge(array("rev_page=$page_id"), $offsets),
458 __METHOD__,
459 array('ORDER BY' => "rev_timestamp $dirs",
460 'USE INDEX' => 'page_timestamp', 'LIMIT' => $limit)
461 );
462
463 $result = array();
464 while (($obj = $dbr->fetchObject($res)) != NULL)
465 $result[] = $obj;
466
467 return $result;
468 }
469
470 /** @todo document */
471 function getNotificationTimestamp() {
472 global $wgUser, $wgShowUpdatedMarker;
473
474 if ($this->mNotificationTimestamp !== NULL)
475 return $this->mNotificationTimestamp;
476
477 if ($wgUser->isAnon() || !$wgShowUpdatedMarker)
478 return $this->mNotificationTimestamp = false;
479
480 $dbr = wfGetDB(DB_SLAVE);
481
482 $this->mNotificationTimestamp = $dbr->selectField(
483 'watchlist',
484 'wl_notificationtimestamp',
485 array( 'wl_namespace' => $this->mTitle->getNamespace(),
486 'wl_title' => $this->mTitle->getDBkey(),
487 'wl_user' => $wgUser->getId()
488 ),
489 __METHOD__ );
490
491 // Don't use the special value reserved for telling whether the field is filled
492 if ( is_null( $this->mNotificationTimestamp ) ) {
493 $this->mNotificationTimestamp = false;
494 }
495
496 return $this->mNotificationTimestamp;
497 }
498
499 /**
500 * Output a subscription feed listing recent edits to this page.
501 * @param string $type
502 */
503 function feed( $type ) {
504 global $wgFeedClasses;
505 if ( !FeedUtils::checkFeedOutput($type) ) {
506 return;
507 }
508
509 $feed = new $wgFeedClasses[$type](
510 $this->mTitle->getPrefixedText() . ' - ' .
511 wfMsgForContent( 'history-feed-title' ),
512 wfMsgForContent( 'history-feed-description' ),
513 $this->mTitle->getFullUrl( 'action=history' ) );
514
515 $items = $this->fetchRevisions(10, 0, PageHistory::DIR_NEXT);
516 $feed->outHeader();
517 if( $items ) {
518 foreach( $items as $row ) {
519 $feed->outItem( $this->feedItem( $row ) );
520 }
521 } else {
522 $feed->outItem( $this->feedEmpty() );
523 }
524 $feed->outFooter();
525 }
526
527 function feedEmpty() {
528 global $wgOut;
529 return new FeedItem(
530 wfMsgForContent( 'nohistory' ),
531 $wgOut->parse( wfMsgForContent( 'history-feed-empty' ) ),
532 $this->mTitle->getFullUrl(),
533 wfTimestamp( TS_MW ),
534 '',
535 $this->mTitle->getTalkPage()->getFullUrl() );
536 }
537
538 /**
539 * Generate a FeedItem object from a given revision table row
540 * Borrows Recent Changes' feed generation functions for formatting;
541 * includes a diff to the previous revision (if any).
542 *
543 * @param $row
544 * @return FeedItem
545 */
546 function feedItem( $row ) {
547 $rev = new Revision( $row );
548 $rev->setTitle( $this->mTitle );
549 $text = FeedUtils::formatDiffRow( $this->mTitle,
550 $this->mTitle->getPreviousRevisionID( $rev->getId() ),
551 $rev->getId(),
552 $rev->getTimestamp(),
553 $rev->getComment() );
554
555 if( $rev->getComment() == '' ) {
556 global $wgContLang;
557 $title = wfMsgForContent( 'history-feed-item-nocomment',
558 $rev->getUserText(),
559 $wgContLang->timeanddate( $rev->getTimestamp() ) );
560 } else {
561 $title = $rev->getUserText() . ": " . $this->stripComment( $rev->getComment() );
562 }
563
564 return new FeedItem(
565 $title,
566 $text,
567 $this->mTitle->getFullUrl( 'diff=' . $rev->getId() . '&oldid=prev' ),
568 $rev->getTimestamp(),
569 $rev->getUserText(),
570 $this->mTitle->getTalkPage()->getFullUrl() );
571 }
572
573 /**
574 * Quickie hack... strip out wikilinks to more legible form from the comment.
575 */
576 function stripComment( $text ) {
577 return preg_replace( '/\[\[([^]]*\|)?([^]]+)\]\]/', '\2', $text );
578 }
579 }
580
581
582 /**
583 * @ingroup Pager
584 */
585 class PageHistoryPager extends ReverseChronologicalPager {
586 public $mLastRow = false, $mPageHistory;
587
588 function __construct( $pageHistory ) {
589 parent::__construct();
590 $this->mPageHistory = $pageHistory;
591 }
592
593 function getQueryInfo() {
594 $queryInfo = array(
595 'tables' => array('revision'),
596 'fields' => Revision::selectFields(),
597 'conds' => array('rev_page' => $this->mPageHistory->mTitle->getArticleID() ),
598 'options' => array( 'USE INDEX' => array('revision','page_timestamp') )
599 );
600 wfRunHooks( 'PageHistoryPager::getQueryInfo', array( &$this, &$queryInfo ) );
601 return $queryInfo;
602 }
603
604 function getIndexField() {
605 return 'rev_timestamp';
606 }
607
608 function formatRow( $row ) {
609 if ( $this->mLastRow ) {
610 $latest = $this->mCounter == 1 && $this->mIsFirst;
611 $firstInList = $this->mCounter == 1;
612 $s = $this->mPageHistory->historyLine( $this->mLastRow, $row, $this->mCounter++,
613 $this->mPageHistory->getNotificationTimestamp(), $latest, $firstInList );
614 } else {
615 $s = '';
616 }
617 $this->mLastRow = $row;
618 return $s;
619 }
620
621 function getStartBody() {
622 $this->mLastRow = false;
623 $this->mCounter = 1;
624 return '';
625 }
626
627 function getEndBody() {
628 if ( $this->mLastRow ) {
629 $latest = $this->mCounter == 1 && $this->mIsFirst;
630 $firstInList = $this->mCounter == 1;
631 if ( $this->mIsBackwards ) {
632 # Next row is unknown, but for UI reasons, probably exists if an offset has been specified
633 if ( $this->mOffset == '' ) {
634 $next = null;
635 } else {
636 $next = 'unknown';
637 }
638 } else {
639 # The next row is the past-the-end row
640 $next = $this->mPastTheEndRow;
641 }
642 $s = $this->mPageHistory->historyLine( $this->mLastRow, $next, $this->mCounter++,
643 $this->mPageHistory->getNotificationTimestamp(), $latest, $firstInList );
644 } else {
645 $s = '';
646 }
647 return $s;
648 }
649 }