Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
67.20% covered (warning)
67.20%
125 / 186
25.00% covered (danger)
25.00%
2 / 8
CRAP
0.00% covered (danger)
0.00%
0 / 1
SpecialLog
67.57% covered (warning)
67.57%
125 / 185
25.00% covered (danger)
25.00%
2 / 8
106.08
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 execute
72.31% covered (warning)
72.31%
47 / 65
0.00% covered (danger)
0.00%
0 / 1
26.67
 getLogTypesOnUser
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
2
 getSubpagesForPrefixSearch
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 parseParams
88.89% covered (warning)
88.89%
8 / 9
0.00% covered (danger)
0.00%
0 / 1
6.05
 show
92.16% covered (success)
92.16%
47 / 51
0.00% covered (danger)
0.00%
0 / 1
8.03
 getActionButtons
13.51% covered (danger)
13.51%
5 / 37
0.00% covered (danger)
0.00%
0 / 1
21.17
 getGroupName
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2/**
3 * Implements Special:Log
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 * @file
21 * @ingroup SpecialPage
22 */
23
24namespace MediaWiki\Specials;
25
26use ChangeTags;
27use LogEventsList;
28use LogPage;
29use MediaWiki\Cache\LinkBatchFactory;
30use MediaWiki\HookContainer\HookRunner;
31use MediaWiki\Html\FormOptions;
32use MediaWiki\Html\Html;
33use MediaWiki\Html\ListToggle;
34use MediaWiki\MainConfigNames;
35use MediaWiki\MediaWikiServices;
36use MediaWiki\Pager\LogPager;
37use MediaWiki\SpecialPage\SpecialPage;
38use MediaWiki\Title\Title;
39use MediaWiki\User\ActorNormalization;
40use MediaWiki\User\UserIdentityLookup;
41use MediaWiki\User\UserNameUtils;
42use MediaWiki\Utils\MWTimestamp;
43use PermissionsError;
44use Wikimedia\IPUtils;
45use Wikimedia\Rdbms\IConnectionProvider;
46use Wikimedia\Timestamp\TimestampException;
47
48/**
49 * A special page that lists log entries
50 *
51 * @ingroup SpecialPage
52 */
53class SpecialLog extends SpecialPage {
54
55    private LinkBatchFactory $linkBatchFactory;
56
57    private IConnectionProvider $dbProvider;
58
59    private ActorNormalization $actorNormalization;
60
61    private UserIdentityLookup $userIdentityLookup;
62
63    private UserNameUtils $userNameUtils;
64
65    /**
66     * @param LinkBatchFactory $linkBatchFactory
67     * @param IConnectionProvider $dbProvider
68     * @param ActorNormalization $actorNormalization
69     * @param UserIdentityLookup $userIdentityLookup
70     * @param UserNameUtils $userNameUtils
71     */
72    public function __construct(
73        LinkBatchFactory $linkBatchFactory,
74        IConnectionProvider $dbProvider,
75        ActorNormalization $actorNormalization,
76        UserIdentityLookup $userIdentityLookup,
77        UserNameUtils $userNameUtils
78    ) {
79        parent::__construct( 'Log' );
80        $this->linkBatchFactory = $linkBatchFactory;
81        $this->dbProvider = $dbProvider;
82        $this->actorNormalization = $actorNormalization;
83        $this->userIdentityLookup = $userIdentityLookup;
84        $this->userNameUtils = $userNameUtils;
85    }
86
87    public function execute( $par ) {
88        $this->setHeaders();
89        $this->outputHeader();
90        $out = $this->getOutput();
91        $out->addModules( 'mediawiki.userSuggest' );
92        $out->addModuleStyles( 'mediawiki.interface.helpers.styles' );
93        $this->addHelpLink( 'Help:Log' );
94
95        $opts = new FormOptions;
96        $opts->add( 'type', '' );
97        $opts->add( 'user', '' );
98        $opts->add( 'page', '' );
99        $opts->add( 'pattern', false );
100        $opts->add( 'year', null, FormOptions::INTNULL );
101        $opts->add( 'month', null, FormOptions::INTNULL );
102        $opts->add( 'day', null, FormOptions::INTNULL );
103        $opts->add( 'tagfilter', '' );
104        $opts->add( 'tagInvert', false );
105        $opts->add( 'offset', '' );
106        $opts->add( 'dir', '' );
107        $opts->add( 'offender', '' );
108        $opts->add( 'subtype', '' );
109        $opts->add( 'logid', '' );
110
111        // Set values
112        if ( $par !== null ) {
113            $this->parseParams( (string)$par );
114        }
115        $opts->fetchValuesFromRequest( $this->getRequest() );
116
117        // Set date values
118        $dateString = $this->getRequest()->getVal( 'wpdate' );
119        if ( $dateString ) {
120            try {
121                $dateStamp = MWTimestamp::getInstance( $dateString . ' 00:00:00' );
122            } catch ( TimestampException $e ) {
123                // If users provide an invalid date, silently ignore it
124                // instead of letting an exception bubble up (T201411)
125                $dateStamp = false;
126            }
127            if ( $dateStamp ) {
128                $opts->setValue( 'year', (int)$dateStamp->format( 'Y' ) );
129                $opts->setValue( 'month', (int)$dateStamp->format( 'm' ) );
130                $opts->setValue( 'day', (int)$dateStamp->format( 'd' ) );
131            }
132        }
133
134        // If the user doesn't have the right permission to view the specific
135        // log type, throw a PermissionsError
136        $logRestrictions = $this->getConfig()->get( MainConfigNames::LogRestrictions );
137        $type = $opts->getValue( 'type' );
138        if ( isset( $logRestrictions[$type] )
139            && !$this->getAuthority()->isAllowed( $logRestrictions[$type] )
140        ) {
141            throw new PermissionsError( $logRestrictions[$type] );
142        }
143
144        # TODO: Move this into LogPager like other query conditions.
145        # Handle type-specific inputs
146        $qc = [];
147        $offenderName = $opts->getValue( 'offender' );
148        if ( $opts->getValue( 'type' ) == 'suppress' && $offenderName !== '' ) {
149            $dbr = $this->dbProvider->getReplicaDatabase();
150            $offenderId = $this->actorNormalization->findActorIdByName( $offenderName, $dbr );
151            if ( $offenderId ) {
152                $qc = [ 'ls_field' => 'target_author_actor', 'ls_value' => strval( $offenderId ) ];
153            } else {
154                // Unknown offender, thus results have to be empty
155                $qc = [ '1=0' ];
156            }
157        } else {
158            // Allow extensions to add relations to their search types
159            $this->getHookRunner()->onSpecialLogAddLogSearchRelations(
160                $opts->getValue( 'type' ), $this->getRequest(), $qc );
161        }
162
163        # TODO: Move this into LogEventList and use it as filter-callback in the field descriptor.
164        # Some log types are only for a 'User:' title but we might have been given
165        # only the username instead of the full title 'User:username'. This part try
166        # to lookup for a user by that name and eventually fix user input. See T3697.
167        if ( in_array( $opts->getValue( 'type' ), self::getLogTypesOnUser( $this->getHookRunner() ) ) ) {
168            # ok we have a type of log which expect a user title.
169            $page = $opts->getValue( 'page' );
170            $target = Title::newFromText( $page );
171            if ( $target && $target->getNamespace() === NS_MAIN ) {
172                if ( IPUtils::isValidRange( $target->getText() ) ) {
173                    $page = IPUtils::sanitizeRange( $target->getText() );
174                }
175                # User forgot to add 'User:', we are adding it for him
176                $target = Title::makeTitleSafe( NS_USER, $page );
177            } elseif ( $target && $target->getNamespace() === NS_USER
178                && IPUtils::isValidRange( $target->getText() )
179            ) {
180                $ipOrRange = IPUtils::sanitizeRange( $target->getText() );
181                if ( $ipOrRange !== $target->getText() ) {
182                    $target = Title::makeTitleSafe( NS_USER, $ipOrRange );
183                }
184            }
185            if ( $target !== null ) {
186                $page = $target->getPrefixedText();
187                $opts->setValue( 'page', $page );
188                $this->getRequest()->setVal( 'page', $page );
189            }
190        }
191
192        $this->show( $opts, $qc );
193    }
194
195    /**
196     * List log type for which the target is a user
197     * Thus if the given target is in NS_MAIN we can alter it to be an NS_USER
198     * Title user instead.
199     *
200     * @since 1.25
201     * @since 1.36 Added $runner parameter
202     *
203     * @param HookRunner|null $runner
204     * @return array
205     */
206    public static function getLogTypesOnUser( HookRunner $runner = null ) {
207        static $types = null;
208        if ( $types !== null ) {
209            return $types;
210        }
211        $types = [
212            'block',
213            'newusers',
214            'rights',
215            'renameuser',
216        ];
217
218        ( $runner ?? new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )
219            ->onGetLogTypesOnUser( $types );
220        return $types;
221    }
222
223    /**
224     * Return an array of subpages that this special page will accept.
225     *
226     * @return string[] subpages
227     */
228    public function getSubpagesForPrefixSearch() {
229        $subpages = LogPage::validTypes();
230        $subpages[] = 'all';
231        sort( $subpages );
232        return $subpages;
233    }
234
235    /**
236     * Set options based on the subpage title parts:
237     * - One part that is a valid log type: Special:Log/logtype
238     * - Two parts: Special:Log/logtype/username
239     * - Otherwise, assume the whole subpage is a username.
240     *
241     * @param string $par
242     */
243    private function parseParams( string $par ) {
244        # Get parameters
245        $parms = explode( '/', $par, 2 );
246        $symsForAll = [ '*', 'all' ];
247        if ( $parms[0] !== '' &&
248            ( in_array( $parms[0], LogPage::validTypes() ) || in_array( $parms[0], $symsForAll ) )
249        ) {
250            $this->getRequest()->setVal( 'type', $parms[0] );
251            if ( count( $parms ) === 2 ) {
252                $this->getRequest()->setVal( 'user', $parms[1] );
253            }
254        } elseif ( $par !== '' ) {
255            $this->getRequest()->setVal( 'user', $par );
256        }
257    }
258
259    private function show( FormOptions $opts, array $extraConds ) {
260        # Create a LogPager item to get the results and a LogEventsList item to format them...
261        $loglist = new LogEventsList(
262            $this->getContext(),
263            $this->getLinkRenderer(),
264            LogEventsList::USE_CHECKBOXES
265        );
266        $pager = new LogPager(
267            $loglist,
268            $opts->getValue( 'type' ),
269            $opts->getValue( 'user' ),
270            $opts->getValue( 'page' ),
271            $opts->getValue( 'pattern' ),
272            $extraConds,
273            $opts->getValue( 'year' ),
274            $opts->getValue( 'month' ),
275            $opts->getValue( 'day' ),
276            $opts->getValue( 'tagfilter' ),
277            $opts->getValue( 'subtype' ),
278            $opts->getValue( 'logid' ),
279            $this->linkBatchFactory,
280            $this->actorNormalization,
281            $opts->getValue( 'tagInvert' )
282        );
283
284        # Set relevant user
285        $performer = $pager->getPerformer();
286        if ( $performer ) {
287            $performerUser = $this->userIdentityLookup->getUserIdentityByName( $performer );
288            // Only set valid local user as the relevant user (T344886)
289            // Uses the same condition as the SpecialContributions class did
290            if ( $performerUser && !IPUtils::isValidRange( $performer ) &&
291                ( $this->userNameUtils->isIP( $performer ) || $performerUser->isRegistered() )
292            ) {
293                $this->getSkin()->setRelevantUser( $performerUser );
294            }
295        }
296
297        # Show form options
298        $succeed = $loglist->showOptions(
299            $opts->getValue( 'type' ),
300            $opts->getValue( 'year' ),
301            $opts->getValue( 'month' ),
302            $opts->getValue( 'day' )
303        );
304        if ( !$succeed ) {
305            return;
306        }
307
308        $this->getOutput()->setPageTitleMsg(
309            ( new LogPage( $opts->getValue( 'type' ) ) )->getName()
310        );
311
312        # Insert list
313        $logBody = $pager->getBody();
314        if ( $logBody ) {
315            $this->getOutput()->addHTML(
316                $pager->getNavigationBar() .
317                    $this->getActionButtons(
318                        $loglist->beginLogEventsList() .
319                            $logBody .
320                            $loglist->endLogEventsList()
321                    ) .
322                    $pager->getNavigationBar()
323            );
324        } else {
325            $this->getOutput()->addWikiMsg( 'logempty' );
326        }
327    }
328
329    private function getActionButtons( $formcontents ) {
330        $canRevDelete = $this->getAuthority()
331            ->isAllowedAll( 'deletedhistory', 'deletelogentry' );
332        $showTagEditUI = ChangeTags::showTagEditingUI( $this->getAuthority() );
333        # If the user doesn't have the ability to delete log entries nor edit tags,
334        # don't bother showing them the button(s).
335        if ( !$canRevDelete && !$showTagEditUI ) {
336            return $formcontents;
337        }
338
339        # Show button to hide log entries and/or edit change tags
340        $s = Html::openElement(
341            'form',
342            [ 'action' => wfScript(), 'id' => 'mw-log-deleterevision-submit' ]
343        ) . "\n";
344        $s .= Html::hidden( 'type', 'logging' ) . "\n";
345
346        $buttons = '';
347        if ( $canRevDelete ) {
348            $buttons .= Html::element(
349                'button',
350                [
351                    'type' => 'submit',
352                    'name' => 'title',
353                    'value' => SpecialPage::getTitleFor( 'Revisiondelete' )->getPrefixedDBkey(),
354                    'class' => "deleterevision-log-submit mw-log-deleterevision-button mw-ui-button"
355                ],
356                $this->msg( 'showhideselectedlogentries' )->text()
357            ) . "\n";
358        }
359        if ( $showTagEditUI ) {
360            $buttons .= Html::element(
361                'button',
362                [
363                    'type' => 'submit',
364                    'name' => 'title',
365                    'value' => SpecialPage::getTitleFor( 'EditTags' )->getPrefixedDBkey(),
366                    'class' => "editchangetags-log-submit mw-log-editchangetags-button mw-ui-button"
367                ],
368                $this->msg( 'log-edit-tags' )->text()
369            ) . "\n";
370        }
371
372        $buttons .= ( new ListToggle( $this->getOutput() ) )->getHTML();
373
374        $s .= $buttons . $formcontents . $buttons;
375        $s .= Html::closeElement( 'form' );
376
377        return $s;
378    }
379
380    protected function getGroupName() {
381        return 'changes';
382    }
383}
384
385/** @deprecated class alias since 1.41 */
386class_alias( SpecialLog::class, 'SpecialLog' );