Pass user to LogEventsList::getExcludeClause
[lhc/web/wiklou.git] / includes / logging / LogEventsList.php
1 <?php
2 /**
3 * Contain classes to list log entries
4 *
5 * Copyright © 2004 Brion Vibber <brion@pobox.com>, 2008 Aaron Schulz
6 * http://www.mediawiki.org/
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
22 *
23 * @file
24 */
25
26 class LogEventsList extends ContextSource {
27 const NO_ACTION_LINK = 1;
28 const NO_EXTRA_USER_LINKS = 2;
29 const USE_REVDEL_CHECKBOXES = 4;
30
31 public $flags;
32
33 /**
34 * @var Array
35 */
36 protected $mDefaultQuery;
37
38 /**
39 * Constructor.
40 * The first two parameters used to be $skin and $out, but now only a context
41 * is needed, that's why there's a second unused parameter.
42 *
43 * @param $context IContextSource Context to use; formerly it was Skin object.
44 * @param $unused void Unused; used to be an OutputPage object.
45 * @param $flags int flags; can be a combinaison of self::NO_ACTION_LINK,
46 * self::NO_EXTRA_USER_LINKS or self::USE_REVDEL_CHECKBOXES.
47 */
48 public function __construct( $context, $unused = null, $flags = 0 ) {
49 if ( $context instanceof IContextSource ) {
50 $this->setContext( $context );
51 } else {
52 // Old parameters, $context should be a Skin object
53 $this->setContext( $context->getContext() );
54 }
55
56 $this->flags = $flags;
57 }
58
59 /**
60 * Deprecated alias for getTitle(); do not use.
61 *
62 * @deprecated in 1.20; use getTitle() instead.
63 * @return Title object
64 */
65 public function getDisplayTitle() {
66 return $this->getTitle();
67 }
68
69 /**
70 * Set page title and show header for this log type
71 * @param $type Array
72 * @deprecated in 1.19
73 */
74 public function showHeader( $type ) {
75 wfDeprecated( __METHOD__, '1.19' );
76 // If only one log type is used, then show a special message...
77 $headerType = (count($type) == 1) ? $type[0] : '';
78 $out = $this->getOutput();
79 if( LogPage::isLogType( $headerType ) ) {
80 $page = new LogPage( $headerType );
81 $out->setPageTitle( $page->getName()->text() );
82 $out->addHTML( $page->getDescription()->parseAsBlock() );
83 } else {
84 $out->addHTML( $this->msg( 'alllogstext' )->parse() );
85 }
86 }
87
88 /**
89 * Show options for the log list
90 *
91 * @param $types string or Array
92 * @param $user String
93 * @param $page String
94 * @param $pattern String
95 * @param $year Integer: year
96 * @param $month Integer: month
97 * @param $filter: array
98 * @param $tagFilter: array?
99 */
100 public function showOptions( $types=array(), $user='', $page='', $pattern='', $year='',
101 $month = '', $filter = null, $tagFilter='' ) {
102 global $wgScript, $wgMiserMode;
103
104 $title = SpecialPage::getTitleFor( 'Log' );
105
106 // For B/C, we take strings, but make sure they are converted...
107 $types = ($types === '') ? array() : (array)$types;
108
109 $tagSelector = ChangeTags::buildTagFilterSelector( $tagFilter );
110
111 $html = Html::hidden( 'title', $title->getPrefixedDBkey() );
112
113 // Basic selectors
114 $html .= $this->getTypeMenu( $types ) . "\n";
115 $html .= $this->getUserInput( $user ) . "\n";
116 $html .= $this->getTitleInput( $page ) . "\n";
117 $html .= $this->getExtraInputs( $types ) . "\n";
118
119 // Title pattern, if allowed
120 if (!$wgMiserMode) {
121 $html .= $this->getTitlePattern( $pattern ) . "\n";
122 }
123
124 // date menu
125 $html .= Xml::tags( 'p', null, Xml::dateMenu( $year, $month ) );
126
127 // Tag filter
128 if ($tagSelector) {
129 $html .= Xml::tags( 'p', null, implode( '&#160;', $tagSelector ) );
130 }
131
132 // Filter links
133 if ($filter) {
134 $html .= Xml::tags( 'p', null, $this->getFilterLinks( $filter ) );
135 }
136
137 // Submit button
138 $html .= Xml::submitButton( $this->msg( 'allpagessubmit' )->text() );
139
140 // Fieldset
141 $html = Xml::fieldset( $this->msg( 'log' )->text(), $html );
142
143 // Form wrapping
144 $html = Xml::tags( 'form', array( 'action' => $wgScript, 'method' => 'get' ), $html );
145
146 $this->getOutput()->addHTML( $html );
147 }
148
149 /**
150 * @param $filter Array
151 * @return String: Formatted HTML
152 */
153 private function getFilterLinks( $filter ) {
154 // show/hide links
155 $messages = array( $this->msg( 'show' )->escaped(), $this->msg( 'hide' )->escaped() );
156 // Option value -> message mapping
157 $links = array();
158 $hiddens = ''; // keep track for "go" button
159 foreach( $filter as $type => $val ) {
160 // Should the below assignment be outside the foreach?
161 // Then it would have to be copied. Not certain what is more expensive.
162 $query = $this->getDefaultQuery();
163 $queryKey = "hide_{$type}_log";
164
165 $hideVal = 1 - intval($val);
166 $query[$queryKey] = $hideVal;
167
168 $link = Linker::linkKnown(
169 $this->getTitle(),
170 $messages[$hideVal],
171 array(),
172 $query
173 );
174
175 $links[$type] = $this->msg( "log-show-hide-{$type}" )->rawParams( $link )->escaped();
176 $hiddens .= Html::hidden( "hide_{$type}_log", $val ) . "\n";
177 }
178 // Build links
179 return '<small>'.$this->getLanguage()->pipeList( $links ) . '</small>' . $hiddens;
180 }
181
182 private function getDefaultQuery() {
183 if ( !isset( $this->mDefaultQuery ) ) {
184 $this->mDefaultQuery = $this->getRequest()->getQueryValues();
185 unset( $this->mDefaultQuery['title'] );
186 unset( $this->mDefaultQuery['dir'] );
187 unset( $this->mDefaultQuery['offset'] );
188 unset( $this->mDefaultQuery['limit'] );
189 unset( $this->mDefaultQuery['order'] );
190 unset( $this->mDefaultQuery['month'] );
191 unset( $this->mDefaultQuery['year'] );
192 }
193 return $this->mDefaultQuery;
194 }
195
196 /**
197 * @param $queryTypes Array
198 * @return String: Formatted HTML
199 */
200 private function getTypeMenu( $queryTypes ) {
201 $queryType = count($queryTypes) == 1 ? $queryTypes[0] : '';
202 $selector = $this->getTypeSelector();
203 $selector->setDefault( $queryType );
204 return $selector->getHtml();
205 }
206
207 /**
208 * Returns log page selector.
209 * @return XmlSelect
210 * @since 1.19
211 */
212 public function getTypeSelector() {
213 $typesByName = array(); // Temporary array
214 // First pass to load the log names
215 foreach( LogPage::validTypes() as $type ) {
216 $page = new LogPage( $type );
217 $restriction = $page->getRestriction();
218 if ( $this->getUser()->isAllowed( $restriction ) ) {
219 $typesByName[$type] = $page->getName()->text();
220 }
221 }
222
223 // Second pass to sort by name
224 asort($typesByName);
225
226 // Always put "All public logs" on top
227 $public = $typesByName[''];
228 unset( $typesByName[''] );
229 $typesByName = array( '' => $public ) + $typesByName;
230
231 $select = new XmlSelect( 'type' );
232 foreach( $typesByName as $type => $name ) {
233 $select->addOption( $name, $type );
234 }
235
236 return $select;
237 }
238
239 /**
240 * @param $user String
241 * @return String: Formatted HTML
242 */
243 private function getUserInput( $user ) {
244 return '<span style="white-space: nowrap">' .
245 Xml::inputLabel( $this->msg( 'specialloguserlabel' )->text(), 'user', 'mw-log-user', 15, $user ) .
246 '</span>';
247 }
248
249 /**
250 * @param $title String
251 * @return String: Formatted HTML
252 */
253 private function getTitleInput( $title ) {
254 return '<span style="white-space: nowrap">' .
255 Xml::inputLabel( $this->msg( 'speciallogtitlelabel' )->text(), 'page', 'mw-log-page', 20, $title ) .
256 '</span>';
257 }
258
259 /**
260 * @param $pattern
261 * @return string Checkbox
262 */
263 private function getTitlePattern( $pattern ) {
264 return '<span style="white-space: nowrap">' .
265 Xml::checkLabel( $this->msg( 'log-title-wildcard' )->text(), 'pattern', 'pattern', $pattern ) .
266 '</span>';
267 }
268
269 /**
270 * @param $types
271 * @return string
272 */
273 private function getExtraInputs( $types ) {
274 $offender = $this->getRequest()->getVal( 'offender' );
275 $user = User::newFromName( $offender, false );
276 if( !$user || ($user->getId() == 0 && !IP::isIPAddress($offender) ) ) {
277 $offender = ''; // Blank field if invalid
278 }
279 if( count($types) == 1 && $types[0] == 'suppress' ) {
280 return Xml::inputLabel( $this->msg( 'revdelete-offender' )->text(), 'offender',
281 'mw-log-offender', 20, $offender );
282 }
283 return '';
284 }
285
286 /**
287 * @return string
288 */
289 public function beginLogEventsList() {
290 return "<ul>\n";
291 }
292
293 /**
294 * @return string
295 */
296 public function endLogEventsList() {
297 return "</ul>\n";
298 }
299
300 /**
301 * @param $row Row: a single row from the result set
302 * @return String: Formatted HTML list item
303 */
304 public function logLine( $row ) {
305 $entry = DatabaseLogEntry::newFromRow( $row );
306 $formatter = LogFormatter::newFromEntry( $entry );
307 $formatter->setContext( $this->getContext() );
308 $formatter->setShowUserToolLinks( !( $this->flags & self::NO_EXTRA_USER_LINKS ) );
309
310 $title = $entry->getTarget();
311 $time = htmlspecialchars( $this->getLanguage()->userTimeAndDate(
312 $entry->getTimestamp(), $this->getUser() ) );
313
314 $action = $formatter->getActionText();
315
316 if ( $this->flags & self::NO_ACTION_LINK ) {
317 $revert = '';
318 } else {
319 $revert = $formatter->getActionLinks();
320 if ( $revert != '' ) {
321 $revert = '<span class="mw-logevent-actionlink">' . $revert . '</span>';
322 }
323 }
324
325 $comment = $formatter->getComment();
326
327 // Some user can hide log items and have review links
328 $del = $this->getShowHideLinks( $row );
329
330 // Any tags...
331 list( $tagDisplay, $newClasses ) = ChangeTags::formatSummaryRow( $row->ts_tags, 'logevent' );
332 $classes = array_merge(
333 array( 'mw-logline-' . $entry->getType() ),
334 $newClasses
335 );
336
337 return Html::rawElement( 'li', array( 'class' => $classes ),
338 "$del $time $action $comment $revert $tagDisplay" ) . "\n";
339 }
340
341 /**
342 * @param $row Row
343 * @return string
344 */
345 private function getShowHideLinks( $row ) {
346 if( ( $this->flags == self::NO_ACTION_LINK ) // we don't want to see the links
347 || $row->log_type == 'suppress' ) { // no one can hide items from the suppress log
348 return '';
349 }
350 $del = '';
351 $user = $this->getUser();
352 // Don't show useless checkbox to people who cannot hide log entries
353 if( $user->isAllowed( 'deletedhistory' ) ) {
354 $canHide = $user->isAllowed( 'deletelogentry' );
355 if( $row->log_deleted || $canHide ) {
356 if ( $canHide && $this->flags & self::USE_REVDEL_CHECKBOXES ) { // Show checkboxes instead of links.
357 if ( !self::userCan( $row, LogPage::DELETED_RESTRICTED, $user ) ) { // If event was hidden from sysops
358 $del = Xml::check( 'deleterevisions', false, array( 'disabled' => 'disabled' ) );
359 } else {
360 $del = Xml::check( 'showhiderevisions', false, array( 'name' => 'ids[' . $row->log_id . ']' ) );
361 }
362 } else {
363 if ( !self::userCan( $row, LogPage::DELETED_RESTRICTED, $user ) ) { // If event was hidden from sysops
364 $del = Linker::revDeleteLinkDisabled( $canHide );
365 } else {
366 $query = array(
367 'target' => SpecialPage::getTitleFor( 'Log', $row->log_type )->getPrefixedDBkey(),
368 'type' => 'logging',
369 'ids' => $row->log_id,
370 );
371 $del = Linker::revDeleteLink( $query, self::isDeleted( $row, LogPage::DELETED_RESTRICTED ), $canHide );
372 }
373 }
374 }
375 }
376 return $del;
377 }
378
379 /**
380 * @param $row Row
381 * @param $type Mixed: string/array
382 * @param $action Mixed: string/array
383 * @param $right string
384 * @return Boolean
385 */
386 public static function typeAction( $row, $type, $action, $right='' ) {
387 $match = is_array($type) ?
388 in_array( $row->log_type, $type ) : $row->log_type == $type;
389 if( $match ) {
390 $match = is_array( $action ) ?
391 in_array( $row->log_action, $action ) : $row->log_action == $action;
392 if( $match && $right ) {
393 global $wgUser;
394 $match = $wgUser->isAllowed( $right );
395 }
396 }
397 return $match;
398 }
399
400 /**
401 * Determine if the current user is allowed to view a particular
402 * field of this log row, if it's marked as deleted.
403 *
404 * @param $row Row
405 * @param $field Integer
406 * @param $user User object to check, or null to use $wgUser
407 * @return Boolean
408 */
409 public static function userCan( $row, $field, User $user = null ) {
410 return self::userCanBitfield( $row->log_deleted, $field, $user );
411 }
412
413 /**
414 * Determine if the current user is allowed to view a particular
415 * field of this log row, if it's marked as deleted.
416 *
417 * @param $bitfield Integer (current field)
418 * @param $field Integer
419 * @param $user User object to check, or null to use $wgUser
420 * @return Boolean
421 */
422 public static function userCanBitfield( $bitfield, $field, User $user = null ) {
423 if( $bitfield & $field ) {
424 if ( $bitfield & LogPage::DELETED_RESTRICTED ) {
425 $permission = 'suppressrevision';
426 } else {
427 $permission = 'deletedhistory';
428 }
429 wfDebug( "Checking for $permission due to $field match on $bitfield\n" );
430 if ( $user === null ) {
431 global $wgUser;
432 $user = $wgUser;
433 }
434 return $user->isAllowed( $permission );
435 } else {
436 return true;
437 }
438 }
439
440 /**
441 * @param $row Row
442 * @param $field Integer: one of DELETED_* bitfield constants
443 * @return Boolean
444 */
445 public static function isDeleted( $row, $field ) {
446 return ( $row->log_deleted & $field ) == $field;
447 }
448
449 /**
450 * Show log extract. Either with text and a box (set $msgKey) or without (don't set $msgKey)
451 *
452 * @param $out OutputPage|String-by-reference
453 * @param $types String|Array Log types to show
454 * @param $page String|Title The page title to show log entries for
455 * @param $user String The user who made the log entries
456 * @param $param array Associative Array with the following additional options:
457 * - lim Integer Limit of items to show, default is 50
458 * - conds Array Extra conditions for the query (e.g. "log_action != 'revision'")
459 * - showIfEmpty boolean Set to false if you don't want any output in case the loglist is empty
460 * if set to true (default), "No matching items in log" is displayed if loglist is empty
461 * - msgKey Array If you want a nice box with a message, set this to the key of the message.
462 * First element is the message key, additional optional elements are parameters for the key
463 * that are processed with wfMessage
464 * - offset Set to overwrite offset parameter in WebRequest
465 * set to '' to unset offset
466 * - wrap String Wrap the message in html (usually something like "<div ...>$1</div>").
467 * - flags Integer display flags (NO_ACTION_LINK,NO_EXTRA_USER_LINKS)
468 * @return Integer Number of total log items (not limited by $lim)
469 */
470 public static function showLogExtract(
471 &$out, $types=array(), $page='', $user='', $param = array()
472 ) {
473 $defaultParameters = array(
474 'lim' => 25,
475 'conds' => array(),
476 'showIfEmpty' => true,
477 'msgKey' => array(''),
478 'wrap' => "$1",
479 'flags' => 0
480 );
481 # The + operator appends elements of remaining keys from the right
482 # handed array to the left handed, whereas duplicated keys are NOT overwritten.
483 $param += $defaultParameters;
484 # Convert $param array to individual variables
485 $lim = $param['lim'];
486 $conds = $param['conds'];
487 $showIfEmpty = $param['showIfEmpty'];
488 $msgKey = $param['msgKey'];
489 $wrap = $param['wrap'];
490 $flags = $param['flags'];
491 if ( !is_array( $msgKey ) ) {
492 $msgKey = array( $msgKey );
493 }
494
495 if ( $out instanceof OutputPage ) {
496 $context = $out->getContext();
497 } else {
498 $context = RequestContext::getMain();
499 }
500
501 # Insert list of top 50 (or top $lim) items
502 $loglist = new LogEventsList( $context, null, $flags );
503 $pager = new LogPager( $loglist, $types, $user, $page, '', $conds );
504 if ( isset( $param['offset'] ) ) { # Tell pager to ignore WebRequest offset
505 $pager->setOffset( $param['offset'] );
506 }
507 if( $lim > 0 ) $pager->mLimit = $lim;
508 $logBody = $pager->getBody();
509 $s = '';
510 if( $logBody ) {
511 if ( $msgKey[0] ) {
512 $s = '<div class="mw-warning-with-logexcerpt">';
513
514 if ( count( $msgKey ) == 1 ) {
515 $s .= $context->msg( $msgKey[0] )->parseAsBlock();
516 } else { // Process additional arguments
517 $args = $msgKey;
518 array_shift( $args );
519 $s .= $context->msg( $msgKey[0], $args )->parseAsBlock();
520 }
521 }
522 $s .= $loglist->beginLogEventsList() .
523 $logBody .
524 $loglist->endLogEventsList();
525 } else {
526 if ( $showIfEmpty ) {
527 $s = Html::rawElement( 'div', array( 'class' => 'mw-warning-logempty' ),
528 $context->msg( 'logempty' )->parse() );
529 }
530 }
531 if( $pager->getNumRows() > $pager->mLimit ) { # Show "Full log" link
532 $urlParam = array();
533 if ( $page instanceof Title ) {
534 $urlParam['page'] = $page->getPrefixedDBkey();
535 } elseif ( $page != '' ) {
536 $urlParam['page'] = $page;
537 }
538 if ( $user != '')
539 $urlParam['user'] = $user;
540 if ( !is_array( $types ) ) # Make it an array, if it isn't
541 $types = array( $types );
542 # If there is exactly one log type, we can link to Special:Log?type=foo
543 if ( count( $types ) == 1 )
544 $urlParam['type'] = $types[0];
545 $s .= Linker::link(
546 SpecialPage::getTitleFor( 'Log' ),
547 $context->msg( 'log-fulllog' )->escaped(),
548 array(),
549 $urlParam
550 );
551 }
552 if ( $logBody && $msgKey[0] ) {
553 $s .= '</div>';
554 }
555
556 if ( $wrap != '' ) { // Wrap message in html
557 $s = str_replace( '$1', $s, $wrap );
558 }
559
560 /* hook can return false, if we don't want the message to be emitted (Wikia BugId:7093) */
561 if ( wfRunHooks( 'LogEventsListShowLogExtract', array( &$s, $types, $page, $user, $param ) ) ) {
562 // $out can be either an OutputPage object or a String-by-reference
563 if ( $out instanceof OutputPage ){
564 $out->addHTML( $s );
565 } else {
566 $out = $s;
567 }
568 }
569
570 return $pager->getNumRows();
571 }
572
573 /**
574 * SQL clause to skip forbidden log types for this user
575 *
576 * @param $db DatabaseBase
577 * @param $audience string, public/user
578 * @param $user User object to check, or null to use $wgUser
579 * @return Mixed: string or false
580 */
581 public static function getExcludeClause( $db, $audience = 'public', User $user = null ) {
582 global $wgLogRestrictions;
583
584 if ( $audience != 'public' && $user === null ) {
585 global $wgUser;
586 $user = $wgUser;
587 }
588
589 // Reset the array, clears extra "where" clauses when $par is used
590 $hiddenLogs = array();
591
592 // Don't show private logs to unprivileged users
593 foreach( $wgLogRestrictions as $logType => $right ) {
594 if( $audience == 'public' || !$user->isAllowed( $right ) ) {
595 $hiddenLogs[] = $logType;
596 }
597 }
598 if( count( $hiddenLogs ) == 1 ) {
599 return 'log_type != ' . $db->addQuotes( $hiddenLogs[0] );
600 } elseif( $hiddenLogs ) {
601 return 'log_type NOT IN (' . $db->makeList( $hiddenLogs ) . ')';
602 }
603 return false;
604 }
605 }