* (bug 7071) Properly handle an 'oldid' passed to view or edit that doesn't
[lhc/web/wiklou.git] / includes / SpecialLog.php
1 <?php
2 # Copyright (C) 2004 Brion Vibber <brion@pobox.com>
3 # http://www.mediawiki.org/
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 # http://www.gnu.org/copyleft/gpl.html
19
20 /**
21 *
22 * @addtogroup SpecialPage
23 */
24
25 /**
26 * constructor
27 */
28 function wfSpecialLog( $par = '' ) {
29 global $wgRequest;
30 $logReader = new LogReader( $wgRequest );
31 if( $wgRequest->getVal( 'type' ) == '' && $par != '' ) {
32 $logReader->limitType( $par );
33 }
34 $logViewer = new LogViewer( $logReader );
35 $logViewer->show();
36 }
37
38 /**
39 *
40 * @addtogroup SpecialPage
41 */
42 class LogReader {
43 var $db, $joinClauses, $whereClauses;
44 var $type = '', $user = '', $title = null, $pattern = false;
45
46 /**
47 * @param WebRequest $request For internal use use a FauxRequest object to pass arbitrary parameters.
48 */
49 function LogReader( $request ) {
50 $this->db = wfGetDB( DB_SLAVE );
51 $this->setupQuery( $request );
52 }
53
54 /**
55 * Basic setup and applies the limiting factors from the WebRequest object.
56 * @param WebRequest $request
57 * @private
58 */
59 function setupQuery( $request ) {
60 $page = $this->db->tableName( 'page' );
61 $user = $this->db->tableName( 'user' );
62 $this->joinClauses = array(
63 "LEFT OUTER JOIN $page ON log_namespace=page_namespace AND log_title=page_title",
64 "INNER JOIN $user ON user_id=log_user" );
65 $this->whereClauses = array();
66
67 $this->limitType( $request->getVal( 'type' ) );
68 $this->limitUser( $request->getText( 'user' ) );
69 $this->limitTitle( $request->getText( 'page' ) , $request->getBool( 'pattern' ) );
70 $this->limitTime( $request->getVal( 'from' ), '>=' );
71 $this->limitTime( $request->getVal( 'until' ), '<=' );
72
73 list( $this->limit, $this->offset ) = $request->getLimitOffset();
74
75 // XXX This all needs to use Pager, ugly hack for now.
76 global $wgMiserMode;
77 if( $wgMiserMode )
78 $this->offset = min( $this->offset, 10000 );
79 }
80
81 /**
82 * Set the log reader to return only entries of the given type.
83 * @param string $type A log type ('upload', 'delete', etc)
84 * @private
85 */
86 function limitType( $type ) {
87 if( empty( $type ) ) {
88 return false;
89 }
90 $this->type = $type;
91 $safetype = $this->db->strencode( $type );
92 $this->whereClauses[] = "log_type='$safetype'";
93 }
94
95 /**
96 * Set the log reader to return only entries by the given user.
97 * @param string $name (In)valid user name
98 * @private
99 */
100 function limitUser( $name ) {
101 if ( $name == '' )
102 return false;
103 $usertitle = Title::makeTitleSafe( NS_USER, $name );
104 if ( is_null( $usertitle ) )
105 return false;
106 $this->user = $usertitle->getText();
107
108 /* Fetch userid at first, if known, provides awesome query plan afterwards */
109 $userid = $this->db->selectField('user','user_id',array('user_name'=>$this->user));
110 if (!$userid)
111 /* It should be nicer to abort query at all,
112 but for now it won't pass anywhere behind the optimizer */
113 $this->whereClauses[] = "NULL";
114 else
115 $this->whereClauses[] = "log_user=$userid";
116 }
117
118 /**
119 * Set the log reader to return only entries affecting the given page.
120 * (For the block and rights logs, this is a user page.)
121 * @param string $page Title name as text
122 * @private
123 */
124 function limitTitle( $page , $pattern ) {
125 global $wgMiserMode;
126 $title = Title::newFromText( $page );
127 if( empty( $page ) || is_null( $title ) ) {
128 return false;
129 }
130 $this->title =& $title;
131 $this->pattern = $pattern;
132 $ns = $title->getNamespace();
133 if ( $pattern && !$wgMiserMode ) {
134 $safetitle = $this->db->escapeLike( $title->getDBkey() ); // use escapeLike to avoid expensive search patterns like 't%st%'
135 $this->whereClauses[] = "log_namespace=$ns AND log_title LIKE '$safetitle%'";
136 } else {
137 $safetitle = $this->db->strencode( $title->getDBkey() );
138 $this->whereClauses[] = "log_namespace=$ns AND log_title = '$safetitle'";
139 }
140 }
141
142 /**
143 * Set the log reader to return only entries in a given time range.
144 * @param string $time Timestamp of one endpoint
145 * @param string $direction either ">=" or "<=" operators
146 * @private
147 */
148 function limitTime( $time, $direction ) {
149 # Direction should be a comparison operator
150 if( empty( $time ) ) {
151 return false;
152 }
153 $safetime = $this->db->strencode( wfTimestamp( TS_MW, $time ) );
154 $this->whereClauses[] = "log_timestamp $direction '$safetime'";
155 }
156
157 /**
158 * Build an SQL query from all the set parameters.
159 * @return string the SQL query
160 * @private
161 */
162 function getQuery() {
163 $logging = $this->db->tableName( "logging" );
164 $sql = "SELECT /*! STRAIGHT_JOIN */ log_type, log_action, log_timestamp,
165 log_user, user_name,
166 log_namespace, log_title, page_id,
167 log_comment, log_params FROM $logging ";
168 if( !empty( $this->joinClauses ) ) {
169 $sql .= implode( ' ', $this->joinClauses );
170 }
171 if( !empty( $this->whereClauses ) ) {
172 $sql .= " WHERE " . implode( ' AND ', $this->whereClauses );
173 }
174 $sql .= " ORDER BY log_timestamp DESC ";
175 $sql = $this->db->limitResult($sql, $this->limit, $this->offset );
176 return $sql;
177 }
178
179 /**
180 * Execute the query and start returning results.
181 * @return ResultWrapper result object to return the relevant rows
182 */
183 function getRows() {
184 $res = $this->db->query( $this->getQuery(), 'LogReader::getRows' );
185 return $this->db->resultObject( $res );
186 }
187
188 /**
189 * @return string The query type that this LogReader has been limited to.
190 */
191 function queryType() {
192 return $this->type;
193 }
194
195 /**
196 * @return string The username type that this LogReader has been limited to, if any.
197 */
198 function queryUser() {
199 return $this->user;
200 }
201
202 /**
203 * @return boolean The checkbox, if titles should be searched by a pattern too
204 */
205 function queryPattern() {
206 return $this->pattern;
207 }
208
209 /**
210 * @return string The text of the title that this LogReader has been limited to.
211 */
212 function queryTitle() {
213 if( is_null( $this->title ) ) {
214 return '';
215 } else {
216 return $this->title->getPrefixedText();
217 }
218 }
219
220 /**
221 * Is there at least one row?
222 *
223 * @return bool
224 */
225 public function hasRows() {
226 # Little hack...
227 $limit = $this->limit;
228 $this->limit = 1;
229 $res = $this->db->query( $this->getQuery() );
230 $this->limit = $limit;
231 $ret = $this->db->numRows( $res ) > 0;
232 $this->db->freeResult( $res );
233 return $ret;
234 }
235
236 }
237
238 /**
239 *
240 * @addtogroup SpecialPage
241 */
242 class LogViewer {
243 /**
244 * @var LogReader $reader
245 */
246 var $reader;
247 var $numResults = 0;
248
249 /**
250 * @param LogReader &$reader where to get our data from
251 */
252 function LogViewer( &$reader ) {
253 global $wgUser;
254 $this->skin = $wgUser->getSkin();
255 $this->reader =& $reader;
256 }
257
258 /**
259 * Take over the whole output page in $wgOut with the log display.
260 */
261 function show() {
262 global $wgOut;
263 $this->showHeader( $wgOut );
264 $this->showOptions( $wgOut );
265 $result = $this->getLogRows();
266 if ( $this->numResults > 0 ) {
267 $this->showPrevNext( $wgOut );
268 $this->doShowList( $wgOut, $result );
269 $this->showPrevNext( $wgOut );
270 } else {
271 $this->showError( $wgOut );
272 }
273 }
274
275 /**
276 * Load the data from the linked LogReader
277 * Preload the link cache
278 * Initialise numResults
279 *
280 * Must be called before calling showPrevNext
281 *
282 * @return object database result set
283 */
284 function getLogRows() {
285 $result = $this->reader->getRows();
286 $this->numResults = 0;
287
288 // Fetch results and form a batch link existence query
289 $batch = new LinkBatch;
290 while ( $s = $result->fetchObject() ) {
291 // User link
292 $batch->addObj( Title::makeTitleSafe( NS_USER, $s->user_name ) );
293 $batch->addObj( Title::makeTitleSafe( NS_USER_TALK, $s->user_name ) );
294
295 // Move destination link
296 if ( $s->log_type == 'move' ) {
297 $paramArray = LogPage::extractParams( $s->log_params );
298 $title = Title::newFromText( $paramArray[0] );
299 $batch->addObj( $title );
300 }
301 ++$this->numResults;
302 }
303 $batch->execute();
304
305 return $result;
306 }
307
308
309 /**
310 * Output just the list of entries given by the linked LogReader,
311 * with extraneous UI elements. Use for displaying log fragments in
312 * another page (eg at Special:Undelete)
313 * @param OutputPage $out where to send output
314 */
315 function showList( &$out ) {
316 $result = $this->getLogRows();
317 if ( $this->numResults > 0 ) {
318 $this->doShowList( $out, $result );
319 } else {
320 $this->showError( $out );
321 }
322 }
323
324 function doShowList( &$out, $result ) {
325 global $wgLang;
326
327 $lastdate = '';
328 $listopen = false;
329 // Rewind result pointer and go through it again, making the HTML
330 $html = '';
331 $result->seek( 0 );
332 while( $s = $result->fetchObject() ) {
333 $date = $wgLang->date( $s->log_timestamp, /* adj */ true );
334 if ( $date != $lastdate ) {
335 if ( $listopen ) { $html .= Xml::closeElement( 'ul' ); }
336 $html .= Xml::element('h4', null, $date) . "\n";
337 $html .= Xml::openElement( 'ul' );
338 $listopen = true;
339 $lastdate = $date;
340 }
341 $html .= Xml::tags('li', null, $this->logLine( $s ) ) . "\n";
342 }
343 if ( $listopen ) { $html .= Xml::closeElement( 'ul' ); }
344 $out->addHTML( $html );
345 $result->free();
346 }
347
348 function showError( &$out ) {
349 $out->addWikiText( wfMsg( 'logempty' ) );
350 }
351
352 /**
353 * @param Object $s a single row from the result set
354 * @return string Formatted HTML list item
355 * @private
356 */
357 function logLine( $s ) {
358 global $wgLang, $wgUser;;
359 $skin = $wgUser->getSkin();
360 $title = Title::makeTitle( $s->log_namespace, $s->log_title );
361 $time = $wgLang->time( wfTimestamp(TS_MW, $s->log_timestamp), true );
362
363 // Enter the existence or non-existence of this page into the link cache,
364 // for faster makeLinkObj() in LogPage::actionText()
365 $linkCache =& LinkCache::singleton();
366 if( $s->page_id ) {
367 $linkCache->addGoodLinkObj( $s->page_id, $title );
368 } else {
369 $linkCache->addBadLinkObj( $title );
370 }
371
372 $userLink = $this->skin->userLink( $s->log_user, $s->user_name ) . $this->skin->userToolLinksRedContribs( $s->log_user, $s->user_name );
373 $comment = $this->skin->commentBlock( $s->log_comment );
374 $paramArray = LogPage::extractParams( $s->log_params );
375 $revert = '';
376 // show revertmove link
377 if ( $s->log_type == 'move' && isset( $paramArray[0] ) ) {
378 $destTitle = Title::newFromText( $paramArray[0] );
379 if ( $destTitle ) {
380 $revert = '(' . $this->skin->makeKnownLinkObj( SpecialPage::getTitleFor( 'Movepage' ),
381 wfMsg( 'revertmove' ),
382 'wpOldTitle=' . urlencode( $destTitle->getPrefixedDBkey() ) .
383 '&wpNewTitle=' . urlencode( $title->getPrefixedDBkey() ) .
384 '&wpReason=' . urlencode( wfMsgForContent( 'revertmove' ) ) .
385 '&wpMovetalk=0' ) . ')';
386 }
387 // show undelete link
388 } elseif ( $s->log_action == 'delete' && $wgUser->isAllowed( 'delete' ) ) {
389 $revert = '(' . $this->skin->makeKnownLinkObj( SpecialPage::getTitleFor( 'Undelete' ),
390 wfMsg( 'undeletebtn' ) ,
391 'target='. urlencode( $title->getPrefixedDBkey() ) ) . ')';
392
393 // show unblock link
394 } elseif ( $s->log_action == 'block' && $wgUser->isAllowed( 'block' ) ) {
395 $revert = '(' . $skin->makeKnownLinkObj( SpecialPage::getTitleFor( 'Ipblocklist' ),
396 wfMsg( 'unblocklink' ),
397 'action=unblock&ip=' . urlencode( $s->log_title ) ) . ')';
398 // show change protection link
399 } elseif ( ( $s->log_action == 'protect' || $s->log_action == 'modify' ) && $wgUser->isAllowed( 'protect' ) ) {
400 $revert = '(' . $skin->makeKnownLinkObj( $title, wfMsg( 'protect_change' ), 'action=unprotect' ) . ')';
401 // show user tool links for self created users
402 // TODO: The extension should be handling this, get it out of core!
403 } elseif ( $s->log_action == 'create2' ) {
404 if( isset( $paramArray[0] ) ) {
405 $revert = $this->skin->userToolLinks( $paramArray[0], $s->log_title, true );
406 } else {
407 # Fall back to a blue contributions link
408 $revert = $this->skin->userToolLinks( 1, $s->log_title );
409 }
410 # Suppress $comment from old entries, not needed and can contain incorrect links
411 $comment = '';
412 }
413
414 $action = LogPage::actionText( $s->log_type, $s->log_action, $title, $this->skin, $paramArray, true, true );
415 $out = "$time $userLink $action $comment $revert";
416 return $out;
417 }
418
419 /**
420 * @param OutputPage &$out where to send output
421 * @private
422 */
423 function showHeader( &$out ) {
424 $type = $this->reader->queryType();
425 if( LogPage::isLogType( $type ) ) {
426 $out->setPageTitle( LogPage::logName( $type ) );
427 $out->addWikiText( LogPage::logHeader( $type ) );
428 }
429 }
430
431 /**
432 * @param OutputPage &$out where to send output
433 * @private
434 */
435 function showOptions( &$out ) {
436 global $wgScript, $wgMiserMode;
437 $action = htmlspecialchars( $wgScript );
438 $title = SpecialPage::getTitleFor( 'Log' );
439 $special = htmlspecialchars( $title->getPrefixedDBkey() );
440 $out->addHTML( "<form action=\"$action\" method=\"get\">\n" .
441 '<fieldset>' .
442 Xml::element( 'legend', array(), wfMsg( 'log' ) ) .
443 Xml::hidden( 'title', $special ) . "\n" .
444 $this->getTypeMenu() . "\n" .
445 $this->getUserInput() . "\n" .
446 $this->getTitleInput() . "\n" .
447 (!$wgMiserMode?($this->getTitlePattern()."\n"):"") .
448 Xml::submitButton( wfMsg( 'allpagessubmit' ) ) . "\n" .
449 "</fieldset></form>" );
450 }
451
452 /**
453 * @return string Formatted HTML
454 * @private
455 */
456 function getTypeMenu() {
457 $out = "<select name='type'>\n";
458
459 $validTypes = LogPage::validTypes();
460 $m = array(); // Temporary array
461
462 // First pass to load the log names
463 foreach( $validTypes as $type ) {
464 $text = LogPage::logName( $type );
465 $m[$text] = $type;
466 }
467
468 // Second pass to sort by name
469 ksort($m);
470
471 // Third pass generates sorted XHTML content
472 foreach( $m as $text => $type ) {
473 $selected = ($type == $this->reader->queryType());
474 $out .= Xml::option( $text, $type, $selected ) . "\n";
475 }
476
477 $out .= '</select>';
478 return $out;
479 }
480
481 /**
482 * @return string Formatted HTML
483 * @private
484 */
485 function getUserInput() {
486 $user = $this->reader->queryUser();
487 return Xml::inputLabel( wfMsg( 'specialloguserlabel' ), 'user', 'user', 12, $user );
488 }
489
490 /**
491 * @return string Formatted HTML
492 * @private
493 */
494 function getTitleInput() {
495 $title = $this->reader->queryTitle();
496 return Xml::inputLabel( wfMsg( 'speciallogtitlelabel' ), 'page', 'page', 20, $title );
497 }
498
499 /**
500 * @return boolean Checkbox
501 * @private
502 */
503 function getTitlePattern() {
504 $pattern = $this->reader->queryPattern();
505 return Xml::checkLabel( wfMsg( 'log-title-wildcard' ), 'pattern', 'pattern', $pattern );
506 }
507
508 /**
509 * @param OutputPage &$out where to send output
510 * @private
511 */
512 function showPrevNext( &$out ) {
513 global $wgContLang,$wgRequest;
514 $pieces = array();
515 $pieces[] = 'type=' . urlencode( $this->reader->queryType() );
516 $pieces[] = 'user=' . urlencode( $this->reader->queryUser() );
517 $pieces[] = 'page=' . urlencode( $this->reader->queryTitle() );
518 $pieces[] = 'pattern=' . urlencode( $this->reader->queryPattern() );
519 $bits = implode( '&', $pieces );
520 list( $limit, $offset ) = $wgRequest->getLimitOffset();
521
522 # TODO: use timestamps instead of offsets to make it more natural
523 # to go huge distances in time
524 $html = wfViewPrevNext( $offset, $limit,
525 $wgContLang->specialpage( 'Log' ),
526 $bits,
527 $this->numResults < $limit);
528 $out->addHTML( '<p>' . $html . '</p>' );
529 }
530 }
531
532
533 ?>