Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
75.00% covered (warning)
75.00%
168 / 224
20.00% covered (danger)
20.00%
2 / 10
CRAP
0.00% covered (danger)
0.00%
0 / 1
SpecialLog
75.00% covered (warning)
75.00%
168 / 224
20.00% covered (danger)
20.00%
2 / 10
107.77
0.00% covered (danger)
0.00%
0 / 1
 __construct
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 execute
96.15% covered (success)
96.15%
75 / 78
0.00% covered (danger)
0.00%
0 / 1
23
 normalizeUserPage
63.64% covered (warning)
63.64%
7 / 11
0.00% covered (danger)
0.00%
0 / 1
11.08
 getLogTypesOnUser
25.00% covered (danger)
25.00%
3 / 12
0.00% covered (danger)
0.00%
0 / 1
3.69
 getSubpagesForPrefixSearch
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
1
 parseParams
75.00% covered (warning)
75.00%
6 / 8
0.00% covered (danger)
0.00%
0 / 1
4.25
 resolveLogType
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
3
 show
92.45% covered (success)
92.45%
49 / 53
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 * @license GPL-2.0-or-later
4 * @file
5 */
6
7namespace MediaWiki\Specials;
8
9use MediaWiki\ChangeTags\ChangeTags;
10use MediaWiki\Exception\PermissionsError;
11use MediaWiki\HookContainer\HookRunner;
12use MediaWiki\Html\FormOptions;
13use MediaWiki\Html\Html;
14use MediaWiki\Html\ListToggle;
15use MediaWiki\Logging\LogEventsList;
16use MediaWiki\Logging\LogFormatterFactory;
17use MediaWiki\Logging\LogPage;
18use MediaWiki\Logging\Pager\LogPager;
19use MediaWiki\MainConfigNames;
20use MediaWiki\MediaWikiServices;
21use MediaWiki\Page\LinkBatchFactory;
22use MediaWiki\SpecialPage\SpecialPage;
23use MediaWiki\Title\Title;
24use MediaWiki\User\ActorNormalization;
25use MediaWiki\User\TempUser\TempUserConfig;
26use MediaWiki\User\UserIdentityLookup;
27use MediaWiki\User\UserNameUtils;
28use MediaWiki\Utils\MWTimestamp;
29use Wikimedia\IPUtils;
30use Wikimedia\Rdbms\IConnectionProvider;
31use Wikimedia\Rdbms\IExpression;
32use Wikimedia\Timestamp\TimestampException;
33
34/**
35 * A special page that lists log entries
36 *
37 * @ingroup SpecialPage
38 */
39class SpecialLog extends SpecialPage {
40
41    private readonly TempUserConfig $tempUserConfig;
42
43    public function __construct(
44        private readonly LinkBatchFactory $linkBatchFactory,
45        private readonly IConnectionProvider $dbProvider,
46        private readonly ActorNormalization $actorNormalization,
47        private readonly UserIdentityLookup $userIdentityLookup,
48        private readonly UserNameUtils $userNameUtils,
49        private readonly LogFormatterFactory $logFormatterFactory,
50        ?TempUserConfig $tempUserConfig = null
51    ) {
52        parent::__construct( 'Log' );
53        if ( $tempUserConfig instanceof TempUserConfig ) {
54            $this->tempUserConfig = $tempUserConfig;
55        } else {
56            $this->tempUserConfig = MediaWikiServices::getInstance()->getTempUserConfig();
57        }
58    }
59
60    /** @inheritDoc */
61    public function execute( $par ) {
62        $this->setHeaders();
63        $this->outputHeader();
64        $out = $this->getOutput();
65        $out->addModuleStyles( 'mediawiki.interface.helpers.styles' );
66        $this->addHelpLink( 'Help:Log' );
67
68        $opts = new FormOptions;
69        $opts->add( 'type', '' );
70        $opts->add( 'user', '' );
71        $opts->add( 'page', [] );
72        $opts->add( 'pattern', false );
73        $opts->add( 'year', null, FormOptions::INTNULL );
74        $opts->add( 'month', null, FormOptions::INTNULL );
75        $opts->add( 'day', null, FormOptions::INTNULL );
76        $opts->add( 'tagfilter', '' );
77        $opts->add( 'tagInvert', false );
78        $opts->add( 'offset', '' );
79        $opts->add( 'dir', '' );
80        $opts->add( 'offender', '' );
81        $opts->add( 'subtype', '' );
82        $opts->add( 'logid', '' );
83
84        // Set values
85        if ( $par !== null ) {
86            $this->parseParams( (string)$par );
87        }
88        $opts->fetchValuesFromRequest( $this->getRequest() );
89
90        // Set date values
91        $dateString = $this->getRequest()->getVal( 'wpdate' );
92        if ( $dateString ) {
93            try {
94                $dateStamp = MWTimestamp::getInstance( $dateString . ' 00:00:00' );
95            } catch ( TimestampException ) {
96                // If users provide an invalid date, silently ignore it
97                // instead of letting an exception bubble up (T201411)
98                $dateStamp = false;
99            }
100            if ( $dateStamp ) {
101                $opts->setValue( 'year', (int)$dateStamp->format( 'Y' ) );
102                $opts->setValue( 'month', (int)$dateStamp->format( 'm' ) );
103                $opts->setValue( 'day', (int)$dateStamp->format( 'd' ) );
104            }
105        }
106
107        // If the user doesn't have the right permission to view the specific
108        // log type, throw a PermissionsError
109        $logRestrictions = $this->getConfig()->get( MainConfigNames::LogRestrictions );
110        $type = $opts->getValue( 'type' );
111        if ( isset( $logRestrictions[$type] )
112            && !$this->getAuthority()->isAllowed( $logRestrictions[$type] )
113        ) {
114            throw new PermissionsError( $logRestrictions[$type] );
115        }
116
117        # TODO: Move this into LogPager like other query conditions.
118        # Handle type-specific inputs
119        $qc = [];
120        $offenderName = $opts->getValue( 'offender' );
121        if ( $opts->getValue( 'type' ) == 'suppress' && $offenderName !== '' ) {
122            $dbr = $this->dbProvider->getReplicaDatabase();
123            $offenderId = $this->actorNormalization->findActorIdByName( $offenderName, $dbr );
124            if ( $offenderId ) {
125                $qc = [ 'ls_field' => 'target_author_actor', 'ls_value' => strval( $offenderId ) ];
126            } else {
127                // Unknown offender, thus results have to be empty
128                $qc = [ '1=0' ];
129            }
130        } else {
131            if ( $this->tempUserConfig->isKnown() ) {
132                // See T398423
133                // Three cases possible:
134                // 1. Special:Log/newusers is loaded as-is with 'user' field empty or set to non-temp user.
135                // The checkbox will be shown checked by default but have no value and is expected to exclude
136                // temporary accounts.
137                // 2. Special:Log/newusers is loaded as-is with 'user' field set to a temp username.
138                // The checkbox will be shown unchecked and have no value. We expect not to exclude temporary accounts.
139                // 3. form submitted, exclude temp accounts
140                // 4. form submitted, include temp accounts
141                // Check for cases 1 and 3 and omit temporary accounts in the pager query.
142                $formWasSubmitted = $this->getRequest()->getVal( 'wpFormIdentifier' ) === 'logeventslist';
143                if (
144                    (
145                        !$formWasSubmitted &&
146                        !$this->getRequest()->getVal( 'logid' ) &&
147                        !$this->getRequest()->getVal( 'excludetempacct' ) &&
148                        !$this->tempUserConfig->isTempName( $opts->getValue( 'user' ) )
149                    ) ||
150                    (
151                        $formWasSubmitted &&
152                        !$this->getRequest()->getVal( 'logid' ) &&
153                        $this->getRequest()->getVal( 'excludetempacct' )
154                    )
155                ) {
156                    $dbr = $this->dbProvider->getReplicaDatabase();
157                    if ( $opts->getValue( 'type' ) === '' ) {
158                        // Support excluding temporary account creations on Special:Log
159                        $qc = [
160                            $dbr->expr( 'log_type', '!=', 'newusers' )->orExpr(
161                                $dbr->expr( 'log_type', '=', 'newusers' )
162                                    ->andExpr( $this->tempUserConfig
163                                    ->getMatchCondition( $dbr, 'logging_actor.actor_name', IExpression::NOT_LIKE ) )
164                            )
165                        ];
166                    } elseif ( $opts->getValue( 'type' ) === 'newusers' ) {
167                        $qc = [
168                            $this->tempUserConfig
169                                ->getMatchCondition( $dbr, 'logging_actor.actor_name', IExpression::NOT_LIKE )
170                        ];
171                    }
172                }
173            }
174
175            // Allow extensions to add relations to their search types
176            $this->getHookRunner()->onSpecialLogAddLogSearchRelations(
177                $opts->getValue( 'type' ), $this->getRequest(), $qc );
178        }
179
180        # TODO: Move this into LogEventList and use it as filter-callback in the field descriptor.
181        # Some log types are only for a 'User:' title but we might have been given
182        # only the username instead of the full title 'User:username'. This part try
183        # to lookup for a user by that name and eventually fix user input. See T3697.
184        if ( in_array( $opts->getValue( 'type' ), self::getLogTypesOnUser( $this->getHookRunner() ) ) ) {
185            $pages = [];
186            foreach ( $opts->getValue( 'page' ) as $page ) {
187                $page = $this->normalizeUserPage( $page );
188                if ( $page !== null ) {
189                    $pages[] = $page->getPrefixedText();
190                }
191            }
192            $opts->setValue( 'page', $pages );
193        }
194
195        $this->show( $opts, $qc );
196    }
197
198    /**
199     * Add the namespace prefix to a user page and validate it
200     *
201     * @param string $page
202     * @return Title|null
203     */
204    private function normalizeUserPage( $page ) {
205        $target = Title::newFromText( $page );
206        if ( $target && $target->getNamespace() === NS_MAIN ) {
207            if ( IPUtils::isValidRange( $target->getText() ) ) {
208                $page = IPUtils::sanitizeRange( $target->getText() );
209            }
210            # User forgot to add 'User:', we are adding it for them
211            $target = Title::makeTitleSafe( NS_USER, $page );
212        } elseif ( $target && $target->getNamespace() === NS_USER
213            && IPUtils::isValidRange( $target->getText() )
214        ) {
215            $ipOrRange = IPUtils::sanitizeRange( $target->getText() );
216            if ( $ipOrRange !== $target->getText() ) {
217                $target = Title::makeTitleSafe( NS_USER, $ipOrRange );
218            }
219        }
220        return $target;
221    }
222
223    /**
224     * List log type for which the target is a user
225     * Thus if the given target is in NS_MAIN we can alter it to be an NS_USER
226     * Title user instead.
227     *
228     * @since 1.25
229     * @since 1.36 Added $runner parameter
230     *
231     * @param HookRunner|null $runner
232     * @return array
233     */
234    public static function getLogTypesOnUser( ?HookRunner $runner = null ) {
235        static $types = null;
236        if ( $types !== null ) {
237            return $types;
238        }
239        $types = [
240            'block',
241            'newusers',
242            'rights',
243            'renameuser',
244        ];
245
246        ( $runner ?? new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )
247            ->onGetLogTypesOnUser( $types );
248        return $types;
249    }
250
251    /**
252     * Return an array of subpages that this special page will accept.
253     *
254     * @return string[] subpages
255     */
256    public function getSubpagesForPrefixSearch() {
257        $subpages = LogPage::validTypes();
258
259        // Mechanism allowing extensions to change the log types listed as
260        // search hints (T398293).
261        $this->getHookRunner()->onSpecialLogGetSubpagesForPrefixSearch(
262            $this->getContext(),
263            $subpages
264        );
265
266        $subpages[] = 'all';
267
268        // Remove duplicates just in case a hook provides the same subpage twice
269        $subpages = array_unique( $subpages );
270        sort( $subpages );
271        return $subpages;
272    }
273
274    /**
275     * Set options based on the subpage title parts:
276     * - One part that is a valid log type: Special:Log/logtype
277     * - Two parts: Special:Log/logtype/username
278     * - Otherwise, assume the whole subpage is a username.
279     *
280     * @param string $par
281     */
282    private function parseParams( string $par ) {
283        $params = explode( '/', $par, 2 );
284        $logType = $this->resolveLogType( $params );
285
286        if ( $logType ) {
287            $this->getRequest()->setVal( 'type', $logType );
288            if ( count( $params ) === 2 ) {
289                $this->getRequest()->setVal( 'user', $params[1] );
290            }
291        } elseif ( $par !== '' ) {
292            $this->getRequest()->setVal( 'user', $par );
293        }
294    }
295
296    /**
297     * Determines the requested log type based on the parameters from the
298     * requested URL, which are obtained by splitting the path by the slash
299     * character.
300     *
301     * This method returns the requested type, if one is provided and is '*',
302     * 'all', or is included in the values from LogPage::validTypes(); or an
303     * empty string otherwise.
304     *
305     * Extensions may modify the requested type by implementing the
306     * SpecialLogResolveLogType hook, which may be used to change the log type
307     * obtained from the URL and other request parameters.
308     *
309     * @param array $params Values resulting from splitting the URL by '/'.
310     * @return string The requested type if valid, or an empty string otherwise.
311     */
312    private function resolveLogType( array $params ): string {
313        // Mechanism for changing the parameters of Special:Log
314        // from extensions (T381875)
315        $logType = $params[0] ?? null;
316
317        $this->getHookRunner()->onSpecialLogResolveLogType(
318            $params,
319            $logType
320        );
321
322        if ( $logType !== '' ) {
323            $symsForAll = [ '*', 'all' ];
324            $allowedTypes = array_merge( LogPage::validTypes(), $symsForAll );
325
326            if ( in_array( $logType, $allowedTypes ) ) {
327                return $logType;
328            }
329        }
330
331        return '';
332    }
333
334    private function show( FormOptions $opts, array $extraConds ) {
335        # Create a LogPager item to get the results and a LogEventsList item to format them...
336        $loglist = new LogEventsList(
337            $this->getContext(),
338            $this->getLinkRenderer(),
339            LogEventsList::USE_CHECKBOXES
340        );
341        $pager = new LogPager(
342            $loglist,
343            $opts->getValue( 'type' ),
344            $opts->getValue( 'user' ),
345            $opts->getValue( 'page' ),
346            $opts->getValue( 'pattern' ),
347            $extraConds,
348            $opts->getValue( 'year' ),
349            $opts->getValue( 'month' ),
350            $opts->getValue( 'day' ),
351            $opts->getValue( 'tagfilter' ),
352            $opts->getValue( 'subtype' ),
353            $opts->getValue( 'logid' ),
354            $this->linkBatchFactory,
355            $this->actorNormalization,
356            $this->logFormatterFactory,
357            $opts->getValue( 'tagInvert' )
358        );
359
360        # Set relevant user
361        $performer = $pager->getPerformer();
362        if ( $performer ) {
363            $performerUser = $this->userIdentityLookup->getUserIdentityByName( $performer );
364            // Only set valid local user as the relevant user (T344886)
365            // Uses the same condition as the SpecialContributions class did
366            if ( $performerUser && !IPUtils::isValidRange( $performer ) &&
367                ( $this->userNameUtils->isIP( $performer ) || $performerUser->isRegistered() )
368            ) {
369                $this->getSkin()->setRelevantUser( $performerUser );
370            }
371        }
372
373        # Show form options
374        $succeed = $loglist->showOptions(
375            $opts->getValue( 'type' ),
376            $opts->getValue( 'year' ),
377            $opts->getValue( 'month' ),
378            $opts->getValue( 'day' ),
379            $opts->getValue( 'user' ),
380        );
381        if ( !$succeed ) {
382            return;
383        }
384
385        $this->getOutput()->setPageTitleMsg(
386            ( new LogPage( $opts->getValue( 'type' ) ) )->getName()
387        );
388
389        # Insert list
390        $logBody = $pager->getBody();
391        if ( $logBody ) {
392            $this->getOutput()->addHTML(
393                $pager->getNavigationBar() .
394                    $this->getActionButtons(
395                        $loglist->beginLogEventsList() .
396                            $logBody .
397                            $loglist->endLogEventsList()
398                    ) .
399                    $pager->getNavigationBar()
400            );
401        } else {
402            $this->getOutput()->addWikiMsg( 'logempty' );
403        }
404    }
405
406    private function getActionButtons( string $formcontents ): string {
407        $canRevDelete = $this->getAuthority()
408            ->isAllowedAll( 'deletedhistory', 'deletelogentry' );
409        $showTagEditUI = ChangeTags::showTagEditingUI( $this->getAuthority() );
410        # If the user doesn't have the ability to delete log entries nor edit tags,
411        # don't bother showing them the button(s).
412        if ( !$canRevDelete && !$showTagEditUI ) {
413            return $formcontents;
414        }
415
416        # Show button to hide log entries and/or edit change tags
417        $s = Html::openElement(
418            'form',
419            [ 'action' => wfScript(), 'id' => 'mw-log-deleterevision-submit' ]
420        ) . "\n";
421        $s .= Html::hidden( 'type', 'logging' ) . "\n";
422
423        $buttons = '';
424        if ( $canRevDelete ) {
425            $buttons .= Html::element(
426                'button',
427                [
428                    'type' => 'submit',
429                    'name' => 'title',
430                    'value' => SpecialPage::getTitleFor( 'Revisiondelete' )->getPrefixedDBkey(),
431                    'class' => "deleterevision-log-submit mw-log-deleterevision-button mw-ui-button"
432                ],
433                $this->msg( 'showhideselectedlogentries' )->text()
434            ) . "\n";
435        }
436        if ( $showTagEditUI ) {
437            $buttons .= Html::element(
438                'button',
439                [
440                    'type' => 'submit',
441                    'name' => 'title',
442                    'value' => SpecialPage::getTitleFor( 'EditTags' )->getPrefixedDBkey(),
443                    'class' => "editchangetags-log-submit mw-log-editchangetags-button mw-ui-button"
444                ],
445                $this->msg( 'log-edit-tags' )->text()
446            ) . "\n";
447        }
448
449        $buttons .= ( new ListToggle( $this->getOutput() ) )->getHTML();
450
451        $s .= $buttons . $formcontents . $buttons;
452        $s .= Html::closeElement( 'form' );
453
454        return $s;
455    }
456
457    /** @inheritDoc */
458    protected function getGroupName() {
459        return 'changes';
460    }
461}
462
463// @codeCoverageIgnoreStart
464/** @deprecated class alias since 1.41 */
465class_alias( SpecialLog::class, 'SpecialLog' );
466// @codeCoverageIgnoreEnd