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