Use WebRequest::getQueryValues() to get all query strings parameters instead of ...
[lhc/web/wiklou.git] / includes / 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 {
27 const NO_ACTION_LINK = 1;
28 const NO_EXTRA_USER_LINKS = 2;
29
30 /**
31 * @var Skin
32 */
33 private $skin;
34
35 /**
36 * @var OutputPage
37 */
38 private $out;
39 public $flags;
40
41 /**
42 * @var Array
43 */
44 protected $message;
45
46 /**
47 * @var Array
48 */
49 protected $mDefaultQuery;
50
51 public function __construct( $skin, $out, $flags = 0 ) {
52 $this->skin = $skin;
53 $this->out = $out;
54 $this->flags = $flags;
55 $this->preCacheMessages();
56 }
57
58 /**
59 * As we use the same small set of messages in various methods and that
60 * they are called often, we call them once and save them in $this->message
61 */
62 private function preCacheMessages() {
63 // Precache various messages
64 if( !isset( $this->message ) ) {
65 $messages = array( 'revertmerge', 'protect_change', 'unblocklink', 'change-blocklink',
66 'revertmove', 'undeletelink', 'undeleteviewlink', 'revdel-restore', 'hist', 'diff',
67 'pipe-separator', 'revdel-restore-deleted', 'revdel-restore-visible' );
68 foreach( $messages as $msg ) {
69 $this->message[$msg] = wfMsgExt( $msg, array( 'escapenoentities' ) );
70 }
71 }
72 }
73
74 /**
75 * Set page title and show header for this log type
76 * @param $type Array
77 */
78 public function showHeader( $type ) {
79 // If only one log type is used, then show a special message...
80 $headerType = (count($type) == 1) ? $type[0] : '';
81 if( LogPage::isLogType( $headerType ) ) {
82 $this->out->setPageTitle( LogPage::logName( $headerType ) );
83 $this->out->addHTML( LogPage::logHeader( $headerType ) );
84 } else {
85 $this->out->addHTML( wfMsgExt('alllogstext',array('parseinline')) );
86 }
87 }
88
89 /**
90 * Show options for the log list
91 *
92 * @param $types string 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='',
102 $month = '', $filter = null, $tagFilter='' ) {
103 global $wgScript, $wgMiserMode;
104
105 $action = $wgScript;
106 $title = SpecialPage::getTitleFor( 'Log' );
107 $special = $title->getPrefixedDBkey();
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', $special );
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( $year, $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( wfMsg( 'allpagessubmit' ) );
142
143 // Fieldset
144 $html = Xml::fieldset( wfMsg( 'log' ), $html );
145
146 // Form wrapping
147 $html = Xml::tags( 'form', array( 'action' => $action, 'method' => 'get' ), $html );
148
149 $this->out->addHTML( $html );
150 }
151
152 /**
153 * @param $filter Array
154 * @return String: Formatted HTML
155 */
156 private function getFilterLinks( $filter ) {
157 global $wgLang;
158 // show/hide links
159 $messages = array( wfMsgHtml( 'show' ), wfMsgHtml( 'hide' ) );
160 // Option value -> message mapping
161 $links = array();
162 $hiddens = ''; // keep track for "go" button
163 foreach( $filter as $type => $val ) {
164 // Should the below assignment be outside the foreach?
165 // Then it would have to be copied. Not certain what is more expensive.
166 $query = $this->getDefaultQuery();
167 $queryKey = "hide_{$type}_log";
168
169 $hideVal = 1 - intval($val);
170 $query[$queryKey] = $hideVal;
171
172 $link = $this->skin->link(
173 $this->out->getTitle(),
174 $messages[$hideVal],
175 array(),
176 $query,
177 array( 'known', 'noclasses' )
178 );
179
180 $links[$type] = wfMsgHtml( "log-show-hide-{$type}", $link );
181 $hiddens .= Html::hidden( "hide_{$type}_log", $val ) . "\n";
182 }
183 // Build links
184 return '<small>'.$wgLang->pipeList( $links ) . '</small>' . $hiddens;
185 }
186
187 private function getDefaultQuery() {
188 global $wgRequest;
189
190 if ( !isset( $this->mDefaultQuery ) ) {
191 $this->mDefaultQuery = $wgRequest->getQueryValues();
192 unset( $this->mDefaultQuery['title'] );
193 unset( $this->mDefaultQuery['dir'] );
194 unset( $this->mDefaultQuery['offset'] );
195 unset( $this->mDefaultQuery['limit'] );
196 unset( $this->mDefaultQuery['order'] );
197 unset( $this->mDefaultQuery['month'] );
198 unset( $this->mDefaultQuery['year'] );
199 }
200 return $this->mDefaultQuery;
201 }
202
203 /**
204 * @param $queryTypes Array
205 * @return String: Formatted HTML
206 */
207 private function getTypeMenu( $queryTypes ) {
208 global $wgLogRestrictions, $wgUser;
209
210 $html = "<select name='type'>\n";
211
212 $validTypes = LogPage::validTypes();
213 $typesByName = array(); // Temporary array
214
215 // First pass to load the log names
216 foreach( $validTypes as $type ) {
217 $text = LogPage::logName( $type );
218 $typesByName[$type] = $text;
219 }
220
221 // Second pass to sort by name
222 asort($typesByName);
223
224 // Note the query type
225 $queryType = count($queryTypes) == 1 ? $queryTypes[0] : '';
226
227 // Always put "All public logs" on top
228 if ( isset( $typesByName[''] ) ) {
229 $all = $typesByName[''];
230 unset( $typesByName[''] );
231 $typesByName = array( '' => $all ) + $typesByName;
232 }
233
234 // Third pass generates sorted XHTML content
235 foreach( $typesByName as $type => $text ) {
236 $selected = ($type == $queryType);
237 // Restricted types
238 if ( isset($wgLogRestrictions[$type]) ) {
239 if ( $wgUser->isAllowed( $wgLogRestrictions[$type] ) ) {
240 $html .= Xml::option( $text, $type, $selected ) . "\n";
241 }
242 } else {
243 $html .= Xml::option( $text, $type, $selected ) . "\n";
244 }
245 }
246
247 $html .= '</select>';
248 return $html;
249 }
250
251 /**
252 * @param $user String
253 * @return String: Formatted HTML
254 */
255 private function getUserInput( $user ) {
256 return '<span style="white-space: nowrap">' .
257 Xml::inputLabel( wfMsg( 'specialloguserlabel' ), 'user', 'mw-log-user', 15, $user ) .
258 '</span>';
259 }
260
261 /**
262 * @param $title String
263 * @return String: Formatted HTML
264 */
265 private function getTitleInput( $title ) {
266 return '<span style="white-space: nowrap">' .
267 Xml::inputLabel( wfMsg( 'speciallogtitlelabel' ), 'page', 'mw-log-page', 20, $title ) .
268 '</span>';
269 }
270
271 /**
272 * @return boolean Checkbox
273 */
274 private function getTitlePattern( $pattern ) {
275 return '<span style="white-space: nowrap">' .
276 Xml::checkLabel( wfMsg( 'log-title-wildcard' ), 'pattern', 'pattern', $pattern ) .
277 '</span>';
278 }
279
280 private function getExtraInputs( $types ) {
281 global $wgRequest;
282 $offender = $wgRequest->getVal('offender');
283 $user = User::newFromName( $offender, false );
284 if( !$user || ($user->getId() == 0 && !IP::isIPAddress($offender) ) ) {
285 $offender = ''; // Blank field if invalid
286 }
287 if( count($types) == 1 && $types[0] == 'suppress' ) {
288 return Xml::inputLabel( wfMsg('revdelete-offender'), 'offender',
289 'mw-log-offender', 20, $offender );
290 }
291 return '';
292 }
293
294 public function beginLogEventsList() {
295 return "<ul>\n";
296 }
297
298 public function endLogEventsList() {
299 return "</ul>\n";
300 }
301
302 /**
303 * @param $row Row: a single row from the result set
304 * @return String: Formatted HTML list item
305 */
306 public function logLine( $row ) {
307 $classes = array( 'mw-logline-' . $row->log_type );
308 $title = Title::makeTitle( $row->log_namespace, $row->log_title );
309 // Log time
310 $time = $this->logTimestamp( $row );
311 // User links
312 $userLink = $this->logUserLinks( $row );
313 // Extract extra parameters
314 $paramArray = LogPage::extractParams( $row->log_params );
315 // Event description
316 $action = $this->logAction( $row, $title, $paramArray );
317 // Log comment
318 $comment = $this->logComment( $row );
319 // Add review/revert links and such...
320 $revert = $this->logActionLinks( $row, $title, $paramArray, $comment );
321
322 // Some user can hide log items and have review links
323 $del = $this->getShowHideLinks( $row );
324 if( $del != '' ) $del .= ' ';
325
326 // Any tags...
327 list( $tagDisplay, $newClasses ) = ChangeTags::formatSummaryRow( $row->ts_tags, 'logevent' );
328 $classes = array_merge( $classes, $newClasses );
329
330 return Xml::tags( 'li', array( "class" => implode( ' ', $classes ) ),
331 $del . "$time $userLink $action $comment $revert $tagDisplay" ) . "\n";
332 }
333
334 private function logTimestamp( $row ) {
335 global $wgLang;
336 $time = $wgLang->timeanddate( wfTimestamp( TS_MW, $row->log_timestamp ), true );
337 return htmlspecialchars( $time );
338 }
339
340 private function logUserLinks( $row ) {
341 if( self::isDeleted( $row, LogPage::DELETED_USER ) ) {
342 $userLinks = '<span class="history-deleted">' .
343 wfMsgHtml( 'rev-deleted-user' ) . '</span>';
344 } else {
345 $userLinks = $this->skin->userLink( $row->log_user, $row->user_name );
346 // Talk|Contribs links...
347 if( !( $this->flags & self::NO_EXTRA_USER_LINKS ) ) {
348 $userLinks .= $this->skin->userToolLinks(
349 $row->log_user, $row->user_name, true, 0, $row->user_editcount );
350 }
351 }
352 return $userLinks;
353 }
354
355 private function logAction( $row, $title, $paramArray ) {
356 if( self::isDeleted( $row, LogPage::DELETED_ACTION ) ) {
357 $action = '<span class="history-deleted">' .
358 wfMsgHtml( 'rev-deleted-event' ) . '</span>';
359 } else {
360 $action = LogPage::actionText(
361 $row->log_type, $row->log_action, $title, $this->skin, $paramArray, true );
362 }
363 return $action;
364 }
365
366 private function logComment( $row ) {
367 global $wgContLang;
368 if( self::isDeleted( $row, LogPage::DELETED_COMMENT ) ) {
369 $comment = '<span class="history-deleted">' .
370 wfMsgHtml( 'rev-deleted-comment' ) . '</span>';
371 } else {
372 $comment = $wgContLang->getDirMark() .
373 $this->skin->commentBlock( $row->log_comment );
374 }
375 return $comment;
376 }
377
378 /**
379 * @TODO: split up!
380 *
381 * @param $row
382 * @param Title $title
383 * @param Array $paramArray
384 * @param $comment
385 * @return String
386 */
387 private function logActionLinks( $row, $title, $paramArray, &$comment ) {
388 global $wgUser;
389 if( ( $this->flags & self::NO_ACTION_LINK ) // we don't want to see the action
390 || self::isDeleted( $row, LogPage::DELETED_ACTION ) ) // action is hidden
391 {
392 return '';
393 }
394 $revert = '';
395 if( self::typeAction( $row, 'move', 'move', 'move' ) && !empty( $paramArray[0] ) ) {
396 $destTitle = Title::newFromText( $paramArray[0] );
397 if( $destTitle ) {
398 $revert = '(' . $this->skin->link(
399 SpecialPage::getTitleFor( 'Movepage' ),
400 $this->message['revertmove'],
401 array(),
402 array(
403 'wpOldTitle' => $destTitle->getPrefixedDBkey(),
404 'wpNewTitle' => $title->getPrefixedDBkey(),
405 'wpReason' => wfMsgForContent( 'revertmove' ),
406 'wpMovetalk' => 0
407 ),
408 array( 'known', 'noclasses' )
409 ) . ')';
410 }
411 // Show undelete link
412 } else if( self::typeAction( $row, array( 'delete', 'suppress' ), 'delete', 'deletedhistory' ) ) {
413 if( !$wgUser->isAllowed( 'undelete' ) ) {
414 $viewdeleted = $this->message['undeleteviewlink'];
415 } else {
416 $viewdeleted = $this->message['undeletelink'];
417 }
418 $revert = '(' . $this->skin->link(
419 SpecialPage::getTitleFor( 'Undelete' ),
420 $viewdeleted,
421 array(),
422 array( 'target' => $title->getPrefixedDBkey() ),
423 array( 'known', 'noclasses' )
424 ) . ')';
425 // Show unblock/change block link
426 } else if( self::typeAction( $row, array( 'block', 'suppress' ), array( 'block', 'reblock' ), 'block' ) ) {
427 $revert = '(' .
428 $this->skin->link(
429 SpecialPage::getTitleFor( 'Unblock', $row->log_title ),
430 $this->message['unblocklink'],
431 array(),
432 array(),
433 'known'
434 ) .
435 $this->message['pipe-separator'] .
436 $this->skin->link(
437 SpecialPage::getTitleFor( 'Block', $row->log_title ),
438 $this->message['change-blocklink'],
439 array(),
440 array(),
441 'known'
442 ) .
443 ')';
444 // Show change protection link
445 } else if( self::typeAction( $row, 'protect', array( 'modify', 'protect', 'unprotect' ) ) ) {
446 $revert .= ' (' .
447 $this->skin->link( $title,
448 $this->message['hist'],
449 array(),
450 array(
451 'action' => 'history',
452 'offset' => $row->log_timestamp
453 )
454 );
455 if( $wgUser->isAllowed( 'protect' ) ) {
456 $revert .= $this->message['pipe-separator'] .
457 $this->skin->link( $title,
458 $this->message['protect_change'],
459 array(),
460 array( 'action' => 'protect' ),
461 'known' );
462 }
463 $revert .= ')';
464 // Show unmerge link
465 } else if( self::typeAction( $row, 'merge', 'merge', 'mergehistory' ) ) {
466 $revert = '(' . $this->skin->link(
467 SpecialPage::getTitleFor( 'MergeHistory' ),
468 $this->message['revertmerge'],
469 array(),
470 array(
471 'target' => $paramArray[0],
472 'dest' => $title->getPrefixedDBkey(),
473 'mergepoint' => $paramArray[1]
474 ),
475 array( 'known', 'noclasses' )
476 ) . ')';
477 // If an edit was hidden from a page give a review link to the history
478 } else if( self::typeAction( $row, array( 'delete', 'suppress' ), 'revision', 'deletedhistory' ) ) {
479 $revert = RevisionDeleter::getLogLinks( $title, $paramArray,
480 $this->skin, $this->message );
481 // Hidden log items, give review link
482 } else if( self::typeAction( $row, array( 'delete', 'suppress' ), 'event', 'deletedhistory' ) ) {
483 if( count($paramArray) >= 1 ) {
484 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
485 // $paramArray[1] is a CSV of the IDs
486 $query = $paramArray[0];
487 // Link to each hidden object ID, $paramArray[1] is the url param
488 $revert = '(' . $this->skin->link(
489 $revdel,
490 $this->message['revdel-restore'],
491 array(),
492 array(
493 'target' => $title->getPrefixedText(),
494 'type' => 'logging',
495 'ids' => $query
496 ),
497 array( 'known', 'noclasses' )
498 ) . ')';
499 }
500 // Self-created users
501 } else if( self::typeAction( $row, 'newusers', 'create2' ) ) {
502 if( isset( $paramArray[0] ) ) {
503 $revert = $this->skin->userToolLinks( $paramArray[0], $title->getDBkey(), true );
504 } else {
505 # Fall back to a blue contributions link
506 $revert = $this->skin->userToolLinks( 1, $title->getDBkey() );
507 }
508 $ts = wfTimestamp( TS_UNIX, $row->log_timestamp );
509 if( $ts < '20080129000000' ) {
510 # Suppress $comment from old entries (before 2008-01-29),
511 # not needed and can contain incorrect links
512 $comment = '';
513 }
514 // Do nothing. The implementation is handled by the hook modifiying the passed-by-ref parameters.
515 } else {
516 wfRunHooks( 'LogLine', array( $row->log_type, $row->log_action, $title, $paramArray,
517 &$comment, &$revert, $row->log_timestamp ) );
518 }
519 if( $revert != '' ) {
520 $revert = '<span class="mw-logevent-actionlink">' . $revert . '</span>';
521 }
522 return $revert;
523 }
524
525 /**
526 * @param $row Row
527 * @return string
528 */
529 private function getShowHideLinks( $row ) {
530 global $wgUser;
531 if( ( $this->flags & self::NO_ACTION_LINK ) // we don't want to see the links
532 || $row->log_type == 'suppress' ) { // no one can hide items from the suppress log
533 return '';
534 }
535 $del = '';
536 // Don't show useless link to people who cannot hide revisions
537 if( $wgUser->isAllowed( 'deletedhistory' ) ) {
538 if( $row->log_deleted || $wgUser->isAllowed( 'deleterevision' ) ) {
539 $canHide = $wgUser->isAllowed( 'deleterevision' );
540 // If event was hidden from sysops
541 if( !self::userCan( $row, LogPage::DELETED_RESTRICTED ) ) {
542 $del = $this->skin->revDeleteLinkDisabled( $canHide );
543 } else {
544 $target = SpecialPage::getTitleFor( 'Log', $row->log_type );
545 $query = array(
546 'target' => $target->getPrefixedDBkey(),
547 'type' => 'logging',
548 'ids' => $row->log_id,
549 );
550 $del = $this->skin->revDeleteLink( $query,
551 self::isDeleted( $row, LogPage::DELETED_RESTRICTED ), $canHide );
552 }
553 }
554 }
555 return $del;
556 }
557
558 /**
559 * @param $row Row
560 * @param $type Mixed: string/array
561 * @param $action Mixed: string/array
562 * @param $right string
563 * @return Boolean
564 */
565 public static function typeAction( $row, $type, $action, $right='' ) {
566 $match = is_array($type) ?
567 in_array( $row->log_type, $type ) : $row->log_type == $type;
568 if( $match ) {
569 $match = is_array( $action ) ?
570 in_array( $row->log_action, $action ) : $row->log_action == $action;
571 if( $match && $right ) {
572 global $wgUser;
573 $match = $wgUser->isAllowed( $right );
574 }
575 }
576 return $match;
577 }
578
579 /**
580 * Determine if the current user is allowed to view a particular
581 * field of this log row, if it's marked as deleted.
582 *
583 * @param $row Row
584 * @param $field Integer
585 * @return Boolean
586 */
587 public static function userCan( $row, $field ) {
588 return self::userCanBitfield( $row->log_deleted, $field );
589 }
590
591 /**
592 * Determine if the current user is allowed to view a particular
593 * field of this log row, if it's marked as deleted.
594 *
595 * @param $bitfield Integer (current field)
596 * @param $field Integer
597 * @return Boolean
598 */
599 public static function userCanBitfield( $bitfield, $field ) {
600 if( $bitfield & $field ) {
601 global $wgUser;
602
603 if ( $bitfield & LogPage::DELETED_RESTRICTED ) {
604 $permission = 'suppressrevision';
605 } else {
606 $permission = 'deletedhistory';
607 }
608 wfDebug( "Checking for $permission due to $field match on $bitfield\n" );
609 return $wgUser->isAllowed( $permission );
610 } else {
611 return true;
612 }
613 }
614
615 /**
616 * @param $row Row
617 * @param $field Integer: one of DELETED_* bitfield constants
618 * @return Boolean
619 */
620 public static function isDeleted( $row, $field ) {
621 return ( $row->log_deleted & $field ) == $field;
622 }
623
624 /**
625 * Show log extract. Either with text and a box (set $msgKey) or without (don't set $msgKey)
626 *
627 * @param $out OutputPage|String-by-reference
628 * @param $types String or Array
629 * @param $page String The page title to show log entries for
630 * @param $user String The user who made the log entries
631 * @param $param Associative Array with the following additional options:
632 * - lim Integer Limit of items to show, default is 50
633 * - conds Array Extra conditions for the query (e.g. "log_action != 'revision'")
634 * - showIfEmpty boolean Set to false if you don't want any output in case the loglist is empty
635 * if set to true (default), "No matching items in log" is displayed if loglist is empty
636 * - msgKey Array If you want a nice box with a message, set this to the key of the message.
637 * First element is the message key, additional optional elements are parameters for the key
638 * that are processed with wgMsgExt and option 'parse'
639 * - offset Set to overwrite offset parameter in $wgRequest
640 * set to '' to unset offset
641 * - wrap String Wrap the message in html (usually something like "<div ...>$1</div>").
642 * - flags Integer display flags (NO_ACTION_LINK,NO_EXTRA_USER_LINKS)
643 * @return Integer Number of total log items (not limited by $lim)
644 */
645 public static function showLogExtract(
646 &$out, $types=array(), $page='', $user='', $param = array()
647 ) {
648 global $wgUser, $wgOut;
649 $defaultParameters = array(
650 'lim' => 25,
651 'conds' => array(),
652 'showIfEmpty' => true,
653 'msgKey' => array(''),
654 'wrap' => "$1",
655 'flags' => 0
656 );
657 # The + operator appends elements of remaining keys from the right
658 # handed array to the left handed, whereas duplicated keys are NOT overwritten.
659 $param += $defaultParameters;
660 # Convert $param array to individual variables
661 $lim = $param['lim'];
662 $conds = $param['conds'];
663 $showIfEmpty = $param['showIfEmpty'];
664 $msgKey = $param['msgKey'];
665 $wrap = $param['wrap'];
666 $flags = $param['flags'];
667 if ( !is_array( $msgKey ) ) {
668 $msgKey = array( $msgKey );
669 }
670 # Insert list of top 50 (or top $lim) items
671 $loglist = new LogEventsList( $wgUser->getSkin(), $wgOut, $flags );
672 $pager = new LogPager( $loglist, $types, $user, $page, '', $conds );
673 if ( isset( $param['offset'] ) ) { # Tell pager to ignore $wgRequest offset
674 $pager->setOffset( $param['offset'] );
675 }
676 if( $lim > 0 ) $pager->mLimit = $lim;
677 $logBody = $pager->getBody();
678 $s = '';
679 if( $logBody ) {
680 if ( $msgKey[0] ) {
681 $s = '<div class="mw-warning-with-logexcerpt">';
682
683 if ( count( $msgKey ) == 1 ) {
684 $s .= wfMsgExt( $msgKey[0], array( 'parse' ) );
685 } else { // Process additional arguments
686 $args = $msgKey;
687 array_shift( $args );
688 $s .= wfMsgExt( $msgKey[0], array( 'parse' ), $args );
689 }
690 }
691 $s .= $loglist->beginLogEventsList() .
692 $logBody .
693 $loglist->endLogEventsList();
694 } else {
695 if ( $showIfEmpty )
696 $s = Html::rawElement( 'div', array( 'class' => 'mw-warning-logempty' ),
697 wfMsgExt( 'logempty', array( 'parseinline' ) ) );
698 }
699 if( $pager->getNumRows() > $pager->mLimit ) { # Show "Full log" link
700 $urlParam = array();
701 if ( $page != '')
702 $urlParam['page'] = $page;
703 if ( $user != '')
704 $urlParam['user'] = $user;
705 if ( !is_array( $types ) ) # Make it an array, if it isn't
706 $types = array( $types );
707 # If there is exactly one log type, we can link to Special:Log?type=foo
708 if ( count( $types ) == 1 )
709 $urlParam['type'] = $types[0];
710 $s .= $wgUser->getSkin()->link(
711 SpecialPage::getTitleFor( 'Log' ),
712 wfMsgHtml( 'log-fulllog' ),
713 array(),
714 $urlParam
715 );
716 }
717 if ( $logBody && $msgKey[0] ) {
718 $s .= '</div>';
719 }
720
721 if ( $wrap!='' ) { // Wrap message in html
722 $s = str_replace( '$1', $s, $wrap );
723 }
724
725 // $out can be either an OutputPage object or a String-by-reference
726 if( $out instanceof OutputPage ){
727 $out->addHTML( $s );
728 } else {
729 $out = $s;
730 }
731 return $pager->getNumRows();
732 }
733
734 /**
735 * SQL clause to skip forbidden log types for this user
736 *
737 * @param $db Database
738 * @param $audience string, public/user
739 * @return Mixed: string or false
740 */
741 public static function getExcludeClause( $db, $audience = 'public' ) {
742 global $wgLogRestrictions, $wgUser;
743 // Reset the array, clears extra "where" clauses when $par is used
744 $hiddenLogs = array();
745 // Don't show private logs to unprivileged users
746 foreach( $wgLogRestrictions as $logType => $right ) {
747 if( $audience == 'public' || !$wgUser->isAllowed($right) ) {
748 $safeType = $db->strencode( $logType );
749 $hiddenLogs[] = $safeType;
750 }
751 }
752 if( count($hiddenLogs) == 1 ) {
753 return 'log_type != ' . $db->addQuotes( $hiddenLogs[0] );
754 } elseif( $hiddenLogs ) {
755 return 'log_type NOT IN (' . $db->makeList($hiddenLogs) . ')';
756 }
757 return false;
758 }
759 }
760
761 /**
762 * @ingroup Pager
763 */
764 class LogPager extends ReverseChronologicalPager {
765 private $types = array(), $user = '', $title = '', $pattern = '';
766 private $typeCGI = '';
767 public $mLogEventsList;
768
769 /**
770 * Constructor
771 *
772 * @param $list LogEventsList
773 * @param $types String or Array: log types to show
774 * @param $user String: the user who made the log entries
775 * @param $title String: the page title the log entries are for
776 * @param $pattern String: do a prefix search rather than an exact title match
777 * @param $conds Array: extra conditions for the query
778 * @param $year Integer: the year to start from
779 * @param $month Integer: the month to start from
780 * @param $tagFilter String: tag
781 */
782 public function __construct( $list, $types = array(), $user = '', $title = '', $pattern = '',
783 $conds = array(), $year = false, $month = false, $tagFilter = '' ) {
784 parent::__construct();
785 $this->mConds = $conds;
786
787 $this->mLogEventsList = $list;
788
789 $this->limitType( $types ); // also excludes hidden types
790 $this->limitUser( $user );
791 $this->limitTitle( $title, $pattern );
792 $this->getDateCond( $year, $month );
793 $this->mTagFilter = $tagFilter;
794 }
795
796 public function getDefaultQuery() {
797 $query = parent::getDefaultQuery();
798 $query['type'] = $this->typeCGI; // arrays won't work here
799 $query['user'] = $this->user;
800 $query['month'] = $this->mMonth;
801 $query['year'] = $this->mYear;
802 return $query;
803 }
804
805 // Call ONLY after calling $this->limitType() already!
806 public function getFilterParams() {
807 global $wgFilterLogTypes, $wgUser, $wgRequest;
808 $filters = array();
809 if( count($this->types) ) {
810 return $filters;
811 }
812 foreach( $wgFilterLogTypes as $type => $default ) {
813 // Avoid silly filtering
814 if( $type !== 'patrol' || $wgUser->useNPPatrol() ) {
815 $hide = $wgRequest->getInt( "hide_{$type}_log", $default );
816 $filters[$type] = $hide;
817 if( $hide )
818 $this->mConds[] = 'log_type != ' . $this->mDb->addQuotes( $type );
819 }
820 }
821 return $filters;
822 }
823
824 /**
825 * Set the log reader to return only entries of the given type.
826 * Type restrictions enforced here
827 *
828 * @param $types String or array: Log types ('upload', 'delete', etc);
829 * empty string means no restriction
830 */
831 private function limitType( $types ) {
832 global $wgLogRestrictions, $wgUser;
833 // If $types is not an array, make it an array
834 $types = ($types === '') ? array() : (array)$types;
835 // Don't even show header for private logs; don't recognize it...
836 foreach ( $types as $type ) {
837 if( isset( $wgLogRestrictions[$type] )
838 && !$wgUser->isAllowed($wgLogRestrictions[$type])
839 ) {
840 $types = array_diff( $types, array( $type ) );
841 }
842 }
843 $this->types = $types;
844 // Don't show private logs to unprivileged users.
845 // Also, only show them upon specific request to avoid suprises.
846 $audience = $types ? 'user' : 'public';
847 $hideLogs = LogEventsList::getExcludeClause( $this->mDb, $audience );
848 if( $hideLogs !== false ) {
849 $this->mConds[] = $hideLogs;
850 }
851 if( count($types) ) {
852 $this->mConds['log_type'] = $types;
853 // Set typeCGI; used in url param for paging
854 if( count($types) == 1 ) $this->typeCGI = $types[0];
855 }
856 }
857
858 /**
859 * Set the log reader to return only entries by the given user.
860 *
861 * @param $name String: (In)valid user name
862 */
863 private function limitUser( $name ) {
864 if( $name == '' ) {
865 return false;
866 }
867 $usertitle = Title::makeTitleSafe( NS_USER, $name );
868 if( is_null($usertitle) ) {
869 return false;
870 }
871 /* Fetch userid at first, if known, provides awesome query plan afterwards */
872 $userid = User::idFromName( $name );
873 if( !$userid ) {
874 /* It should be nicer to abort query at all,
875 but for now it won't pass anywhere behind the optimizer */
876 $this->mConds[] = "NULL";
877 } else {
878 global $wgUser;
879 $this->mConds['log_user'] = $userid;
880 // Paranoia: avoid brute force searches (bug 17342)
881 if( !$wgUser->isAllowed( 'deletedhistory' ) ) {
882 $this->mConds[] = $this->mDb->bitAnd('log_deleted', LogPage::DELETED_USER) . ' = 0';
883 } else if( !$wgUser->isAllowed( 'suppressrevision' ) ) {
884 $this->mConds[] = $this->mDb->bitAnd('log_deleted', LogPage::SUPPRESSED_USER) .
885 ' != ' . LogPage::SUPPRESSED_USER;
886 }
887 $this->user = $usertitle->getText();
888 }
889 }
890
891 /**
892 * Set the log reader to return only entries affecting the given page.
893 * (For the block and rights logs, this is a user page.)
894 *
895 * @param $page String: Title name as text
896 * @param $pattern String
897 */
898 private function limitTitle( $page, $pattern ) {
899 global $wgMiserMode, $wgUser;
900
901 $title = Title::newFromText( $page );
902 if( strlen( $page ) == 0 || !$title instanceof Title ) {
903 return false;
904 }
905
906 $this->title = $title->getPrefixedText();
907 $ns = $title->getNamespace();
908 $db = $this->mDb;
909
910 # Using the (log_namespace, log_title, log_timestamp) index with a
911 # range scan (LIKE) on the first two parts, instead of simple equality,
912 # makes it unusable for sorting. Sorted retrieval using another index
913 # would be possible, but then we might have to scan arbitrarily many
914 # nodes of that index. Therefore, we need to avoid this if $wgMiserMode
915 # is on.
916 #
917 # This is not a problem with simple title matches, because then we can
918 # use the page_time index. That should have no more than a few hundred
919 # log entries for even the busiest pages, so it can be safely scanned
920 # in full to satisfy an impossible condition on user or similar.
921 if( $pattern && !$wgMiserMode ) {
922 $this->mConds['log_namespace'] = $ns;
923 $this->mConds[] = 'log_title ' . $db->buildLike( $title->getDBkey(), $db->anyString() );
924 $this->pattern = $pattern;
925 } else {
926 $this->mConds['log_namespace'] = $ns;
927 $this->mConds['log_title'] = $title->getDBkey();
928 }
929 // Paranoia: avoid brute force searches (bug 17342)
930 if( !$wgUser->isAllowed( 'deletedhistory' ) ) {
931 $this->mConds[] = $db->bitAnd('log_deleted', LogPage::DELETED_ACTION) . ' = 0';
932 } else if( !$wgUser->isAllowed( 'suppressrevision' ) ) {
933 $this->mConds[] = $db->bitAnd('log_deleted', LogPage::SUPPRESSED_ACTION) .
934 ' != ' . LogPage::SUPPRESSED_ACTION;
935 }
936 }
937
938 public function getQueryInfo() {
939 $tables = array( 'logging', 'user' );
940 $this->mConds[] = 'user_id = log_user';
941 $index = array();
942 $options = array();
943 # Add log_search table if there are conditions on it.
944 # This filters the results to only include log rows that have
945 # log_search records with the specified ls_field and ls_value values.
946 if( array_key_exists( 'ls_field', $this->mConds ) ) {
947 $tables[] = 'log_search';
948 $index['log_search'] = 'ls_field_val';
949 $index['logging'] = 'PRIMARY';
950 if ( !$this->hasEqualsClause( 'ls_field' )
951 || !$this->hasEqualsClause( 'ls_value' ) )
952 {
953 # Since (ls_field,ls_value,ls_logid) is unique, if the condition is
954 # to match a specific (ls_field,ls_value) tuple, then there will be
955 # no duplicate log rows. Otherwise, we need to remove the duplicates.
956 $options[] = 'DISTINCT';
957 }
958 # Avoid usage of the wrong index by limiting
959 # the choices of available indexes. This mainly
960 # avoids site-breaking filesorts.
961 } else if( $this->title || $this->pattern || $this->user ) {
962 $index['logging'] = array( 'page_time', 'user_time' );
963 if( count($this->types) == 1 ) {
964 $index['logging'][] = 'log_user_type_time';
965 }
966 } else if( count($this->types) == 1 ) {
967 $index['logging'] = 'type_time';
968 } else {
969 $index['logging'] = 'times';
970 }
971 $options['USE INDEX'] = $index;
972 # Don't show duplicate rows when using log_search
973 $info = array(
974 'tables' => $tables,
975 'fields' => array( 'log_type', 'log_action', 'log_user', 'log_namespace',
976 'log_title', 'log_params', 'log_comment', 'log_id', 'log_deleted',
977 'log_timestamp', 'user_name', 'user_editcount' ),
978 'conds' => $this->mConds,
979 'options' => $options,
980 'join_conds' => array(
981 'user' => array( 'INNER JOIN', 'user_id=log_user' ),
982 'log_search' => array( 'INNER JOIN', 'ls_log_id=log_id' )
983 )
984 );
985 # Add ChangeTags filter query
986 ChangeTags::modifyDisplayQuery( $info['tables'], $info['fields'], $info['conds'],
987 $info['join_conds'], $info['options'], $this->mTagFilter );
988 return $info;
989 }
990
991 // Checks if $this->mConds has $field matched to a *single* value
992 protected function hasEqualsClause( $field ) {
993 return (
994 array_key_exists( $field, $this->mConds ) &&
995 ( !is_array( $this->mConds[$field] ) || count( $this->mConds[$field] ) == 1 )
996 );
997 }
998
999 function getIndexField() {
1000 return 'log_timestamp';
1001 }
1002
1003 public function getStartBody() {
1004 wfProfileIn( __METHOD__ );
1005 # Do a link batch query
1006 if( $this->getNumRows() > 0 ) {
1007 $lb = new LinkBatch;
1008 foreach ( $this->mResult as $row ) {
1009 $lb->add( $row->log_namespace, $row->log_title );
1010 $lb->addObj( Title::makeTitleSafe( NS_USER, $row->user_name ) );
1011 $lb->addObj( Title::makeTitleSafe( NS_USER_TALK, $row->user_name ) );
1012 }
1013 $lb->execute();
1014 $this->mResult->seek( 0 );
1015 }
1016 wfProfileOut( __METHOD__ );
1017 return '';
1018 }
1019
1020 public function formatRow( $row ) {
1021 return $this->mLogEventsList->logLine( $row );
1022 }
1023
1024 public function getType() {
1025 return $this->types;
1026 }
1027
1028 public function getUser() {
1029 return $this->user;
1030 }
1031
1032 public function getPage() {
1033 return $this->title;
1034 }
1035
1036 public function getPattern() {
1037 return $this->pattern;
1038 }
1039
1040 public function getYear() {
1041 return $this->mYear;
1042 }
1043
1044 public function getMonth() {
1045 return $this->mMonth;
1046 }
1047
1048 public function getTagFilter() {
1049 return $this->mTagFilter;
1050 }
1051
1052 public function doQuery() {
1053 // Workaround MySQL optimizer bug
1054 $this->mDb->setBigSelects();
1055 parent::doQuery();
1056 $this->mDb->setBigSelects( 'default' );
1057 }
1058 }
1059