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