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