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