Merge "JSON i18n shim: Only register LocalisationCacheRecache handler once"
[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 * Deprecated alias for getTitle(); do not use.
62 *
63 * @deprecated since 1.20; use getTitle() instead.
64 * @return Title
65 */
66 public function getDisplayTitle() {
67 wfDeprecated( __METHOD__, '1.20' );
68 return $this->getTitle();
69 }
70
71 /**
72 * Set page title and show header for this log type
73 * @param array $type
74 * @deprecated since 1.19
75 */
76 public function showHeader( $type ) {
77 wfDeprecated( __METHOD__, '1.19' );
78 // If only one log type is used, then show a special message...
79 $headerType = count( $type ) == 1 ? $type[0] : '';
80 $out = $this->getOutput();
81 if ( LogPage::isLogType( $headerType ) ) {
82 $page = new LogPage( $headerType );
83 $out->setPageTitle( $page->getName()->text() );
84 $out->addHTML( $page->getDescription()->parseAsBlock() );
85 } else {
86 $out->addHTML( $this->msg( 'alllogstext' )->parse() );
87 }
88 }
89
90 /**
91 * Show options for the log list
92 *
93 * @param array|string $types
94 * @param string $user
95 * @param string $page
96 * @param string $pattern
97 * @param int $year Year
98 * @param int $month Month
99 * @param array $filter
100 * @param string $tagFilter Tag to select by default
101 */
102 public function showOptions( $types = array(), $user = '', $page = '', $pattern = '', $year = 0,
103 $month = 0, $filter = null, $tagFilter = ''
104 ) {
105 global $wgScript, $wgMiserMode;
106
107 $title = SpecialPage::getTitleFor( 'Log' );
108
109 // For B/C, we take strings, but make sure they are converted...
110 $types = ( $types === '' ) ? array() : (array)$types;
111
112 $tagSelector = ChangeTags::buildTagFilterSelector( $tagFilter );
113
114 $html = Html::hidden( 'title', $title->getPrefixedDBkey() );
115
116 // Basic selectors
117 $html .= $this->getTypeMenu( $types ) . "\n";
118 $html .= $this->getUserInput( $user ) . "\n";
119 $html .= $this->getTitleInput( $page ) . "\n";
120 $html .= $this->getExtraInputs( $types ) . "\n";
121
122 // Title pattern, if allowed
123 if ( !$wgMiserMode ) {
124 $html .= $this->getTitlePattern( $pattern ) . "\n";
125 }
126
127 // date menu
128 $html .= Xml::tags( 'p', null, Xml::dateMenu( (int)$year, (int)$month ) );
129
130 // Tag filter
131 if ( $tagSelector ) {
132 $html .= Xml::tags( 'p', null, implode( '&#160;', $tagSelector ) );
133 }
134
135 // Filter links
136 if ( $filter ) {
137 $html .= Xml::tags( 'p', null, $this->getFilterLinks( $filter ) );
138 }
139
140 // Submit button
141 $html .= Xml::submitButton( $this->msg( 'allpagessubmit' )->text() );
142
143 // Fieldset
144 $html = Xml::fieldset( $this->msg( 'log' )->text(), $html );
145
146 // Form wrapping
147 $html = Xml::tags( 'form', array( 'action' => $wgScript, 'method' => 'get' ), $html );
148
149 $this->getOutput()->addHTML( $html );
150 }
151
152 /**
153 * @param array $filter
154 * @return string Formatted HTML
155 */
156 private function getFilterLinks( $filter ) {
157 // show/hide links
158 $messages = array( $this->msg( 'show' )->escaped(), $this->msg( 'hide' )->escaped() );
159 // Option value -> message mapping
160 $links = array();
161 $hiddens = ''; // keep track for "go" button
162 foreach ( $filter as $type => $val ) {
163 // Should the below assignment be outside the foreach?
164 // Then it would have to be copied. Not certain what is more expensive.
165 $query = $this->getDefaultQuery();
166 $queryKey = "hide_{$type}_log";
167
168 $hideVal = 1 - intval( $val );
169 $query[$queryKey] = $hideVal;
170
171 $link = Linker::linkKnown(
172 $this->getTitle(),
173 $messages[$hideVal],
174 array(),
175 $query
176 );
177
178 // Message: log-show-hide-patrol
179 $links[$type] = $this->msg( "log-show-hide-{$type}" )->rawParams( $link )->escaped();
180 $hiddens .= Html::hidden( "hide_{$type}_log", $val ) . "\n";
181 }
182
183 // Build links
184 return '<small>' . $this->getLanguage()->pipeList( $links ) . '</small>' . $hiddens;
185 }
186
187 private function getDefaultQuery() {
188 if ( !isset( $this->mDefaultQuery ) ) {
189 $this->mDefaultQuery = $this->getRequest()->getQueryValues();
190 unset( $this->mDefaultQuery['title'] );
191 unset( $this->mDefaultQuery['dir'] );
192 unset( $this->mDefaultQuery['offset'] );
193 unset( $this->mDefaultQuery['limit'] );
194 unset( $this->mDefaultQuery['order'] );
195 unset( $this->mDefaultQuery['month'] );
196 unset( $this->mDefaultQuery['year'] );
197 }
198
199 return $this->mDefaultQuery;
200 }
201
202 /**
203 * @param array $queryTypes
204 * @return string Formatted HTML
205 */
206 private function getTypeMenu( $queryTypes ) {
207 $queryType = count( $queryTypes ) == 1 ? $queryTypes[0] : '';
208 $selector = $this->getTypeSelector();
209 $selector->setDefault( $queryType );
210
211 return $selector->getHtml();
212 }
213
214 /**
215 * Returns log page selector.
216 * @return XmlSelect
217 * @since 1.19
218 */
219 public function getTypeSelector() {
220 $typesByName = array(); // Temporary array
221 // First pass to load the log names
222 foreach ( LogPage::validTypes() as $type ) {
223 $page = new LogPage( $type );
224 $restriction = $page->getRestriction();
225 if ( $this->getUser()->isAllowed( $restriction ) ) {
226 $typesByName[$type] = $page->getName()->text();
227 }
228 }
229
230 // Second pass to sort by name
231 asort( $typesByName );
232
233 // Always put "All public logs" on top
234 $public = $typesByName[''];
235 unset( $typesByName[''] );
236 $typesByName = array( '' => $public ) + $typesByName;
237
238 $select = new XmlSelect( 'type' );
239 foreach ( $typesByName as $type => $name ) {
240 $select->addOption( $name, $type );
241 }
242
243 return $select;
244 }
245
246 /**
247 * @param string $user
248 * @return string Formatted HTML
249 */
250 private function getUserInput( $user ) {
251 $label = Xml::inputLabel(
252 $this->msg( 'specialloguserlabel' )->text(),
253 'user',
254 'mw-log-user',
255 15,
256 $user
257 );
258
259 return '<span style="white-space: nowrap">' . $label . '</span>';
260 }
261
262 /**
263 * @param string $title
264 * @return string Formatted HTML
265 */
266 private function getTitleInput( $title ) {
267 $label = Xml::inputLabel(
268 $this->msg( 'speciallogtitlelabel' )->text(),
269 'page',
270 'mw-log-page',
271 20,
272 $title
273 );
274
275 return '<span style="white-space: nowrap">' . $label . '</span>';
276 }
277
278 /**
279 * @param string $pattern
280 * @return string Checkbox
281 */
282 private function getTitlePattern( $pattern ) {
283 return '<span style="white-space: nowrap">' .
284 Xml::checkLabel( $this->msg( 'log-title-wildcard' )->text(), 'pattern', 'pattern', $pattern ) .
285 '</span>';
286 }
287
288 /**
289 * @param array $types
290 * @return string
291 */
292 private function getExtraInputs( $types ) {
293 $offender = $this->getRequest()->getVal( 'offender' );
294 $user = User::newFromName( $offender, false );
295 if ( !$user || ( $user->getId() == 0 && !IP::isIPAddress( $offender ) ) ) {
296 $offender = ''; // Blank field if invalid
297 }
298 if ( count( $types ) == 1 && $types[0] == 'suppress' ) {
299 return Xml::inputLabel( $this->msg( 'revdelete-offender' )->text(), 'offender',
300 'mw-log-offender', 20, $offender );
301 }
302
303 return '';
304 }
305
306 /**
307 * @return string
308 */
309 public function beginLogEventsList() {
310 return "<ul>\n";
311 }
312
313 /**
314 * @return string
315 */
316 public function endLogEventsList() {
317 return "</ul>\n";
318 }
319
320 /**
321 * @param stdClass $row A single row from the result set
322 * @return string Formatted HTML list item
323 */
324 public function logLine( $row ) {
325 $entry = DatabaseLogEntry::newFromRow( $row );
326 $formatter = LogFormatter::newFromEntry( $entry );
327 $formatter->setContext( $this->getContext() );
328 $formatter->setShowUserToolLinks( !( $this->flags & self::NO_EXTRA_USER_LINKS ) );
329
330 $time = htmlspecialchars( $this->getLanguage()->userTimeAndDate(
331 $entry->getTimestamp(), $this->getUser() ) );
332
333 $action = $formatter->getActionText();
334
335 if ( $this->flags & self::NO_ACTION_LINK ) {
336 $revert = '';
337 } else {
338 $revert = $formatter->getActionLinks();
339 if ( $revert != '' ) {
340 $revert = '<span class="mw-logevent-actionlink">' . $revert . '</span>';
341 }
342 }
343
344 $comment = $formatter->getComment();
345
346 // Some user can hide log items and have review links
347 $del = $this->getShowHideLinks( $row );
348
349 // Any tags...
350 list( $tagDisplay, $newClasses ) = ChangeTags::formatSummaryRow( $row->ts_tags, 'logevent' );
351 $classes = array_merge(
352 array( 'mw-logline-' . $entry->getType() ),
353 $newClasses
354 );
355
356 return Html::rawElement( 'li', array( 'class' => $classes ),
357 "$del $time $action $comment $revert $tagDisplay" ) . "\n";
358 }
359
360 /**
361 * @param stdClass $row Row
362 * @return string
363 */
364 private function getShowHideLinks( $row ) {
365 // We don't want to see the links and
366 // no one can hide items from the suppress log.
367 if ( ( $this->flags == self::NO_ACTION_LINK )
368 || $row->log_type == 'suppress'
369 ) {
370 return '';
371 }
372 $del = '';
373 $user = $this->getUser();
374 // Don't show useless checkbox to people who cannot hide log entries
375 if ( $user->isAllowed( 'deletedhistory' ) ) {
376 $canHide = $user->isAllowed( 'deletelogentry' );
377 if ( $row->log_deleted || $canHide ) {
378 // Show checkboxes instead of links.
379 if ( $canHide && $this->flags & self::USE_REVDEL_CHECKBOXES ) {
380 // If event was hidden from sysops
381 if ( !self::userCan( $row, LogPage::DELETED_RESTRICTED, $user ) ) {
382 $del = Xml::check( 'deleterevisions', false, array( 'disabled' => 'disabled' ) );
383 } else {
384 $del = Xml::check(
385 'showhiderevisions',
386 false,
387 array( 'name' => 'ids[' . $row->log_id . ']' )
388 );
389 }
390 } else {
391 // If event was hidden from sysops
392 if ( !self::userCan( $row, LogPage::DELETED_RESTRICTED, $user ) ) {
393 $del = Linker::revDeleteLinkDisabled( $canHide );
394 } else {
395 $query = array(
396 'target' => SpecialPage::getTitleFor( 'Log', $row->log_type )->getPrefixedDBkey(),
397 'type' => 'logging',
398 'ids' => $row->log_id,
399 );
400 $del = Linker::revDeleteLink(
401 $query,
402 self::isDeleted( $row, LogPage::DELETED_RESTRICTED ),
403 $canHide
404 );
405 }
406 }
407 }
408 }
409
410 return $del;
411 }
412
413 /**
414 * @param stdClass $row Row
415 * @param string|array $type
416 * @param string|array $action
417 * @param string $right
418 * @return bool
419 */
420 public static function typeAction( $row, $type, $action, $right = '' ) {
421 $match = is_array( $type ) ?
422 in_array( $row->log_type, $type ) : $row->log_type == $type;
423 if ( $match ) {
424 $match = is_array( $action ) ?
425 in_array( $row->log_action, $action ) : $row->log_action == $action;
426 if ( $match && $right ) {
427 global $wgUser;
428 $match = $wgUser->isAllowed( $right );
429 }
430 }
431
432 return $match;
433 }
434
435 /**
436 * Determine if the current user is allowed to view a particular
437 * field of this log row, if it's marked as deleted.
438 *
439 * @param stdClass $row Row
440 * @param int $field
441 * @param User $user User to check, or null to use $wgUser
442 * @return bool
443 */
444 public static function userCan( $row, $field, User $user = null ) {
445 return self::userCanBitfield( $row->log_deleted, $field, $user );
446 }
447
448 /**
449 * Determine if the current user is allowed to view a particular
450 * field of this log row, if it's marked as deleted.
451 *
452 * @param int $bitfield Current field
453 * @param int $field
454 * @param User $user User to check, or null to use $wgUser
455 * @return bool
456 */
457 public static function userCanBitfield( $bitfield, $field, User $user = null ) {
458 if ( $bitfield & $field ) {
459 if ( $bitfield & LogPage::DELETED_RESTRICTED ) {
460 $permission = 'suppressrevision';
461 } else {
462 $permission = 'deletedhistory';
463 }
464 wfDebug( "Checking for $permission due to $field match on $bitfield\n" );
465 if ( $user === null ) {
466 global $wgUser;
467 $user = $wgUser;
468 }
469
470 return $user->isAllowed( $permission );
471 }
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
564 $logBody = $pager->getBody();
565 $s = '';
566
567 if ( $logBody ) {
568 if ( $msgKey[0] ) {
569 $dir = $context->getLanguage()->getDir();
570 $lang = $context->getLanguage()->getCode();
571
572 $s = Xml::openElement( 'div', array(
573 'class' => "mw-warning-with-logexcerpt mw-content-$dir",
574 'dir' => $dir,
575 'lang' => $lang,
576 ) );
577
578 if ( count( $msgKey ) == 1 ) {
579 $s .= $context->msg( $msgKey[0] )->parseAsBlock();
580 } else { // Process additional arguments
581 $args = $msgKey;
582 array_shift( $args );
583 $s .= $context->msg( $msgKey[0], $args )->parseAsBlock();
584 }
585 }
586 $s .= $loglist->beginLogEventsList() .
587 $logBody .
588 $loglist->endLogEventsList();
589 } elseif ( $showIfEmpty ) {
590 $s = Html::rawElement( 'div', array( 'class' => 'mw-warning-logempty' ),
591 $context->msg( 'logempty' )->parse() );
592 }
593
594 if ( $pager->getNumRows() > $pager->mLimit ) { # Show "Full log" link
595 $urlParam = array();
596 if ( $page instanceof Title ) {
597 $urlParam['page'] = $page->getPrefixedDBkey();
598 } elseif ( $page != '' ) {
599 $urlParam['page'] = $page;
600 }
601
602 if ( $user != '' ) {
603 $urlParam['user'] = $user;
604 }
605
606 if ( !is_array( $types ) ) { # Make it an array, if it isn't
607 $types = array( $types );
608 }
609
610 # If there is exactly one log type, we can link to Special:Log?type=foo
611 if ( count( $types ) == 1 ) {
612 $urlParam['type'] = $types[0];
613 }
614
615 $s .= Linker::link(
616 SpecialPage::getTitleFor( 'Log' ),
617 $context->msg( 'log-fulllog' )->escaped(),
618 array(),
619 $urlParam
620 );
621 }
622
623 if ( $logBody && $msgKey[0] ) {
624 $s .= '</div>';
625 }
626
627 if ( $wrap != '' ) { // Wrap message in html
628 $s = str_replace( '$1', $s, $wrap );
629 }
630
631 /* hook can return false, if we don't want the message to be emitted (Wikia BugId:7093) */
632 if ( wfRunHooks( 'LogEventsListShowLogExtract', array( &$s, $types, $page, $user, $param ) ) ) {
633 // $out can be either an OutputPage object or a String-by-reference
634 if ( $out instanceof OutputPage ) {
635 $out->addHTML( $s );
636 } else {
637 $out = $s;
638 }
639 }
640
641 return $pager->getNumRows();
642 }
643
644 /**
645 * SQL clause to skip forbidden log types for this user
646 *
647 * @param DatabaseBase $db
648 * @param string $audience Public/user
649 * @param User $user User to check, or null to use $wgUser
650 * @return string|bool String on success, false on failure.
651 */
652 public static function getExcludeClause( $db, $audience = 'public', User $user = null ) {
653 global $wgLogRestrictions;
654
655 if ( $audience != 'public' && $user === null ) {
656 global $wgUser;
657 $user = $wgUser;
658 }
659
660 // Reset the array, clears extra "where" clauses when $par is used
661 $hiddenLogs = array();
662
663 // Don't show private logs to unprivileged users
664 foreach ( $wgLogRestrictions as $logType => $right ) {
665 if ( $audience == 'public' || !$user->isAllowed( $right ) ) {
666 $hiddenLogs[] = $logType;
667 }
668 }
669 if ( count( $hiddenLogs ) == 1 ) {
670 return 'log_type != ' . $db->addQuotes( $hiddenLogs[0] );
671 } elseif ( $hiddenLogs ) {
672 return 'log_type NOT IN (' . $db->makeList( $hiddenLogs ) . ')';
673 }
674
675 return false;
676 }
677 }