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