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