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