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