Failed Conditions
Pull Request — user-welcomefix (#623)
by Simon
32:14 queued 18:22
created

PageViewRequest::setupUsernameData()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
eloc 8
c 0
b 0
f 0
dl 0
loc 15
ccs 0
cts 12
cp 0
rs 10
cc 2
nc 2
nop 1
crap 6
1
<?php
2
/******************************************************************************
3
 * Wikipedia Account Creation Assistance tool                                 *
4
 *                                                                            *
5
 * All code in this file is released into the public domain by the ACC        *
6
 * Development Team. Please see team.json for a list of contributors.         *
7
 ******************************************************************************/
8
9
namespace Waca\Pages;
10
11
use Exception;
12
use Waca\DataObjects\Comment;
13
use Waca\DataObjects\EmailTemplate;
14
use Waca\DataObjects\JobQueue;
15
use Waca\DataObjects\Log;
16
use Waca\DataObjects\Request;
17
use Waca\DataObjects\User;
18
use Waca\Exceptions\ApplicationLogicException;
19
use Waca\Fragments\RequestData;
20
use Waca\Helpers\LogHelper;
21
use Waca\Helpers\OAuthUserHelper;
22
use Waca\PdoDatabase;
23
use Waca\Tasks\InternalPageBase;
24
use Waca\WebRequest;
25
26
class PageViewRequest extends InternalPageBase
27
{
28
    use RequestData;
29
    const STATUS_SYMBOL_OPEN = '&#927';
30
    const STATUS_SYMBOL_ACCEPTED = '&#x2611';
31
    const STATUS_SYMBOL_REJECTED = '&#x2612';
32
33
    /**
34
     * Main function for this page, when no specific actions are called.
35
     * @throws ApplicationLogicException
36
     */
37
    protected function main()
38
    {
39
        // set up csrf protection
40
        $this->assignCSRFToken();
41
42
        // get some useful objects
43
        $database = $this->getDatabase();
44
        $request = $this->getRequest($database, WebRequest::getInt('id'));
45
        $config = $this->getSiteConfiguration();
46
        $currentUser = User::getCurrent($database);
47
48
        // Test we should be able to look at this request
49
        if ($config->getEmailConfirmationEnabled()) {
50
            if ($request->getEmailConfirm() !== 'Confirmed') {
51
                // Not allowed to look at this yet.
52
                throw new ApplicationLogicException('The email address has not yet been confirmed for this request.');
53
            }
54
        }
55
56
        $this->setupBasicData($request, $config);
57
58
        $this->setupUsernameData($request);
59
60
        $this->setupTitle($request);
61
62
        $this->setupReservationDetails($request->getReserved(), $database, $currentUser);
63
        $this->setupGeneralData($database);
64
65
        $this->assign('requestDataCleared', false);
66
        if ($request->getEmail() === $this->getSiteConfiguration()->getDataClearEmail()) {
67
            $this->assign('requestDataCleared', true);
68
        }
69
70
        $allowedPrivateData = $this->isAllowedPrivateData($request, $currentUser);
71
72
        $this->setupCreationTypes($currentUser);
73
74
        $this->setupLogData($request, $database);
75
76
        $this->addJs("/api.php?action=templates&targetVariable=templateconfirms");
77
78
        $this->assign('showRevealLink', false);
79
        if ($request->getReserved() === $currentUser->getId() ||
80
            $this->barrierTest('alwaysSeeHash', $currentUser, 'RequestData')
81
        ) {
82
            $this->assign('showRevealLink', true);
83
            $this->assign('revealHash', $request->getRevealHash());
84
        }
85
86
        $this->assign('canSeeRelatedRequests', false);
87
        if ($allowedPrivateData || $this->barrierTest('seeRelatedRequests', $currentUser, 'RequestData')) {
88
            $this->setupRelatedRequests($request, $config, $database);
89
        }
90
91
        if ($allowedPrivateData) {
92
            $this->setTemplate('view-request/main-with-data.tpl');
93
            $this->setupPrivateData($request);
94
95
            $this->assign('canSetBan', $this->barrierTest('set', $currentUser, PageBan::class));
96
            $this->assign('canSeeCheckuserData', $this->barrierTest('seeUserAgentData', $currentUser, 'RequestData'));
97
98
            if ($this->barrierTest('seeUserAgentData', $currentUser, 'RequestData')) {
99
                $this->setTemplate('view-request/main-with-checkuser-data.tpl');
100
                $this->setupCheckUserData($request);
101
            }
102
        }
103
        else {
104
            $this->setTemplate('view-request/main.tpl');
105
        }
106
    }
107
108
    /**
109
     * @param Request $request
110
     */
111
    protected function setupTitle(Request $request)
112
    {
113
        $statusSymbol = self::STATUS_SYMBOL_OPEN;
114
        if ($request->getStatus() === 'Closed') {
115
            if ($request->getWasCreated()) {
116
                $statusSymbol = self::STATUS_SYMBOL_ACCEPTED;
117
            }
118
            else {
119
                $statusSymbol = self::STATUS_SYMBOL_REJECTED;
120
            }
121
        }
122
123
        $this->setHtmlTitle($statusSymbol . ' #' . $request->getId());
124
    }
125
126
    /**
127
     * Sets up data unrelated to the request, such as the email template information
128
     *
129
     * @param PdoDatabase $database
130
     */
131
    protected function setupGeneralData(PdoDatabase $database)
132
    {
133
        $config = $this->getSiteConfiguration();
134
135
        $this->assign('createAccountReason', 'Requested account at [[WP:ACC]], request #');
136
137
        $this->assign('defaultRequestState', $config->getDefaultRequestStateKey());
0 ignored issues
show
Deprecated Code introduced by
The function Waca\SiteConfiguration::...efaultRequestStateKey() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

137
        $this->assign('defaultRequestState', /** @scrutinizer ignore-deprecated */ $config->getDefaultRequestStateKey());
Loading history...
138
139
        $this->assign('requestStates', $config->getRequestStates());
0 ignored issues
show
Deprecated Code introduced by
The function Waca\SiteConfiguration::getRequestStates() has been deprecated: To be removed after dynamic queues hit production. This will need to be major point release. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

139
        $this->assign('requestStates', /** @scrutinizer ignore-deprecated */ $config->getRequestStates());

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
140
141
        /** @var EmailTemplate $createdTemplate */
142
        $createdTemplate = EmailTemplate::getById($config->getDefaultCreatedTemplateId(), $database);
0 ignored issues
show
Deprecated Code introduced by
The function Waca\SiteConfiguration::...aultCreatedTemplateId() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

142
        $createdTemplate = EmailTemplate::getById(/** @scrutinizer ignore-deprecated */ $config->getDefaultCreatedTemplateId(), $database);
Loading history...
143
144
        $this->assign('createdHasJsQuestion', $createdTemplate->getJsquestion() != '');
145
        $this->assign('createdId', $createdTemplate->getId());
146
        $this->assign('createdName', $createdTemplate->getName());
147
148
        $createReasons = EmailTemplate::getActiveTemplates(EmailTemplate::CREATED, $database);
149
        $this->assign("createReasons", $createReasons);
150
        $declineReasons = EmailTemplate::getActiveTemplates(EmailTemplate::NOT_CREATED, $database);
151
        $this->assign("declineReasons", $declineReasons);
152
153
        $allCreateReasons = EmailTemplate::getAllActiveTemplates(EmailTemplate::CREATED, $database);
154
        $this->assign("allCreateReasons", $allCreateReasons);
155
        $allDeclineReasons = EmailTemplate::getAllActiveTemplates(EmailTemplate::NOT_CREATED, $database);
156
        $this->assign("allDeclineReasons", $allDeclineReasons);
157
        $allOtherReasons = EmailTemplate::getAllActiveTemplates(false, $database);
158
        $this->assign("allOtherReasons", $allOtherReasons);
159
    }
160
161
    private function setupLogData(Request $request, PdoDatabase $database)
162
    {
163
        $currentUser = User::getCurrent($database);
164
165
        $logs = LogHelper::getRequestLogsWithComments($request->getId(), $database, $this->getSecurityManager());
166
        $requestLogs = array();
167
168
        /** @var User[] $nameCache */
169
        $nameCache = array();
170
171
        $editableComments = $this->barrierTest('editOthers', $currentUser, PageEditComment::class);
172
173
        /** @var Log|Comment $entry */
174
        foreach ($logs as $entry) {
175
            // both log and comment have a 'user' field
176
            if (!array_key_exists($entry->getUser(), $nameCache)) {
1 ignored issue
show
Bug introduced by
The method getUser() does not exist on Waca\DataObject. It seems like you code against a sub-type of Waca\DataObject such as Waca\DataObjects\Log or Waca\DataObjects\Ban or Waca\DataObjects\UserDomain or Waca\DataObjects\UserRole or Waca\DataObjects\Comment. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

176
            if (!array_key_exists($entry->/** @scrutinizer ignore-call */ getUser(), $nameCache)) {
Loading history...
177
                $entryUser = User::getById($entry->getUser(), $database);
178
                $nameCache[$entry->getUser()] = $entryUser;
179
            }
180
181
            if ($entry instanceof Comment) {
182
                $requestLogs[] = array(
183
                    'type'     => 'comment',
184
                    'security' => $entry->getVisibility(),
185
                    'user'     => $entry->getVisibility() == 'requester' ? $request->getName() : $nameCache[$entry->getUser()]->getUsername(),
186
                    'userid'   => $entry->getUser() == -1 ? null : $entry->getUser(),
187
                    'entry'    => null,
188
                    'time'     => $entry->getTime(),
189
                    'canedit'  => ($editableComments || $entry->getUser() == $currentUser->getId()),
190
                    'id'       => $entry->getId(),
191
                    'comment'  => $entry->getComment(),
192
                );
193
            }
194
195
            if ($entry instanceof Log) {
196
                $invalidUserId = $entry->getUser() === -1 || $entry->getUser() === 0;
197
                $entryUser = $invalidUserId ? User::getCommunity() : $nameCache[$entry->getUser()];
198
199
                $entryComment = $entry->getComment();
200
201
                if ($entry->getAction() === 'JobIssueRequest' || $entry->getAction() === 'JobCompletedRequest') {
202
                    $data = unserialize($entry->getComment());
203
                    /** @var JobQueue $job */
204
                    $job = JobQueue::getById($data['job'], $database);
205
                    $requestLogs[] = array(
206
                        'type'     => 'joblog',
207
                        'security' => 'user',
208
                        'userid'   => $entry->getUser() == -1 ? null : $entry->getUser(),
209
                        'user'     => $entryUser->getUsername(),
210
                        'entry'    => LogHelper::getLogDescription($entry),
211
                        'time'     => $entry->getTimestamp(),
212
                        'canedit'  => false,
213
                        'id'       => $entry->getId(),
214
                        'jobId'    => $job->getId(),
215
                        'jobDesc'  => JobQueue::getTaskDescriptions()[$job->getTask()],
216
                    );
217
                } else {
218
                    $requestLogs[] = array(
219
                        'type'     => 'log',
220
                        'security' => 'user',
221
                        'userid'   => $entry->getUser() == -1 ? null : $entry->getUser(),
222
                        'user'     => $entryUser->getUsername(),
223
                        'entry'    => LogHelper::getLogDescription($entry),
224
                        'time'     => $entry->getTimestamp(),
225
                        'canedit'  => false,
226
                        'id'       => $entry->getId(),
227
                        'comment'  => $entryComment,
228
                    );
229
                }
230
            }
231
        }
232
233
        $this->addJs("/api.php?action=users&targetVariable=typeaheaddata");
234
235
        $this->assign("requestLogs", $requestLogs);
236
    }
237
238
    /**
239
     * @param Request $request
240
     */
241
    protected function setupUsernameData(Request $request)
242
    {
243
        $blacklistData = $this->getBlacklistHelper()->isBlacklisted($request->getName());
244
245
        $this->assign('requestIsBlacklisted', $blacklistData !== false);
246
        $this->assign('requestBlacklist', $blacklistData);
247
248
        try {
249
            $spoofs = $this->getAntiSpoofProvider()->getSpoofs($request->getName());
250
        }
251
        catch (Exception $ex) {
252
            $spoofs = $ex->getMessage();
253
        }
254
255
        $this->assign("spoofs", $spoofs);
256
    }
257
258
    private function setupCreationTypes(User $user)
259
    {
260
        $this->assign('allowWelcomeSkip', false);
261
        $this->assign('forceWelcomeSkip', false);
262
263
        $oauth = new OAuthUserHelper($user, $this->getDatabase(), $this->getOAuthProtocolHelper(), $this->getSiteConfiguration());
264
265
        if ($user->getWelcomeTemplate() != 0) {
266
            $this->assign('allowWelcomeSkip', true);
267
268
            if (!$oauth->canWelcome()) {
269
                $this->assign('forceWelcomeSkip', true);
270
            }
271
        }
272
273
        // test credentials
274
        $canManualCreate = $this->barrierTest(User::CREATION_MANUAL, $user, 'RequestCreation');
275
        $canOauthCreate = $this->barrierTest(User::CREATION_OAUTH, $user, 'RequestCreation');
276
        $canBotCreate = $this->barrierTest(User::CREATION_BOT, $user, 'RequestCreation');
277
278
        $this->assign('canManualCreate', $canManualCreate);
279
        $this->assign('canOauthCreate', $canOauthCreate);
280
        $this->assign('canBotCreate', $canBotCreate);
281
282
        // show/hide the type radio buttons
283
        $creationHasChoice = count(array_filter([$canManualCreate, $canOauthCreate, $canBotCreate])) > 1;
284
285
        if (!$this->barrierTest($user->getCreationMode(), $user, 'RequestCreation')) {
286
            // user is not allowed to use their default. Force a choice.
287
            $creationHasChoice = true;
288
        }
289
290
        $this->assign('creationHasChoice', $creationHasChoice);
291
292
        // determine problems in creation types
293
        $this->assign('botProblem', false);
294
        if ($canBotCreate && $this->getSiteConfiguration()->getCreationBotPassword() === null) {
0 ignored issues
show
introduced by
The condition $this->getSiteConfigurat...nBotPassword() === null is always false.
Loading history...
295
            $this->assign('botProblem', true);
296
        }
297
298
        $this->assign('oauthProblem', false);
299
        if ($canOauthCreate && !$oauth->canCreateAccount()) {
300
            $this->assign('oauthProblem', true);
301
        }
302
    }
303
}
304