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