Merge "mime.types: allow bzip2 upload"
[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 * https://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 IContextSource|Skin $context Context to use; formerly it was
44 * a Skin object. Use of Skin is deprecated.
45 * @param null $unused Unused; used to be an OutputPage object.
46 * @param int $flags Can be a combination of self::NO_ACTION_LINK,
47 * self::NO_EXTRA_USER_LINKS or self::USE_REVDEL_CHECKBOXES.
48 */
49 public function __construct( $context, $unused = null, $flags = 0 ) {
50 if ( $context instanceof IContextSource ) {
51 $this->setContext( $context );
52 } else {
53 // Old parameters, $context should be a Skin object
54 $this->setContext( $context->getContext() );
55 }
56
57 $this->flags = $flags;
58 }
59
60 /**
61 * Show options for the log list
62 *
63 * @param array|string $types
64 * @param string $user
65 * @param string $page
66 * @param string $pattern
67 * @param int $year Year
68 * @param int $month Month
69 * @param array $filter
70 * @param string $tagFilter Tag to select by default
71 */
72 public function showOptions( $types = array(), $user = '', $page = '', $pattern = '', $year = 0,
73 $month = 0, $filter = null, $tagFilter = ''
74 ) {
75 global $wgScript, $wgMiserMode;
76
77 $title = SpecialPage::getTitleFor( 'Log' );
78
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 $html = Html::hidden( 'title', $title->getPrefixedDBkey() );
85
86 // Basic selectors
87 $html .= $this->getTypeMenu( $types ) . "\n";
88 $html .= $this->getUserInput( $user ) . "\n";
89 $html .= $this->getTitleInput( $page ) . "\n";
90 $html .= $this->getExtraInputs( $types ) . "\n";
91
92 // Title pattern, if allowed
93 if ( !$wgMiserMode ) {
94 $html .= $this->getTitlePattern( $pattern ) . "\n";
95 }
96
97 // date menu
98 $html .= Xml::tags( 'p', null, Xml::dateMenu( (int)$year, (int)$month ) );
99
100 // Tag filter
101 if ( $tagSelector ) {
102 $html .= Xml::tags( 'p', null, implode( '&#160;', $tagSelector ) );
103 }
104
105 // Filter links
106 if ( $filter ) {
107 $html .= Xml::tags( 'p', null, $this->getFilterLinks( $filter ) );
108 }
109
110 // Submit button
111 $html .= Xml::submitButton( $this->msg( 'allpagessubmit' )->text() );
112
113 // Fieldset
114 $html = Xml::fieldset( $this->msg( 'log' )->text(), $html );
115
116 // Form wrapping
117 $html = Xml::tags( 'form', array( 'action' => $wgScript, 'method' => 'get' ), $html );
118
119 $this->getOutput()->addHTML( $html );
120 }
121
122 /**
123 * @param array $filter
124 * @return string Formatted HTML
125 */
126 private function getFilterLinks( $filter ) {
127 // show/hide links
128 $messages = array( $this->msg( 'show' )->escaped(), $this->msg( 'hide' )->escaped() );
129 // Option value -> message mapping
130 $links = array();
131 $hiddens = ''; // keep track for "go" button
132 foreach ( $filter as $type => $val ) {
133 // Should the below assignment be outside the foreach?
134 // Then it would have to be copied. Not certain what is more expensive.
135 $query = $this->getDefaultQuery();
136 $queryKey = "hide_{$type}_log";
137
138 $hideVal = 1 - intval( $val );
139 $query[$queryKey] = $hideVal;
140
141 $link = Linker::linkKnown(
142 $this->getTitle(),
143 $messages[$hideVal],
144 array(),
145 $query
146 );
147
148 // Message: log-show-hide-patrol
149 $links[$type] = $this->msg( "log-show-hide-{$type}" )->rawParams( $link )->escaped();
150 $hiddens .= Html::hidden( "hide_{$type}_log", $val ) . "\n";
151 }
152
153 // Build links
154 return '<small>' . $this->getLanguage()->pipeList( $links ) . '</small>' . $hiddens;
155 }
156
157 private function getDefaultQuery() {
158 if ( !isset( $this->mDefaultQuery ) ) {
159 $this->mDefaultQuery = $this->getRequest()->getQueryValues();
160 unset( $this->mDefaultQuery['title'] );
161 unset( $this->mDefaultQuery['dir'] );
162 unset( $this->mDefaultQuery['offset'] );
163 unset( $this->mDefaultQuery['limit'] );
164 unset( $this->mDefaultQuery['order'] );
165 unset( $this->mDefaultQuery['month'] );
166 unset( $this->mDefaultQuery['year'] );
167 }
168
169 return $this->mDefaultQuery;
170 }
171
172 /**
173 * @param array $queryTypes
174 * @return string Formatted HTML
175 */
176 private function getTypeMenu( $queryTypes ) {
177 $queryType = count( $queryTypes ) == 1 ? $queryTypes[0] : '';
178 $selector = $this->getTypeSelector();
179 $selector->setDefault( $queryType );
180
181 return $selector->getHtml();
182 }
183
184 /**
185 * Returns log page selector.
186 * @return XmlSelect
187 * @since 1.19
188 */
189 public function getTypeSelector() {
190 $typesByName = array(); // Temporary array
191 // First pass to load the log names
192 foreach ( LogPage::validTypes() as $type ) {
193 $page = new LogPage( $type );
194 $restriction = $page->getRestriction();
195 if ( $this->getUser()->isAllowed( $restriction ) ) {
196 $typesByName[$type] = $page->getName()->text();
197 }
198 }
199
200 // Second pass to sort by name
201 asort( $typesByName );
202
203 // Always put "All public logs" on top
204 $public = $typesByName[''];
205 unset( $typesByName[''] );
206 $typesByName = array( '' => $public ) + $typesByName;
207
208 $select = new XmlSelect( 'type' );
209 foreach ( $typesByName as $type => $name ) {
210 $select->addOption( $name, $type );
211 }
212
213 return $select;
214 }
215
216 /**
217 * @param string $user
218 * @return string Formatted HTML
219 */
220 private function getUserInput( $user ) {
221 $label = Xml::inputLabel(
222 $this->msg( 'specialloguserlabel' )->text(),
223 'user',
224 'mw-log-user',
225 15,
226 $user,
227 array( 'class' => 'mw-autocomplete-user' )
228 );
229
230 return '<span style="white-space: nowrap">' . $label . '</span>';
231 }
232
233 /**
234 * @param string $title
235 * @return string Formatted HTML
236 */
237 private function getTitleInput( $title ) {
238 $label = Xml::inputLabel(
239 $this->msg( 'speciallogtitlelabel' )->text(),
240 'page',
241 'mw-log-page',
242 20,
243 $title
244 );
245
246 return '<span style="white-space: nowrap">' . $label . '</span>';
247 }
248
249 /**
250 * @param string $pattern
251 * @return string Checkbox
252 */
253 private function getTitlePattern( $pattern ) {
254 return '<span style="white-space: nowrap">' .
255 Xml::checkLabel( $this->msg( 'log-title-wildcard' )->text(), 'pattern', 'pattern', $pattern ) .
256 '</span>';
257 }
258
259 /**
260 * @param array $types
261 * @return string
262 */
263 private function getExtraInputs( $types ) {
264 if ( count( $types ) == 1 ) {
265 if ( $types[0] == 'suppress' ) {
266 $offender = $this->getRequest()->getVal( 'offender' );
267 $user = User::newFromName( $offender, false );
268 if ( !$user || ( $user->getId() == 0 && !IP::isIPAddress( $offender ) ) ) {
269 $offender = ''; // Blank field if invalid
270 }
271 return Xml::inputLabel( $this->msg( 'revdelete-offender' )->text(), 'offender',
272 'mw-log-offender', 20, $offender );
273 } else {
274 // Allow extensions to add their own extra inputs
275 $input = '';
276 Hooks::run( 'LogEventsListGetExtraInputs', array( $types[0], $this, &$input ) );
277 return $input;
278 }
279 }
280
281 return '';
282 }
283
284 /**
285 * @return string
286 */
287 public function beginLogEventsList() {
288 return "<ul>\n";
289 }
290
291 /**
292 * @return string
293 */
294 public function endLogEventsList() {
295 return "</ul>\n";
296 }
297
298 /**
299 * @param stdClass $row A single row from the result set
300 * @return string Formatted HTML list item
301 */
302 public function logLine( $row ) {
303 $entry = DatabaseLogEntry::newFromRow( $row );
304 $formatter = LogFormatter::newFromEntry( $entry );
305 $formatter->setContext( $this->getContext() );
306 $formatter->setShowUserToolLinks( !( $this->flags & self::NO_EXTRA_USER_LINKS ) );
307
308 $time = htmlspecialchars( $this->getLanguage()->userTimeAndDate(
309 $entry->getTimestamp(), $this->getUser() ) );
310
311 $action = $formatter->getActionText();
312
313 if ( $this->flags & self::NO_ACTION_LINK ) {
314 $revert = '';
315 } else {
316 $revert = $formatter->getActionLinks();
317 if ( $revert != '' ) {
318 $revert = '<span class="mw-logevent-actionlink">' . $revert . '</span>';
319 }
320 }
321
322 $comment = $formatter->getComment();
323
324 // Some user can hide log items and have review links
325 $del = $this->getShowHideLinks( $row );
326
327 // Any tags...
328 list( $tagDisplay, $newClasses ) = ChangeTags::formatSummaryRow( $row->ts_tags, 'logevent' );
329 $classes = array_merge(
330 array( 'mw-logline-' . $entry->getType() ),
331 $newClasses
332 );
333
334 return Html::rawElement( 'li', array( 'class' => $classes ),
335 "$del $time $action $comment $revert $tagDisplay" ) . "\n";
336 }
337
338 /**
339 * @param stdClass $row Row
340 * @return string
341 */
342 private function getShowHideLinks( $row ) {
343 // We don't want to see the links and
344 // no one can hide items from the suppress log.
345 if ( ( $this->flags == self::NO_ACTION_LINK )
346 || $row->log_type == 'suppress'
347 ) {
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 $canViewSuppressedOnly = $user->isAllowed( 'viewsuppressed' ) &&
356 !$user->isAllowed( 'suppressrevision' );
357 $entryIsSuppressed = self::isDeleted( $row, LogPage::DELETED_RESTRICTED );
358 $canViewThisSuppressedEntry = $canViewSuppressedOnly && $entryIsSuppressed;
359 if ( $row->log_deleted || $canHide ) {
360 // Show checkboxes instead of links.
361 if ( $canHide && $this->flags & self::USE_REVDEL_CHECKBOXES && !$canViewThisSuppressedEntry ) {
362 // If event was hidden from sysops
363 if ( !self::userCan( $row, LogPage::DELETED_RESTRICTED, $user ) ) {
364 $del = Xml::check( 'deleterevisions', false, array( 'disabled' => 'disabled' ) );
365 } else {
366 $del = Xml::check(
367 'showhiderevisions',
368 false,
369 array( 'name' => 'ids[' . $row->log_id . ']' )
370 );
371 }
372 } else {
373 // If event was hidden from sysops
374 if ( !self::userCan( $row, LogPage::DELETED_RESTRICTED, $user ) ) {
375 $del = Linker::revDeleteLinkDisabled( $canHide );
376 } else {
377 $query = array(
378 'target' => SpecialPage::getTitleFor( 'Log', $row->log_type )->getPrefixedDBkey(),
379 'type' => 'logging',
380 'ids' => $row->log_id,
381 );
382 $del = Linker::revDeleteLink(
383 $query,
384 $entryIsSuppressed,
385 $canHide && !$canViewThisSuppressedEntry
386 );
387 }
388 }
389 }
390 }
391
392 return $del;
393 }
394
395 /**
396 * @param stdClass $row Row
397 * @param string|array $type
398 * @param string|array $action
399 * @param string $right
400 * @return bool
401 */
402 public static function typeAction( $row, $type, $action, $right = '' ) {
403 $match = is_array( $type ) ?
404 in_array( $row->log_type, $type ) : $row->log_type == $type;
405 if ( $match ) {
406 $match = is_array( $action ) ?
407 in_array( $row->log_action, $action ) : $row->log_action == $action;
408 if ( $match && $right ) {
409 global $wgUser;
410 $match = $wgUser->isAllowed( $right );
411 }
412 }
413
414 return $match;
415 }
416
417 /**
418 * Determine if the current user is allowed to view a particular
419 * field of this log row, if it's marked as deleted.
420 *
421 * @param stdClass $row Row
422 * @param int $field
423 * @param User $user User to check, or null to use $wgUser
424 * @return bool
425 */
426 public static function userCan( $row, $field, User $user = null ) {
427 return self::userCanBitfield( $row->log_deleted, $field, $user );
428 }
429
430 /**
431 * Determine if the current user is allowed to view a particular
432 * field of this log row, if it's marked as deleted.
433 *
434 * @param int $bitfield Current field
435 * @param int $field
436 * @param User $user User to check, or null to use $wgUser
437 * @return bool
438 */
439 public static function userCanBitfield( $bitfield, $field, User $user = null ) {
440 if ( $bitfield & $field ) {
441 if ( $user === null ) {
442 global $wgUser;
443 $user = $wgUser;
444 }
445 if ( $bitfield & LogPage::DELETED_RESTRICTED ) {
446 $permissions = array( 'suppressrevision', 'viewsuppressed' );
447 } else {
448 $permissions = array( 'deletedhistory' );
449 }
450 $permissionlist = implode( ', ', $permissions );
451 wfDebug( "Checking for $permissionlist due to $field match on $bitfield\n" );
452 return call_user_func_array( array( $user, 'isAllowedAny' ), $permissions );
453 }
454 return true;
455 }
456
457 /**
458 * @param stdClass $row Row
459 * @param int $field One of DELETED_* bitfield constants
460 * @return bool
461 */
462 public static function isDeleted( $row, $field ) {
463 return ( $row->log_deleted & $field ) == $field;
464 }
465
466 /**
467 * Show log extract. Either with text and a box (set $msgKey) or without (don't set $msgKey)
468 *
469 * @param OutputPage|string $out By-reference
470 * @param string|array $types Log types to show
471 * @param string|Title $page The page title to show log entries for
472 * @param string $user The user who made the log entries
473 * @param array $param Associative Array with the following additional options:
474 * - lim Integer Limit of items to show, default is 50
475 * - conds Array Extra conditions for the query (e.g. "log_action != 'revision'")
476 * - showIfEmpty boolean Set to false if you don't want any output in case the loglist is empty
477 * if set to true (default), "No matching items in log" is displayed if loglist is empty
478 * - msgKey Array If you want a nice box with a message, set this to the key of the message.
479 * First element is the message key, additional optional elements are parameters for the key
480 * that are processed with wfMessage
481 * - offset Set to overwrite offset parameter in WebRequest
482 * set to '' to unset offset
483 * - wrap String Wrap the message in html (usually something like "<div ...>$1</div>").
484 * - flags Integer display flags (NO_ACTION_LINK,NO_EXTRA_USER_LINKS)
485 * - useRequestParams boolean Set true to use Pager-related parameters in the WebRequest
486 * - useMaster boolean Use master DB
487 * @return int Number of total log items (not limited by $lim)
488 */
489 public static function showLogExtract(
490 &$out, $types = array(), $page = '', $user = '', $param = array()
491 ) {
492 $defaultParameters = array(
493 'lim' => 25,
494 'conds' => array(),
495 'showIfEmpty' => true,
496 'msgKey' => array( '' ),
497 'wrap' => "$1",
498 'flags' => 0,
499 'useRequestParams' => false,
500 'useMaster' => false,
501 );
502 # The + operator appends elements of remaining keys from the right
503 # handed array to the left handed, whereas duplicated keys are NOT overwritten.
504 $param += $defaultParameters;
505 # Convert $param array to individual variables
506 $lim = $param['lim'];
507 $conds = $param['conds'];
508 $showIfEmpty = $param['showIfEmpty'];
509 $msgKey = $param['msgKey'];
510 $wrap = $param['wrap'];
511 $flags = $param['flags'];
512 $useRequestParams = $param['useRequestParams'];
513 if ( !is_array( $msgKey ) ) {
514 $msgKey = array( $msgKey );
515 }
516
517 if ( $out instanceof OutputPage ) {
518 $context = $out->getContext();
519 } else {
520 $context = RequestContext::getMain();
521 }
522
523 # Insert list of top 50 (or top $lim) items
524 $loglist = new LogEventsList( $context, null, $flags );
525 $pager = new LogPager( $loglist, $types, $user, $page, '', $conds );
526 if ( !$useRequestParams ) {
527 # Reset vars that may have been taken from the request
528 $pager->mLimit = 50;
529 $pager->mDefaultLimit = 50;
530 $pager->mOffset = "";
531 $pager->mIsBackwards = false;
532 }
533
534 if ( $param['useMaster'] ) {
535 $pager->mDb = wfGetDB( DB_MASTER );
536 }
537 if ( isset( $param['offset'] ) ) { # Tell pager to ignore WebRequest offset
538 $pager->setOffset( $param['offset'] );
539 }
540
541 if ( $lim > 0 ) {
542 $pager->mLimit = $lim;
543 }
544 // Fetch the log rows and build the HTML if needed
545 $logBody = $pager->getBody();
546 $numRows = $pager->getNumRows();
547
548 $s = '';
549
550 if ( $logBody ) {
551 if ( $msgKey[0] ) {
552 $dir = $context->getLanguage()->getDir();
553 $lang = $context->getLanguage()->getHtmlCode();
554
555 $s = Xml::openElement( 'div', array(
556 'class' => "mw-warning-with-logexcerpt mw-content-$dir",
557 'dir' => $dir,
558 'lang' => $lang,
559 ) );
560
561 if ( count( $msgKey ) == 1 ) {
562 $s .= $context->msg( $msgKey[0] )->parseAsBlock();
563 } else { // Process additional arguments
564 $args = $msgKey;
565 array_shift( $args );
566 $s .= $context->msg( $msgKey[0], $args )->parseAsBlock();
567 }
568 }
569 $s .= $loglist->beginLogEventsList() .
570 $logBody .
571 $loglist->endLogEventsList();
572 } elseif ( $showIfEmpty ) {
573 $s = Html::rawElement( 'div', array( 'class' => 'mw-warning-logempty' ),
574 $context->msg( 'logempty' )->parse() );
575 }
576
577 if ( $numRows > $pager->mLimit ) { # Show "Full log" link
578 $urlParam = array();
579 if ( $page instanceof Title ) {
580 $urlParam['page'] = $page->getPrefixedDBkey();
581 } elseif ( $page != '' ) {
582 $urlParam['page'] = $page;
583 }
584
585 if ( $user != '' ) {
586 $urlParam['user'] = $user;
587 }
588
589 if ( !is_array( $types ) ) { # Make it an array, if it isn't
590 $types = array( $types );
591 }
592
593 # If there is exactly one log type, we can link to Special:Log?type=foo
594 if ( count( $types ) == 1 ) {
595 $urlParam['type'] = $types[0];
596 }
597
598 $s .= Linker::link(
599 SpecialPage::getTitleFor( 'Log' ),
600 $context->msg( 'log-fulllog' )->escaped(),
601 array(),
602 $urlParam
603 );
604 }
605
606 if ( $logBody && $msgKey[0] ) {
607 $s .= '</div>';
608 }
609
610 if ( $wrap != '' ) { // Wrap message in html
611 $s = str_replace( '$1', $s, $wrap );
612 }
613
614 /* hook can return false, if we don't want the message to be emitted (Wikia BugId:7093) */
615 if ( Hooks::run( 'LogEventsListShowLogExtract', array( &$s, $types, $page, $user, $param ) ) ) {
616 // $out can be either an OutputPage object or a String-by-reference
617 if ( $out instanceof OutputPage ) {
618 $out->addHTML( $s );
619 } else {
620 $out = $s;
621 }
622 }
623
624 return $numRows;
625 }
626
627 /**
628 * SQL clause to skip forbidden log types for this user
629 *
630 * @param DatabaseBase $db
631 * @param string $audience Public/user
632 * @param User $user User to check, or null to use $wgUser
633 * @return string|bool String on success, false on failure.
634 */
635 public static function getExcludeClause( $db, $audience = 'public', User $user = null ) {
636 global $wgLogRestrictions;
637
638 if ( $audience != 'public' && $user === null ) {
639 global $wgUser;
640 $user = $wgUser;
641 }
642
643 // Reset the array, clears extra "where" clauses when $par is used
644 $hiddenLogs = array();
645
646 // Don't show private logs to unprivileged users
647 foreach ( $wgLogRestrictions as $logType => $right ) {
648 if ( $audience == 'public' || !$user->isAllowed( $right ) ) {
649 $hiddenLogs[] = $logType;
650 }
651 }
652 if ( count( $hiddenLogs ) == 1 ) {
653 return 'log_type != ' . $db->addQuotes( $hiddenLogs[0] );
654 } elseif ( $hiddenLogs ) {
655 return 'log_type NOT IN (' . $db->makeList( $hiddenLogs ) . ')';
656 }
657
658 return false;
659 }
660 }