Failed Conditions
Push — newinternal-releasecandidate ( 327c61...a30d14 )
by Simon
15:28 queued 05:26
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
        $this->addJs("/api.php?action=templates&targetVariable=templateconfirms");
77
78
        if ($allowedPrivateData) {
79
            $this->setTemplate('view-request/main-with-data.tpl');
80
            $this->setupPrivateData($request, $currentUser, $this->getSiteConfiguration(), $database);
81
82
            $this->assign('canSetBan', $this->barrierTest('set', $currentUser, PageBan::class));
83
            $this->assign('canSeeCheckuserData', $this->barrierTest('seeUserAgentData', $currentUser, 'RequestData'));
84
85
            if ($this->barrierTest('seeUserAgentData', $currentUser, 'RequestData')) {
86
                $this->setTemplate('view-request/main-with-checkuser-data.tpl');
87
                $this->setupCheckUserData($request);
88
            }
89
        }
90
        else {
91
            $this->setTemplate('view-request/main.tpl');
92
        }
93
    }
94
95
    /**
96
     * @param Request $request
97
     */
98
    protected function setupTitle(Request $request)
99
    {
100
        $statusSymbol = self::STATUS_SYMBOL_OPEN;
101
        if ($request->getStatus() === 'Closed') {
102
            if ($request->getWasCreated()) {
103
                $statusSymbol = self::STATUS_SYMBOL_ACCEPTED;
104
            }
105
            else {
106
                $statusSymbol = self::STATUS_SYMBOL_REJECTED;
107
            }
108
        }
109
110
        $this->setHtmlTitle($statusSymbol . ' #' . $request->getId());
111
    }
112
113
    /**
114
     * Sets up data unrelated to the request, such as the email template information
115
     *
116
     * @param PdoDatabase $database
117
     */
118
    protected function setupGeneralData(PdoDatabase $database)
119
    {
120
        $config = $this->getSiteConfiguration();
121
122
        $this->assign('createAccountReason', 'Requested account at [[WP:ACC]], request #');
123
124
        $this->assign('defaultRequestState', $config->getDefaultRequestStateKey());
125
126
        $this->assign('requestStates', $config->getRequestStates());
127
128
        /** @var EmailTemplate $createdTemplate */
129
        $createdTemplate = EmailTemplate::getById($config->getDefaultCreatedTemplateId(), $database);
130
131
        $this->assign('createdHasJsQuestion', $createdTemplate->getJsquestion() != '');
132
        $this->assign('createdId', $createdTemplate->getId());
133
        $this->assign('createdName', $createdTemplate->getName());
134
135
        $createReasons = EmailTemplate::getActiveTemplates(EmailTemplate::CREATED, $database);
136
        $this->assign("createReasons", $createReasons);
137
        $declineReasons = EmailTemplate::getActiveTemplates(EmailTemplate::NOT_CREATED, $database);
138
        $this->assign("declineReasons", $declineReasons);
139
140
        $allCreateReasons = EmailTemplate::getAllActiveTemplates(EmailTemplate::CREATED, $database);
141
        $this->assign("allCreateReasons", $allCreateReasons);
142
        $allDeclineReasons = EmailTemplate::getAllActiveTemplates(EmailTemplate::NOT_CREATED, $database);
143
        $this->assign("allDeclineReasons", $allDeclineReasons);
144
        $allOtherReasons = EmailTemplate::getAllActiveTemplates(false, $database);
145
        $this->assign("allOtherReasons", $allOtherReasons);
146
    }
147
148
    private function setupLogData(Request $request, PdoDatabase $database)
149
    {
150
        $currentUser = User::getCurrent($database);
151
152
        $logs = LogHelper::getRequestLogsWithComments($request->getId(), $database, $this->getSecurityManager());
153
        $requestLogs = array();
154
155
        if (trim($request->getComment()) !== "") {
156
            $requestLogs[] = array(
157
                'type'     => 'comment',
158
                'security' => 'user',
159
                'userid'   => null,
160
                'user'     => $request->getName(),
161
                'entry'    => null,
162
                'time'     => $request->getDate(),
163
                'canedit'  => false,
164
                'id'       => $request->getId(),
165
                'comment'  => $request->getComment(),
166
            );
167
        }
168
169
        /** @var User[] $nameCache */
170
        $nameCache = array();
171
172
        $editableComments = $this->barrierTest('editOthers', $currentUser, PageEditComment::class);
173
174
        /** @var Log|Comment $entry */
175
        foreach ($logs as $entry) {
176
            // both log and comment have a 'user' field
177
            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

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