Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
88.46% covered (warning)
88.46%
23 / 26
50.00% covered (danger)
50.00%
1 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
UserNotLoggedIn
92.00% covered (success)
92.00%
23 / 25
50.00% covered (danger)
50.00%
1 / 2
9.04
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
4
 report
88.89% covered (warning)
88.89%
16 / 18
0.00% covered (danger)
0.00%
0 / 1
5.03
1<?php
2/**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21namespace MediaWiki\Exception;
22
23use LoginHelper;
24use MediaWiki\Context\RequestContext;
25use MediaWiki\SpecialPage\SpecialPage;
26
27/**
28 * Redirect a user to the login page or account creation page
29 *
30 * This is essentially an ErrorPageError exception which by default uses the
31 * 'exception-nologin' as a title and 'exception-nologin-text' for the message.
32 *
33 * When the user is a temporary account, the redirect will point to the Special:CreateAccount page unless
34 * specifically set not to. In all other cases, the redirect is to the Special:UserLogin page.
35 *
36 * The message key for the reason will be modified to include '-for-temp-user' when the user is logged
37 * in to a temporary account and this message key exists (i.e. defined and not empty).
38 *
39 * @note In order for this exception to redirect, the error message passed to the
40 * constructor has to be explicitly added to LoginHelper::validErrorMessages or with
41 * the LoginFormValidErrorMessages hook. Otherwise, the user will just be shown the message
42 * rather than redirected.
43 *
44 * @par Example:
45 * @code
46 * if ( $user->isAnon() ) {
47 *   throw new UserNotLoggedIn();
48 * }
49 * @endcode
50 *
51 * Note the parameter order differs from ErrorPageError, this allows you to
52 * simply specify a reason without overriding the default title.
53 *
54 * @par Example:
55 * @code
56 * if ( $user->isAnon() ) {
57 *   throw new UserNotLoggedIn( 'action-require-loggedin' );
58 * }
59 * @endcode
60 *
61 * You can use {@link SpecialPage::requireLogin} and {@link SpecialPage::requireNamedUser} to throw this
62 * exception when the user is an anon user or not named respectively.
63 *
64 * @newable
65 * @see T39627
66 * @since 1.20
67 * @ingroup Exception
68 */
69class UserNotLoggedIn extends ErrorPageError {
70
71    private bool $alwaysRedirectToLoginPage;
72
73    /**
74     * @stable to call
75     *
76     * @note The value of the $reasonMsg parameter must be set with the LoginFormValidErrorMessages
77     * hook if you want the user to be automatically redirected to the login form.
78     *
79     * @param string $reasonMsg A message key containing the reason for the error. '-for-temp-user' will be
80     *        appended to the end of the message key if the user is a temporary account and the redirect is
81     *        to the Special:CreateAccount page. The modification is skipped if the message key does not
82     *        exist.
83     *        Optional, default: 'exception-nologin-text'
84     * @param string $titleMsg A message key to set the page title.
85     *        Optional, default: 'exception-nologin'
86     * @param array $params Parameters to wfMessage() for $reasonMsg and $tempUserReasonMsg
87     *        Optional, default: []
88     * @param bool $alwaysRedirectToLoginPage Whether we should always redirect to the login page, even if the
89     *        user is a temporary account. If false (the default), the redirect will be to Special:CreateAccount
90     *        when the user is logged in to a temporary account.
91     */
92    public function __construct(
93        $reasonMsg = 'exception-nologin-text',
94        $titleMsg = 'exception-nologin',
95        $params = [],
96        bool $alwaysRedirectToLoginPage = false
97    ) {
98        $context = RequestContext::getMain();
99        // Replace the reason message for one that describes creating account when the user is a temporary account
100        // when such a custom message exists (T358586).
101        if ( $context->getUser()->isTemp() && !$alwaysRedirectToLoginPage ) {
102            // For grep to find usages: exception-nologin-text-for-temp-user
103            $tempUserReasonMsg = $reasonMsg . '-for-temp-user';
104            if ( $context->msg( $tempUserReasonMsg )->exists() ) {
105                $reasonMsg = $tempUserReasonMsg;
106            }
107        }
108        parent::__construct( $titleMsg, $reasonMsg, $params );
109        $this->alwaysRedirectToLoginPage = $alwaysRedirectToLoginPage;
110    }
111
112    /**
113     * Redirect to Special:Userlogin or Special:CreateAccount if the specified message is compatible. Otherwise,
114     * show an error page as usual.
115     * @param int $action
116     */
117    public function report( $action = self::SEND_OUTPUT ) {
118        // If an unsupported message is used, don't try redirecting to Special:Userlogin,
119        // since the message may not be compatible.
120        if ( !in_array( $this->msg, LoginHelper::getValidErrorMessages() ) ) {
121            parent::report( $action );
122            return;
123        }
124
125        $context = RequestContext::getMain();
126
127        // Message is valid. Redirect to Special:Userlogin, unless the user is a temporary account in which case
128        // redirect to Special:CreateAccount (T358586).
129        $specialPageName = 'Userlogin';
130        if ( $context->getUser()->isTemp() && !$this->alwaysRedirectToLoginPage ) {
131            $specialPageName = 'CreateAccount';
132        }
133
134        $output = $context->getOutput();
135        $query = $context->getRequest()->getQueryValues();
136        // Title will be overridden by returnto
137        unset( $query['title'] );
138        // Redirect to Special:Userlogin
139        $output->redirect( SpecialPage::getTitleFor( $specialPageName )->getFullURL( [
140            // Return to this page when the user logs in
141            'returnto' => $context->getTitle()->getFullText(),
142            'returntoquery' => wfArrayToCgi( $query ),
143            'warning' => $this->msg,
144            // Forward the 'display' parameter if provided
145            'display' => $query['display'] ?? null,
146        ] ) );
147
148        if ( $action === self::SEND_OUTPUT ) {
149            $output->output();
150        }
151    }
152}
153
154/** @deprecated class alias since 1.44 */
155class_alias( UserNotLoggedIn::class, 'UserNotLoggedIn' );