Failed Conditions
Pull Request — newinternal-releasecandidate (#544)
by Simon
13:56 queued 04:02
created

PageViewRequest::setupCreationTypes()   B

Complexity

Conditions 8
Paths 24

Size

Total Lines 43
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 23
c 0
b 0
f 0
dl 0
loc 43
rs 8.4444
cc 8
nc 24
nop 1
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 = '&#x2610';
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
        if ($allowedPrivateData) {
77
            $this->setTemplate('view-request/main-with-data.tpl');
78
            $this->setupPrivateData($request, $currentUser, $this->getSiteConfiguration(), $database);
79
80
            $this->assign('canSetBan', $this->barrierTest('set', $currentUser, PageBan::class));
81
            $this->assign('canSeeCheckuserData', $this->barrierTest('seeUserAgentData', $currentUser, 'RequestData'));
82
83
            if ($this->barrierTest('seeUserAgentData', $currentUser, 'RequestData')) {
84
                $this->setTemplate('view-request/main-with-checkuser-data.tpl');
85
                $this->setupCheckUserData($request);
86
            }
87
        }
88
        else {
89
            $this->setTemplate('view-request/main.tpl');
90
        }
91
    }
92
93
    /**
94
     * @param Request $request
95
     */
96
    protected function setupTitle(Request $request)
97
    {
98
        $statusSymbol = self::STATUS_SYMBOL_OPEN;
99
        if ($request->getStatus() === 'Closed') {
100
            if ($request->getWasCreated()) {
101
                $statusSymbol = self::STATUS_SYMBOL_ACCEPTED;
102
            }
103
            else {
104
                $statusSymbol = self::STATUS_SYMBOL_REJECTED;
105
            }
106
        }
107
108
        $this->setHtmlTitle($statusSymbol . ' #' . $request->getId());
109
    }
110
111
    /**
112
     * Sets up data unrelated to the request, such as the email template information
113
     *
114
     * @param PdoDatabase $database
115
     */
116
    protected function setupGeneralData(PdoDatabase $database)
117
    {
118
        $config = $this->getSiteConfiguration();
119
120
        $this->assign('createAccountReason', 'Requested account at [[WP:ACC]], request #');
121
122
        $this->assign('defaultRequestState', $config->getDefaultRequestStateKey());
123
124
        $this->assign('requestStates', $config->getRequestStates());
125
126
        /** @var EmailTemplate $createdTemplate */
127
        $createdTemplate = EmailTemplate::getById($config->getDefaultCreatedTemplateId(), $database);
128
129
        $this->assign('createdHasJsQuestion', $createdTemplate->getJsquestion() != '');
130
        $this->assign('createdJsQuestion', $createdTemplate->getJsquestion());
131
        $this->assign('createdId', $createdTemplate->getId());
132
        $this->assign('createdName', $createdTemplate->getName());
133
134
        $createReasons = EmailTemplate::getActiveTemplates(EmailTemplate::CREATED, $database);
135
        $this->assign("createReasons", $createReasons);
136
        $declineReasons = EmailTemplate::getActiveTemplates(EmailTemplate::NOT_CREATED, $database);
137
        $this->assign("declineReasons", $declineReasons);
138
139
        $allCreateReasons = EmailTemplate::getAllActiveTemplates(EmailTemplate::CREATED, $database);
140
        $this->assign("allCreateReasons", $allCreateReasons);
141
        $allDeclineReasons = EmailTemplate::getAllActiveTemplates(EmailTemplate::NOT_CREATED, $database);
142
        $this->assign("allDeclineReasons", $allDeclineReasons);
143
        $allOtherReasons = EmailTemplate::getAllActiveTemplates(false, $database);
144
        $this->assign("allOtherReasons", $allOtherReasons);
145
    }
146
147
    private function setupLogData(Request $request, PdoDatabase $database)
148
    {
149
        $currentUser = User::getCurrent($database);
150
151
        $logs = LogHelper::getRequestLogsWithComments($request->getId(), $database, $this->getSecurityManager());
152
        $requestLogs = array();
153
154
        if (trim($request->getComment()) !== "") {
155
            $requestLogs[] = array(
156
                'type'     => 'comment',
157
                'security' => 'user',
158
                'userid'   => null,
159
                'user'     => $request->getName(),
160
                'entry'    => null,
161
                'time'     => $request->getDate(),
162
                'canedit'  => false,
163
                'id'       => $request->getId(),
164
                'comment'  => $request->getComment(),
165
            );
166
        }
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\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'     => $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) {
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