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