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