PageViewRequest::setupLogData()   F
last analyzed

Complexity

Conditions 23
Paths 13091

Size

Total Lines 104
Code Lines 68

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 68
c 0
b 0
f 0
dl 0
loc 104
rs 0
cc 23
nc 13091
nop 3

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
 * ACC Development Team. Please see team.json for a list of contributors.     *
5
 *                                                                            *
6
 * This is free and unencumbered software released into the public domain.    *
7
 * Please see LICENSE.md for the full licencing statement.                    *
8
 ******************************************************************************/
9
10
namespace Waca\Pages;
11
12
use Exception;
13
use DateTime;
14
use Waca\DataObjects\Comment;
15
use Waca\DataObjects\Domain;
16
use Waca\DataObjects\EmailTemplate;
17
use Waca\DataObjects\JobQueue;
18
use Waca\DataObjects\Log;
19
use Waca\DataObjects\Request;
20
use Waca\DataObjects\RequestQueue;
21
use Waca\DataObjects\User;
22
use Waca\Exceptions\ApplicationLogicException;
23
use Waca\Fragments\RequestData;
24
use Waca\Helpers\LogHelper;
25
use Waca\Helpers\OAuthUserHelper;
26
use Waca\Helpers\PreferenceManager;
27
use Waca\Pages\RequestAction\PageManuallyConfirm;
28
use Waca\PdoDatabase;
29
use Waca\Security\RoleConfigurationBase;
30
use Waca\RequestStatus;
31
use Waca\Tasks\InternalPageBase;
32
use Waca\WebRequest;
33
34
class PageViewRequest extends InternalPageBase
35
{
36
    use RequestData;
37
38
    const STATUS_SYMBOL_OPEN = '&#927';
39
    const STATUS_SYMBOL_ACCEPTED = '&#x2611';
40
    const STATUS_SYMBOL_REJECTED = '&#x2612';
41
42
    /**
43
     * Main function for this page, when no specific actions are called.
44
     * @throws ApplicationLogicException
45
     */
46
    protected function main()
47
    {
48
        // set up csrf protection
49
        $this->assignCSRFToken();
50
51
        // get some useful objects
52
        $database = $this->getDatabase();
53
        $request = $this->getRequest($database, WebRequest::getInt('id'));
54
        $config = $this->getSiteConfiguration();
55
        $currentUser = User::getCurrent($database);
56
57
        // FIXME: domains!
58
        /** @var Domain $domain */
59
        $domain = Domain::getById(1, $this->getDatabase());
60
        $this->assign('mediawikiScriptPath', $domain->getWikiArticlePath());
61
62
        // Shows a page if the email is not confirmed.
63
        if ($request->getEmailConfirm() !== 'Confirmed') {
64
            // Show a banner if the user can manually confirm the request
65
            $viewConfirm = $this->barrierTest(RoleConfigurationBase::MAIN, $currentUser, PageManuallyConfirm::class);
66
67
            // If the request is purged, there's nothing to confirm!
68
            if ($request->getEmail() === $this->getSiteConfiguration()->getDataClearEmail()) {
69
                $viewConfirm = false;
70
            }
71
72
            // Render
73
            $this->setTemplate("view-request/not-confirmed.tpl");
74
            $this->assign("requestId", $request->getId());
75
            $this->assign("requestVersion", $request->getUpdateVersion());
76
            $this->assign('canViewConfirmButton', $viewConfirm);
77
78
            // Make sure to return, to prevent the leaking of other information.
79
            return;
80
        }
81
82
        $this->setupBasicData($request, $config);
83
84
        $this->setupUsernameData($request);
85
86
        $this->setupTitle($request);
87
88
        $this->setupReservationDetails($request->getReserved(), $database, $currentUser);
89
        $this->setupGeneralData($database);
90
91
        $this->assign('requestDataCleared', false);
92
        if ($request->getEmail() === $this->getSiteConfiguration()->getDataClearEmail()) {
93
            $this->assign('requestDataCleared', true);
94
        }
95
96
        $allowedPrivateData = $this->isAllowedPrivateData($request, $currentUser);
97
98
        $this->setupCreationTypes($currentUser);
99
100
        $this->setupLogData($request, $database, $allowedPrivateData);
101
102
        $this->addJs("/api.php?action=templates&targetVariable=templateconfirms");
103
104
        $this->assign('showRevealLink', false);
105
        if ($request->getReserved() === $currentUser->getId() ||
106
            $this->barrierTest('alwaysSeeHash', $currentUser, 'RequestData')
107
        ) {
108
            $this->assign('showRevealLink', true);
109
            $this->assign('revealHash', $request->getRevealHash());
110
        }
111
112
        $this->assign('canSeeRelatedRequests', false);
113
        if ($allowedPrivateData || $this->barrierTest('seeRelatedRequests', $currentUser, 'RequestData')) {
114
            $this->setupRelatedRequests($request, $config, $database);
115
        }
116
117
        $this->assign('canCreateLocalAccount', $this->barrierTest('createLocalAccount', $currentUser, 'RequestData'));
118
119
        $closureDate = $request->getClosureDate();
120
        $date = new DateTime();
121
        $date->modify("-7 days");
122
        if ($request->getStatus() == "Closed" && $closureDate < $date) {
123
            $this->assign('isOldRequest', true);
124
        }
125
        $this->assign('canResetOldRequest', $this->barrierTest('reopenOldRequest', $currentUser, 'RequestData'));
126
        $this->assign('canResetPurgedRequest', $this->barrierTest('reopenClearedRequest', $currentUser, 'RequestData'));
127
128
        $this->assign('requestEmailSent', $request->getEmailSent());
129
130
        if ($allowedPrivateData) {
131
            $this->setTemplate('view-request/main-with-data.tpl');
132
            $this->setupPrivateData($request, $config);
133
            $this->assign('canSetBan', $this->barrierTest('set', $currentUser, PageBan::class));
134
            $this->assign('canSeeCheckuserData', $this->barrierTest('seeUserAgentData', $currentUser, 'RequestData'));
135
136
            if ($this->barrierTest('seeUserAgentData', $currentUser, 'RequestData')) {
137
                $this->setTemplate('view-request/main-with-checkuser-data.tpl');
138
                $this->setupCheckUserData($request);
139
            }
140
        }
141
        else {
142
            $this->setTemplate('view-request/main.tpl');
143
        }
144
    }
145
146
    /**
147
     * @param Request $request
148
     */
149
    protected function setupTitle(Request $request)
150
    {
151
        $statusSymbol = self::STATUS_SYMBOL_OPEN;
152
        if ($request->getStatus() === RequestStatus::CLOSED) {
153
            if ($request->getWasCreated()) {
154
                $statusSymbol = self::STATUS_SYMBOL_ACCEPTED;
155
            }
156
            else {
157
                $statusSymbol = self::STATUS_SYMBOL_REJECTED;
158
            }
159
        }
160
161
        $this->setHtmlTitle($statusSymbol . ' #' . $request->getId());
162
    }
163
164
    /**
165
     * Sets up data unrelated to the request, such as the email template information
166
     *
167
     * @param PdoDatabase $database
168
     */
169
    protected function setupGeneralData(PdoDatabase $database)
170
    {
171
        $this->assign('createAccountReason', 'Requested account at [[WP:ACC]], request #');
172
173
        // FIXME: domains
174
        /** @var Domain $domain */
175
        $domain = Domain::getById(1, $database);
176
        $this->assign('defaultRequestState', RequestQueue::getDefaultQueue($database, 1)->getApiName());
177
        $this->assign('activeRequestQueues', RequestQueue::getEnabledQueues($database));
178
179
        /** @var EmailTemplate $createdTemplate */
180
        $createdTemplate = EmailTemplate::getById($domain->getDefaultClose(), $database);
181
182
        $this->assign('createdHasJsQuestion', $createdTemplate->getJsquestion() != '');
183
        $this->assign('createdId', $createdTemplate->getId());
184
        $this->assign('createdName', $createdTemplate->getName());
185
186
        $preferenceManager = PreferenceManager::getForCurrent($database);
187
        $skipJsAborts = $preferenceManager->getPreference(PreferenceManager::PREF_SKIP_JS_ABORT);
188
        $preferredCreationMode = (int)$preferenceManager->getPreference(PreferenceManager::PREF_CREATION_MODE);
189
        $this->assign('skipJsAborts', $skipJsAborts);
190
        $this->assign('preferredCreationMode', $preferredCreationMode);
191
192
        $createReasons = EmailTemplate::getActiveNonpreloadTemplates(
193
            EmailTemplate::ACTION_CREATED,
194
            $database,
195
            $domain->getId(),
196
            $domain->getDefaultClose());
197
        $this->assign("createReasons", $createReasons);
198
199
        $declineReasons = EmailTemplate::getActiveNonpreloadTemplates(
200
            EmailTemplate::ACTION_NOT_CREATED,
201
            $database,
202
            $domain->getId());
203
        $this->assign("declineReasons", $declineReasons);
204
205
        $allCreateReasons = EmailTemplate::getAllActiveTemplates(
206
            EmailTemplate::ACTION_CREATED,
207
            $database,
208
            $domain->getId());
209
        $this->assign("allCreateReasons", $allCreateReasons);
210
211
        $allDeclineReasons = EmailTemplate::getAllActiveTemplates(
212
            EmailTemplate::ACTION_NOT_CREATED,
213
            $database,
214
            $domain->getId());
215
        $this->assign("allDeclineReasons", $allDeclineReasons);
216
217
        $allOtherReasons = EmailTemplate::getAllActiveTemplates(
218
            false,
219
            $database,
220
            $domain->getId());
221
        $this->assign("allOtherReasons", $allOtherReasons);
222
    }
223
224
    private function setupLogData(Request $request, PdoDatabase $database, bool $allowedPrivateData)
225
    {
226
        $currentUser = User::getCurrent($database);
227
228
        $logs = LogHelper::getRequestLogsWithComments($request->getId(), $database, $this->getSecurityManager());
229
        $requestLogs = array();
230
231
        /** @var User[] $nameCache */
232
        $nameCache = array();
233
234
        $editableComments = $this->barrierTest('editOthers', $currentUser, PageEditComment::class);
235
236
        $canFlag = $this->barrierTest(RoleConfigurationBase::MAIN, $currentUser, PageFlagComment::class);
237
        $canUnflag = $this->barrierTest('unflag', $currentUser, PageFlagComment::class);
238
239
        /** @var Log|Comment $entry */
240
        foreach ($logs as $entry) {
241
            // both log and comment have a 'user' field
242
            if (!array_key_exists($entry->getUser(), $nameCache)) {
243
                $entryUser = User::getById($entry->getUser(), $database);
244
                $nameCache[$entry->getUser()] = $entryUser;
245
            }
246
247
            if ($entry instanceof Comment) {
248
                // Determine if the comment contains private information.
249
                // Private defined as flagged or restricted visibility, but only when the user isn't allowed
250
                // to see private data
251
                $commentIsRestricted =
252
                    ($entry->getFlagged()
253
                        || $entry->getVisibility() == 'admin' || $entry->getVisibility() == 'checkuser')
254
                    && !$allowedPrivateData;
255
256
                // Only allow comment editing if the user is able to edit comments or this is the user's own comment,
257
                // but only when they're allowed to see the comment itself.
258
                $commentIsEditable = ($editableComments || $entry->getUser() == $currentUser->getId())
259
                    && !$commentIsRestricted;
260
261
                // Flagging/unflagging can only be done if you can see the comment
262
                $canFlagThisComment = $canFlag
263
                    && (
264
                        (!$entry->getFlagged() && !$commentIsRestricted)
265
                        || ($entry->getFlagged() && $canUnflag && $commentIsEditable)
266
                    );
267
268
                $requestLogs[] = array(
269
                    'type'          => 'comment',
270
                    'security'      => $entry->getVisibility(),
271
                    'user'          => $entry->getVisibility() == 'requester' ? $request->getName() : $nameCache[$entry->getUser()]->getUsername(),
272
                    'userid'        => $entry->getUser() == -1 ? null : $entry->getUser(),
273
                    'entry'         => null,
274
                    'time'          => $entry->getTime(),
275
                    'canedit'       => $commentIsEditable,
276
                    'id'            => $entry->getId(),
277
                    'comment'       => $entry->getComment(),
278
                    'flagged'       => $entry->getFlagged(),
279
                    'canflag'       => $canFlagThisComment,
280
                    'updateversion' => $entry->getUpdateVersion(),
281
                    'edited'        => $entry->getEdited(),
282
                    'hidden'        => $commentIsRestricted
283
                );
284
            }
285
286
            if ($entry instanceof Log) {
287
                $invalidUserId = $entry->getUser() === -1 || $entry->getUser() === 0;
288
                $entryUser = $invalidUserId ? User::getCommunity() : $nameCache[$entry->getUser()];
289
290
                $entryComment = $entry->getComment();
291
292
                if ($entry->getAction() === 'JobIssueRequest' || $entry->getAction() === 'JobCompletedRequest') {
293
                    $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

293
                    $data = unserialize(/** @scrutinizer ignore-type */ $entry->getComment());
Loading history...
294
                    /** @var JobQueue $job */
295
                    $job = JobQueue::getById($data['job'], $database);
296
                    $requestLogs[] = array(
297
                        'type'     => 'joblog',
298
                        'security' => 'user',
299
                        'userid'   => $entry->getUser() == -1 ? null : $entry->getUser(),
300
                        'user'     => $entryUser->getUsername(),
301
                        'entry'    => LogHelper::getLogDescription($entry),
302
                        'time'     => $entry->getTimestamp(),
303
                        'canedit'  => false,
304
                        'id'       => $entry->getId(),
305
                        'jobId'    => $job->getId(),
306
                        'jobDesc'  => JobQueue::getTaskDescriptions()[$job->getTask()],
307
                    );
308
                }
309
                else {
310
                    $requestLogs[] = array(
311
                        'type'     => 'log',
312
                        'security' => 'user',
313
                        'userid'   => $entry->getUser() == -1 ? null : $entry->getUser(),
314
                        'user'     => $entryUser->getUsername(),
315
                        'entry'    => LogHelper::getLogDescription($entry),
316
                        'time'     => $entry->getTimestamp(),
317
                        'canedit'  => false,
318
                        'id'       => $entry->getId(),
319
                        'comment'  => $entryComment,
320
                    );
321
                }
322
            }
323
        }
324
325
        $this->addJs("/api.php?action=users&targetVariable=typeaheaddata");
326
327
        $this->assign("requestLogs", $requestLogs);
328
    }
329
330
    /**
331
     * @param Request $request
332
     */
333
    protected function setupUsernameData(Request $request)
334
    {
335
        $blacklistData = $this->getBlacklistHelper()->isBlacklisted($request->getName());
336
337
        $this->assign('requestIsBlacklisted', $blacklistData !== false);
338
        $this->assign('requestBlacklist', $blacklistData);
339
340
        try {
341
            $spoofs = $this->getAntiSpoofProvider()->getSpoofs($request->getName());
342
        }
343
        catch (Exception $ex) {
344
            $spoofs = $ex->getMessage();
345
        }
346
347
        $this->assign("spoofs", $spoofs);
348
    }
349
350
    private function setupCreationTypes(User $user)
351
    {
352
        $this->assign('allowWelcomeSkip', false);
353
        $this->assign('forceWelcomeSkip', false);
354
355
        $database = $this->getDatabase();
356
        $preferenceManager = PreferenceManager::getForCurrent($database);
357
358
        $oauth = new OAuthUserHelper($user, $database, $this->getOAuthProtocolHelper(), $this->getSiteConfiguration());
359
360
        $welcomeTemplate = $preferenceManager->getPreference(PreferenceManager::PREF_WELCOMETEMPLATE);
361
362
        if ($welcomeTemplate != null) {
363
            $this->assign('allowWelcomeSkip', true);
364
365
            if (!$oauth->canWelcome()) {
366
                $this->assign('forceWelcomeSkip', true);
367
            }
368
        }
369
370
        // test credentials
371
        $canManualCreate = $this->barrierTest(PreferenceManager::CREATION_MANUAL, $user, 'RequestCreation');
372
        $canOauthCreate = $this->barrierTest(PreferenceManager::CREATION_OAUTH, $user, 'RequestCreation');
373
        $canBotCreate = $this->barrierTest(PreferenceManager::CREATION_BOT, $user, 'RequestCreation');
374
375
        $this->assign('canManualCreate', $canManualCreate);
376
        $this->assign('canOauthCreate', $canOauthCreate);
377
        $this->assign('canBotCreate', $canBotCreate);
378
379
        // show/hide the type radio buttons
380
        $creationHasChoice = count(array_filter([$canManualCreate, $canOauthCreate, $canBotCreate])) > 1;
381
382
        $creationModePreference = $preferenceManager->getPreference(PreferenceManager::PREF_CREATION_MODE);
383
        if (!$this->barrierTest($creationModePreference, $user, 'RequestCreation')) {
384
            // user is not allowed to use their default. Force a choice.
385
            $creationHasChoice = true;
386
        }
387
388
        $this->assign('creationHasChoice', $creationHasChoice);
389
390
        // determine problems in creation types
391
        $this->assign('botProblem', false);
392
        if ($canBotCreate && $this->getSiteConfiguration()->getCreationBotPassword() === null) {
0 ignored issues
show
introduced by
The condition $this->getSiteConfigurat...nBotPassword() === null is always false.
Loading history...
393
            $this->assign('botProblem', true);
394
        }
395
396
        $this->assign('oauthProblem', false);
397
        if ($canOauthCreate && !$oauth->canCreateAccount()) {
398
            $this->assign('oauthProblem', true);
399
        }
400
    }
401
}
402