*Add a special page to merge non-overlapping page histories to fix copy-paste moves...
[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
127 $title = Title::newFromText( $page );
128
129 if( strlen( $page ) == 0 || !$title instanceof Title )
130 return false;
131
132 $this->title =& $title;
133 $this->pattern = $pattern;
134 $ns = $title->getNamespace();
135 if ( $pattern && !$wgMiserMode ) {
136 $safetitle = $this->db->escapeLike( $title->getDBkey() ); // use escapeLike to avoid expensive search patterns like 't%st%'
137 $this->whereClauses[] = "log_namespace=$ns AND log_title LIKE '$safetitle%'";
138 } else {
139 $safetitle = $this->db->strencode( $title->getDBkey() );
140 $this->whereClauses[] = "log_namespace=$ns AND log_title = '$safetitle'";
141 }
142 }
143
144 /**
145 * Set the log reader to return only entries in a given time range.
146 * @param string $time Timestamp of one endpoint
147 * @param string $direction either ">=" or "<=" operators
148 * @private
149 */
150 function limitTime( $time, $direction ) {
151 # Direction should be a comparison operator
152 if( empty( $time ) ) {
153 return false;
154 }
155 $safetime = $this->db->strencode( wfTimestamp( TS_MW, $time ) );
156 $this->whereClauses[] = "log_timestamp $direction '$safetime'";
157 }
158
159 /**
160 * Build an SQL query from all the set parameters.
161 * @return string the SQL query
162 * @private
163 */
164 function getQuery() {
165 $logging = $this->db->tableName( "logging" );
166 $sql = "SELECT /*! STRAIGHT_JOIN */ log_type, log_action, log_timestamp,
167 log_user, user_name,
168 log_namespace, log_title, page_id,
169 log_comment, log_params FROM $logging ";
170 if( !empty( $this->joinClauses ) ) {
171 $sql .= implode( ' ', $this->joinClauses );
172 }
173 if( !empty( $this->whereClauses ) ) {
174 $sql .= " WHERE " . implode( ' AND ', $this->whereClauses );
175 }
176 $sql .= " ORDER BY log_timestamp DESC ";
177 $sql = $this->db->limitResult($sql, $this->limit, $this->offset );
178 return $sql;
179 }
180
181 /**
182 * Execute the query and start returning results.
183 * @return ResultWrapper result object to return the relevant rows
184 */
185 function getRows() {
186 $res = $this->db->query( $this->getQuery(), __METHOD__ );
187 return $this->db->resultObject( $res );
188 }
189
190 /**
191 * @return string The query type that this LogReader has been limited to.
192 */
193 function queryType() {
194 return $this->type;
195 }
196
197 /**
198 * @return string The username type that this LogReader has been limited to, if any.
199 */
200 function queryUser() {
201 return $this->user;
202 }
203
204 /**
205 * @return boolean The checkbox, if titles should be searched by a pattern too
206 */
207 function queryPattern() {
208 return $this->pattern;
209 }
210
211 /**
212 * @return string The text of the title that this LogReader has been limited to.
213 */
214 function queryTitle() {
215 if( is_null( $this->title ) ) {
216 return '';
217 } else {
218 return $this->title->getPrefixedText();
219 }
220 }
221
222 /**
223 * Is there at least one row?
224 *
225 * @return bool
226 */
227 public function hasRows() {
228 # Little hack...
229 $limit = $this->limit;
230 $this->limit = 1;
231 $res = $this->db->query( $this->getQuery() );
232 $this->limit = $limit;
233 $ret = $this->db->numRows( $res ) > 0;
234 $this->db->freeResult( $res );
235 return $ret;
236 }
237
238 }
239
240 /**
241 *
242 * @addtogroup SpecialPage
243 */
244 class LogViewer {
245 const NO_ACTION_LINK = 1;
246
247 /**
248 * @var LogReader $reader
249 */
250 var $reader;
251 var $numResults = 0;
252 var $flags = 0;
253
254 /**
255 * @param LogReader &$reader where to get our data from
256 * @param integer $flags Bitwise combination of flags:
257 * self::NO_ACTION_LINK Don't show restore/unblock/block links
258 */
259 function LogViewer( &$reader, $flags = 0 ) {
260 global $wgUser;
261 $this->skin = $wgUser->getSkin();
262 $this->reader =& $reader;
263 $this->flags = $flags;
264 }
265
266 /**
267 * Take over the whole output page in $wgOut with the log display.
268 */
269 function show() {
270 global $wgOut;
271 $this->showHeader( $wgOut );
272 $this->showOptions( $wgOut );
273 $result = $this->getLogRows();
274 if ( $this->numResults > 0 ) {
275 $this->showPrevNext( $wgOut );
276 $this->doShowList( $wgOut, $result );
277 $this->showPrevNext( $wgOut );
278 } else {
279 $this->showError( $wgOut );
280 }
281 }
282
283 /**
284 * Load the data from the linked LogReader
285 * Preload the link cache
286 * Initialise numResults
287 *
288 * Must be called before calling showPrevNext
289 *
290 * @return object database result set
291 */
292 function getLogRows() {
293 $result = $this->reader->getRows();
294 $this->numResults = 0;
295
296 // Fetch results and form a batch link existence query
297 $batch = new LinkBatch;
298 while ( $s = $result->fetchObject() ) {
299 // User link
300 $batch->addObj( Title::makeTitleSafe( NS_USER, $s->user_name ) );
301 $batch->addObj( Title::makeTitleSafe( NS_USER_TALK, $s->user_name ) );
302
303 // Move destination link
304 if ( $s->log_type == 'move' ) {
305 $paramArray = LogPage::extractParams( $s->log_params );
306 $title = Title::newFromText( $paramArray[0] );
307 $batch->addObj( $title );
308 }
309 ++$this->numResults;
310 }
311 $batch->execute();
312
313 return $result;
314 }
315
316
317 /**
318 * Output just the list of entries given by the linked LogReader,
319 * with extraneous UI elements. Use for displaying log fragments in
320 * another page (eg at Special:Undelete)
321 * @param OutputPage $out where to send output
322 */
323 function showList( &$out ) {
324 $result = $this->getLogRows();
325 if ( $this->numResults > 0 ) {
326 $this->doShowList( $out, $result );
327 } else {
328 $this->showError( $out );
329 }
330 }
331
332 function doShowList( &$out, $result ) {
333 // Rewind result pointer and go through it again, making the HTML
334 $html = "\n<ul>\n";
335 $result->seek( 0 );
336 while( $s = $result->fetchObject() ) {
337 $html .= $this->logLine( $s );
338 }
339 $html .= "\n</ul>\n";
340 $out->addHTML( $html );
341 $result->free();
342 }
343
344 function showError( &$out ) {
345 $out->addWikiText( wfMsg( 'logempty' ) );
346 }
347
348 /**
349 * @param Object $s a single row from the result set
350 * @return string Formatted HTML list item
351 * @private
352 */
353 function logLine( $s ) {
354 global $wgLang, $wgUser, $wgContLang;
355 $skin = $wgUser->getSkin();
356 $title = Title::makeTitle( $s->log_namespace, $s->log_title );
357 $time = $wgLang->timeanddate( wfTimestamp(TS_MW, $s->log_timestamp), true );
358
359 // Enter the existence or non-existence of this page into the link cache,
360 // for faster makeLinkObj() in LogPage::actionText()
361 $linkCache =& LinkCache::singleton();
362 if( $s->page_id ) {
363 $linkCache->addGoodLinkObj( $s->page_id, $title );
364 } else {
365 $linkCache->addBadLinkObj( $title );
366 }
367
368 $userLink = $this->skin->userLink( $s->log_user, $s->user_name ) . $this->skin->userToolLinksRedContribs( $s->log_user, $s->user_name );
369 $comment = $wgContLang->getDirMark() . $this->skin->commentBlock( $s->log_comment );
370 $paramArray = LogPage::extractParams( $s->log_params );
371 $revert = '';
372 // show revertmove link
373 if ( !( $this->flags & self::NO_ACTION_LINK ) ) {
374 if ( $s->log_type == 'move' && isset( $paramArray[0] ) && $wgUser->isAllowed( 'move' ) ) {
375 $destTitle = Title::newFromText( $paramArray[0] );
376 if ( $destTitle ) {
377 $revert = '(' . $this->skin->makeKnownLinkObj( SpecialPage::getTitleFor( 'Movepage' ),
378 wfMsg( 'revertmove' ),
379 'wpOldTitle=' . urlencode( $destTitle->getPrefixedDBkey() ) .
380 '&wpNewTitle=' . urlencode( $title->getPrefixedDBkey() ) .
381 '&wpReason=' . urlencode( wfMsgForContent( 'revertmove' ) ) .
382 '&wpMovetalk=0' ) . ')';
383 }
384 // show undelete link
385 } elseif ( $s->log_action == 'delete' && $wgUser->isAllowed( 'delete' ) ) {
386 $revert = '(' . $this->skin->makeKnownLinkObj( SpecialPage::getTitleFor( 'Undelete' ),
387 wfMsg( 'undeletebtn' ) ,
388 'target='. urlencode( $title->getPrefixedDBkey() ) ) . ')';
389 // show unblock link
390 } elseif ( $s->log_action == 'block' && $wgUser->isAllowed( 'block' ) ) {
391 $revert = '(' . $skin->makeKnownLinkObj( SpecialPage::getTitleFor( 'Ipblocklist' ),
392 wfMsg( 'unblocklink' ),
393 'action=unblock&ip=' . urlencode( $s->log_title ) ) . ')';
394 // show change protection link
395 } elseif ( ( $s->log_action == 'protect' || $s->log_action == 'modify' ) && $wgUser->isAllowed( 'protect' ) ) {
396 $revert = '(' . $skin->makeKnownLinkObj( $title, wfMsg( 'protect_change' ), 'action=unprotect' ) . ')';
397 // show user tool links for self created users
398 // @todo The extension should be handling this, get it out of core! E.g. Use the hook below.
399 } elseif ( $s->log_action == 'create2' ) {
400 if( isset( $paramArray[0] ) ) {
401 $revert = $this->skin->userToolLinks( $paramArray[0], $s->log_title, true );
402 } else {
403 # Fall back to a blue contributions link
404 $revert = $this->skin->userToolLinks( 1, $s->log_title );
405 }
406 # Suppress $comment from old entries, not needed and can contain incorrect links
407 $comment = '';
408 // Show unmerge link
409 } elseif ( $s->log_action == 'merge' ) {
410 $merge = SpecialPage::getTitleFor( 'Mergehistory' );
411 $revert = '(' . $this->skin->makeKnownLinkObj( $merge, wfMsg('revertmerge'),
412 wfArrayToCGI( array('target' => $paramArray[0], 'dest' => $title->getPrefixedText() ) ) ) . ')';
413 } elseif ( wfRunHooks( 'LogLine', array( $s->log_type, $s->log_action, $title, $paramArray, &$comment, &$revert ) ) ) {
414 // wfDebug( "Invoked LogLine hook for " $s->log_type . ", " . $s->log_action . "\n" );
415 // Do nothing. The implementation is handled by the hook modifiying the passed-by-ref parameters.
416 }
417 }
418
419 $action = LogPage::actionText( $s->log_type, $s->log_action, $title, $this->skin, $paramArray, true );
420 $out = "<li>$time $userLink $action $comment $revert</li>\n";
421 return $out;
422 }
423
424 /**
425 * @param OutputPage &$out where to send output
426 * @private
427 */
428 function showHeader( &$out ) {
429 $type = $this->reader->queryType();
430 if( LogPage::isLogType( $type ) ) {
431 $out->setPageTitle( LogPage::logName( $type ) );
432 $out->addWikiText( LogPage::logHeader( $type ) );
433 }
434 }
435
436 /**
437 * @param OutputPage &$out where to send output
438 * @private
439 */
440 function showOptions( &$out ) {
441 global $wgScript, $wgMiserMode;
442 $action = htmlspecialchars( $wgScript );
443 $title = SpecialPage::getTitleFor( 'Log' );
444 $special = htmlspecialchars( $title->getPrefixedDBkey() );
445 $out->addHTML( "<form action=\"$action\" method=\"get\">\n" .
446 '<fieldset>' .
447 Xml::element( 'legend', array(), wfMsg( 'log' ) ) .
448 Xml::hidden( 'title', $special ) . "\n" .
449 $this->getTypeMenu() . "\n" .
450 $this->getUserInput() . "\n" .
451 $this->getTitleInput() . "\n" .
452 (!$wgMiserMode?($this->getTitlePattern()."\n"):"") .
453 Xml::submitButton( wfMsg( 'allpagessubmit' ) ) . "\n" .
454 "</fieldset></form>" );
455 }
456
457 /**
458 * @return string Formatted HTML
459 * @private
460 */
461 function getTypeMenu() {
462 $out = "<select name='type'>\n";
463
464 $validTypes = LogPage::validTypes();
465 $m = array(); // Temporary array
466
467 // First pass to load the log names
468 foreach( $validTypes as $type ) {
469 $text = LogPage::logName( $type );
470 $m[$text] = $type;
471 }
472
473 // Second pass to sort by name
474 ksort($m);
475
476 // Third pass generates sorted XHTML content
477 foreach( $m as $text => $type ) {
478 $selected = ($type == $this->reader->queryType());
479 $out .= Xml::option( $text, $type, $selected ) . "\n";
480 }
481
482 $out .= '</select>';
483 return $out;
484 }
485
486 /**
487 * @return string Formatted HTML
488 * @private
489 */
490 function getUserInput() {
491 $user = $this->reader->queryUser();
492 return Xml::inputLabel( wfMsg( 'specialloguserlabel' ), 'user', 'user', 12, $user );
493 }
494
495 /**
496 * @return string Formatted HTML
497 * @private
498 */
499 function getTitleInput() {
500 $title = $this->reader->queryTitle();
501 return Xml::inputLabel( wfMsg( 'speciallogtitlelabel' ), 'page', 'page', 20, $title );
502 }
503
504 /**
505 * @return boolean Checkbox
506 * @private
507 */
508 function getTitlePattern() {
509 $pattern = $this->reader->queryPattern();
510 return Xml::checkLabel( wfMsg( 'log-title-wildcard' ), 'pattern', 'pattern', $pattern );
511 }
512
513 /**
514 * @param OutputPage &$out where to send output
515 * @private
516 */
517 function showPrevNext( &$out ) {
518 global $wgContLang,$wgRequest;
519 $pieces = array();
520 $pieces[] = 'type=' . urlencode( $this->reader->queryType() );
521 $pieces[] = 'user=' . urlencode( $this->reader->queryUser() );
522 $pieces[] = 'page=' . urlencode( $this->reader->queryTitle() );
523 $pieces[] = 'pattern=' . urlencode( $this->reader->queryPattern() );
524 $bits = implode( '&', $pieces );
525 list( $limit, $offset ) = $wgRequest->getLimitOffset();
526
527 # TODO: use timestamps instead of offsets to make it more natural
528 # to go huge distances in time
529 $html = wfViewPrevNext( $offset, $limit,
530 $wgContLang->specialpage( 'Log' ),
531 $bits,
532 $this->numResults < $limit);
533 $out->addHTML( '<p>' . $html . '</p>' );
534 }
535 }