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