Merge "Don't check namespace in SpecialWantedtemplates"
[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 = array(), $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() : (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( 'allpagessubmit' )->text() );
118
119 // Fieldset
120 $html = Xml::fieldset( $this->msg( 'log' )->text(), $html );
121
122 // Form wrapping
123 $html = Xml::tags( 'form', array( '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 = array( $this->msg( 'show' )->escaped(), $this->msg( 'hide' )->escaped() );
135 // Option value -> message mapping
136 $links = array();
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 array(),
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 = array(); // 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 = array( '' => $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 array( 'class' => 'mw-autocomplete-user' )
234 );
235
236 return '<span style="white-space: nowrap">' . $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 style="white-space: nowrap">' . $label . '</span>';
253 }
254
255 /**
256 * @param string $pattern
257 * @return string Checkbox
258 */
259 private function getTitlePattern( $pattern ) {
260 return '<span style="white-space: nowrap">' .
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', array( $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( $row->ts_tags, 'logevent' );
335 $classes = array_merge(
336 array( 'mw-logline-' . $entry->getType() ),
337 $newClasses
338 );
339
340 return Html::rawElement( 'li', array( 'class' => $classes ),
341 "$del $time $action $comment $revert $tagDisplay" ) . "\n";
342 }
343
344 /**
345 * @param stdClass $row Row
346 * @return string
347 */
348 private function getShowHideLinks( $row ) {
349 // We don't want to see the links and
350 if ( $this->flags == self::NO_ACTION_LINK ) {
351 return '';
352 }
353
354 $user = $this->getUser();
355
356 // If change tag editing is available to this user, return the checkbox
357 if ( $this->flags & self::USE_CHECKBOXES && $this->showTagEditUI ) {
358 return Xml::check(
359 'showhiderevisions',
360 false,
361 array( 'name' => 'ids[' . $row->log_id . ']' )
362 );
363 }
364
365 // no one can hide items from the suppress log.
366 if ( $row->log_type == 'suppress' ) {
367 return '';
368 }
369
370 $del = '';
371 // Don't show useless checkbox to people who cannot hide log entries
372 if ( $user->isAllowed( 'deletedhistory' ) ) {
373 $canHide = $user->isAllowed( 'deletelogentry' );
374 $canViewSuppressedOnly = $user->isAllowed( 'viewsuppressed' ) &&
375 !$user->isAllowed( 'suppressrevision' );
376 $entryIsSuppressed = self::isDeleted( $row, LogPage::DELETED_RESTRICTED );
377 $canViewThisSuppressedEntry = $canViewSuppressedOnly && $entryIsSuppressed;
378 if ( $row->log_deleted || $canHide ) {
379 // Show checkboxes instead of links.
380 if ( $canHide && $this->flags & self::USE_CHECKBOXES && !$canViewThisSuppressedEntry ) {
381 // If event was hidden from sysops
382 if ( !self::userCan( $row, LogPage::DELETED_RESTRICTED, $user ) ) {
383 $del = Xml::check( 'deleterevisions', false, array( 'disabled' => 'disabled' ) );
384 } else {
385 $del = Xml::check(
386 'showhiderevisions',
387 false,
388 array( 'name' => 'ids[' . $row->log_id . ']' )
389 );
390 }
391 } else {
392 // If event was hidden from sysops
393 if ( !self::userCan( $row, LogPage::DELETED_RESTRICTED, $user ) ) {
394 $del = Linker::revDeleteLinkDisabled( $canHide );
395 } else {
396 $query = array(
397 'target' => SpecialPage::getTitleFor( 'Log', $row->log_type )->getPrefixedDBkey(),
398 'type' => 'logging',
399 'ids' => $row->log_id,
400 );
401 $del = Linker::revDeleteLink(
402 $query,
403 $entryIsSuppressed,
404 $canHide && !$canViewThisSuppressedEntry
405 );
406 }
407 }
408 }
409 }
410
411 return $del;
412 }
413
414 /**
415 * @param stdClass $row Row
416 * @param string|array $type
417 * @param string|array $action
418 * @param string $right
419 * @return bool
420 */
421 public static function typeAction( $row, $type, $action, $right = '' ) {
422 $match = is_array( $type ) ?
423 in_array( $row->log_type, $type ) : $row->log_type == $type;
424 if ( $match ) {
425 $match = is_array( $action ) ?
426 in_array( $row->log_action, $action ) : $row->log_action == $action;
427 if ( $match && $right ) {
428 global $wgUser;
429 $match = $wgUser->isAllowed( $right );
430 }
431 }
432
433 return $match;
434 }
435
436 /**
437 * Determine if the current user is allowed to view a particular
438 * field of this log row, if it's marked as deleted.
439 *
440 * @param stdClass $row Row
441 * @param int $field
442 * @param User $user User to check, or null to use $wgUser
443 * @return bool
444 */
445 public static function userCan( $row, $field, User $user = null ) {
446 return self::userCanBitfield( $row->log_deleted, $field, $user );
447 }
448
449 /**
450 * Determine if the current user is allowed to view a particular
451 * field of this log row, if it's marked as deleted.
452 *
453 * @param int $bitfield Current field
454 * @param int $field
455 * @param User $user User to check, or null to use $wgUser
456 * @return bool
457 */
458 public static function userCanBitfield( $bitfield, $field, User $user = null ) {
459 if ( $bitfield & $field ) {
460 if ( $user === null ) {
461 global $wgUser;
462 $user = $wgUser;
463 }
464 if ( $bitfield & LogPage::DELETED_RESTRICTED ) {
465 $permissions = array( 'suppressrevision', 'viewsuppressed' );
466 } else {
467 $permissions = array( 'deletedhistory' );
468 }
469 $permissionlist = implode( ', ', $permissions );
470 wfDebug( "Checking for $permissionlist due to $field match on $bitfield\n" );
471 return call_user_func_array( array( $user, 'isAllowedAny' ), $permissions );
472 }
473 return true;
474 }
475
476 /**
477 * @param stdClass $row Row
478 * @param int $field One of DELETED_* bitfield constants
479 * @return bool
480 */
481 public static function isDeleted( $row, $field ) {
482 return ( $row->log_deleted & $field ) == $field;
483 }
484
485 /**
486 * Show log extract. Either with text and a box (set $msgKey) or without (don't set $msgKey)
487 *
488 * @param OutputPage|string $out By-reference
489 * @param string|array $types Log types to show
490 * @param string|Title $page The page title to show log entries for
491 * @param string $user The user who made the log entries
492 * @param array $param Associative Array with the following additional options:
493 * - lim Integer Limit of items to show, default is 50
494 * - conds Array Extra conditions for the query (e.g. "log_action != 'revision'")
495 * - showIfEmpty boolean Set to false if you don't want any output in case the loglist is empty
496 * if set to true (default), "No matching items in log" is displayed if loglist is empty
497 * - msgKey Array If you want a nice box with a message, set this to the key of the message.
498 * First element is the message key, additional optional elements are parameters for the key
499 * that are processed with wfMessage
500 * - offset Set to overwrite offset parameter in WebRequest
501 * set to '' to unset offset
502 * - wrap String Wrap the message in html (usually something like "<div ...>$1</div>").
503 * - flags Integer display flags (NO_ACTION_LINK,NO_EXTRA_USER_LINKS)
504 * - useRequestParams boolean Set true to use Pager-related parameters in the WebRequest
505 * - useMaster boolean Use master DB
506 * @return int Number of total log items (not limited by $lim)
507 */
508 public static function showLogExtract(
509 &$out, $types = array(), $page = '', $user = '', $param = array()
510 ) {
511 $defaultParameters = array(
512 'lim' => 25,
513 'conds' => array(),
514 'showIfEmpty' => true,
515 'msgKey' => array( '' ),
516 'wrap' => "$1",
517 'flags' => 0,
518 'useRequestParams' => false,
519 'useMaster' => false,
520 );
521 # The + operator appends elements of remaining keys from the right
522 # handed array to the left handed, whereas duplicated keys are NOT overwritten.
523 $param += $defaultParameters;
524 # Convert $param array to individual variables
525 $lim = $param['lim'];
526 $conds = $param['conds'];
527 $showIfEmpty = $param['showIfEmpty'];
528 $msgKey = $param['msgKey'];
529 $wrap = $param['wrap'];
530 $flags = $param['flags'];
531 $useRequestParams = $param['useRequestParams'];
532 if ( !is_array( $msgKey ) ) {
533 $msgKey = array( $msgKey );
534 }
535
536 if ( $out instanceof OutputPage ) {
537 $context = $out->getContext();
538 } else {
539 $context = RequestContext::getMain();
540 }
541
542 # Insert list of top 50 (or top $lim) items
543 $loglist = new LogEventsList( $context, null, $flags );
544 $pager = new LogPager( $loglist, $types, $user, $page, '', $conds );
545 if ( !$useRequestParams ) {
546 # Reset vars that may have been taken from the request
547 $pager->mLimit = 50;
548 $pager->mDefaultLimit = 50;
549 $pager->mOffset = "";
550 $pager->mIsBackwards = false;
551 }
552
553 if ( $param['useMaster'] ) {
554 $pager->mDb = wfGetDB( DB_MASTER );
555 }
556 if ( isset( $param['offset'] ) ) { # Tell pager to ignore WebRequest offset
557 $pager->setOffset( $param['offset'] );
558 }
559
560 if ( $lim > 0 ) {
561 $pager->mLimit = $lim;
562 }
563 // Fetch the log rows and build the HTML if needed
564 $logBody = $pager->getBody();
565 $numRows = $pager->getNumRows();
566
567 $s = '';
568
569 if ( $logBody ) {
570 if ( $msgKey[0] ) {
571 $dir = $context->getLanguage()->getDir();
572 $lang = $context->getLanguage()->getHtmlCode();
573
574 $s = Xml::openElement( 'div', array(
575 'class' => "mw-warning-with-logexcerpt mw-content-$dir",
576 'dir' => $dir,
577 'lang' => $lang,
578 ) );
579
580 if ( count( $msgKey ) == 1 ) {
581 $s .= $context->msg( $msgKey[0] )->parseAsBlock();
582 } else { // Process additional arguments
583 $args = $msgKey;
584 array_shift( $args );
585 $s .= $context->msg( $msgKey[0], $args )->parseAsBlock();
586 }
587 }
588 $s .= $loglist->beginLogEventsList() .
589 $logBody .
590 $loglist->endLogEventsList();
591 } elseif ( $showIfEmpty ) {
592 $s = Html::rawElement( 'div', array( 'class' => 'mw-warning-logempty' ),
593 $context->msg( 'logempty' )->parse() );
594 }
595
596 if ( $numRows > $pager->mLimit ) { # Show "Full log" link
597 $urlParam = array();
598 if ( $page instanceof Title ) {
599 $urlParam['page'] = $page->getPrefixedDBkey();
600 } elseif ( $page != '' ) {
601 $urlParam['page'] = $page;
602 }
603
604 if ( $user != '' ) {
605 $urlParam['user'] = $user;
606 }
607
608 if ( !is_array( $types ) ) { # Make it an array, if it isn't
609 $types = array( $types );
610 }
611
612 # If there is exactly one log type, we can link to Special:Log?type=foo
613 if ( count( $types ) == 1 ) {
614 $urlParam['type'] = $types[0];
615 }
616
617 $s .= Linker::link(
618 SpecialPage::getTitleFor( 'Log' ),
619 $context->msg( 'log-fulllog' )->escaped(),
620 array(),
621 $urlParam
622 );
623 }
624
625 if ( $logBody && $msgKey[0] ) {
626 $s .= '</div>';
627 }
628
629 if ( $wrap != '' ) { // Wrap message in html
630 $s = str_replace( '$1', $s, $wrap );
631 }
632
633 /* hook can return false, if we don't want the message to be emitted (Wikia BugId:7093) */
634 if ( Hooks::run( 'LogEventsListShowLogExtract', array( &$s, $types, $page, $user, $param ) ) ) {
635 // $out can be either an OutputPage object or a String-by-reference
636 if ( $out instanceof OutputPage ) {
637 $out->addHTML( $s );
638 } else {
639 $out = $s;
640 }
641 }
642
643 return $numRows;
644 }
645
646 /**
647 * SQL clause to skip forbidden log types for this user
648 *
649 * @param DatabaseBase $db
650 * @param string $audience Public/user
651 * @param User $user User to check, or null to use $wgUser
652 * @return string|bool String on success, false on failure.
653 */
654 public static function getExcludeClause( $db, $audience = 'public', User $user = null ) {
655 global $wgLogRestrictions;
656
657 if ( $audience != 'public' && $user === null ) {
658 global $wgUser;
659 $user = $wgUser;
660 }
661
662 // Reset the array, clears extra "where" clauses when $par is used
663 $hiddenLogs = array();
664
665 // Don't show private logs to unprivileged users
666 foreach ( $wgLogRestrictions as $logType => $right ) {
667 if ( $audience == 'public' || !$user->isAllowed( $right ) ) {
668 $hiddenLogs[] = $logType;
669 }
670 }
671 if ( count( $hiddenLogs ) == 1 ) {
672 return 'log_type != ' . $db->addQuotes( $hiddenLogs[0] );
673 } elseif ( $hiddenLogs ) {
674 return 'log_type NOT IN (' . $db->makeList( $hiddenLogs ) . ')';
675 }
676
677 return false;
678 }
679 }