]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - includes/LogEventsList.php
MediaWiki 1.17.4
[autoinstalls/mediawiki.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         private $skin;
31         private $out;
32         public $flags;
33
34         public function __construct( $skin, $out, $flags = 0 ) {
35                 $this->skin = $skin;
36                 $this->out = $out;
37                 $this->flags = $flags;
38                 $this->preCacheMessages();
39         }
40
41         /**
42          * As we use the same small set of messages in various methods and that
43          * they are called often, we call them once and save them in $this->message
44          */
45         private function preCacheMessages() {
46                 // Precache various messages
47                 if( !isset( $this->message ) ) {
48                         $messages = array( 'revertmerge', 'protect_change', 'unblocklink', 'change-blocklink',
49                                 'revertmove', 'undeletelink', 'undeleteviewlink', 'revdel-restore', 'hist', 'diff',
50                                 'pipe-separator', 'revdel-restore-deleted', 'revdel-restore-visible' );
51                         foreach( $messages as $msg ) {
52                                 $this->message[$msg] = wfMsgExt( $msg, array( 'escapenoentities' ) );
53                         }
54                 }
55         }
56
57         /**
58          * Set page title and show header for this log type
59          * @param $type Array
60          */
61         public function showHeader( $type ) {
62                 // If only one log type is used, then show a special message...
63                 $headerType = (count($type) == 1) ? $type[0] : '';
64                 if( LogPage::isLogType( $headerType ) ) {
65                         $this->out->setPageTitle( LogPage::logName( $headerType ) );
66                         $this->out->addHTML( LogPage::logHeader( $headerType ) );
67                 } else {
68                         $this->out->addHTML( wfMsgExt('alllogstext',array('parseinline')) );
69                 }
70         }
71
72         /**
73          * Show options for the log list
74          *
75          * @param $types string or Array
76          * @param $user String
77          * @param $page String
78          * @param $pattern String
79          * @param $year Integer: year
80          * @param $month Integer: month
81          * @param $filter: array
82          * @param $tagFilter: array?
83          */
84         public function showOptions( $types=array(), $user='', $page='', $pattern='', $year='', 
85                 $month = '', $filter = null, $tagFilter='' )
86         {
87                 global $wgScript, $wgMiserMode;
88
89                 $action = $wgScript;
90                 $title = SpecialPage::getTitleFor( 'Log' );
91                 $special = $title->getPrefixedDBkey();
92
93                 // For B/C, we take strings, but make sure they are converted...
94                 $types = ($types === '') ? array() : (array)$types;
95
96                 $tagSelector = ChangeTags::buildTagFilterSelector( $tagFilter );
97
98                 $html = Html::hidden( 'title', $special );
99
100                 // Basic selectors
101                 $html .= $this->getTypeMenu( $types ) . "\n";
102                 $html .= $this->getUserInput( $user ) . "\n";
103                 $html .= $this->getTitleInput( $page ) . "\n";
104                 $html .= $this->getExtraInputs( $types ) . "\n";
105
106                 // Title pattern, if allowed
107                 if (!$wgMiserMode) {
108                         $html .= $this->getTitlePattern( $pattern ) . "\n";
109                 }
110
111                 // date menu
112                 $html .= Xml::tags( 'p', null, Xml::dateMenu( $year, $month ) );
113
114                 // Tag filter
115                 if ($tagSelector) {
116                         $html .= Xml::tags( 'p', null, implode( '&#160;', $tagSelector ) );
117                 }
118
119                 // Filter links
120                 if ($filter) {
121                         $html .= Xml::tags( 'p', null, $this->getFilterLinks( $filter ) );
122                 }
123
124                 // Submit button
125                 $html .= Xml::submitButton( wfMsg( 'allpagessubmit' ) );
126
127                 // Fieldset
128                 $html = Xml::fieldset( wfMsg( 'log' ), $html );
129
130                 // Form wrapping
131                 $html = Xml::tags( 'form', array( 'action' => $action, 'method' => 'get' ), $html );
132
133                 $this->out->addHTML( $html );
134         }
135
136         /**
137          * @param $filter Array
138          * @return String: Formatted HTML
139          */
140         private function getFilterLinks( $filter ) {
141                 global $wgTitle, $wgLang;
142                 // show/hide links
143                 $messages = array( wfMsgHtml( 'show' ), wfMsgHtml( 'hide' ) );
144                 // Option value -> message mapping
145                 $links = array();
146                 $hiddens = ''; // keep track for "go" button
147                 foreach( $filter as $type => $val ) {
148                         // Should the below assignment be outside the foreach?
149                         // Then it would have to be copied. Not certain what is more expensive.
150                         $query = $this->getDefaultQuery();
151                         $queryKey = "hide_{$type}_log";
152
153                         $hideVal = 1 - intval($val);
154                         $query[$queryKey] = $hideVal;
155
156                         $link = $this->skin->link(
157                                 $wgTitle,
158                                 $messages[$hideVal],
159                                 array(),
160                                 $query,
161                                 array( 'known', 'noclasses' )
162                         );
163
164                         $links[$type] = wfMsgHtml( "log-show-hide-{$type}", $link );
165                         $hiddens .= Html::hidden( "hide_{$type}_log", $val ) . "\n";
166                 }
167                 // Build links
168                 return '<small>'.$wgLang->pipeList( $links ) . '</small>' . $hiddens;
169         }
170
171         private function getDefaultQuery() {
172                 if ( !isset( $this->mDefaultQuery ) ) {
173                         $this->mDefaultQuery = $_GET;
174                         unset( $this->mDefaultQuery['title'] );
175                         unset( $this->mDefaultQuery['dir'] );
176                         unset( $this->mDefaultQuery['offset'] );
177                         unset( $this->mDefaultQuery['limit'] );
178                         unset( $this->mDefaultQuery['order'] );
179                         unset( $this->mDefaultQuery['month'] );
180                         unset( $this->mDefaultQuery['year'] );
181                 }
182                 return $this->mDefaultQuery;
183         }
184
185         /**
186          * @param $queryTypes Array
187          * @return String: Formatted HTML
188          */
189         private function getTypeMenu( $queryTypes ) {
190                 global $wgLogRestrictions, $wgUser;
191
192                 $html = "<select name='type'>\n";
193
194                 $validTypes = LogPage::validTypes();
195                 $typesByName = array(); // Temporary array
196
197                 // First pass to load the log names
198                 foreach( $validTypes as $type ) {
199                         $text = LogPage::logName( $type );
200                         $typesByName[$type] = $text;
201                 }
202
203                 // Second pass to sort by name
204                 asort($typesByName);
205
206                 // Note the query type
207                 $queryType = count($queryTypes) == 1 ? $queryTypes[0] : '';
208
209                 // Always put "All public logs" on top
210                 if ( isset( $typesByName[''] ) ) {
211                         $all = $typesByName[''];
212                         unset( $typesByName[''] );
213                         $typesByName = array( '' => $all ) + $typesByName;
214                 }
215
216                 // Third pass generates sorted XHTML content
217                 foreach( $typesByName as $type => $text ) {
218                         $selected = ($type == $queryType);
219                         // Restricted types
220                         if ( isset($wgLogRestrictions[$type]) ) {
221                                 if ( $wgUser->isAllowed( $wgLogRestrictions[$type] ) ) {
222                                         $html .= Xml::option( $text, $type, $selected ) . "\n";
223                                 }
224                         } else {
225                                 $html .= Xml::option( $text, $type, $selected ) . "\n";
226                         }
227                 }
228
229                 $html .= '</select>';
230                 return $html;
231         }
232
233         /**
234          * @param $user String
235          * @return String: Formatted HTML
236          */
237         private function getUserInput( $user ) {
238                 return '<span style="white-space: nowrap">' .
239                         Xml::inputLabel( wfMsg( 'specialloguserlabel' ), 'user', 'mw-log-user', 15, $user ) .
240                         '</span>';
241         }
242
243         /**
244          * @param $title String
245          * @return String: Formatted HTML
246          */
247         private function getTitleInput( $title ) {
248                 return '<span style="white-space: nowrap">' .
249                         Xml::inputLabel( wfMsg( 'speciallogtitlelabel' ), 'page', 'mw-log-page', 20, $title ) .
250                         '</span>';
251         }
252
253         /**
254          * @return boolean Checkbox
255          */
256         private function getTitlePattern( $pattern ) {
257                 return '<span style="white-space: nowrap">' .
258                         Xml::checkLabel( wfMsg( 'log-title-wildcard' ), 'pattern', 'pattern', $pattern ) .
259                         '</span>';
260         }
261
262         private function getExtraInputs( $types ) {
263                 global $wgRequest;
264                 $offender = $wgRequest->getVal('offender');
265                 $user = User::newFromName( $offender, false );
266                 if( !$user || ($user->getId() == 0 && !IP::isIPAddress($offender) ) ) {
267                         $offender = ''; // Blank field if invalid
268                 }
269                 if( count($types) == 1 && $types[0] == 'suppress' ) {
270                         return Xml::inputLabel( wfMsg('revdelete-offender'), 'offender',
271                                 'mw-log-offender', 20, $offender );
272                 }
273                 return '';
274         }
275
276         public function beginLogEventsList() {
277                 return "<ul>\n";
278         }
279
280         public function endLogEventsList() {
281                 return "</ul>\n";
282         }
283
284         /**
285          * @param $row Row: a single row from the result set
286          * @return String: Formatted HTML list item
287          */
288         public function logLine( $row ) {
289                 $classes = array( 'mw-logline-' . $row->log_type );
290                 $title = Title::makeTitle( $row->log_namespace, $row->log_title );
291                 // Log time
292                 $time = $this->logTimestamp( $row );
293                 // User links
294                 $userLink = $this->logUserLinks( $row );
295                 // Extract extra parameters
296                 $paramArray = LogPage::extractParams( $row->log_params );
297                 // Event description
298                 $action = $this->logAction( $row, $title, $paramArray );
299                 // Log comment
300                 $comment = $this->logComment( $row );
301                 // Add review/revert links and such...
302                 $revert = $this->logActionLinks( $row, $title, $paramArray, $comment );
303
304                 // Some user can hide log items and have review links
305                 $del = $this->getShowHideLinks( $row );
306                 if( $del != '' ) $del .= ' ';
307
308                 // Any tags...
309                 list( $tagDisplay, $newClasses ) = ChangeTags::formatSummaryRow( $row->ts_tags, 'logevent' );
310                 $classes = array_merge( $classes, $newClasses );
311
312                 return Xml::tags( 'li', array( "class" => implode( ' ', $classes ) ),
313                         $del . "$time $userLink $action $comment $revert $tagDisplay" ) . "\n";
314         }
315         
316         private function logTimestamp( $row ) {
317                 global $wgLang;
318                 $time = $wgLang->timeanddate( wfTimestamp( TS_MW, $row->log_timestamp ), true );
319                 return htmlspecialchars( $time );
320         }
321
322         private function logUserLinks( $row ) {
323                 if( self::isDeleted( $row, LogPage::DELETED_USER ) ) {
324                         $userLinks = '<span class="history-deleted">' .
325                                 wfMsgHtml( 'rev-deleted-user' ) . '</span>';
326                 } else {
327                         $userLinks = $this->skin->userLink( $row->log_user, $row->user_name );
328                         // Talk|Contribs links...
329                         if( !( $this->flags & self::NO_EXTRA_USER_LINKS ) ) {
330                                 $userLinks .= $this->skin->userToolLinks(
331                                         $row->log_user, $row->user_name, true, 0, $row->user_editcount );
332                         }
333                 }
334                 return $userLinks;
335         }
336
337         private function logAction( $row, $title, $paramArray ) {
338                 if( self::isDeleted( $row, LogPage::DELETED_ACTION ) ) {
339                         $action = '<span class="history-deleted">' .
340                                 wfMsgHtml( 'rev-deleted-event' ) . '</span>';
341                 } else {
342                         $action = LogPage::actionText(
343                                 $row->log_type, $row->log_action, $title, $this->skin, $paramArray, true );
344                 }
345                 return $action;
346         }
347         
348         private function logComment( $row ) {
349                 global $wgContLang;
350                 if( self::isDeleted( $row, LogPage::DELETED_COMMENT ) ) {
351                         $comment = '<span class="history-deleted">' .
352                                 wfMsgHtml( 'rev-deleted-comment' ) . '</span>';
353                 } else {
354                         $comment = $wgContLang->getDirMark() .
355                                 $this->skin->commentBlock( $row->log_comment );
356                 }
357                 return $comment;
358         }
359
360         // @TODO: split up!
361         private function logActionLinks( $row, $title, $paramArray, &$comment ) {
362                 global $wgUser;
363                 if( ( $this->flags & self::NO_ACTION_LINK ) // we don't want to see the action
364                         || self::isDeleted( $row, LogPage::DELETED_ACTION ) ) // action is hidden
365                 {
366                         return '';
367                 }
368                 $revert = '';
369                 if( self::typeAction( $row, 'move', 'move', 'move' ) && !empty( $paramArray[0] ) ) {
370                         $destTitle = Title::newFromText( $paramArray[0] );
371                         if( $destTitle ) {
372                                 $revert = '(' . $this->skin->link(
373                                         SpecialPage::getTitleFor( 'Movepage' ),
374                                         $this->message['revertmove'],
375                                         array(),
376                                         array(
377                                                 'wpOldTitle' => $destTitle->getPrefixedDBkey(),
378                                                 'wpNewTitle' => $title->getPrefixedDBkey(),
379                                                 'wpReason'   => wfMsgForContent( 'revertmove' ),
380                                                 'wpMovetalk' => 0
381                                         ),
382                                         array( 'known', 'noclasses' )
383                                 ) . ')';
384                         }
385                 // Show undelete link
386                 } else if( self::typeAction( $row, array( 'delete', 'suppress' ), 'delete', 'deletedhistory' ) ) {
387                         if( !$wgUser->isAllowed( 'undelete' ) ) {
388                                 $viewdeleted = $this->message['undeleteviewlink'];
389                         } else {
390                                 $viewdeleted = $this->message['undeletelink'];
391                         }
392                         $revert = '(' . $this->skin->link(
393                                 SpecialPage::getTitleFor( 'Undelete' ),
394                                 $viewdeleted,
395                                 array(),
396                                 array( 'target' => $title->getPrefixedDBkey() ),
397                                 array( 'known', 'noclasses' )
398                          ) . ')';
399                 // Show unblock/change block link
400                 } else if( self::typeAction( $row, array( 'block', 'suppress' ), array( 'block', 'reblock' ), 'block' ) ) {
401                         $revert = '(' .
402                                 $this->skin->link(
403                                         SpecialPage::getTitleFor( 'Ipblocklist' ),
404                                         $this->message['unblocklink'],
405                                         array(),
406                                         array(
407                                                 'action' => 'unblock',
408                                                 'ip' => $row->log_title
409                                         ),
410                                         'known'
411                                 ) .
412                                 $this->message['pipe-separator'] .
413                                 $this->skin->link(
414                                         SpecialPage::getTitleFor( 'Blockip', $row->log_title ),
415                                         $this->message['change-blocklink'],
416                                         array(),
417                                         array(),
418                                         'known'
419                                 ) .
420                                 ')';
421                 // Show change protection link
422                 } else if( self::typeAction( $row, 'protect', array( 'modify', 'protect', 'unprotect' ) ) ) {
423                         $revert .= ' (' .
424                                 $this->skin->link( $title,
425                                         $this->message['hist'],
426                                         array(),
427                                         array(
428                                                 'action' => 'history',
429                                                 'offset' => $row->log_timestamp
430                                         )
431                                 );
432                         if( $wgUser->isAllowed( 'protect' ) ) {
433                                 $revert .= $this->message['pipe-separator'] .
434                                         $this->skin->link( $title,
435                                                 $this->message['protect_change'],
436                                                 array(),
437                                                 array( 'action' => 'protect' ),
438                                                 'known' );
439                         }
440                         $revert .= ')';
441                 // Show unmerge link
442                 } else if( self::typeAction( $row, 'merge', 'merge', 'mergehistory' ) ) {
443                         $revert = '(' . $this->skin->link(
444                                 SpecialPage::getTitleFor( 'MergeHistory' ),
445                                 $this->message['revertmerge'],
446                                 array(),
447                                 array(
448                                         'target' => $paramArray[0],
449                                         'dest' => $title->getPrefixedDBkey(),
450                                         'mergepoint' => $paramArray[1]
451                                 ),
452                                 array( 'known', 'noclasses' )
453                         ) . ')';
454                 // If an edit was hidden from a page give a review link to the history
455                 } else if( self::typeAction( $row, array( 'delete', 'suppress' ), 'revision', 'deletedhistory' ) ) {
456                         $revert = RevisionDeleter::getLogLinks( $title, $paramArray,
457                                                                 $this->skin, $this->message );
458                 // Hidden log items, give review link
459                 } else if( self::typeAction( $row, array( 'delete', 'suppress' ), 'event', 'deletedhistory' ) ) {
460                         if( count($paramArray) >= 1 ) {
461                                 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
462                                 // $paramArray[1] is a CSV of the IDs
463                                 $query = $paramArray[0];
464                                 // Link to each hidden object ID, $paramArray[1] is the url param
465                                 $revert = '(' . $this->skin->link(
466                                         $revdel,
467                                         $this->message['revdel-restore'], 
468                                         array(),
469                                         array(
470                                                 'target' => $title->getPrefixedText(),
471                                                 'type' => 'logging',
472                                                 'ids' => $query
473                                         ),
474                                         array( 'known', 'noclasses' )
475                                 ) . ')';
476                         }
477                 // Self-created users
478                 } else if( self::typeAction( $row, 'newusers', 'create2' ) ) {
479                         if( isset( $paramArray[0] ) ) {
480                                 $revert = $this->skin->userToolLinks( $paramArray[0], $title->getDBkey(), true );
481                         } else {
482                                 # Fall back to a blue contributions link
483                                 $revert = $this->skin->userToolLinks( 1, $title->getDBkey() );
484                         }
485                         if( wfTimestamp( TS_MW, $row->log_timestamp ) < '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
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                         foreach ( $this->mResult as $row ) {
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( $this->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 }