* (bug 24563) Entries on Special:WhatLinksHere now have a link to their history
[lhc/web/wiklou.git] / includes / LogEventsList.php
1 <?php
2 # Copyright (C) 2004 Brion Vibber <brion@pobox.com>, 2008 Aaron Schulz
3 # http://www.mediawiki.org/
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 # http://www.gnu.org/copyleft/gpl.html
19
20 class LogEventsList {
21 const NO_ACTION_LINK = 1;
22 const NO_EXTRA_USER_LINKS = 2;
23
24 private $skin;
25 private $out;
26 public $flags;
27
28 public function __construct( $skin, $out, $flags = 0 ) {
29 $this->skin = $skin;
30 $this->out = $out;
31 $this->flags = $flags;
32 $this->preCacheMessages();
33 }
34
35 /**
36 * As we use the same small set of messages in various methods and that
37 * they are called often, we call them once and save them in $this->message
38 */
39 private function preCacheMessages() {
40 // Precache various messages
41 if( !isset( $this->message ) ) {
42 $messages = array( 'revertmerge', 'protect_change', 'unblocklink', 'change-blocklink',
43 'revertmove', 'undeletelink', 'undeleteviewlink', 'revdel-restore', 'hist', 'diff',
44 'pipe-separator', 'revdel-restore-deleted', 'revdel-restore-visible' );
45 foreach( $messages as $msg ) {
46 $this->message[$msg] = wfMsgExt( $msg, array( 'escapenoentities' ) );
47 }
48 }
49 }
50
51 /**
52 * Set page title and show header for this log type
53 * @param $type Array
54 */
55 public function showHeader( $type ) {
56 // If only one log type is used, then show a special message...
57 $headerType = (count($type) == 1) ? $type[0] : '';
58 if( LogPage::isLogType( $headerType ) ) {
59 $this->out->setPageTitle( LogPage::logName( $headerType ) );
60 $this->out->addHTML( LogPage::logHeader( $headerType ) );
61 } else {
62 $this->out->addHTML( wfMsgExt('alllogstext',array('parseinline')) );
63 }
64 }
65
66 /**
67 * Show options for the log list
68 *
69 * @param $types string or Array
70 * @param $user String
71 * @param $page String
72 * @param $pattern String
73 * @param $year Integer: year
74 * @param $month Integer: month
75 * @param $filter: array
76 * @param $tagFilter: array?
77 */
78 public function showOptions( $types=array(), $user='', $page='', $pattern='', $year='',
79 $month = '', $filter = null, $tagFilter='' )
80 {
81 global $wgScript, $wgMiserMode;
82
83 $action = $wgScript;
84 $title = SpecialPage::getTitleFor( 'Log' );
85 $special = $title->getPrefixedDBkey();
86
87 // For B/C, we take strings, but make sure they are converted...
88 $types = ($types === '') ? array() : (array)$types;
89
90 $tagSelector = ChangeTags::buildTagFilterSelector( $tagFilter );
91
92 $html = '';
93 $html .= Xml::hidden( 'title', $special );
94
95 // Basic selectors
96 $html .= $this->getTypeMenu( $types ) . "\n";
97 $html .= $this->getUserInput( $user ) . "\n";
98 $html .= $this->getTitleInput( $page ) . "\n";
99 $html .= $this->getExtraInputs( $types ) . "\n";
100
101 // Title pattern, if allowed
102 if (!$wgMiserMode) {
103 $html .= $this->getTitlePattern( $pattern ) . "\n";
104 }
105
106 // date menu
107 $html .= Xml::tags( 'p', null, Xml::dateMenu( $year, $month ) );
108
109 // Tag filter
110 if ($tagSelector) {
111 $html .= Xml::tags( 'p', null, implode( '&#160;', $tagSelector ) );
112 }
113
114 // Filter links
115 if ($filter) {
116 $html .= Xml::tags( 'p', null, $this->getFilterLinks( $filter ) );
117 }
118
119 // Submit button
120 $html .= Xml::submitButton( wfMsg( 'allpagessubmit' ) );
121
122 // Fieldset
123 $html = Xml::fieldset( wfMsg( 'log' ), $html );
124
125 // Form wrapping
126 $html = Xml::tags( 'form', array( 'action' => $action, 'method' => 'get' ), $html );
127
128 $this->out->addHTML( $html );
129 }
130
131 /**
132 * @param $filter Array
133 * @return String: Formatted HTML
134 */
135 private function getFilterLinks( $filter ) {
136 global $wgTitle, $wgLang;
137 // show/hide links
138 $messages = array( wfMsgHtml( 'show' ), wfMsgHtml( 'hide' ) );
139 // Option value -> message mapping
140 $links = array();
141 $hiddens = ''; // keep track for "go" button
142 foreach( $filter as $type => $val ) {
143 // Should the below assignment be outside the foreach?
144 // Then it would have to be copied. Not certain what is more expensive.
145 $query = $this->getDefaultQuery();
146 $queryKey = "hide_{$type}_log";
147
148 $hideVal = 1 - intval($val);
149 $query[$queryKey] = $hideVal;
150
151 $link = $this->skin->link(
152 $wgTitle,
153 $messages[$hideVal],
154 array(),
155 $query,
156 array( 'known', 'noclasses' )
157 );
158
159 $links[$type] = wfMsgHtml( "log-show-hide-{$type}", $link );
160 $hiddens .= Xml::hidden( "hide_{$type}_log", $val ) . "\n";
161 }
162 // Build links
163 return '<small>'.$wgLang->pipeList( $links ) . '</small>' . $hiddens;
164 }
165
166 private function getDefaultQuery() {
167 if ( !isset( $this->mDefaultQuery ) ) {
168 $this->mDefaultQuery = $_GET;
169 unset( $this->mDefaultQuery['title'] );
170 unset( $this->mDefaultQuery['dir'] );
171 unset( $this->mDefaultQuery['offset'] );
172 unset( $this->mDefaultQuery['limit'] );
173 unset( $this->mDefaultQuery['order'] );
174 unset( $this->mDefaultQuery['month'] );
175 unset( $this->mDefaultQuery['year'] );
176 }
177 return $this->mDefaultQuery;
178 }
179
180 /**
181 * @param $queryTypes Array
182 * @return String: Formatted HTML
183 */
184 private function getTypeMenu( $queryTypes ) {
185 global $wgLogRestrictions, $wgUser;
186
187 $html = "<select name='type'>\n";
188
189 $validTypes = LogPage::validTypes();
190 $typesByName = array(); // Temporary array
191
192 // First pass to load the log names
193 foreach( $validTypes as $type ) {
194 $text = LogPage::logName( $type );
195 $typesByName[$type] = $text;
196 }
197
198 // Second pass to sort by name
199 asort($typesByName);
200
201 // Note the query type
202 $queryType = count($queryTypes) == 1 ? $queryTypes[0] : '';
203
204 // Always put "All public logs" on top
205 if ( isset( $typesByName[''] ) ) {
206 $all = $typesByName[''];
207 unset( $typesByName[''] );
208 $typesByName = array( '' => $all ) + $typesByName;
209 }
210
211 // Third pass generates sorted XHTML content
212 foreach( $typesByName as $type => $text ) {
213 $selected = ($type == $queryType);
214 // Restricted types
215 if ( isset($wgLogRestrictions[$type]) ) {
216 if ( $wgUser->isAllowed( $wgLogRestrictions[$type] ) ) {
217 $html .= Xml::option( $text, $type, $selected ) . "\n";
218 }
219 } else {
220 $html .= Xml::option( $text, $type, $selected ) . "\n";
221 }
222 }
223
224 $html .= '</select>';
225 return $html;
226 }
227
228 /**
229 * @param $user String
230 * @return String: Formatted HTML
231 */
232 private function getUserInput( $user ) {
233 return '<span style="white-space: nowrap">' .
234 Xml::inputLabel( wfMsg( 'specialloguserlabel' ), 'user', 'mw-log-user', 15, $user ) .
235 '</span>';
236 }
237
238 /**
239 * @param $title String
240 * @return String: Formatted HTML
241 */
242 private function getTitleInput( $title ) {
243 return '<span style="white-space: nowrap">' .
244 Xml::inputLabel( wfMsg( 'speciallogtitlelabel' ), 'page', 'mw-log-page', 20, $title ) .
245 '</span>';
246 }
247
248 /**
249 * @return boolean Checkbox
250 */
251 private function getTitlePattern( $pattern ) {
252 return '<span style="white-space: nowrap">' .
253 Xml::checkLabel( wfMsg( 'log-title-wildcard' ), 'pattern', 'pattern', $pattern ) .
254 '</span>';
255 }
256
257 private function getExtraInputs( $types ) {
258 global $wgRequest;
259 $offender = $wgRequest->getVal('offender');
260 $user = User::newFromName( $offender, false );
261 if( !$user || ($user->getId() == 0 && !IP::isIPAddress($offender) ) ) {
262 $offender = ''; // Blank field if invalid
263 }
264 if( count($types) == 1 && $types[0] == 'suppress' ) {
265 return Xml::inputLabel( wfMsg('revdelete-offender'), 'offender',
266 'mw-log-offender', 20, $offender );
267 }
268 return '';
269 }
270
271 public function beginLogEventsList() {
272 return "<ul>\n";
273 }
274
275 public function endLogEventsList() {
276 return "</ul>\n";
277 }
278
279 /**
280 * @param $row Row: a single row from the result set
281 * @return String: Formatted HTML list item
282 */
283 public function logLine( $row ) {
284 $classes = array( 'mw-logline-' . $row->log_type );
285 $title = Title::makeTitle( $row->log_namespace, $row->log_title );
286 // Log time
287 $time = $this->logTimestamp( $row );
288 // User links
289 $userLink = $this->logUserLinks( $row );
290 // Extract extra parameters
291 $paramArray = LogPage::extractParams( $row->log_params );
292 // Event description
293 $action = $this->logAction( $row, $title, $paramArray );
294 // Log comment
295 $comment = $this->logComment( $row );
296 // Add review/revert links and such...
297 $revert = $this->logActionLinks( $row, $title, $paramArray, $comment );
298
299 // Some user can hide log items and have review links
300 $del = $this->getShowHideLinks( $row );
301 if( $del != '' ) $del .= ' ';
302
303 // Any tags...
304 list( $tagDisplay, $newClasses ) = ChangeTags::formatSummaryRow( $row->ts_tags, 'logevent' );
305 $classes = array_merge( $classes, $newClasses );
306
307 return Xml::tags( 'li', array( "class" => implode( ' ', $classes ) ),
308 $del . "$time $userLink $action $comment $revert $tagDisplay" ) . "\n";
309 }
310
311 private function logTimestamp( $row ) {
312 global $wgLang;
313 $time = $wgLang->timeanddate( wfTimestamp( TS_MW, $row->log_timestamp ), true );
314 return htmlspecialchars( $time );
315 }
316
317 private function logUserLinks( $row ) {
318 $userLinks = '';
319 if( self::isDeleted( $row, LogPage::DELETED_USER ) ) {
320 $userLinks = '<span class="history-deleted">' .
321 wfMsgHtml( 'rev-deleted-user' ) . '</span>';
322 } else {
323 $userLinks = $this->skin->userLink( $row->log_user, $row->user_name );
324 // Talk|Contribs links...
325 if( !( $this->flags & self::NO_EXTRA_USER_LINKS ) ) {
326 $userLinks .= $this->skin->userToolLinks(
327 $row->log_user, $row->user_name, true, 0, $row->user_editcount );
328 }
329 }
330 return $userLinks;
331 }
332
333 private function logAction( $row, $title, $paramArray ) {
334 $action = '';
335 if( self::isDeleted( $row, LogPage::DELETED_ACTION ) ) {
336 $action = '<span class="history-deleted">' .
337 wfMsgHtml( 'rev-deleted-event' ) . '</span>';
338 } else {
339 $action = LogPage::actionText(
340 $row->log_type, $row->log_action, $title, $this->skin, $paramArray, true );
341 }
342 return $action;
343 }
344
345 private function logComment( $row ) {
346 global $wgContLang;
347 $comment = '';
348 if( self::isDeleted( $row, LogPage::DELETED_COMMENT ) ) {
349 $comment = '<span class="history-deleted">' .
350 wfMsgHtml( 'rev-deleted-comment' ) . '</span>';
351 } else {
352 $comment = $wgContLang->getDirMark() .
353 $this->skin->commentBlock( $row->log_comment );
354 }
355 return $comment;
356 }
357
358 // @TODO: split up!
359 private function logActionLinks( $row, $title, $paramArray, &$comment ) {
360 global $wgUser;
361 if( ( $this->flags & self::NO_ACTION_LINK ) // we don't want to see the action
362 || self::isDeleted( $row, LogPage::DELETED_ACTION ) ) // action is hidden
363 {
364 return '';
365 }
366 $revert = '';
367 if( self::typeAction( $row, 'move', 'move', 'move' ) && !empty( $paramArray[0] ) ) {
368 $destTitle = Title::newFromText( $paramArray[0] );
369 if( $destTitle ) {
370 $revert = '(' . $this->skin->link(
371 SpecialPage::getTitleFor( 'Movepage' ),
372 $this->message['revertmove'],
373 array(),
374 array(
375 'wpOldTitle' => $destTitle->getPrefixedDBkey(),
376 'wpNewTitle' => $title->getPrefixedDBkey(),
377 'wpReason' => wfMsgForContent( 'revertmove' ),
378 'wpMovetalk' => 0
379 ),
380 array( 'known', 'noclasses' )
381 ) . ')';
382 }
383 // Show undelete link
384 } else if( self::typeAction( $row, array( 'delete', 'suppress' ), 'delete', 'deletedhistory' ) ) {
385 if( !$wgUser->isAllowed( 'undelete' ) ) {
386 $viewdeleted = $this->message['undeleteviewlink'];
387 } else {
388 $viewdeleted = $this->message['undeletelink'];
389 }
390 $revert = '(' . $this->skin->link(
391 SpecialPage::getTitleFor( 'Undelete' ),
392 $viewdeleted,
393 array(),
394 array( 'target' => $title->getPrefixedDBkey() ),
395 array( 'known', 'noclasses' )
396 ) . ')';
397 // Show unblock/change block link
398 } else if( self::typeAction( $row, array( 'block', 'suppress' ), array( 'block', 'reblock' ), 'block' ) ) {
399 $revert = '(' .
400 $this->skin->link(
401 SpecialPage::getTitleFor( 'Ipblocklist' ),
402 $this->message['unblocklink'],
403 array(),
404 array(
405 'action' => 'unblock',
406 'ip' => $row->log_title
407 ),
408 'known'
409 ) .
410 $this->message['pipe-separator'] .
411 $this->skin->link(
412 SpecialPage::getTitleFor( 'Blockip', $row->log_title ),
413 $this->message['change-blocklink'],
414 array(),
415 array(),
416 'known'
417 ) .
418 ')';
419 // Show change protection link
420 } else if( self::typeAction( $row, 'protect', array( 'modify', 'protect', 'unprotect' ) ) ) {
421 $revert .= ' (' .
422 $this->skin->link( $title,
423 $this->message['hist'],
424 array(),
425 array(
426 'action' => 'history',
427 'offset' => $row->log_timestamp
428 )
429 );
430 if( $wgUser->isAllowed( 'protect' ) ) {
431 $revert .= $this->message['pipe-separator'] .
432 $this->skin->link( $title,
433 $this->message['protect_change'],
434 array(),
435 array( 'action' => 'protect' ),
436 'known' );
437 }
438 $revert .= ')';
439 // Show unmerge link
440 } else if( self::typeAction( $row, 'merge', 'merge', 'mergehistory' ) ) {
441 $revert = '(' . $this->skin->link(
442 SpecialPage::getTitleFor( 'MergeHistory' ),
443 $this->message['revertmerge'],
444 array(),
445 array(
446 'target' => $paramArray[0],
447 'dest' => $title->getPrefixedDBkey(),
448 'mergepoint' => $paramArray[1]
449 ),
450 array( 'known', 'noclasses' )
451 ) . ')';
452 // If an edit was hidden from a page give a review link to the history
453 } else if( self::typeAction( $row, array( 'delete', 'suppress' ), 'revision', 'deletedhistory' ) ) {
454 $revert = RevisionDeleter::getLogLinks( $title, $paramArray,
455 $this->skin, $this->message );
456 // Hidden log items, give review link
457 } else if( self::typeAction( $row, array( 'delete', 'suppress' ), 'event', 'deletedhistory' ) ) {
458 if( count($paramArray) >= 1 ) {
459 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
460 // $paramArray[1] is a CSV of the IDs
461 $Ids = explode( ',', $paramArray[0] );
462 $query = $paramArray[0];
463 // Link to each hidden object ID, $paramArray[1] is the url param
464 $revert = '(' . $this->skin->link(
465 $revdel,
466 $this->message['revdel-restore'],
467 array(),
468 array(
469 'target' => $title->getPrefixedText(),
470 'type' => 'logging',
471 'ids' => $query
472 ),
473 array( 'known', 'noclasses' )
474 ) . ')';
475 }
476 // Self-created users
477 } else if( self::typeAction( $row, 'newusers', 'create2' ) ) {
478 if( isset( $paramArray[0] ) ) {
479 $revert = $this->skin->userToolLinks( $paramArray[0], $title->getDBkey(), true );
480 } else {
481 # Fall back to a blue contributions link
482 $revert = $this->skin->userToolLinks( 1, $title->getDBkey() );
483 }
484 $ts = wfTimestamp( TS_UNIX, $row->log_timestamp );
485 if( $ts < '20080129000000' ) {
486 # Suppress $comment from old entries (before 2008-01-29),
487 # not needed and can contain incorrect links
488 $comment = '';
489 }
490 // Do nothing. The implementation is handled by the hook modifiying the passed-by-ref parameters.
491 } else {
492 wfRunHooks( 'LogLine', array( $row->log_type, $row->log_action, $title, $paramArray,
493 &$comment, &$revert, $row->log_timestamp ) );
494 }
495 if( $revert != '' ) {
496 $revert = '<span class="mw-logevent-actionlink">' . $revert . '</span>';
497 }
498 return $revert;
499 }
500
501 /**
502 * @param $row Row
503 * @return string
504 */
505 private function getShowHideLinks( $row ) {
506 global $wgUser;
507 if( ( $this->flags & self::NO_ACTION_LINK ) // we don't want to see the links
508 || $row->log_type == 'suppress' ) // no one can hide items from the suppress log
509 {
510 return '';
511 }
512 $del = '';
513 // Don't show useless link to people who cannot hide revisions
514 if( $wgUser->isAllowed( 'deletedhistory' ) ) {
515 if( $row->log_deleted || $wgUser->isAllowed( 'deleterevision' ) ) {
516 $canHide = $wgUser->isAllowed( 'deleterevision' );
517 // If event was hidden from sysops
518 if( !self::userCan( $row, LogPage::DELETED_RESTRICTED ) ) {
519 $del = $this->skin->revDeleteLinkDisabled( $canHide );
520 } else {
521 $target = SpecialPage::getTitleFor( 'Log', $row->log_type );
522 $query = array(
523 'target' => $target->getPrefixedDBkey(),
524 'type' => 'logging',
525 'ids' => $row->log_id,
526 );
527 $del = $this->skin->revDeleteLink( $query,
528 self::isDeleted( $row, LogPage::DELETED_RESTRICTED ), $canHide );
529 }
530 }
531 }
532 return $del;
533 }
534
535 /**
536 * @param $row Row
537 * @param $type Mixed: string/array
538 * @param $action Mixed: string/array
539 * @param $right string
540 * @return Boolean
541 */
542 public static function typeAction( $row, $type, $action, $right='' ) {
543 $match = is_array($type) ?
544 in_array( $row->log_type, $type ) : $row->log_type == $type;
545 if( $match ) {
546 $match = is_array( $action ) ?
547 in_array( $row->log_action, $action ) : $row->log_action == $action;
548 if( $match && $right ) {
549 global $wgUser;
550 $match = $wgUser->isAllowed( $right );
551 }
552 }
553 return $match;
554 }
555
556 /**
557 * Determine if the current user is allowed to view a particular
558 * field of this log row, if it's marked as deleted.
559 *
560 * @param $row Row
561 * @param $field Integer
562 * @return Boolean
563 */
564 public static function userCan( $row, $field ) {
565 return self::userCanBitfield( $row->log_deleted, $field );
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 $bitfield Integer (current field)
573 * @param $field Integer
574 * @return Boolean
575 */
576 public static function userCanBitfield( $bitfield, $field ) {
577 if( $bitfield & $field ) {
578 global $wgUser;
579 $permission = '';
580 if ( $bitfield & LogPage::DELETED_RESTRICTED ) {
581 $permission = 'suppressrevision';
582 } else {
583 $permission = 'deletedhistory';
584 }
585 wfDebug( "Checking for $permission due to $field match on $bitfield\n" );
586 return $wgUser->isAllowed( $permission );
587 } else {
588 return true;
589 }
590 }
591
592 /**
593 * @param $row Row
594 * @param $field Integer: one of DELETED_* bitfield constants
595 * @return Boolean
596 */
597 public static function isDeleted( $row, $field ) {
598 return ( $row->log_deleted & $field ) == $field;
599 }
600
601 /**
602 * Show log extract. Either with text and a box (set $msgKey) or without (don't set $msgKey)
603 *
604 * @param $out OutputPage or String-by-reference
605 * @param $types String or Array
606 * @param $page String The page title to show log entries for
607 * @param $user String The user who made the log entries
608 * @param $param Associative Array with the following additional options:
609 * - lim Integer Limit of items to show, default is 50
610 * - conds Array Extra conditions for the query (e.g. "log_action != 'revision'")
611 * - showIfEmpty boolean Set to false if you don't want any output in case the loglist is empty
612 * if set to true (default), "No matching items in log" is displayed if loglist is empty
613 * - msgKey Array If you want a nice box with a message, set this to the key of the message.
614 * First element is the message key, additional optional elements are parameters for the key
615 * that are processed with wgMsgExt and option 'parse'
616 * - offset Set to overwrite offset parameter in $wgRequest
617 * set to '' to unset offset
618 * - wrap String Wrap the message in html (usually something like "<div ...>$1</div>").
619 * - flags Integer display flags (NO_ACTION_LINK,NO_EXTRA_USER_LINKS)
620 * @return Integer Number of total log items (not limited by $lim)
621 */
622 public static function showLogExtract(
623 &$out, $types=array(), $page='', $user='', $param = array()
624 ) {
625 global $wgUser, $wgOut;
626 $defaultParameters = array(
627 'lim' => 25,
628 'conds' => array(),
629 'showIfEmpty' => true,
630 'msgKey' => array(''),
631 'wrap' => "$1",
632 'flags' => 0
633 );
634 # The + operator appends elements of remaining keys from the right
635 # handed array to the left handed, whereas duplicated keys are NOT overwritten.
636 $param += $defaultParameters;
637 # Convert $param array to individual variables
638 $lim = $param['lim'];
639 $conds = $param['conds'];
640 $showIfEmpty = $param['showIfEmpty'];
641 $msgKey = $param['msgKey'];
642 $wrap = $param['wrap'];
643 $flags = $param['flags'];
644 if ( !is_array( $msgKey ) ) {
645 $msgKey = array( $msgKey );
646 }
647 # Insert list of top 50 (or top $lim) items
648 $loglist = new LogEventsList( $wgUser->getSkin(), $wgOut, $flags );
649 $pager = new LogPager( $loglist, $types, $user, $page, '', $conds );
650 if ( isset( $param['offset'] ) ) { # Tell pager to ignore $wgRequest offset
651 $pager->setOffset( $param['offset'] );
652 }
653 if( $lim > 0 ) $pager->mLimit = $lim;
654 $logBody = $pager->getBody();
655 $s = '';
656 if( $logBody ) {
657 if ( $msgKey[0] ) {
658 $s = '<div class="mw-warning-with-logexcerpt">';
659
660 if ( count( $msgKey ) == 1 ) {
661 $s .= wfMsgExt( $msgKey[0], array( 'parse' ) );
662 } else { // Process additional arguments
663 $args = $msgKey;
664 array_shift( $args );
665 $s .= wfMsgExt( $msgKey[0], array( 'parse' ), $args );
666 }
667 }
668 $s .= $loglist->beginLogEventsList() .
669 $logBody .
670 $loglist->endLogEventsList();
671 } else {
672 if ( $showIfEmpty )
673 $s = Html::rawElement( 'div', array( 'class' => 'mw-warning-logempty' ),
674 wfMsgExt( 'logempty', array( 'parseinline' ) ) );
675 }
676 if( $pager->getNumRows() > $pager->mLimit ) { # Show "Full log" link
677 $urlParam = array();
678 if ( $page != '')
679 $urlParam['page'] = $page;
680 if ( $user != '')
681 $urlParam['user'] = $user;
682 if ( !is_array( $types ) ) # Make it an array, if it isn't
683 $types = array( $types );
684 # If there is exactly one log type, we can link to Special:Log?type=foo
685 if ( count( $types ) == 1 )
686 $urlParam['type'] = $types[0];
687 $s .= $wgUser->getSkin()->link(
688 SpecialPage::getTitleFor( 'Log' ),
689 wfMsgHtml( 'log-fulllog' ),
690 array(),
691 $urlParam
692 );
693 }
694 if ( $logBody && $msgKey[0] ) {
695 $s .= '</div>';
696 }
697
698 if ( $wrap!='' ) { // Wrap message in html
699 $s = str_replace( '$1', $s, $wrap );
700 }
701
702 // $out can be either an OutputPage object or a String-by-reference
703 if( $out instanceof OutputPage ){
704 $out->addHTML( $s );
705 } else {
706 $out = $s;
707 }
708 return $pager->getNumRows();
709 }
710
711 /**
712 * SQL clause to skip forbidden log types for this user
713 *
714 * @param $db Database
715 * @param $audience string, public/user
716 * @return Mixed: string or false
717 */
718 public static function getExcludeClause( $db, $audience = 'public' ) {
719 global $wgLogRestrictions, $wgUser;
720 // Reset the array, clears extra "where" clauses when $par is used
721 $hiddenLogs = array();
722 // Don't show private logs to unprivileged users
723 foreach( $wgLogRestrictions as $logType => $right ) {
724 if( $audience == 'public' || !$wgUser->isAllowed($right) ) {
725 $safeType = $db->strencode( $logType );
726 $hiddenLogs[] = $safeType;
727 }
728 }
729 if( count($hiddenLogs) == 1 ) {
730 return 'log_type != ' . $db->addQuotes( $hiddenLogs[0] );
731 } elseif( $hiddenLogs ) {
732 return 'log_type NOT IN (' . $db->makeList($hiddenLogs) . ')';
733 }
734 return false;
735 }
736 }
737
738 /**
739 * @ingroup Pager
740 */
741 class LogPager extends ReverseChronologicalPager {
742 private $types = array(), $user = '', $title = '', $pattern = '';
743 private $typeCGI = '';
744 public $mLogEventsList;
745
746 /**
747 * Constructor
748 *
749 * @param $list LogEventsList
750 * @param $types String or Array: log types to show
751 * @param $user String: the user who made the log entries
752 * @param $title String: the page title the log entries are for
753 * @param $pattern String: do a prefix search rather than an exact title match
754 * @param $conds Array: extra conditions for the query
755 * @param $year Integer: the year to start from
756 * @param $month Integer: the month to start from
757 * @param $tagFilter String: tag
758 */
759 public function __construct( $list, $types = array(), $user = '', $title = '', $pattern = '',
760 $conds = array(), $year = false, $month = false, $tagFilter = '' )
761 {
762 parent::__construct();
763 $this->mConds = $conds;
764
765 $this->mLogEventsList = $list;
766
767 $this->limitType( $types ); // also excludes hidden types
768 $this->limitUser( $user );
769 $this->limitTitle( $title, $pattern );
770 $this->getDateCond( $year, $month );
771 $this->mTagFilter = $tagFilter;
772 }
773
774 public function getDefaultQuery() {
775 $query = parent::getDefaultQuery();
776 $query['type'] = $this->typeCGI; // arrays won't work here
777 $query['user'] = $this->user;
778 $query['month'] = $this->mMonth;
779 $query['year'] = $this->mYear;
780 return $query;
781 }
782
783 // Call ONLY after calling $this->limitType() already!
784 public function getFilterParams() {
785 global $wgFilterLogTypes, $wgUser, $wgRequest;
786 $filters = array();
787 if( count($this->types) ) {
788 return $filters;
789 }
790 foreach( $wgFilterLogTypes as $type => $default ) {
791 // Avoid silly filtering
792 if( $type !== 'patrol' || $wgUser->useNPPatrol() ) {
793 $hide = $wgRequest->getInt( "hide_{$type}_log", $default );
794 $filters[$type] = $hide;
795 if( $hide )
796 $this->mConds[] = 'log_type != ' . $this->mDb->addQuotes( $type );
797 }
798 }
799 return $filters;
800 }
801
802 /**
803 * Set the log reader to return only entries of the given type.
804 * Type restrictions enforced here
805 *
806 * @param $types String or array: Log types ('upload', 'delete', etc);
807 * empty string means no restriction
808 */
809 private function limitType( $types ) {
810 global $wgLogRestrictions, $wgUser;
811 // If $types is not an array, make it an array
812 $types = ($types === '') ? array() : (array)$types;
813 // Don't even show header for private logs; don't recognize it...
814 foreach ( $types as $type ) {
815 if( isset( $wgLogRestrictions[$type] )
816 && !$wgUser->isAllowed($wgLogRestrictions[$type])
817 ) {
818 $types = array_diff( $types, array( $type ) );
819 }
820 }
821 $this->types = $types;
822 // Don't show private logs to unprivileged users.
823 // Also, only show them upon specific request to avoid suprises.
824 $audience = $types ? 'user' : 'public';
825 $hideLogs = LogEventsList::getExcludeClause( $this->mDb, $audience );
826 if( $hideLogs !== false ) {
827 $this->mConds[] = $hideLogs;
828 }
829 if( count($types) ) {
830 $this->mConds['log_type'] = $types;
831 // Set typeCGI; used in url param for paging
832 if( count($types) == 1 ) $this->typeCGI = $types[0];
833 }
834 }
835
836 /**
837 * Set the log reader to return only entries by the given user.
838 *
839 * @param $name String: (In)valid user name
840 */
841 private function limitUser( $name ) {
842 if( $name == '' ) {
843 return false;
844 }
845 $usertitle = Title::makeTitleSafe( NS_USER, $name );
846 if( is_null($usertitle) ) {
847 return false;
848 }
849 /* Fetch userid at first, if known, provides awesome query plan afterwards */
850 $userid = User::idFromName( $name );
851 if( !$userid ) {
852 /* It should be nicer to abort query at all,
853 but for now it won't pass anywhere behind the optimizer */
854 $this->mConds[] = "NULL";
855 } else {
856 global $wgUser;
857 $this->mConds['log_user'] = $userid;
858 // Paranoia: avoid brute force searches (bug 17342)
859 if( !$wgUser->isAllowed( 'deletedhistory' ) ) {
860 $this->mConds[] = $this->mDb->bitAnd('log_deleted', LogPage::DELETED_USER) . ' = 0';
861 } else if( !$wgUser->isAllowed( 'suppressrevision' ) ) {
862 $this->mConds[] = $this->mDb->bitAnd('log_deleted', LogPage::SUPPRESSED_USER) .
863 ' != ' . LogPage::SUPPRESSED_USER;
864 }
865 $this->user = $usertitle->getText();
866 }
867 }
868
869 /**
870 * Set the log reader to return only entries affecting the given page.
871 * (For the block and rights logs, this is a user page.)
872 *
873 * @param $page String: Title name as text
874 * @param $pattern String
875 */
876 private function limitTitle( $page, $pattern ) {
877 global $wgMiserMode, $wgUser;
878
879 $title = Title::newFromText( $page );
880 if( strlen( $page ) == 0 || !$title instanceof Title )
881 return false;
882
883 $this->title = $title->getPrefixedText();
884 $ns = $title->getNamespace();
885 $db = $this->mDb;
886
887 # Using the (log_namespace, log_title, log_timestamp) index with a
888 # range scan (LIKE) on the first two parts, instead of simple equality,
889 # makes it unusable for sorting. Sorted retrieval using another index
890 # would be possible, but then we might have to scan arbitrarily many
891 # nodes of that index. Therefore, we need to avoid this if $wgMiserMode
892 # is on.
893 #
894 # This is not a problem with simple title matches, because then we can
895 # use the page_time index. That should have no more than a few hundred
896 # log entries for even the busiest pages, so it can be safely scanned
897 # in full to satisfy an impossible condition on user or similar.
898 if( $pattern && !$wgMiserMode ) {
899 $this->mConds['log_namespace'] = $ns;
900 $this->mConds[] = 'log_title ' . $db->buildLike( $title->getDBkey(), $db->anyString() );
901 $this->pattern = $pattern;
902 } else {
903 $this->mConds['log_namespace'] = $ns;
904 $this->mConds['log_title'] = $title->getDBkey();
905 }
906 // Paranoia: avoid brute force searches (bug 17342)
907 if( !$wgUser->isAllowed( 'deletedhistory' ) ) {
908 $this->mConds[] = $db->bitAnd('log_deleted', LogPage::DELETED_ACTION) . ' = 0';
909 } else if( !$wgUser->isAllowed( 'suppressrevision' ) ) {
910 $this->mConds[] = $db->bitAnd('log_deleted', LogPage::SUPPRESSED_ACTION) .
911 ' != ' . LogPage::SUPPRESSED_ACTION;
912 }
913 }
914
915 public function getQueryInfo() {
916 $tables = array( 'logging', 'user' );
917 $this->mConds[] = 'user_id = log_user';
918 $index = array();
919 $options = array();
920 # Add log_search table if there are conditions on it
921 if( array_key_exists('ls_field',$this->mConds) ) {
922 $tables[] = 'log_search';
923 $index['log_search'] = 'ls_field_val';
924 $index['logging'] = 'PRIMARY';
925 $options[] = 'DISTINCT';
926 # Avoid usage of the wrong index by limiting
927 # the choices of available indexes. This mainly
928 # avoids site-breaking filesorts.
929 } else if( $this->title || $this->pattern || $this->user ) {
930 $index['logging'] = array( 'page_time', 'user_time' );
931 if( count($this->types) == 1 ) {
932 $index['logging'][] = 'log_user_type_time';
933 }
934 } else if( count($this->types) == 1 ) {
935 $index['logging'] = 'type_time';
936 } else {
937 $index['logging'] = 'times';
938 }
939 $options['USE INDEX'] = $index;
940 # Don't show duplicate rows when using log_search
941 $info = array(
942 'tables' => $tables,
943 'fields' => array( 'log_type', 'log_action', 'log_user', 'log_namespace',
944 'log_title', 'log_params', 'log_comment', 'log_id', 'log_deleted',
945 'log_timestamp', 'user_name', 'user_editcount' ),
946 'conds' => $this->mConds,
947 'options' => $options,
948 'join_conds' => array(
949 'user' => array( 'INNER JOIN', 'user_id=log_user' ),
950 'log_search' => array( 'INNER JOIN', 'ls_log_id=log_id' )
951 )
952 );
953 # Add ChangeTags filter query
954 ChangeTags::modifyDisplayQuery( $info['tables'], $info['fields'], $info['conds'],
955 $info['join_conds'], $info['options'], $this->mTagFilter );
956 return $info;
957 }
958
959 function getIndexField() {
960 return 'log_timestamp';
961 }
962
963 public function getStartBody() {
964 wfProfileIn( __METHOD__ );
965 # Do a link batch query
966 if( $this->getNumRows() > 0 ) {
967 $lb = new LinkBatch;
968 while( $row = $this->mResult->fetchObject() ) {
969 $lb->add( $row->log_namespace, $row->log_title );
970 $lb->addObj( Title::makeTitleSafe( NS_USER, $row->user_name ) );
971 $lb->addObj( Title::makeTitleSafe( NS_USER_TALK, $row->user_name ) );
972 }
973 $lb->execute();
974 $this->mResult->seek( 0 );
975 }
976 wfProfileOut( __METHOD__ );
977 return '';
978 }
979
980 public function formatRow( $row ) {
981 return $this->mLogEventsList->logLine( $row );
982 }
983
984 public function getType() {
985 return $this->types;
986 }
987
988 public function getUser() {
989 return $this->user;
990 }
991
992 public function getPage() {
993 return $this->title;
994 }
995
996 public function getPattern() {
997 return $this->pattern;
998 }
999
1000 public function getYear() {
1001 return $this->mYear;
1002 }
1003
1004 public function getMonth() {
1005 return $this->mMonth;
1006 }
1007
1008 public function getTagFilter() {
1009 return $this->mTagFilter;
1010 }
1011
1012 public function doQuery() {
1013 // Workaround MySQL optimizer bug
1014 $this->mDb->setBigSelects();
1015 parent::doQuery();
1016 $this->mDb->setBigSelects( 'default' );
1017 }
1018 }
1019
1020 /**
1021 * @deprecated
1022 * @ingroup SpecialPage
1023 */
1024 class LogReader {
1025 var $pager;
1026
1027 /**
1028 * @param $request WebRequest: for internal use use a FauxRequest object to pass arbitrary parameters.
1029 */
1030 function __construct( $request ) {
1031 global $wgUser, $wgOut;
1032 wfDeprecated(__METHOD__);
1033 # Get parameters
1034 $type = $request->getVal( 'type' );
1035 $user = $request->getText( 'user' );
1036 $title = $request->getText( 'page' );
1037 $pattern = $request->getBool( 'pattern' );
1038 $year = $request->getIntOrNull( 'year' );
1039 $month = $request->getIntOrNull( 'month' );
1040 $tagFilter = $request->getVal( 'tagfilter' );
1041 # Don't let the user get stuck with a certain date
1042 $skip = $request->getText( 'offset' ) || $request->getText( 'dir' ) == 'prev';
1043 if( $skip ) {
1044 $year = '';
1045 $month = '';
1046 }
1047 # Use new list class to output results
1048 $loglist = new LogEventsList( $wgUser->getSkin(), $wgOut, 0 );
1049 $this->pager = new LogPager( $loglist, $type, $user, $title, $pattern, $year, $month, $tagFilter );
1050 }
1051
1052 /**
1053 * Is there at least one row?
1054 * @return bool
1055 */
1056 public function hasRows() {
1057 return isset($this->pager) ? ($this->pager->getNumRows() > 0) : false;
1058 }
1059 }
1060
1061 /**
1062 * @deprecated
1063 * @ingroup SpecialPage
1064 */
1065 class LogViewer {
1066 const NO_ACTION_LINK = 1;
1067
1068 /**
1069 * LogReader object
1070 */
1071 var $reader;
1072
1073 /**
1074 * @param &$reader LogReader: where to get our data from
1075 * @param $flags Integer: Bitwise combination of flags:
1076 * LogEventsList::NO_ACTION_LINK Don't show restore/unblock/block links
1077 */
1078 function __construct( &$reader, $flags = 0 ) {
1079 wfDeprecated(__METHOD__);
1080 $this->reader =& $reader;
1081 $this->reader->pager->mLogEventsList->flags = $flags;
1082 # Aliases for shorter code...
1083 $this->pager =& $this->reader->pager;
1084 $this->list =& $this->reader->pager->mLogEventsList;
1085 }
1086
1087 /**
1088 * Take over the whole output page in $wgOut with the log display.
1089 */
1090 public function show() {
1091 global $wgOut;
1092 # Set title and add header
1093 $this->list->showHeader( $pager->getType() );
1094 # Show form options
1095 $this->list->showOptions( $this->pager->getType(), $this->pager->getUser(), $this->pager->getPage(),
1096 $this->pager->getPattern(), $this->pager->getYear(), $this->pager->getMonth() );
1097 # Insert list
1098 $logBody = $this->pager->getBody();
1099 if( $logBody ) {
1100 $wgOut->addHTML(
1101 $this->pager->getNavigationBar() .
1102 $this->list->beginLogEventsList() .
1103 $logBody .
1104 $this->list->endLogEventsList() .
1105 $this->pager->getNavigationBar()
1106 );
1107 } else {
1108 $wgOut->addWikiMsg( 'logempty' );
1109 }
1110 }
1111
1112 /**
1113 * Output just the list of entries given by the linked LogReader,
1114 * with extraneous UI elements. Use for displaying log fragments in
1115 * another page (eg at Special:Undelete)
1116 *
1117 * @param $out OutputPage: where to send output
1118 */
1119 public function showList( &$out ) {
1120 $logBody = $this->pager->getBody();
1121 if( $logBody ) {
1122 $out->addHTML(
1123 $this->list->beginLogEventsList() .
1124 $logBody .
1125 $this->list->endLogEventsList()
1126 );
1127 } else {
1128 $out->addWikiMsg( 'logempty' );
1129 }
1130 }
1131 }