Completed
Pull Request — newinternal-releasecandidate (#559)
by Simon
16:15 queued 12:01
created

PageViewRequest   A

Complexity

Total Complexity 36

Size/Duplication

Total Lines 270
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 4
Bugs 0 Features 0
Metric Value
wmc 36
eloc 147
c 4
b 0
f 0
dl 0
loc 270
ccs 0
cts 184
cp 0
rs 9.52

6 Methods

Rating   Name   Duplication   Size   Complexity  
B main() 0 63 8
A setupTitle() 0 13 3
A setupGeneralData() 0 28 1
B setupCreationTypes() 0 43 8
A setupUsernameData() 0 15 2
D setupLogData() 0 75 14
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
        $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
        if ($allowedPrivateData) {
87
            $this->setTemplate('view-request/main-with-data.tpl');
88
            $this->setupPrivateData($request, $currentUser, $this->getSiteConfiguration(), $database);
89
90
            $this->assign('canSetBan', $this->barrierTest('set', $currentUser, PageBan::class));
91
            $this->assign('canSeeCheckuserData', $this->barrierTest('seeUserAgentData', $currentUser, 'RequestData'));
92
93
            if ($this->barrierTest('seeUserAgentData', $currentUser, 'RequestData')) {
94
                $this->setTemplate('view-request/main-with-checkuser-data.tpl');
95
                $this->setupCheckUserData($request);
96
            }
97
        }
98
        else {
99
            $this->setTemplate('view-request/main.tpl');
100
        }
101
    }
102
103
    /**
104
     * @param Request $request
105
     */
106
    protected function setupTitle(Request $request)
107
    {
108
        $statusSymbol = self::STATUS_SYMBOL_OPEN;
109
        if ($request->getStatus() === 'Closed') {
110
            if ($request->getWasCreated()) {
111
                $statusSymbol = self::STATUS_SYMBOL_ACCEPTED;
112
            }
113
            else {
114
                $statusSymbol = self::STATUS_SYMBOL_REJECTED;
115
            }
116
        }
117
118
        $this->setHtmlTitle($statusSymbol . ' #' . $request->getId());
119
    }
120
121
    /**
122
     * Sets up data unrelated to the request, such as the email template information
123
     *
124
     * @param PdoDatabase $database
125
     */
126
    protected function setupGeneralData(PdoDatabase $database)
127
    {
128
        $config = $this->getSiteConfiguration();
129
130
        $this->assign('createAccountReason', 'Requested account at [[WP:ACC]], request #');
131
132
        $this->assign('defaultRequestState', $config->getDefaultRequestStateKey());
133
134
        $this->assign('requestStates', $config->getRequestStates());
135
136
        /** @var EmailTemplate $createdTemplate */
137
        $createdTemplate = EmailTemplate::getById($config->getDefaultCreatedTemplateId(), $database);
138
139
        $this->assign('createdHasJsQuestion', $createdTemplate->getJsquestion() != '');
140
        $this->assign('createdId', $createdTemplate->getId());
141
        $this->assign('createdName', $createdTemplate->getName());
142
143
        $createReasons = EmailTemplate::getActiveTemplates(EmailTemplate::CREATED, $database);
144
        $this->assign("createReasons", $createReasons);
145
        $declineReasons = EmailTemplate::getActiveTemplates(EmailTemplate::NOT_CREATED, $database);
146
        $this->assign("declineReasons", $declineReasons);
147
148
        $allCreateReasons = EmailTemplate::getAllActiveTemplates(EmailTemplate::CREATED, $database);
149
        $this->assign("allCreateReasons", $allCreateReasons);
150
        $allDeclineReasons = EmailTemplate::getAllActiveTemplates(EmailTemplate::NOT_CREATED, $database);
151
        $this->assign("allDeclineReasons", $allDeclineReasons);
152
        $allOtherReasons = EmailTemplate::getAllActiveTemplates(false, $database);
153
        $this->assign("allOtherReasons", $allOtherReasons);
154
    }
155
156
    private function setupLogData(Request $request, PdoDatabase $database)
157
    {
158
        $currentUser = User::getCurrent($database);
159
160
        $logs = LogHelper::getRequestLogsWithComments($request->getId(), $database, $this->getSecurityManager());
161
        $requestLogs = array();
162
163
        /** @var User[] $nameCache */
164
        $nameCache = array();
165
166
        $editableComments = $this->barrierTest('editOthers', $currentUser, PageEditComment::class);
167
168
        /** @var Log|Comment $entry */
169
        foreach ($logs as $entry) {
170
            // both log and comment have a 'user' field
171
            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

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