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