Update docs in Pager.php for join_conds
[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 $mLatestId = null;
26
27 private $mOldIdChecked = 0;
28
29 /**
30 * Construct a new PageHistory.
31 *
32 * @param Article $article
33 * @returns nothing
34 */
35 function __construct( $article ) {
36 global $wgUser;
37 $this->mArticle =& $article;
38 $this->mTitle =& $article->mTitle;
39 $this->mSkin = $wgUser->getSkin();
40 $this->preCacheMessages();
41 }
42
43 function getArticle() {
44 return $this->mArticle;
45 }
46
47 function getTitle() {
48 return $this->mTitle;
49 }
50
51 /**
52 * As we use the same small set of messages in various methods and that
53 * they are called often, we call them once and save them in $this->message
54 */
55 function preCacheMessages() {
56 // Precache various messages
57 if( !isset( $this->message ) ) {
58 foreach( explode(' ', 'cur last rev-delundel' ) as $msg ) {
59 $this->message[$msg] = wfMsgExt( $msg, array( 'escape') );
60 }
61 }
62 }
63
64 /**
65 * Print the history page for an article.
66 *
67 * @returns nothing
68 */
69 function history() {
70 global $wgOut, $wgRequest, $wgTitle, $wgScript;
71
72 /*
73 * Allow client caching.
74 */
75 if( $wgOut->checkLastModified( $this->mArticle->getTouched() ) )
76 return; // Client cache fresh and headers sent, nothing more to do.
77
78 wfProfileIn( __METHOD__ );
79
80 /*
81 * Setup page variables.
82 */
83 $wgOut->setPageTitle( wfMsg( 'history-title', $this->mTitle->getPrefixedText() ) );
84 $wgOut->setPageTitleActionText( wfMsg( 'history_short' ) );
85 $wgOut->setArticleFlag( false );
86 $wgOut->setArticleRelated( true );
87 $wgOut->setRobotPolicy( 'noindex,nofollow' );
88 $wgOut->setSyndicated( true );
89 $wgOut->setFeedAppendQuery( 'action=history' );
90 $wgOut->addScriptFile( 'history.js' );
91
92 $logPage = SpecialPage::getTitleFor( 'Log' );
93 $logLink = $this->mSkin->makeKnownLinkObj( $logPage, wfMsgHtml( 'viewpagelogs' ),
94 'page=' . $this->mTitle->getPrefixedUrl() );
95 $wgOut->setSubtitle( $logLink );
96
97 $feedType = $wgRequest->getVal( 'feed' );
98 if( $feedType ) {
99 wfProfileOut( __METHOD__ );
100 return $this->feed( $feedType );
101 }
102
103 /*
104 * Fail if article doesn't exist.
105 */
106 if( !$this->mTitle->exists() ) {
107 $wgOut->addWikiMsg( 'nohistory' );
108 wfProfileOut( __METHOD__ );
109 return;
110 }
111
112 /**
113 * Add date selector to quickly get to a certain time
114 */
115 $year = $wgRequest->getInt( 'year' );
116 $month = $wgRequest->getInt( 'month' );
117 $tagFilter = $wgRequest->getVal( 'tagfilter' );
118 $tagSelector = ChangeTags::buildTagFilterSelector( $tagFilter );
119
120 $action = htmlspecialchars( $wgScript );
121 $wgOut->addHTML(
122 "<form action=\"$action\" method=\"get\" id=\"mw-history-searchform\">" .
123 Xml::fieldset( wfMsg( 'history-fieldset-title' ), false, array( 'id' => 'mw-history-search' ) ) .
124 Xml::hidden( 'title', $this->mTitle->getPrefixedDBKey() ) . "\n" .
125 Xml::hidden( 'action', 'history' ) . "\n" .
126 xml::dateMenu( $year, $month ) . '&nbsp;' .
127 ( $tagSelector ? ( implode( '&nbsp;', $tagSelector ) . '&nbsp;' ) : '' ) .
128 Xml::submitButton( wfMsg( 'allpagessubmit' ) ) . "\n" .
129 '</fieldset></form>'
130 );
131
132 wfRunHooks( 'PageHistoryBeforeList', array( &$this->mArticle ) );
133
134 /**
135 * Do the list
136 */
137 $pager = new PageHistoryPager( $this, $year, $month, $tagFilter );
138 $this->linesonpage = $pager->getNumRows();
139 $wgOut->addHTML(
140 $pager->getNavigationBar() .
141 $this->beginHistoryList() .
142 $pager->getBody() .
143 $this->endHistoryList() .
144 $pager->getNavigationBar()
145 );
146
147 wfProfileOut( __METHOD__ );
148 }
149
150 /**
151 * Creates begin of history list with a submit button
152 *
153 * @return string HTML output
154 */
155 function beginHistoryList() {
156 global $wgTitle, $wgScript, $wgEnableHtmlDiff;
157 $this->lastdate = '';
158 $s = wfMsgExt( 'histlegend', array( 'parse') );
159 $s .= Xml::openElement( 'form', array( 'action' => $wgScript, 'id' => 'mw-history-compare' ) );
160 $s .= Xml::hidden( 'title', $wgTitle->getPrefixedDbKey() );
161 if( $wgEnableHtmlDiff ) {
162 $s .= $this->submitButton( wfMsg( 'visualcomparison'),
163 array(
164 'name' => 'htmldiff',
165 'class' => 'historysubmit',
166 'accesskey' => wfMsg( 'accesskey-visualcomparison' ),
167 'title' => wfMsg( 'tooltip-compareselectedversions' ),
168 )
169 );
170 $s .= $this->submitButton( wfMsg( 'wikicodecomparison'),
171 array(
172 'class' => 'historysubmit',
173 'accesskey' => wfMsg( 'accesskey-compareselectedversions' ),
174 'title' => wfMsg( 'tooltip-compareselectedversions' ),
175 )
176 );
177 } else {
178 $s .= $this->submitButton( wfMsg( 'compareselectedversions'),
179 array(
180 'class' => 'historysubmit',
181 'accesskey' => wfMsg( 'accesskey-compareselectedversions' ),
182 'title' => wfMsg( 'tooltip-compareselectedversions' ),
183 )
184 );
185 }
186 $s .= '<ul id="pagehistory">' . "\n";
187 return $s;
188 }
189
190 /**
191 * Creates end of history list with a submit button
192 *
193 * @return string HTML output
194 */
195 function endHistoryList() {
196 global $wgEnableHtmlDiff;
197 $s = '</ul>';
198 if( $wgEnableHtmlDiff ) {
199 $s .= $this->submitButton( wfMsg( 'visualcomparison'),
200 array(
201 'name' => 'htmldiff',
202 'class' => 'historysubmit',
203 'accesskey' => wfMsg( 'accesskey-visualcomparison' ),
204 'title' => wfMsg( 'tooltip-compareselectedversions' ),
205 )
206 );
207 $s .= $this->submitButton( wfMsg( 'wikicodecomparison'),
208 array(
209 'class' => 'historysubmit',
210 'accesskey' => wfMsg( 'accesskey-compareselectedversions' ),
211 'title' => wfMsg( 'tooltip-compareselectedversions' ),
212 )
213 );
214 } else {
215 $s .= $this->submitButton( wfMsg( 'compareselectedversions'),
216 array(
217 'class' => 'historysubmit',
218 'accesskey' => wfMsg( 'accesskey-compareselectedversions' ),
219 'title' => wfMsg( 'tooltip-compareselectedversions' ),
220 )
221 );
222 }
223 $s .= '</form>';
224 return $s;
225 }
226
227 /**
228 * Creates a submit button
229 *
230 * @param array $attributes attributes
231 * @return string HTML output for the submit button
232 */
233 function submitButton($message, $attributes = array() ) {
234 # Disable submit button if history has 1 revision only
235 if( $this->linesonpage > 1 ) {
236 return Xml::submitButton( $message , $attributes );
237 } else {
238 return '';
239 }
240 }
241
242 /**
243 * Returns a row from the history printout.
244 *
245 * @todo document some more, and maybe clean up the code (some params redundant?)
246 *
247 * @param Row $row The database row corresponding to the previous line.
248 * @param mixed $next The database row corresponding to the next line.
249 * @param int $counter Apparently a counter of what row number we're at, counted from the top row = 1.
250 * @param $notificationtimestamp
251 * @param bool $latest Whether this row corresponds to the page's latest revision.
252 * @param bool $firstInList Whether this row corresponds to the first displayed on this history page.
253 * @return string HTML output for the row
254 */
255 function historyLine( $row, $next, $counter = '', $notificationtimestamp = false,
256 $latest = false, $firstInList = false )
257 {
258 global $wgUser, $wgLang;
259 $rev = new Revision( $row );
260 $rev->setTitle( $this->mTitle );
261
262 $curlink = $this->curLink( $rev, $latest );
263 $lastlink = $this->lastLink( $rev, $next, $counter );
264 $arbitrary = $this->diffButtons( $rev, $firstInList, $counter );
265 $link = $this->revLink( $rev );
266 $classes = array();
267
268 $s = "($curlink) ($lastlink) $arbitrary";
269
270 if( $wgUser->isAllowed( 'deleterevision' ) ) {
271 if( $latest ) {
272 // We don't currently handle well changing the top revision's settings
273 $del = Xml::tags( 'span', array( 'class'=>'mw-revdelundel-link' ), '('.
274 $this->message['rev-delundel'].')' );
275 } else if( !$rev->userCan( Revision::DELETED_RESTRICTED ) ) {
276 // If revision was hidden from sysops
277 $del = Xml::tags( 'span', array( 'class'=>'mw-revdelundel-link' ), '('.
278 $this->message['rev-delundel'].')' );
279 } else {
280 $query = array( 'target' => $this->mTitle->getPrefixedDbkey(),
281 'oldid' => $rev->getId()
282 );
283 $del = $this->mSkin->revDeleteLink( $query, $rev->isDeleted( Revision::DELETED_RESTRICTED ) );
284 }
285 $s .= " $del ";
286 }
287
288 $s .= " $link";
289 $s .= " <span class='history-user'>" . $this->mSkin->revUserTools( $rev, true ) . "</span>";
290
291 if( $rev->isMinor() ) {
292 $s .= ' ' . Xml::element( 'span', array( 'class' => 'minor' ), wfMsg( 'minoreditletter') );
293 }
294
295 if( !is_null( $size = $rev->getSize() ) && !$rev->isDeleted( Revision::DELETED_TEXT ) ) {
296 $s .= ' ' . $this->mSkin->formatRevisionSize( $size );
297 }
298
299 $s .= $this->mSkin->revComment( $rev, false, true );
300
301 if( $notificationtimestamp && ($row->rev_timestamp >= $notificationtimestamp) ) {
302 $s .= ' <span class="updatedmarker">' . wfMsgHtml( 'updatedmarker' ) . '</span>';
303 }
304 if( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
305 $s .= ' <tt>' . wfMsgHtml( 'deletedrev' ) . '</tt>';
306 }
307
308 $tools = array();
309
310 if( !is_null( $next ) && is_object( $next ) ) {
311 if( $latest && $this->mTitle->userCan( 'rollback' ) && $this->mTitle->userCan( 'edit' ) ) {
312 $tools[] = '<span class="mw-rollback-link">'.$this->mSkin->buildRollbackLink( $rev ).'</span>';
313 }
314
315 if( $this->mTitle->quickUserCan( 'edit' ) && !$rev->isDeleted( Revision::DELETED_TEXT ) &&
316 !$next->rev_deleted & Revision::DELETED_TEXT )
317 {
318 # Create undo tooltip for the first (=latest) line only
319 $undoTooltip = $latest
320 ? array( 'title' => wfMsg( 'tooltip-undo' ) )
321 : array();
322 $undolink = $this->mSkin->link(
323 $this->mTitle,
324 wfMsgHtml( 'editundo' ),
325 $undoTooltip,
326 array( 'action' => 'edit', 'undoafter' => $next->rev_id, 'undo' => $rev->getId() ),
327 array( 'known', 'noclasses' )
328 );
329 $tools[] = "<span class=\"mw-history-undo\">{$undolink}</span>";
330 }
331 }
332
333 if( $tools ) {
334 $s .= ' (' . $wgLang->pipeList( $tools ) . ')';
335 }
336
337 # Tags
338 list($tagSummary, $newClasses) = ChangeTags::formatSummaryRow( $row->ts_tags, 'history' );
339 $classes = array_merge( $classes, $newClasses );
340 $s .= " $tagSummary";
341
342 wfRunHooks( 'PageHistoryLineEnding', array( $this, &$row , &$s ) );
343
344 $classes = implode( ' ', $classes );
345
346 return "<li class=\"$classes\">$s</li>\n";
347 }
348
349 /**
350 * Create a link to view this revision of the page
351 * @param Revision $rev
352 * @returns string
353 */
354 function revLink( $rev ) {
355 global $wgLang;
356 $date = $wgLang->timeanddate( wfTimestamp(TS_MW, $rev->getTimestamp()), true );
357 if( $rev->userCan( Revision::DELETED_TEXT ) ) {
358 $link = $this->mSkin->makeKnownLinkObj( $this->mTitle, $date, "oldid=" . $rev->getId() );
359 } else {
360 $link = $date;
361 }
362 if( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
363 $link = "<span class=\"history-deleted\">$link</span>";
364 }
365 return $link;
366 }
367
368 /**
369 * Create a diff-to-current link for this revision for this page
370 * @param Revision $rev
371 * @param Bool $latest, this is the latest revision of the page?
372 * @returns string
373 */
374 function curLink( $rev, $latest ) {
375 $cur = $this->message['cur'];
376 if( $latest || !$rev->userCan( Revision::DELETED_TEXT ) ) {
377 return $cur;
378 } else {
379 return $this->mSkin->makeKnownLinkObj( $this->mTitle, $cur,
380 'diff=' . $this->mTitle->getLatestRevID() . "&oldid=" . $rev->getId() );
381 }
382 }
383
384 /**
385 * Create a diff-to-previous link for this revision for this page.
386 * @param Revision $prevRev, the previous revision
387 * @param mixed $next, the newer revision
388 * @param int $counter, what row on the history list this is
389 * @returns string
390 */
391 function lastLink( $prevRev, $next, $counter ) {
392 $last = $this->message['last'];
393 # $next may either be a Row, null, or "unkown"
394 $nextRev = is_object($next) ? new Revision( $next ) : $next;
395 if( is_null($next) ) {
396 # Probably no next row
397 return $last;
398 } elseif( $next === 'unknown' ) {
399 # Next row probably exists but is unknown, use an oldid=prev link
400 return $this->mSkin->makeKnownLinkObj( $this->mTitle, $last,
401 "diff=" . $prevRev->getId() . "&oldid=prev" );
402 } elseif( !$prevRev->userCan(Revision::DELETED_TEXT) || !$nextRev->userCan(Revision::DELETED_TEXT) ) {
403 return $last;
404 } else {
405 return $this->mSkin->makeKnownLinkObj( $this->mTitle, $last,
406 "diff=" . $prevRev->getId() . "&oldid={$next->rev_id}" );
407 }
408 }
409
410 /**
411 * Create radio buttons for page history
412 *
413 * @param object $rev Revision
414 * @param bool $firstInList Is this version the first one?
415 * @param int $counter A counter of what row number we're at, counted from the top row = 1.
416 * @return string HTML output for the radio buttons
417 */
418 function diffButtons( $rev, $firstInList, $counter ) {
419 if( $this->linesonpage > 1 ) {
420 $radio = array( 'type' => 'radio', 'value' => $rev->getId() );
421 /** @todo: move title texts to javascript */
422 if( $firstInList ) {
423 $first = Xml::element( 'input',
424 array_merge( $radio, array( 'style' => 'visibility:hidden', 'name' => 'oldid' ) )
425 );
426 $checkmark = array( 'checked' => 'checked' );
427 } else {
428 # Check visibility of old revisions
429 if( !$rev->userCan( Revision::DELETED_TEXT ) ) {
430 $radio['disabled'] = 'disabled';
431 $checkmark = array(); // We will check the next possible one
432 } else if( $counter == 2 || !$this->mOldIdChecked ) {
433 $checkmark = array( 'checked' => 'checked' );
434 $this->mOldIdChecked = $rev->getId();
435 } else {
436 $checkmark = array();
437 }
438 $first = Xml::element( 'input', array_merge( $radio, $checkmark, array( 'name' => 'oldid' ) ) );
439 $checkmark = array();
440 }
441 $second = Xml::element( 'input', array_merge( $radio, $checkmark, array( 'name' => 'diff' ) ) );
442 return $first . $second;
443 } else {
444 return '';
445 }
446 }
447
448 /**
449 * Fetch an array of revisions, specified by a given limit, offset and
450 * direction. This is now only used by the feeds. It was previously
451 * used by the main UI but that's now handled by the pager.
452 */
453 function fetchRevisions($limit, $offset, $direction) {
454 $dbr = wfGetDB( DB_SLAVE );
455
456 if( $direction == PageHistory::DIR_PREV )
457 list($dirs, $oper) = array("ASC", ">=");
458 else /* $direction == PageHistory::DIR_NEXT */
459 list($dirs, $oper) = array("DESC", "<=");
460
461 if( $offset )
462 $offsets = array("rev_timestamp $oper '$offset'");
463 else
464 $offsets = array();
465
466 $page_id = $this->mTitle->getArticleID();
467
468 return $dbr->select( 'revision',
469 Revision::selectFields(),
470 array_merge(array("rev_page=$page_id"), $offsets),
471 __METHOD__,
472 array( 'ORDER BY' => "rev_timestamp $dirs",
473 'USE INDEX' => 'page_timestamp', 'LIMIT' => $limit)
474 );
475 }
476
477 /**
478 * Output a subscription feed listing recent edits to this page.
479 * @param string $type
480 */
481 function feed( $type ) {
482 global $wgFeedClasses, $wgRequest, $wgFeedLimit;
483 if( !FeedUtils::checkFeedOutput($type) ) {
484 return;
485 }
486
487 $feed = new $wgFeedClasses[$type](
488 $this->mTitle->getPrefixedText() . ' - ' .
489 wfMsgForContent( 'history-feed-title' ),
490 wfMsgForContent( 'history-feed-description' ),
491 $this->mTitle->getFullUrl( 'action=history' ) );
492
493 // Get a limit on number of feed entries. Provide a sane default
494 // of 10 if none is defined (but limit to $wgFeedLimit max)
495 $limit = $wgRequest->getInt( 'limit', 10 );
496 if( $limit > $wgFeedLimit || $limit < 1 ) {
497 $limit = 10;
498 }
499 $items = $this->fetchRevisions($limit, 0, PageHistory::DIR_NEXT);
500
501 $feed->outHeader();
502 if( $items ) {
503 foreach( $items as $row ) {
504 $feed->outItem( $this->feedItem( $row ) );
505 }
506 } else {
507 $feed->outItem( $this->feedEmpty() );
508 }
509 $feed->outFooter();
510 }
511
512 function feedEmpty() {
513 global $wgOut;
514 return new FeedItem(
515 wfMsgForContent( 'nohistory' ),
516 $wgOut->parse( wfMsgForContent( 'history-feed-empty' ) ),
517 $this->mTitle->getFullUrl(),
518 wfTimestamp( TS_MW ),
519 '',
520 $this->mTitle->getTalkPage()->getFullUrl() );
521 }
522
523 /**
524 * Generate a FeedItem object from a given revision table row
525 * Borrows Recent Changes' feed generation functions for formatting;
526 * includes a diff to the previous revision (if any).
527 *
528 * @param $row
529 * @return FeedItem
530 */
531 function feedItem( $row ) {
532 $rev = new Revision( $row );
533 $rev->setTitle( $this->mTitle );
534 $text = FeedUtils::formatDiffRow( $this->mTitle,
535 $this->mTitle->getPreviousRevisionID( $rev->getId() ),
536 $rev->getId(),
537 $rev->getTimestamp(),
538 $rev->getComment() );
539
540 if( $rev->getComment() == '' ) {
541 global $wgContLang;
542 $title = wfMsgForContent( 'history-feed-item-nocomment',
543 $rev->getUserText(),
544 $wgContLang->timeanddate( $rev->getTimestamp() ) );
545 } else {
546 $title = $rev->getUserText() . wfMsgForContent( 'colon-separator' ) . FeedItem::stripComment( $rev->getComment() );
547 }
548
549 return new FeedItem(
550 $title,
551 $text,
552 $this->mTitle->getFullUrl( 'diff=' . $rev->getId() . '&oldid=prev' ),
553 $rev->getTimestamp(),
554 $rev->getUserText(),
555 $this->mTitle->getTalkPage()->getFullUrl() );
556 }
557 }
558
559
560 /**
561 * @ingroup Pager
562 */
563 class PageHistoryPager extends ReverseChronologicalPager {
564 public $mLastRow = false, $mPageHistory, $mTitle;
565
566 function __construct( $pageHistory, $year='', $month='', $tagFilter = '' ) {
567 parent::__construct();
568 $this->mPageHistory = $pageHistory;
569 $this->mTitle =& $this->mPageHistory->mTitle;
570 $this->tagFilter = $tagFilter;
571 $this->getDateCond( $year, $month );
572 }
573
574 function getQueryInfo() {
575 $queryInfo = array(
576 'tables' => array('revision'),
577 'fields' => array_merge( Revision::selectFields(), array('ts_tags') ),
578 'conds' => array('rev_page' => $this->mPageHistory->mTitle->getArticleID() ),
579 'options' => array( 'USE INDEX' => array('revision' => 'page_timestamp') ),
580 'join_conds' => array( 'tag_summary' => array( 'LEFT JOIN', 'ts_rev_id=rev_id' ) ),
581 );
582 ChangeTags::modifyDisplayQuery( $queryInfo['tables'],
583 $queryInfo['fields'],
584 $queryInfo['conds'],
585 $queryInfo['join_conds'],
586 $queryInfo['options'],
587 $this->tagFilter );
588 wfRunHooks( 'PageHistoryPager::getQueryInfo', array( &$this, &$queryInfo ) );
589 return $queryInfo;
590 }
591
592 function getIndexField() {
593 return 'rev_timestamp';
594 }
595
596 function formatRow( $row ) {
597 if( $this->mLastRow ) {
598 $latest = $this->mCounter == 1 && $this->mIsFirst;
599 $firstInList = $this->mCounter == 1;
600 $s = $this->mPageHistory->historyLine( $this->mLastRow, $row, $this->mCounter++,
601 $this->mTitle->getNotificationTimestamp(), $latest, $firstInList );
602 } else {
603 $s = '';
604 }
605 $this->mLastRow = $row;
606 return $s;
607 }
608
609 function getStartBody() {
610 $this->mLastRow = false;
611 $this->mCounter = 1;
612 return '';
613 }
614
615 function getEndBody() {
616 if( $this->mLastRow ) {
617 $latest = $this->mCounter == 1 && $this->mIsFirst;
618 $firstInList = $this->mCounter == 1;
619 if( $this->mIsBackwards ) {
620 # Next row is unknown, but for UI reasons, probably exists if an offset has been specified
621 if( $this->mOffset == '' ) {
622 $next = null;
623 } else {
624 $next = 'unknown';
625 }
626 } else {
627 # The next row is the past-the-end row
628 $next = $this->mPastTheEndRow;
629 }
630 $s = $this->mPageHistory->historyLine( $this->mLastRow, $next, $this->mCounter++,
631 $this->mTitle->getNotificationTimestamp(), $latest, $firstInList );
632 } else {
633 $s = '';
634 }
635 return $s;
636 }
637 }