* Avoid numerous redundant latest-revision lookups in history
[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 * @package MediaWiki
7 */
8
9 /** */
10 include_once ( 'SpecialValidate.php' );
11
12 define('DIR_PREV', 0);
13 define('DIR_NEXT', 1);
14
15 /**
16 * This class handles printing the history page for an article. In order to
17 * be efficient, it uses timestamps rather than offsets for paging, to avoid
18 * costly LIMIT,offset queries.
19 *
20 * Construct it by passing in an Article, and call $h->history() to print the
21 * history.
22 *
23 * @package MediaWiki
24 */
25
26 class PageHistory {
27 var $mArticle, $mTitle, $mSkin;
28 var $lastdate;
29 var $linesonpage;
30 var $mNotificationTimestamp;
31 var $mLatestId = null;
32
33 /**
34 * Construct a new PageHistory.
35 *
36 * @param Article $article
37 * @returns nothing
38 */
39 function PageHistory($article) {
40 global $wgUser;
41
42 $this->mArticle =& $article;
43 $this->mTitle =& $article->mTitle;
44 $this->mNotificationTimestamp = NULL;
45 $this->mSkin = $wgUser->getSkin();
46
47 $this->defaultLimit = 50;
48 }
49
50 /**
51 * Print the history page for an article.
52 *
53 * @returns nothing
54 */
55 function history() {
56 global $wgUser, $wgOut, $wgLang, $wgShowUpdatedMarker, $wgRequest,
57 $wgTitle, $wgUseValidation;
58
59 /*
60 * Allow client caching.
61 */
62
63 if( $wgOut->checkLastModified( $this->mArticle->getTimestamp() ) )
64 /* Client cache fresh and headers sent, nothing more to do. */
65 return;
66
67 $fname = 'PageHistory::history';
68 wfProfileIn( $fname );
69
70 /*
71 * Setup page variables.
72 */
73 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
74 $wgOut->setSubtitle( wfMsg( 'revhistory' ) );
75 $wgOut->setArticleFlag( false );
76 $wgOut->setArticleRelated( true );
77 $wgOut->setRobotpolicy( 'noindex,nofollow' );
78
79 /*
80 * Fail if article doesn't exist.
81 */
82 if( !$this->mTitle->exists() ) {
83 $wgOut->addWikiText( wfMsg( 'nohistory' ) );
84 wfProfileOut( $fname );
85 return;
86 }
87
88 $dbr =& wfGetDB(DB_SLAVE);
89
90 /*
91 * Extract limit, the number of revisions to show, and
92 * offset, the timestamp to begin at, from the URL.
93 */
94 $limit = $wgRequest->getInt('limit', $this->defaultLimit);
95 $offset = $wgRequest->getText('offset');
96
97 /* Offset must be an integral. */
98 if (!strlen($offset) || !preg_match("/^[0-9]+$/", $offset))
99 $offset = 0;
100 # $offset = $dbr->timestamp($offset);
101 $dboffset = $offset === 0 ? 0 : $dbr->timestamp($offset);
102 /*
103 * "go=last" means to jump to the last history page.
104 */
105 if (($gowhere = $wgRequest->getText("go")) !== NULL) {
106 switch ($gowhere) {
107 case "first":
108 if (($lastid = $this->getLastOffsetForPaging($this->mTitle->getArticleID(), $limit)) === NULL)
109 break;
110 $gourl = $wgTitle->getLocalURL("action=history&limit={$limit}&offset=".
111 wfTimestamp(TS_MW, $lastid));
112 break;
113 default:
114 $gourl = NULL;
115 }
116
117 if (!is_null($gourl)) {
118 $wgOut->redirect($gourl);
119 return;
120 }
121 }
122
123 /*
124 * Fetch revisions.
125 *
126 * If the user clicked "previous", we retrieve the revisions backwards,
127 * then reverse them. This is to avoid needing to know the timestamp of
128 * previous revisions when generating the URL.
129 */
130 $direction = $this->getDirection();
131 $revisions = $this->fetchRevisions($limit, $dboffset, $direction);
132 $navbar = $this->makeNavbar($revisions, $offset, $limit, $direction);
133
134 /*
135 * We fetch one more revision than needed to get the timestamp of the
136 * one after this page (and to know if it exists).
137 *
138 * linesonpage stores the actual number of lines.
139 */
140 if (count($revisions) < $limit + 1)
141 $this->linesonpage = count($revisions);
142 else
143 $this->linesonpage = count($revisions) - 1;
144
145 /* Un-reverse revisions */
146 if ($direction == DIR_PREV)
147 $revisions = array_reverse($revisions);
148
149 /*
150 * Print the top navbar.
151 */
152 $s = $navbar;
153 $s .= $this->beginHistoryList();
154 $counter = 1;
155
156 /*
157 * Print each revision, excluding the one-past-the-end, if any.
158 */
159 foreach (array_slice($revisions, 0, $limit) as $i => $line) {
160 $latest = !$i && $offset == 0;
161 $firstInList = !$i;
162 $next = isset( $revisions[$i + 1] ) ? $revisions[$i + 1 ] : null;
163 $s .= $this->historyLine($line, $next, $counter, $this->getNotificationTimestamp(), $latest, $firstInList);
164 $counter++;
165 }
166
167 /*
168 * End navbar.
169 */
170 $s .= $this->endHistoryList();
171 $s .= $navbar;
172
173 /*
174 * Article validation line.
175 */
176 if ($wgUseValidation)
177 $s .= '<p>' . Validation::getStatisticsLink( $this->mArticle ) . '</p>' ;
178
179 $wgOut->addHTML( $s );
180 wfProfileOut( $fname );
181 }
182
183 /** @todo document */
184 function beginHistoryList() {
185 global $wgTitle;
186 $this->lastdate = '';
187 $s = wfMsgWikiHtml( 'histlegend' );
188 $s .= '<form action="' . $wgTitle->escapeLocalURL( '-' ) . '" method="get">';
189 $prefixedkey = htmlspecialchars($wgTitle->getPrefixedDbKey());
190
191 // The following line is SUPPOSED to have double-quotes around the
192 // $prefixedkey variable, because htmlspecialchars() doesn't escape
193 // single-quotes.
194 //
195 // On at least two occasions people have changed it to single-quotes,
196 // which creates invalid HTML and incorrect display of the resulting
197 // link.
198 //
199 // Please do not break this a third time. Thank you for your kind
200 // consideration and cooperation.
201 //
202 $s .= "<input type='hidden' name='title' value=\"{$prefixedkey}\" />\n";
203
204 $s .= $this->submitButton();
205 $s .= '<ul id="pagehistory">' . "\n";
206 return $s;
207 }
208
209 /** @todo document */
210 function endHistoryList() {
211 $last = wfMsg( 'last' );
212
213 $s = '</ul>';
214 $s .= $this->submitButton( array( 'id' => 'historysubmit' ) );
215 $s .= '</form>';
216 return $s;
217 }
218
219 /** @todo document */
220 function submitButton( $bits = array() ) {
221 return ( $this->linesonpage > 0 )
222 ? wfElement( 'input', array_merge( $bits,
223 array(
224 'class' => 'historysubmit',
225 'type' => 'submit',
226 'accesskey' => wfMsgHtml( 'accesskey-compareselectedversions' ),
227 'title' => wfMsgHtml( 'tooltip-compareselectedversions' ),
228 'value' => wfMsgHtml( 'compareselectedversions' ),
229 ) ) )
230 : '';
231 }
232
233 /** @todo document */
234 function historyLine( $row, $next, $counter = '', $notificationtimestamp = false, $latest = false, $firstInList = false ) {
235 global $wgLang, $wgContLang;
236
237 if ( 0 == $row->rev_user ) {
238 $contribsPage =& Title::makeTitle( NS_SPECIAL, 'Contributions' );
239 $ul = $this->mSkin->makeKnownLinkObj( $contribsPage,
240 htmlspecialchars( $row->rev_user_text ),
241 'target=' . urlencode( $row->rev_user_text ) );
242 } else {
243 $userPage =& Title::makeTitle( NS_USER, $row->rev_user_text );
244 $ul = $this->mSkin->makeLinkObj( $userPage , htmlspecialchars( $row->rev_user_text ) );
245 }
246
247 $s = '<li>';
248 /* This feature is not yet used according to schema */
249 if( $row->rev_deleted ) {
250 $s .= '<span class="history-deleted">';
251 }
252 $curlink = $this->curLink( $row, $latest );
253 $lastlink = $this->lastLink( $row, $next, $counter );
254 $arbitrary = $this->diffButtons( $row, $firstInList, $counter );
255 $link = $this->revLink( $row );
256
257 $s .= "($curlink) ($lastlink) $arbitrary $link <span class='history-user'>$ul</span>";
258
259 if( $row->rev_minor_edit ) {
260 $s .= ' ' . wfElement( 'span', array( 'class' => 'minor' ), wfMsgHtml( 'minoreditletter') );
261 }
262
263 $s .= $this->mSkin->commentBlock( $row->rev_comment, $this->mTitle );
264 if ($notificationtimestamp && ($row->rev_timestamp >= $notificationtimestamp)) {
265 $s .= ' <span class="updatedmarker">' . wfMsgHtml( 'updatedmarker' ) . '</span>';
266 }
267 if( $row->rev_deleted ) {
268 $s .= '</span> ' . wfMsgHtml( 'deletedrev' );
269 }
270 $s .= "</li>\n";
271
272 return $s;
273 }
274
275 /** @todo document */
276 function revLink( $row ) {
277 global $wgUser, $wgLang;
278 $date = $wgLang->timeanddate( wfTimestamp(TS_MW, $row->rev_timestamp), true );
279 if( $row->rev_deleted && !$wgUser->isAllowed( 'undelete' ) ) {
280 return $date;
281 } else {
282 return $this->mSkin->makeKnownLinkObj(
283 $this->mTitle, $date, "oldid={$row->rev_id}" );
284 }
285 }
286
287 /** @todo document */
288 function curLink( $row, $latest ) {
289 global $wgUser;
290 $cur = wfMsgHtml( 'cur' );
291 if( $latest
292 || ( $row->rev_deleted && !$wgUser->isAllowed( 'undelete' ) ) ) {
293 return $cur;
294 } else {
295 return $this->mSkin->makeKnownLinkObj(
296 $this->mTitle, $cur,
297 'diff=' . $this->getLatestID() .
298 "&oldid={$row->rev_id}" );
299 }
300 }
301
302 /** @todo document */
303 function lastLink( $row, $next, $counter ) {
304 global $wgUser;
305 $last = htmlspecialchars( wfMsg( 'last' ) );
306 if( is_null( $next ) ) {
307 if( $row->rev_timestamp == $this->getEarliestOffset() ) {
308 return $last;
309 } else {
310 // Cut off by paging; there are more behind us...
311 return $this->mSkin->makeKnownLinkObj(
312 $this->mTitle,
313 $last,
314 "diff={$row->rev_id}&oldid=prev" );
315 }
316 } elseif( $row->rev_deleted && !$wgUser->isAllowed( 'undelete' ) ) {
317 return $last;
318 } else {
319 return $this->mSkin->makeKnownLinkObj(
320 $this->mTitle,
321 $last,
322 "diff={$row->rev_id}&oldid={$next->rev_id}"
323 /*,
324 '',
325 '',
326 "tabindex={$counter}"*/ );
327 }
328 }
329
330 /** @todo document */
331 function diffButtons( $row, $firstInList, $counter ) {
332 global $wgUser;
333 if( $this->linesonpage > 1) {
334 $radio = array(
335 'type' => 'radio',
336 'value' => $row->rev_id,
337 # do we really need to flood this on every item?
338 # 'title' => wfMsgHtml( 'selectolderversionfordiff' )
339 );
340
341 if( $row->rev_deleted && !$wgUser->isAllowed( 'undelete' ) ) {
342 $radio['disabled'] = 'disabled';
343 }
344
345 /** @todo: move title texts to javascript */
346 if ( $firstInList ) {
347 $first = wfElement( 'input', array_merge(
348 $radio,
349 array(
350 'style' => 'visibility:hidden',
351 'name' => 'oldid' ) ) );
352 $checkmark = array( 'checked' => 'checked' );
353 } else {
354 if( $counter == 2 ) {
355 $checkmark = array( 'checked' => 'checked' );
356 } else {
357 $checkmark = array();
358 }
359 $first = wfElement( 'input', array_merge(
360 $radio,
361 $checkmark,
362 array( 'name' => 'oldid' ) ) );
363 $checkmark = array();
364 }
365 $second = wfElement( 'input', array_merge(
366 $radio,
367 $checkmark,
368 array( 'name' => 'diff' ) ) );
369 return $first . $second;
370 } else {
371 return '';
372 }
373 }
374
375 /** @todo document */
376 function getLatestOffset( $id = null ) {
377 if ( $id === null) $id = $this->mTitle->getArticleID();
378 return $this->getExtremeOffset( $id, 'max' );
379 }
380
381 /** @todo document */
382 function getEarliestOffset( $id = null ) {
383 if ( $id === null) $id = $this->mTitle->getArticleID();
384 return $this->getExtremeOffset( $id, 'min' );
385 }
386
387 /** @todo document */
388 function getExtremeOffset( $id, $func ) {
389 $db =& wfGetDB(DB_SLAVE);
390 return $db->selectField( 'revision',
391 "$func(rev_timestamp)",
392 array( 'rev_page' => $id ),
393 'PageHistory::getExtremeOffset' );
394 }
395
396 /** @todo document */
397 function getLatestId() {
398 if( is_null( $this->mLatestId ) ) {
399 $id = $this->mTitle->getArticleID();
400 $db =& wfGetDB(DB_SLAVE);
401 $this->mLatestId = $db->selectField( 'revision',
402 "max(rev_id)",
403 array( 'rev_page' => $id ),
404 'PageHistory::getLatestID' );
405 }
406 return $this->mLatestId;
407 }
408
409 /** @todo document */
410 function getLastOffsetForPaging( $id, $step ) {
411 $fname = 'PageHistory::getLastOffsetForPaging';
412
413 $dbr =& wfGetDB(DB_SLAVE);
414 $res = $dbr->select(
415 'revision',
416 'rev_timestamp',
417 "rev_page=$id",
418 $fname,
419 array('ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => $step));
420
421 $n = $dbr->numRows( $res );
422 $last = null;
423 while( $obj = $dbr->fetchObject( $res ) ) {
424 $last = $obj->rev_timestamp;
425 }
426 $dbr->freeResult( $res );
427 return $last;
428 }
429
430 /**
431 * @return returns the direction of browsing watchlist
432 */
433 function getDirection() {
434 global $wgRequest;
435 if ($wgRequest->getText("dir") == "prev")
436 return DIR_PREV;
437 else
438 return DIR_NEXT;
439 }
440
441 /** @todo document */
442 function fetchRevisions($limit, $offset, $direction) {
443 global $wgUser, $wgShowUpdatedMarker;
444 $fname = 'PageHistory::fetchRevisions';
445
446 $dbr =& wfGetDB( DB_SLAVE );
447
448 if ($direction == DIR_PREV)
449 list($dirs, $oper) = array("ASC", ">=");
450 else /* $direction == DIR_NEXT */
451 list($dirs, $oper) = array("DESC", "<=");
452
453 if ($offset)
454 $offsets = array("rev_timestamp $oper '$offset'");
455 else
456 $offsets = array();
457
458 $page_id = $this->mTitle->getArticleID();
459
460 $res = $dbr->select(
461 'revision',
462 array('rev_id', 'rev_user', 'rev_comment', 'rev_user_text',
463 'rev_timestamp', 'rev_minor_edit', 'rev_deleted'),
464 array_merge(array("rev_page=$page_id"), $offsets),
465 $fname,
466 array('ORDER BY' => "rev_timestamp $dirs",
467 'USE INDEX' => 'page_timestamp', 'LIMIT' => $limit)
468 );
469
470 $result = array();
471 while (($obj = $dbr->fetchObject($res)) != NULL)
472 $result[] = $obj;
473
474 return $result;
475 }
476
477 /** @todo document */
478 function getNotificationTimestamp() {
479 global $wgUser, $wgShowUpdatedMarker;
480 $fname = 'PageHistory::getNotficationTimestamp';
481
482 if ($this->mNotificationTimestamp !== NULL)
483 return $this->mNotificationTimestamp;
484
485 if ($wgUser->isAnon() || !$wgShowUpdatedMarker)
486 return $this->mNotificationTimestamp = false;
487
488 $dbr =& wfGetDB(DB_SLAVE);
489
490 $this->mNotificationTimestamp = $dbr->selectField(
491 'watchlist',
492 'wl_notificationtimestamp',
493 array( 'wl_namespace' => $this->mTitle->getNamespace(),
494 'wl_title' => $this->mTitle->getDBkey(),
495 'wl_user' => $wgUser->getID()
496 ),
497 $fname);
498
499 return $this->mNotificationTimestamp;
500 }
501
502 /** @todo document */
503 function makeNavbar($revisions, $offset, $limit, $direction) {
504 global $wgTitle, $wgLang;
505
506 $revisions = array_slice($revisions, 0, $limit);
507
508 $latestTimestamp = wfTimestamp(TS_MW, $this->getLatestOffset());
509 $earliestTimestamp = wfTimestamp(TS_MW, $this->getEarliestOffset());
510
511 /*
512 * When we're displaying previous revisions, we need to reverse
513 * the array, because it's queried in reverse order.
514 */
515 if ($direction == DIR_PREV)
516 $revisions = array_reverse($revisions);
517
518 /*
519 * lowts is the timestamp of the first revision on this page.
520 * hights is the timestamp of the last revision.
521 */
522
523 $lowts = $hights = 0;
524
525 if( count( $revisions ) ) {
526 $latestShown = wfTimestamp(TS_MW, $revisions[0]->rev_timestamp);
527 $earliestShown = wfTimestamp(TS_MW, $revisions[count($revisions) - 1]->rev_timestamp);
528 }
529
530 /* Don't announce the limit everywhere if it's the default */
531 $usefulLimit = $limit == $this->defaultLimit ? '' : $limit;
532
533 $urls = array();
534 foreach (array(20, 50, 100, 250, 500) as $num) {
535 $urls[] = $this->MakeLink( $wgLang->formatNum($num),
536 array('offset' => $offset == 0 ? '' : wfTimestamp(TS_MW, $offset), 'limit' => $num, ) );
537 }
538
539 $bits = implode($urls, ' | ');
540
541 wfDebug("latestShown=$latestShown latestTimestamp=$latestTimestamp\n");
542 if( $latestShown < $latestTimestamp ) {
543 $prevtext = $this->MakeLink( wfMsgHtml("prevn", $limit),
544 array( 'dir' => 'prev', 'offset' => $latestShown, 'limit' => $usefulLimit ) );
545 $lasttext = $this->MakeLink( wfMsgHtml('histlast'),
546 array( 'limit' => $usefulLimit ) );
547 } else {
548 $prevtext = wfMsgHtml("prevn", $limit);
549 $lasttext = wfMsgHtml('histlast');
550 }
551
552 wfDebug("earliestShown=$earliestShown earliestTimestamp=$earliestTimestamp\n");
553 if( $earliestShown > $earliestTimestamp ) {
554 $nexttext = $this->MakeLink( wfMsgHtml("nextn", $limit),
555 array( 'offset' => $earliestShown, 'limit' => $usefulLimit ) );
556 $firsttext = $this->MakeLink( wfMsgHtml('histfirst'),
557 array( 'go' => 'first', 'limit' => $usefulLimit ) );
558 } else {
559 $nexttext = wfMsgHtml("nextn", $limit);
560 $firsttext = wfMsgHtml('histfirst');
561 }
562
563 $firstlast = "($lasttext | $firsttext)";
564
565 return "$firstlast " . wfMsgHtml("viewprevnext", $prevtext, $nexttext, $bits);
566 }
567
568 function MakeLink($text, $query = NULL) {
569 if ( $query === null ) return $text;
570 return $this->mSkin->makeKnownLinkObj(
571 $this->mTitle, $text,
572 wfArrayToCGI( $query, array( 'action' => 'history' )));
573 }
574
575
576 }
577
578 ?>