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