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