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