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