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