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