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