Add major contributors raymond, ialex, siebrand
[lhc/web/wiklou.git] / includes / LogEventsList.php
1 <?php
2 # Copyright (C) 2004 Brion Vibber <brion@pobox.com>, 2008 Aaron Schulz
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 class LogEventsList {
21 const NO_ACTION_LINK = 1;
22
23 private $skin;
24 private $out;
25 public $flags;
26
27 public function __construct( $skin, $out, $flags = 0 ) {
28 $this->skin = $skin;
29 $this->out = $out;
30 $this->flags = $flags;
31 $this->preCacheMessages();
32 }
33
34 /**
35 * As we use the same small set of messages in various methods and that
36 * they are called often, we call them once and save them in $this->message
37 */
38 private function preCacheMessages() {
39 // Precache various messages
40 if( !isset( $this->message ) ) {
41 $messages = array( 'revertmerge', 'protect_change', 'unblocklink', 'change-blocklink',
42 'revertmove', 'undeletelink', 'undeleteviewlink', 'revdel-restore', 'rev-delundel', 'hist', 'diff',
43 'pipe-separator' );
44 foreach( $messages as $msg ) {
45 $this->message[$msg] = wfMsgExt( $msg, array( 'escapenoentities' ) );
46 }
47 }
48 }
49
50 /**
51 * Set page title and show header for this log type
52 * @param $type String
53 */
54 public function showHeader( $type ) {
55 if( LogPage::isLogType( $type ) ) {
56 $this->out->setPageTitle( LogPage::logName( $type ) );
57 $this->out->addHTML( LogPage::logHeader( $type ) );
58 }
59 }
60
61 /**
62 * Show options for the log list
63 * @param $types string or Array
64 * @param $user String
65 * @param $page String
66 * @param $pattern String
67 * @param $year Integer: year
68 * @param $month Integer: month
69 * @param $filter: array
70 * @param $tagFilter: array?
71 */
72 public function showOptions( $types=array(), $user='', $page='', $pattern='', $year='',
73 $month = '', $filter = null, $tagFilter='' )
74 {
75 global $wgScript, $wgMiserMode;
76 $action = htmlspecialchars( $wgScript );
77 $title = SpecialPage::getTitleFor( 'Log' );
78 $special = htmlspecialchars( $title->getPrefixedDBkey() );
79 // For B/C, we take strings, but make sure they are converted...
80 $types = ($types === '') ? array() : (array)$types;
81
82 $tagSelector = ChangeTags::buildTagFilterSelector( $tagFilter );
83
84 $this->out->addHTML( "<form action=\"$action\" method=\"get\"><fieldset>" .
85 Xml::element( 'legend', array(), wfMsg( 'log' ) ) .
86 Xml::hidden( 'title', $special ) . "\n" .
87 $this->getTypeMenu( $types ) . "\n" .
88 $this->getUserInput( $user ) . "\n" .
89 $this->getTitleInput( $page ) . "\n" .
90 ( !$wgMiserMode ? ($this->getTitlePattern( $pattern )."\n") : "" ) .
91 "<p>" . Xml::dateMenu( $year, $month ) . "\n" .
92 ( $tagSelector ? Xml::tags( 'p', null, implode( '&nbsp;', $tagSelector ) ) :'' ). "\n" .
93 ( $filter ? "</p><p>".$this->getFilterLinks( $filter )."\n" : "" ) . "\n" .
94 Xml::submitButton( wfMsg( 'allpagessubmit' ) ) . "</p>\n" .
95 "</fieldset></form>"
96 );
97 }
98
99 /**
100 * @param $filter Array
101 * @return String: Formatted HTML
102 */
103 private function getFilterLinks( $filter ) {
104 global $wgTitle, $wgLang;
105 // show/hide links
106 $messages = array( wfMsgHtml( 'show' ), wfMsgHtml( 'hide' ) );
107 // Option value -> message mapping
108 $links = array();
109 $hiddens = ''; // keep track for "go" button
110 foreach( $filter as $type => $val ) {
111 // Should the below assignment be outside the foreach?
112 // Then it would have to be copied. Not certain what is more expensive.
113 $query = $this->getDefaultQuery();
114 $queryKey = "hide_{$type}_log";
115
116 $hideVal = 1 - intval($val);
117 $query[$queryKey] = $hideVal;
118
119 $link = $this->skin->link(
120 $wgTitle,
121 $messages[$hideVal],
122 array(),
123 $query,
124 array( 'known', 'noclasses' )
125 );
126
127 $links[$type] = wfMsgHtml( "log-show-hide-{$type}", $link );
128 $hiddens .= Xml::hidden( "hide_{$type}_log", $val ) . "\n";
129 }
130 // Build links
131 return '<small>'.$wgLang->pipeList( $links ) . '</small>' . $hiddens;
132 }
133
134 private function getDefaultQuery() {
135 if ( !isset( $this->mDefaultQuery ) ) {
136 $this->mDefaultQuery = $_GET;
137 unset( $this->mDefaultQuery['title'] );
138 unset( $this->mDefaultQuery['dir'] );
139 unset( $this->mDefaultQuery['offset'] );
140 unset( $this->mDefaultQuery['limit'] );
141 unset( $this->mDefaultQuery['order'] );
142 unset( $this->mDefaultQuery['month'] );
143 unset( $this->mDefaultQuery['year'] );
144 }
145 return $this->mDefaultQuery;
146 }
147
148 /**
149 * @param $queryTypes Array
150 * @return String: Formatted HTML
151 */
152 private function getTypeMenu( $queryTypes ) {
153 global $wgLogRestrictions, $wgUser;
154
155 $html = "<select name='type'>\n";
156
157 $validTypes = LogPage::validTypes();
158 $typesByName = array(); // Temporary array
159
160 // First pass to load the log names
161 foreach( $validTypes as $type ) {
162 $text = LogPage::logName( $type );
163 $typesByName[$text] = $type;
164 }
165
166 // Second pass to sort by name
167 ksort($typesByName);
168
169 // Note the query type
170 $queryType = count($queryTypes) == 1 ? $queryTypes[0] : '';
171 // Third pass generates sorted XHTML content
172 foreach( $typesByName as $text => $type ) {
173 $selected = ($type == $queryType);
174 // Restricted types
175 if ( isset($wgLogRestrictions[$type]) ) {
176 if ( $wgUser->isAllowed( $wgLogRestrictions[$type] ) ) {
177 $html .= Xml::option( $text, $type, $selected ) . "\n";
178 }
179 } else {
180 $html .= Xml::option( $text, $type, $selected ) . "\n";
181 }
182 }
183
184 $html .= '</select>';
185 return $html;
186 }
187
188 /**
189 * @param $user String
190 * @return String: Formatted HTML
191 */
192 private function getUserInput( $user ) {
193 return Xml::inputLabel( wfMsg( 'specialloguserlabel' ), 'user', 'mw-log-user', 15, $user );
194 }
195
196 /**
197 * @param $title String
198 * @return String: Formatted HTML
199 */
200 private function getTitleInput( $title ) {
201 return Xml::inputLabel( wfMsg( 'speciallogtitlelabel' ), 'page', 'mw-log-page', 20, $title );
202 }
203
204 /**
205 * @return boolean Checkbox
206 */
207 private function getTitlePattern( $pattern ) {
208 return '<span style="white-space: nowrap">' .
209 Xml::checkLabel( wfMsg( 'log-title-wildcard' ), 'pattern', 'pattern', $pattern ) .
210 '</span>';
211 }
212
213 public function beginLogEventsList() {
214 return "<ul>\n";
215 }
216
217 public function endLogEventsList() {
218 return "</ul>\n";
219 }
220
221 /**
222 * @param $row Row: a single row from the result set
223 * @return String: Formatted HTML list item
224 */
225 public function logLine( $row ) {
226 global $wgLang, $wgUser, $wgContLang;
227
228 $title = Title::makeTitle( $row->log_namespace, $row->log_title );
229 $classes = array( "mw-logline-{$row->log_type}" );
230 $time = $wgLang->timeanddate( wfTimestamp(TS_MW, $row->log_timestamp), true );
231 // User links
232 if( self::isDeleted($row,LogPage::DELETED_USER) ) {
233 $userLink = '<span class="history-deleted">' . wfMsgHtml( 'rev-deleted-user' ) . '</span>';
234 } else {
235 $userLink = $this->skin->userLink( $row->log_user, $row->user_name ) .
236 $this->skin->userToolLinks( $row->log_user, $row->user_name, true, 0, $row->user_editcount );
237 }
238 // Comment
239 if( self::isDeleted($row,LogPage::DELETED_COMMENT) ) {
240 $comment = '<span class="history-deleted">' . wfMsgHtml('rev-deleted-comment') . '</span>';
241 } else {
242 $comment = $wgContLang->getDirMark() . $this->skin->commentBlock( $row->log_comment );
243 }
244 // Extract extra parameters
245 $paramArray = LogPage::extractParams( $row->log_params );
246 $revert = $del = '';
247 // Some user can hide log items and have review links
248 if( !($this->flags & self::NO_ACTION_LINK) && $wgUser->isAllowed( 'deleterevision' ) ) {
249 $del = $this->getShowHideLinks( $row ) . ' ';
250 }
251 // Add review links and such...
252 if( ($this->flags & self::NO_ACTION_LINK) || ($row->log_deleted & LogPage::DELETED_ACTION) ) {
253 // Action text is suppressed...
254 } else if( self::typeAction($row,'move','move','move') && !empty($paramArray[0]) ) {
255 $destTitle = Title::newFromText( $paramArray[0] );
256 if( $destTitle ) {
257 $revert = '(' . $this->skin->link(
258 SpecialPage::getTitleFor( 'Movepage' ),
259 $this->message['revertmove'],
260 array(),
261 array(
262 'wpOldTitle' => $destTitle->getPrefixedDBkey(),
263 'wpNewTitle' => $title->getPrefixedDBkey(),
264 'wpReason' => wfMsgForContent( 'revertmove' ),
265 'wpMovetalk' => 0
266 ),
267 array( 'known', 'noclasses' )
268 ) . ')';
269 }
270 // Show undelete link
271 } else if( self::typeAction($row,array('delete','suppress'),'delete','deletedhistory') ) {
272 if( !$wgUser->isAllowed( 'undelete' ) ) {
273 $viewdeleted = $this->message['undeleteviewlink'];
274 } else {
275 $viewdeleted = $this->message['undeletelink'];
276 }
277
278 $revert = '(' . $this->skin->link(
279 SpecialPage::getTitleFor( 'Undelete' ),
280 $viewdeleted,
281 array(),
282 array( 'target' => $title->getPrefixedDBkey() ),
283 array( 'known', 'noclasses' )
284 ) . ')';
285 // Show unblock/change block link
286 } else if( self::typeAction($row,array('block','suppress'),array('block','reblock'),'block') ) {
287 $revert = '(' .
288 $this->skin->link(
289 SpecialPage::getTitleFor( 'Ipblocklist' ),
290 $this->message['unblocklink'],
291 array(),
292 array(
293 'action' => 'unblock',
294 'ip' => $row->log_title
295 ),
296 'known'
297 ) .
298 $this->message['pipe-separator'] .
299 $this->skin->link(
300 SpecialPage::getTitleFor( 'Blockip', $row->log_title ),
301 $this->message['change-blocklink'],
302 array(),
303 array(),
304 'known'
305 ) .
306 ')';
307 // Show change protection link
308 } else if( self::typeAction( $row, 'protect', array( 'modify', 'protect', 'unprotect' ) ) ) {
309 $revert .= ' (' .
310 $this->skin->link( $title,
311 $this->message['hist'],
312 array(),
313 array(
314 'action' => 'history',
315 'offset' => $row->log_timestamp
316 )
317 );
318 if( $wgUser->isAllowed( 'protect' ) ) {
319 $revert .= $this->message['pipe-separator'] .
320 $this->skin->link( $title,
321 $this->message['protect_change'],
322 array(),
323 array( 'action' => 'protect' ),
324 'known' );
325 }
326 $revert .= ')';
327 // Show unmerge link
328 } else if( self::typeAction($row,'merge','merge','mergehistory') ) {
329 $merge = SpecialPage::getTitleFor( 'Mergehistory' );
330 $revert = '(' . $this->skin->link(
331 $merge,
332 $this->message['revertmerge'],
333 array(),
334 array(
335 'target' => $paramArray[0],
336 'dest' => $title->getPrefixedDBkey(),
337 'mergepoint' => $paramArray[1]
338 ),
339 array( 'known', 'noclasses' )
340 ) . ')';
341 // If an edit was hidden from a page give a review link to the history
342 } else if( self::typeAction($row,array('delete','suppress'),'revision','deleterevision') ) {
343 if( count($paramArray) >= 2 ) {
344 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
345 // Different revision types use different URL params...
346 $key = $paramArray[0];
347 // $paramArray[1] is a CSV of the IDs
348 $Ids = explode( ',', $paramArray[1] );
349 $query = $paramArray[1];
350 $revert = array();
351 // Diff link for single rev deletions
352 if( ( $key === 'oldid' || $key == 'revision' ) && count($Ids) == 1 ) {
353 $revert[] = $this->skin->link(
354 $title,
355 $this->message['diff'],
356 array(),
357 array(
358 'diff' => intval( $Ids[0] ),
359 'unhide' => 1
360 ),
361 array( 'known', 'noclasses' )
362 );
363 }
364 // View/modify link...
365 $revert[] = $this->skin->link(
366 $revdel,
367 $this->message['revdel-restore'],
368 array(),
369 array(
370 'target' => $title->getPrefixedText(),
371 'type' => $key,
372 'ids' => $query
373 ),
374 array( 'known', 'noclasses' )
375 );
376
377 // Pipe links
378 $revert = wfMsg( 'parentheses', $wgLang->pipeList( $revert ) );
379 }
380 // Hidden log items, give review link
381 } else if( self::typeAction($row,array('delete','suppress'),'event','deleterevision') ) {
382 if( count($paramArray) >= 1 ) {
383 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
384 // $paramArray[1] is a CSV of the IDs
385 $Ids = explode( ',', $paramArray[0] );
386 $query = $paramArray[0];
387 // Link to each hidden object ID, $paramArray[1] is the url param
388 $revert = '(' . $this->skin->link(
389 $revdel,
390 $this->message['revdel-restore'],
391 array(),
392 array(
393 'target' => $title->getPrefixedText(),
394 'type' => 'logging',
395 'ids' => $query
396 ),
397 array( 'known', 'noclasses' )
398 ) . ')';
399 }
400 // Self-created users
401 } else if( self::typeAction($row,'newusers','create2') ) {
402 if( isset( $paramArray[0] ) ) {
403 $revert = $this->skin->userToolLinks( $paramArray[0], $title->getDBkey(), true );
404 } else {
405 # Fall back to a blue contributions link
406 $revert = $this->skin->userToolLinks( 1, $title->getDBkey() );
407 }
408 if( $time < '20080129000000' ) {
409 # Suppress $comment from old entries (before 2008-01-29),
410 # not needed and can contain incorrect links
411 $comment = '';
412 }
413 // Do nothing. The implementation is handled by the hook modifiying the passed-by-ref parameters.
414 } else {
415 wfRunHooks( 'LogLine', array( $row->log_type, $row->log_action, $title, $paramArray,
416 &$comment, &$revert, $row->log_timestamp ) );
417 }
418 // Event description
419 if( self::isDeleted($row,LogPage::DELETED_ACTION) ) {
420 $action = '<span class="history-deleted">' . wfMsgHtml('rev-deleted-event') . '</span>';
421 } else {
422 $action = LogPage::actionText( $row->log_type, $row->log_action, $title,
423 $this->skin, $paramArray, true );
424 }
425
426 // Any tags...
427 list($tagDisplay, $newClasses) = ChangeTags::formatSummaryRow( $row->ts_tags, 'logevent' );
428 $classes = array_merge( $classes, $newClasses );
429
430 if( $revert != '' ) {
431 $revert = '<span class="mw-logevent-actionlink">' . $revert . '</span>';
432 }
433
434 $time = htmlspecialchars( $time );
435
436 return Xml::tags( 'li', array( "class" => implode( ' ', $classes ) ),
437 $del . $time . ' ' . $userLink . ' ' . $action . ' ' . $comment . ' ' . $revert . " $tagDisplay" ) . "\n";
438 }
439
440 /**
441 * @param $row Row
442 * @return string
443 */
444 private function getShowHideLinks( $row ) {
445 // If event was hidden from sysops
446 if( !self::userCan( $row, LogPage::DELETED_RESTRICTED ) ) {
447 $del = Xml::tags( 'span', array( 'class'=>'mw-revdelundel-link' ),
448 '('.$this->message['rev-delundel'].')' );
449 } else if( $row->log_type == 'suppress' ) {
450 $del = ''; // No one should be hiding from the oversight log
451 } else {
452 $target = SpecialPage::getTitleFor( 'Log', $row->log_type );
453 $page = Title::makeTitle( $row->log_namespace, $row->log_title );
454 $query = array(
455 'target' => $target->getPrefixedDBkey(),
456 'type' => 'logging',
457 'ids' => $row->log_id,
458 );
459 $del = $this->skin->revDeleteLink( $query,
460 self::isDeleted( $row, LogPage::DELETED_RESTRICTED ) );
461 }
462 return $del;
463 }
464
465 /**
466 * @param $row Row
467 * @param $type Mixed: string/array
468 * @param $action Mixed: string/array
469 * @param $right string
470 * @return bool
471 */
472 public static function typeAction( $row, $type, $action, $right='' ) {
473 $match = is_array($type) ?
474 in_array($row->log_type,$type) : $row->log_type == $type;
475 if( $match ) {
476 $match = is_array($action) ?
477 in_array($row->log_action,$action) : $row->log_action == $action;
478 if( $match && $right ) {
479 global $wgUser;
480 $match = $wgUser->isAllowed( $right );
481 }
482 }
483 return $match;
484 }
485
486 /**
487 * Determine if the current user is allowed to view a particular
488 * field of this log row, if it's marked as deleted.
489 * @param $row Row
490 * @param $field Integer
491 * @return Boolean
492 */
493 public static function userCan( $row, $field ) {
494 if( ( $row->log_deleted & $field ) == $field ) {
495 global $wgUser;
496 $permission = ( $row->log_deleted & LogPage::DELETED_RESTRICTED ) == LogPage::DELETED_RESTRICTED
497 ? 'suppressrevision'
498 : 'deleterevision';
499 wfDebug( "Checking for $permission due to $field match on $row->log_deleted\n" );
500 return $wgUser->isAllowed( $permission );
501 } else {
502 return true;
503 }
504 }
505
506 /**
507 * @param $row Row
508 * @param $field Integer: one of DELETED_* bitfield constants
509 * @return Boolean
510 */
511 public static function isDeleted( $row, $field ) {
512 return ($row->log_deleted & $field) == $field;
513 }
514
515 /**
516 * Quick function to show a short log extract
517 * @param $out OutputPage
518 * @param $types String or Array
519 * @param $page String
520 * @param $user String
521 * @param $lim Integer
522 * @param $conds Array
523 */
524 public static function showLogExtract( $out, $types=array(), $page='', $user='', $lim=0, $conds=array() ) {
525 global $wgUser;
526 # Insert list of top 50 or so items
527 $loglist = new LogEventsList( $wgUser->getSkin(), $out, 0 );
528 $pager = new LogPager( $loglist, $types, $user, $page, '', $conds );
529 if( $lim > 0 ) $pager->mLimit = $lim;
530 $logBody = $pager->getBody();
531 if( $logBody ) {
532 $out->addHTML(
533 $loglist->beginLogEventsList() .
534 $logBody .
535 $loglist->endLogEventsList()
536 );
537 } else {
538 $out->addWikiMsg( 'logempty' );
539 }
540 return $pager->getNumRows();
541 }
542
543 /**
544 * SQL clause to skip forbidden log types for this user
545 * @param $db Database
546 * @param $audience string, public/user
547 * @return mixed (string or false)
548 */
549 public static function getExcludeClause( $db, $audience = 'public' ) {
550 global $wgLogRestrictions, $wgUser;
551 // Reset the array, clears extra "where" clauses when $par is used
552 $hiddenLogs = array();
553 // Don't show private logs to unprivileged users
554 foreach( $wgLogRestrictions as $logType => $right ) {
555 if( $audience == 'public' || !$wgUser->isAllowed($right) ) {
556 $safeType = $db->strencode( $logType );
557 $hiddenLogs[] = $safeType;
558 }
559 }
560 if( count($hiddenLogs) == 1 ) {
561 return 'log_type != ' . $db->addQuotes( $hiddenLogs[0] );
562 } elseif( $hiddenLogs ) {
563 return 'log_type NOT IN (' . $db->makeList($hiddenLogs) . ')';
564 }
565 return false;
566 }
567 }
568
569 /**
570 * @ingroup Pager
571 */
572 class LogPager extends ReverseChronologicalPager {
573 private $types = array(), $user = '', $title = '', $pattern = '';
574 private $typeCGI = '';
575 public $mLogEventsList;
576
577 /**
578 * constructor
579 * @param $list LogEventsList
580 * @param $types String or Array
581 * @param $user String
582 * @param $title String
583 * @param $pattern String
584 * @param $conds Array
585 * @param $year Integer
586 * @param $month Integer
587 */
588 public function __construct( $list, $types = array(), $user = '', $title = '', $pattern = '',
589 $conds = array(), $year = false, $month = false, $tagFilter = '' )
590 {
591 parent::__construct();
592 $this->mConds = $conds;
593
594 $this->mLogEventsList = $list;
595
596 $this->limitType( $types ); // also excludes hidden types
597 $this->limitUser( $user );
598 $this->limitTitle( $title, $pattern );
599 $this->getDateCond( $year, $month );
600 $this->mTagFilter = $tagFilter;
601 }
602
603 public function getDefaultQuery() {
604 $query = parent::getDefaultQuery();
605 $query['type'] = $this->typeCGI; // arrays won't work here
606 $query['user'] = $this->user;
607 $query['month'] = $this->mMonth;
608 $query['year'] = $this->mYear;
609 return $query;
610 }
611
612 // Call ONLY after calling $this->limitType() already!
613 public function getFilterParams() {
614 global $wgFilterLogTypes, $wgUser, $wgRequest;
615 $filters = array();
616 if( count($this->types) ) {
617 return $filters;
618 }
619 foreach( $wgFilterLogTypes as $type => $default ) {
620 // Avoid silly filtering
621 if( $type !== 'patrol' || $wgUser->useNPPatrol() ) {
622 $hide = $wgRequest->getInt( "hide_{$type}_log", $default );
623 $filters[$type] = $hide;
624 if( $hide )
625 $this->mConds[] = 'log_type != ' . $this->mDb->addQuotes( $type );
626 }
627 }
628 return $filters;
629 }
630
631 /**
632 * Set the log reader to return only entries of the given type.
633 * Type restrictions enforced here
634 * @param $types String or array: Log types ('upload', 'delete', etc);
635 * empty string means no restriction
636 */
637 private function limitType( $types ) {
638 global $wgLogRestrictions, $wgUser;
639 // If $types is not an array, make it an array
640 $types = ($types === '') ? array() : (array)$types;
641 // Don't even show header for private logs; don't recognize it...
642 foreach ( $types as $type ) {
643 if( isset( $wgLogRestrictions[$type] ) && !$wgUser->isAllowed($wgLogRestrictions[$type]) ) {
644 $types = array_diff( $types, array( $type ) );
645 }
646 }
647 // Don't show private logs to unprivileged users.
648 // Also, only show them upon specific request to avoid suprises.
649 $audience = $types ? 'user' : 'public';
650 $hideLogs = LogEventsList::getExcludeClause( $this->mDb, $audience );
651 if( $hideLogs !== false ) {
652 $this->mConds[] = $hideLogs;
653 }
654 if( count($types) ) {
655 $this->types = $types;
656 $this->mConds['log_type'] = $types;
657 // Set typeCGI; used in url param for paging
658 if( count($types) == 1 ) $this->typeCGI = $types[0];
659 }
660 }
661
662 /**
663 * Set the log reader to return only entries by the given user.
664 * @param $name String: (In)valid user name
665 */
666 private function limitUser( $name ) {
667 if( $name == '' ) {
668 return false;
669 }
670 $usertitle = Title::makeTitleSafe( NS_USER, $name );
671 if( is_null($usertitle) ) {
672 return false;
673 }
674 /* Fetch userid at first, if known, provides awesome query plan afterwards */
675 $userid = User::idFromName( $name );
676 if( !$userid ) {
677 /* It should be nicer to abort query at all,
678 but for now it won't pass anywhere behind the optimizer */
679 $this->mConds[] = "NULL";
680 } else {
681 global $wgUser;
682 $this->mConds['log_user'] = $userid;
683 // Paranoia: avoid brute force searches (bug 17342)
684 if( !$wgUser->isAllowed( 'suppressrevision' ) ) {
685 $this->mConds[] = $this->mDb->bitAnd('log_deleted', LogPage::DELETED_USER) . ' = 0';
686 }
687 $this->user = $usertitle->getText();
688 }
689 }
690
691 /**
692 * Set the log reader to return only entries affecting the given page.
693 * (For the block and rights logs, this is a user page.)
694 * @param $page String: Title name as text
695 * @param $pattern String
696 */
697 private function limitTitle( $page, $pattern ) {
698 global $wgMiserMode, $wgUser;
699
700 $title = Title::newFromText( $page );
701 if( strlen($page) == 0 || !$title instanceof Title )
702 return false;
703
704 $this->title = $title->getPrefixedText();
705 $ns = $title->getNamespace();
706 # Using the (log_namespace, log_title, log_timestamp) index with a
707 # range scan (LIKE) on the first two parts, instead of simple equality,
708 # makes it unusable for sorting. Sorted retrieval using another index
709 # would be possible, but then we might have to scan arbitrarily many
710 # nodes of that index. Therefore, we need to avoid this if $wgMiserMode
711 # is on.
712 #
713 # This is not a problem with simple title matches, because then we can
714 # use the page_time index. That should have no more than a few hundred
715 # log entries for even the busiest pages, so it can be safely scanned
716 # in full to satisfy an impossible condition on user or similar.
717 if( $pattern && !$wgMiserMode ) {
718 # use escapeLike to avoid expensive search patterns like 't%st%'
719 $safetitle = $this->mDb->escapeLike( $title->getDBkey() );
720 $this->mConds['log_namespace'] = $ns;
721 $this->mConds[] = "log_title LIKE '$safetitle%'";
722 $this->pattern = $pattern;
723 } else {
724 $this->mConds['log_namespace'] = $ns;
725 $this->mConds['log_title'] = $title->getDBkey();
726 }
727 // Paranoia: avoid brute force searches (bug 17342)
728 if( !$wgUser->isAllowed( 'suppressrevision' ) ) {
729 $this->mConds[] = $this->mDb->bitAnd('log_deleted', LogPage::DELETED_ACTION) . ' = 0';
730 }
731 }
732
733 public function getQueryInfo() {
734 $tables = array( 'logging', 'user' );
735 $this->mConds[] = 'user_id = log_user';
736 $groupBy = false;
737 # Add log_search table if there are conditions on it
738 if( array_key_exists('ls_field',$this->mConds) ) {
739 $tables[] = 'log_search';
740 $index = array( 'log_search' => 'ls_field_val', 'logging' => 'PRIMARY' );
741 $groupBy = 'ls_log_id';
742 # Don't use the wrong logging index
743 } else if( $this->title || $this->pattern || $this->user ) {
744 $index = array( 'logging' => array('page_time','user_time') );
745 } else if( $this->types ) {
746 $index = array( 'logging' => 'type_time' );
747 } else {
748 $index = array( 'logging' => 'times' );
749 }
750 $options = array( 'USE INDEX' => $index );
751 # Don't show duplicate rows when using log_search
752 if( $groupBy ) $options['GROUP BY'] = $groupBy;
753 $info = array(
754 'tables' => $tables,
755 'fields' => array( 'log_type', 'log_action', 'log_user', 'log_namespace',
756 'log_title', 'log_params', 'log_comment', 'log_id', 'log_deleted',
757 'log_timestamp', 'user_name', 'user_editcount' ),
758 'conds' => $this->mConds,
759 'options' => $options,
760 'join_conds' => array(
761 'user' => array( 'INNER JOIN', 'user_id=log_user' ),
762 'log_search' => array( 'INNER JOIN', 'ls_log_id=log_id' )
763 )
764 );
765 # Add ChangeTags filter query
766 ChangeTags::modifyDisplayQuery( $info['tables'], $info['fields'], $info['conds'],
767 $info['join_conds'], $info['options'], $this->mTagFilter );
768
769 return $info;
770 }
771
772 function getIndexField() {
773 return 'log_timestamp';
774 }
775
776 public function getStartBody() {
777 wfProfileIn( __METHOD__ );
778 # Do a link batch query
779 if( $this->getNumRows() > 0 ) {
780 $lb = new LinkBatch;
781 while( $row = $this->mResult->fetchObject() ) {
782 $lb->add( $row->log_namespace, $row->log_title );
783 $lb->addObj( Title::makeTitleSafe( NS_USER, $row->user_name ) );
784 $lb->addObj( Title::makeTitleSafe( NS_USER_TALK, $row->user_name ) );
785 }
786 $lb->execute();
787 $this->mResult->seek( 0 );
788 }
789 wfProfileOut( __METHOD__ );
790 return '';
791 }
792
793 public function formatRow( $row ) {
794 return $this->mLogEventsList->logLine( $row );
795 }
796
797 public function getType() {
798 return $this->types;
799 }
800
801 public function getUser() {
802 return $this->user;
803 }
804
805 public function getPage() {
806 return $this->title;
807 }
808
809 public function getPattern() {
810 return $this->pattern;
811 }
812
813 public function getYear() {
814 return $this->mYear;
815 }
816
817 public function getMonth() {
818 return $this->mMonth;
819 }
820
821 public function getTagFilter() {
822 return $this->mTagFilter;
823 }
824
825 public function doQuery() {
826 // Workaround MySQL optimizer bug
827 $this->mDb->setBigSelects();
828 parent::doQuery();
829 $this->mDb->setBigSelects( 'default' );
830 }
831 }
832
833 /**
834 * @deprecated
835 * @ingroup SpecialPage
836 */
837 class LogReader {
838 var $pager;
839 /**
840 * @param $request WebRequest: for internal use use a FauxRequest object to pass arbitrary parameters.
841 */
842 function __construct( $request ) {
843 global $wgUser, $wgOut;
844 wfDeprecated(__METHOD__);
845 # Get parameters
846 $type = $request->getVal( 'type' );
847 $user = $request->getText( 'user' );
848 $title = $request->getText( 'page' );
849 $pattern = $request->getBool( 'pattern' );
850 $year = $request->getIntOrNull( 'year' );
851 $month = $request->getIntOrNull( 'month' );
852 $tagFilter = $request->getVal( 'tagfilter' );
853 # Don't let the user get stuck with a certain date
854 $skip = $request->getText( 'offset' ) || $request->getText( 'dir' ) == 'prev';
855 if( $skip ) {
856 $year = '';
857 $month = '';
858 }
859 # Use new list class to output results
860 $loglist = new LogEventsList( $wgUser->getSkin(), $wgOut, 0 );
861 $this->pager = new LogPager( $loglist, $type, $user, $title, $pattern, $year, $month, $tagFilter );
862 }
863
864 /**
865 * Is there at least one row?
866 * @return bool
867 */
868 public function hasRows() {
869 return isset($this->pager) ? ($this->pager->getNumRows() > 0) : false;
870 }
871 }
872
873 /**
874 * @deprecated
875 * @ingroup SpecialPage
876 */
877 class LogViewer {
878 const NO_ACTION_LINK = 1;
879
880 /**
881 * LogReader object
882 */
883 var $reader;
884
885 /**
886 * @param &$reader LogReader: where to get our data from
887 * @param $flags Integer: Bitwise combination of flags:
888 * LogEventsList::NO_ACTION_LINK Don't show restore/unblock/block links
889 */
890 function __construct( &$reader, $flags = 0 ) {
891 wfDeprecated(__METHOD__);
892 $this->reader =& $reader;
893 $this->reader->pager->mLogEventsList->flags = $flags;
894 # Aliases for shorter code...
895 $this->pager =& $this->reader->pager;
896 $this->list =& $this->reader->pager->mLogEventsList;
897 }
898
899 /**
900 * Take over the whole output page in $wgOut with the log display.
901 */
902 public function show() {
903 # Set title and add header
904 $this->list->showHeader( $pager->getType() );
905 # Show form options
906 $this->list->showOptions( $this->pager->getType(), $this->pager->getUser(), $this->pager->getPage(),
907 $this->pager->getPattern(), $this->pager->getYear(), $this->pager->getMonth() );
908 # Insert list
909 $logBody = $this->pager->getBody();
910 if( $logBody ) {
911 $wgOut->addHTML(
912 $this->pager->getNavigationBar() .
913 $this->list->beginLogEventsList() .
914 $logBody .
915 $this->list->endLogEventsList() .
916 $this->pager->getNavigationBar()
917 );
918 } else {
919 $wgOut->addWikiMsg( 'logempty' );
920 }
921 }
922
923 /**
924 * Output just the list of entries given by the linked LogReader,
925 * with extraneous UI elements. Use for displaying log fragments in
926 * another page (eg at Special:Undelete)
927 * @param $out OutputPage: where to send output
928 */
929 public function showList( &$out ) {
930 $logBody = $this->pager->getBody();
931 if( $logBody ) {
932 $out->addHTML(
933 $this->list->beginLogEventsList() .
934 $logBody .
935 $this->list->endLogEventsList()
936 );
937 } else {
938 $out->addWikiMsg( 'logempty' );
939 }
940 }
941 }