Failed Conditions
Pull Request — multiproject/requestqueue (#705)
by Simon
22:10 queued 14:35
created

PageViewRequest::setupLogData()   F

Complexity

Conditions 17
Paths 1123

Size

Total Lines 83
Code Lines 57

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 306

Importance

Changes 3
Bugs 1 Features 0
Metric Value
eloc 57
c 3
b 1
f 0
dl 0
loc 83
ccs 0
cts 65
cp 0
rs 1.0499
cc 17
nc 1123
nop 2
crap 306

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 DateTime;
13
use Waca\DataObjects\Comment;
14
use Waca\DataObjects\Domain;
15
use Waca\DataObjects\EmailTemplate;
16
use Waca\DataObjects\JobQueue;
17
use Waca\DataObjects\Log;
18
use Waca\DataObjects\Request;
19
use Waca\DataObjects\RequestQueue;
20
use Waca\DataObjects\User;
21
use Waca\Exceptions\ApplicationLogicException;
22
use Waca\Fragments\RequestData;
23
use Waca\Helpers\LogHelper;
24
use Waca\Helpers\OAuthUserHelper;
25
use Waca\PdoDatabase;
26
use Waca\Security\RoleConfiguration;
27
use Waca\RequestStatus;
28
use Waca\Tasks\InternalPageBase;
29
use Waca\WebRequest;
30
31
class PageViewRequest extends InternalPageBase
32
{
33
    use RequestData;
34
    const STATUS_SYMBOL_OPEN = '&#927';
35
    const STATUS_SYMBOL_ACCEPTED = '&#x2611';
36
    const STATUS_SYMBOL_REJECTED = '&#x2612';
37
38
    /**
39
     * Main function for this page, when no specific actions are called.
40
     * @throws ApplicationLogicException
41
     */
42
    protected function main()
43
    {
44
        // set up csrf protection
45
        $this->assignCSRFToken();
46
47
        // get some useful objects
48
        $database = $this->getDatabase();
49
        $request = $this->getRequest($database, WebRequest::getInt('id'));
50
        $config = $this->getSiteConfiguration();
51
        $currentUser = User::getCurrent($database);
52
53
        // Test we should be able to look at this request
54
        if ($config->getEmailConfirmationEnabled()) {
55
            if ($request->getEmailConfirm() !== 'Confirmed') {
56
                // Not allowed to look at this yet.
57
                throw new ApplicationLogicException('The email address has not yet been confirmed for this request.');
58
            }
59
        }
60
61
        $this->setupBasicData($request, $config);
62
63
        $this->setupUsernameData($request);
64
65
        $this->setupTitle($request);
66
67
        $this->setupReservationDetails($request->getReserved(), $database, $currentUser);
68
        $this->setupGeneralData($database);
69
70
        $this->assign('requestDataCleared', false);
71
        if ($request->getEmail() === $this->getSiteConfiguration()->getDataClearEmail()) {
72
            $this->assign('requestDataCleared', true);
73
        }
74
75
        $allowedPrivateData = $this->isAllowedPrivateData($request, $currentUser);
76
77
        $this->setupCreationTypes($currentUser);
78
79
        $this->setupLogData($request, $database);
80
81
        $this->addJs("/api.php?action=templates&targetVariable=templateconfirms");
82
83
        $this->assign('showRevealLink', false);
84
        if ($request->getReserved() === $currentUser->getId() ||
85
            $this->barrierTest('alwaysSeeHash', $currentUser, 'RequestData')
86
        ) {
87
            $this->assign('showRevealLink', true);
88
            $this->assign('revealHash', $request->getRevealHash());
89
        }
90
91
        $this->assign('canSeeRelatedRequests', false);
92
        if ($allowedPrivateData || $this->barrierTest('seeRelatedRequests', $currentUser, 'RequestData')) {
93
            $this->setupRelatedRequests($request, $config, $database);
94
        }
95
96
        $this->assign('canCreateLocalAccount', $this->barrierTest('createLocalAccount', $currentUser, 'RequestData'));
97
            
98
        $closureDate = $request->getClosureDate();
99
        $date = new DateTime();
100
        $date->modify("-7 days");
101
        if ($request->getStatus() == "Closed" && $closureDate < $date) {
102
                $this->assign('isOldRequest', true);
103
        }
104
        $this->assign('canResetOldRequest', $this->barrierTest('reopenOldRequest', $currentUser, 'RequestData'));
105
        $this->assign('canResetPurgedRequest', $this->barrierTest('reopenClearedRequest', $currentUser, 'RequestData'));
106
107
        $this->assign('requestEmailSent', $request->getEmailSent());
108
109
        if ($allowedPrivateData) {
110
            $this->setTemplate('view-request/main-with-data.tpl');
111
            $this->setupPrivateData($request, $config);
112
            $this->assign('canSetBan', $this->barrierTest('set', $currentUser, PageBan::class));
113
            $this->assign('canSeeCheckuserData', $this->barrierTest('seeUserAgentData', $currentUser, 'RequestData'));
114
115
            if ($this->barrierTest('seeUserAgentData', $currentUser, 'RequestData')) {
116
                $this->setTemplate('view-request/main-with-checkuser-data.tpl');
117
                $this->setupCheckUserData($request);
118
            }
119
        }
120
        else {
121
            $this->setTemplate('view-request/main.tpl');
122
        }
123
    }
124
125
    /**
126
     * @param Request $request
127
     */
128
    protected function setupTitle(Request $request)
129
    {
130
        $statusSymbol = self::STATUS_SYMBOL_OPEN;
131
        if ($request->getStatus() === RequestStatus::CLOSED) {
132
            if ($request->getWasCreated()) {
133
                $statusSymbol = self::STATUS_SYMBOL_ACCEPTED;
134
            }
135
            else {
136
                $statusSymbol = self::STATUS_SYMBOL_REJECTED;
137
            }
138
        }
139
140
        $this->setHtmlTitle($statusSymbol . ' #' . $request->getId());
141
    }
142
143
    /**
144
     * Sets up data unrelated to the request, such as the email template information
145
     *
146
     * @param PdoDatabase $database
147
     */
148
    protected function setupGeneralData(PdoDatabase $database)
149
    {
150
        $this->assign('createAccountReason', 'Requested account at [[WP:ACC]], request #');
151
152
        // FIXME: domains
153
        /** @var Domain $domain */
154
        $domain = Domain::getById(1, $database);
155
        $this->assign('defaultRequestState', RequestQueue::getDefaultQueue($database, 1)->getApiName());
156
        $this->assign('activeRequestQueues', RequestQueue::getEnabledQueues($database));
157
158
        /** @var EmailTemplate $createdTemplate */
159
        $createdTemplate = EmailTemplate::getById($domain->getDefaultClose(), $database);
160
161
        $this->assign('createdHasJsQuestion', $createdTemplate->getJsquestion() != '');
162
        $this->assign('createdId', $createdTemplate->getId());
163
        $this->assign('createdName', $createdTemplate->getName());
164
165
        $createReasons = EmailTemplate::getActiveTemplates(EmailTemplate::ACTION_CREATED, $database);
166
        $this->assign("createReasons", $createReasons);
167
        $declineReasons = EmailTemplate::getActiveTemplates(EmailTemplate::ACTION_NOT_CREATED, $database);
168
        $this->assign("declineReasons", $declineReasons);
169
170
        $allCreateReasons = EmailTemplate::getAllActiveTemplates(EmailTemplate::ACTION_CREATED, $database);
171
        $this->assign("allCreateReasons", $allCreateReasons);
172
        $allDeclineReasons = EmailTemplate::getAllActiveTemplates(EmailTemplate::ACTION_NOT_CREATED, $database);
173
        $this->assign("allDeclineReasons", $allDeclineReasons);
174
        $allOtherReasons = EmailTemplate::getAllActiveTemplates(false, $database);
175
        $this->assign("allOtherReasons", $allOtherReasons);
176
    }
177
178
    private function setupLogData(Request $request, PdoDatabase $database)
179
    {
180
        $currentUser = User::getCurrent($database);
181
182
        $logs = LogHelper::getRequestLogsWithComments($request->getId(), $database, $this->getSecurityManager());
183
        $requestLogs = array();
184
185
        /** @var User[] $nameCache */
186
        $nameCache = array();
187
188
        $editableComments = $this->barrierTest('editOthers', $currentUser, PageEditComment::class);
189
190
        $canFlag = $this->barrierTest(RoleConfiguration::MAIN, $currentUser, PageFlagComment::class);
191
        $canUnflag = $this->barrierTest('unflag', $currentUser, PageFlagComment::class);
192
193
        /** @var Log|Comment $entry */
194
        foreach ($logs as $entry) {
195
            // both log and comment have a 'user' field
196
            if (!array_key_exists($entry->getUser(), $nameCache)) {
197
                $entryUser = User::getById($entry->getUser(), $database);
198
                $nameCache[$entry->getUser()] = $entryUser;
199
            }
200
201
            if ($entry instanceof Comment) {
202
                $requestLogs[] = array(
203
                    'type'          => 'comment',
204
                    'security'      => $entry->getVisibility(),
205
                    'user'          => $entry->getVisibility() == 'requester' ? $request->getName() : $nameCache[$entry->getUser()]->getUsername(),
206
                    'userid'        => $entry->getUser() == -1 ? null : $entry->getUser(),
207
                    'entry'         => null,
208
                    'time'          => $entry->getTime(),
209
                    'canedit'       => ($editableComments || $entry->getUser() == $currentUser->getId()),
210
                    'id'            => $entry->getId(),
211
                    'comment'       => $entry->getComment(),
212
                    'flagged'       => $entry->getFlagged(),
213
                    'canflag'       => $canFlag && (!$entry->getFlagged() || ($entry->getFlagged() && $canUnflag)),
214
                    'updateversion' => $entry->getUpdateVersion(),
215
                    'edited'        => $entry->getEdited()
216
                );
217
            }
218
219
            if ($entry instanceof Log) {
220
                $invalidUserId = $entry->getUser() === -1 || $entry->getUser() === 0;
221
                $entryUser = $invalidUserId ? User::getCommunity() : $nameCache[$entry->getUser()];
222
223
                $entryComment = $entry->getComment();
224
225
                if ($entry->getAction() === 'JobIssueRequest' || $entry->getAction() === 'JobCompletedRequest') {
226
                    $data = unserialize($entry->getComment());
0 ignored issues
show
Bug introduced by
It seems like $entry->getComment() can also be of type null; however, parameter $data of unserialize() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

226
                    $data = unserialize(/** @scrutinizer ignore-type */ $entry->getComment());
Loading history...
227
                    /** @var JobQueue $job */
228
                    $job = JobQueue::getById($data['job'], $database);
229
                    $requestLogs[] = array(
230
                        'type'     => 'joblog',
231
                        'security' => 'user',
232
                        'userid'   => $entry->getUser() == -1 ? null : $entry->getUser(),
233
                        'user'     => $entryUser->getUsername(),
234
                        'entry'    => LogHelper::getLogDescription($entry),
235
                        'time'     => $entry->getTimestamp(),
236
                        'canedit'  => false,
237
                        'id'       => $entry->getId(),
238
                        'jobId'    => $job->getId(),
239
                        'jobDesc'  => JobQueue::getTaskDescriptions()[$job->getTask()],
240
                    );
241
                }
242
                else {
243
                    $requestLogs[] = array(
244
                        'type'     => 'log',
245
                        'security' => 'user',
246
                        'userid'   => $entry->getUser() == -1 ? null : $entry->getUser(),
247
                        'user'     => $entryUser->getUsername(),
248
                        'entry'    => LogHelper::getLogDescription($entry),
249
                        'time'     => $entry->getTimestamp(),
250
                        'canedit'  => false,
251
                        'id'       => $entry->getId(),
252
                        'comment'  => $entryComment,
253
                    );
254
                }
255
            }
256
        }
257
258
        $this->addJs("/api.php?action=users&targetVariable=typeaheaddata");
259
260
        $this->assign("requestLogs", $requestLogs);
261
    }
262
263
    /**
264
     * @param Request $request
265
     */
266
    protected function setupUsernameData(Request $request)
267
    {
268
        $blacklistData = $this->getBlacklistHelper()->isBlacklisted($request->getName());
269
270
        $this->assign('requestIsBlacklisted', $blacklistData !== false);
271
        $this->assign('requestBlacklist', $blacklistData);
272
273
        try {
274
            $spoofs = $this->getAntiSpoofProvider()->getSpoofs($request->getName());
275
        }
276
        catch (Exception $ex) {
277
            $spoofs = $ex->getMessage();
278
        }
279
280
        $this->assign("spoofs", $spoofs);
281
    }
282
283
    private function setupCreationTypes(User $user)
284
    {
285
        $this->assign('allowWelcomeSkip', false);
286
        $this->assign('forceWelcomeSkip', false);
287
288
        $oauth = new OAuthUserHelper($user, $this->getDatabase(), $this->getOAuthProtocolHelper(), $this->getSiteConfiguration());
289
290
        if ($user->getWelcomeTemplate() != 0) {
291
            $this->assign('allowWelcomeSkip', true);
292
293
            if (!$oauth->canWelcome()) {
294
                $this->assign('forceWelcomeSkip', true);
295
            }
296
        }
297
298
        // test credentials
299
        $canManualCreate = $this->barrierTest(User::CREATION_MANUAL, $user, 'RequestCreation');
300
        $canOauthCreate = $this->barrierTest(User::CREATION_OAUTH, $user, 'RequestCreation');
301
        $canBotCreate = $this->barrierTest(User::CREATION_BOT, $user, 'RequestCreation');
302
303
        $this->assign('canManualCreate', $canManualCreate);
304
        $this->assign('canOauthCreate', $canOauthCreate);
305
        $this->assign('canBotCreate', $canBotCreate);
306
307
        // show/hide the type radio buttons
308
        $creationHasChoice = count(array_filter([$canManualCreate, $canOauthCreate, $canBotCreate])) > 1;
309
310
        if (!$this->barrierTest($user->getCreationMode(), $user, 'RequestCreation')) {
311
            // user is not allowed to use their default. Force a choice.
312
            $creationHasChoice = true;
313
        }
314
315
        $this->assign('creationHasChoice', $creationHasChoice);
316
317
        // determine problems in creation types
318
        $this->assign('botProblem', false);
319
        if ($canBotCreate && $this->getSiteConfiguration()->getCreationBotPassword() === null) {
0 ignored issues
show
introduced by
The condition $this->getSiteConfigurat...nBotPassword() === null is always false.
Loading history...
320
            $this->assign('botProblem', true);
321
        }
322
323
        $this->assign('oauthProblem', false);
324
        if ($canOauthCreate && !$oauth->canCreateAccount()) {
325
            $this->assign('oauthProblem', true);
326
        }
327
    }
328
}
329