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