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