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