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