PageViewRequest::setupTitle()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 7
c 0
b 0
f 0
dl 0
loc 13
rs 10
cc 3
nc 3
nop 1
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
        /** @var Domain $domain */
58
        $domain = Domain::getById($request->getDomain(), $this->getDatabase());
59
        $this->assign('mediawikiScriptPath', $domain->getWikiArticlePath());
60
61
        // Shows a page if the email is not confirmed.
62
        if ($request->getEmailConfirm() !== 'Confirmed') {
63
            // Show a banner if the user can manually confirm the request
64
            $viewConfirm = $this->barrierTest(RoleConfigurationBase::MAIN, $currentUser, PageManuallyConfirm::class);
65
66
            // If the request is purged, there's nothing to confirm!
67
            if ($request->getEmail() === $this->getSiteConfiguration()->getDataClearEmail()) {
68
                $viewConfirm = false;
69
            }
70
71
            // Render
72
            $this->setTemplate("view-request/not-confirmed.tpl");
73
            $this->assign("requestId", $request->getId());
74
            $this->assign("requestVersion", $request->getUpdateVersion());
75
            $this->assign('canViewConfirmButton', $viewConfirm);
76
77
            // Make sure to return, to prevent the leaking of other information.
78
            return;
79
        }
80
81
        $this->setupBasicData($request, $config);
82
83
        $this->setupUsernameData($request);
84
85
        $this->setupTitle($request);
86
87
        $this->setupReservationDetails($request->getReserved(), $database, $currentUser);
88
        $this->setupGeneralData($database);
89
90
        $this->assign('requestDataCleared', false);
91
        if ($request->getEmail() === $this->getSiteConfiguration()->getDataClearEmail()) {
92
            $this->assign('requestDataCleared', true);
93
        }
94
95
        $allowedPrivateData = $this->isAllowedPrivateData($request, $currentUser);
96
97
        $this->setupCreationTypes($currentUser);
98
99
        $this->setupLogData($request, $database, $allowedPrivateData);
100
101
        $this->addJs("/api.php?action=templates&targetVariable=templateconfirms");
102
103
        $this->assign('showRevealLink', false);
104
        if ($request->getReserved() === $currentUser->getId() ||
105
            $this->barrierTest('alwaysSeeHash', $currentUser, 'RequestData')
106
        ) {
107
            $this->assign('showRevealLink', true);
108
            $this->assign('revealHash', $request->getRevealHash());
109
        }
110
111
        $this->assign('canSeeRelatedRequests', false);
112
        if ($allowedPrivateData || $this->barrierTest('seeRelatedRequests', $currentUser, 'RequestData')) {
113
            $this->setupRelatedRequests($request, $config, $database);
114
        }
115
116
        $this->assign('canCreateLocalAccount', $this->barrierTest('createLocalAccount', $currentUser, 'RequestData'));
117
118
        $closureDate = $request->getClosureDate();
119
        $date = new DateTime();
120
        $date->modify("-7 days");
121
        if ($request->getStatus() == "Closed" && $closureDate < $date) {
122
            $this->assign('isOldRequest', true);
123
        }
124
        $this->assign('canResetOldRequest', $this->barrierTest('reopenOldRequest', $currentUser, 'RequestData'));
125
        $this->assign('canResetPurgedRequest', $this->barrierTest('reopenClearedRequest', $currentUser, 'RequestData'));
126
127
        $this->assign('requestEmailSent', $request->getEmailSent());
128
129
        if ($allowedPrivateData) {
130
            $this->assign('manualCreationUrl', $this->getCreationUrl($domain));
131
132
            $this->setTemplate('view-request/main-with-data.tpl');
133
            $this->setupPrivateData($request, $config);
134
            $this->assign('canSetBan', $this->barrierTest('set', $currentUser, PageBan::class));
135
            $this->assign('canSeeCheckuserData', $this->barrierTest('seeUserAgentData', $currentUser, 'RequestData'));
136
137
            if ($this->barrierTest('seeUserAgentData', $currentUser, 'RequestData')) {
138
                $this->setTemplate('view-request/main-with-checkuser-data.tpl');
139
                $this->setupCheckUserData($request);
140
            }
141
        }
142
        else {
143
            $this->setTemplate('view-request/main.tpl');
144
        }
145
    }
146
147
    /**
148
     * @param Request $request
149
     */
150
    protected function setupTitle(Request $request)
151
    {
152
        $statusSymbol = self::STATUS_SYMBOL_OPEN;
153
        if ($request->getStatus() === RequestStatus::CLOSED) {
154
            if ($request->getWasCreated()) {
155
                $statusSymbol = self::STATUS_SYMBOL_ACCEPTED;
156
            }
157
            else {
158
                $statusSymbol = self::STATUS_SYMBOL_REJECTED;
159
            }
160
        }
161
162
        $this->setHtmlTitle($statusSymbol . ' #' . $request->getId());
163
    }
164
165
    /**
166
     * Sets up data unrelated to the request, such as the email template information
167
     *
168
     * @param PdoDatabase $database
169
     */
170
    protected function setupGeneralData(PdoDatabase $database)
171
    {
172
        // FIXME: domains
173
        /** @var Domain $domain */
174
        $domain = Domain::getById(1, $database);
175
        $this->assign('defaultRequestState', RequestQueue::getDefaultQueue($database, 1)->getApiName());
176
        $this->assign('activeRequestQueues', RequestQueue::getEnabledQueues($database));
177
178
        /** @var EmailTemplate $createdTemplate */
179
        $createdTemplate = EmailTemplate::getById($domain->getDefaultClose(), $database);
180
181
        $this->assign('createdHasJsQuestion', $createdTemplate->getJsquestion() != '');
182
        $this->assign('createdId', $createdTemplate->getId());
183
        $this->assign('createdName', $createdTemplate->getName());
184
185
        $preferenceManager = PreferenceManager::getForCurrent($database);
186
        $skipJsAborts = $preferenceManager->getPreference(PreferenceManager::PREF_SKIP_JS_ABORT);
187
        $preferredCreationMode = (int)$preferenceManager->getPreference(PreferenceManager::PREF_CREATION_MODE);
188
        $this->assign('skipJsAborts', $skipJsAborts);
189
        $this->assign('preferredCreationMode', $preferredCreationMode);
190
191
        $createReasons = EmailTemplate::getActiveNonpreloadTemplates(
192
            EmailTemplate::ACTION_CREATED,
193
            $database,
194
            $domain->getId(),
195
            $domain->getDefaultClose());
196
        $this->assign("createReasons", $createReasons);
197
198
        $declineReasons = EmailTemplate::getActiveNonpreloadTemplates(
199
            EmailTemplate::ACTION_NOT_CREATED,
200
            $database,
201
            $domain->getId());
202
        $this->assign("declineReasons", $declineReasons);
203
204
        $allCreateReasons = EmailTemplate::getAllActiveTemplates(
205
            EmailTemplate::ACTION_CREATED,
206
            $database,
207
            $domain->getId());
208
        $this->assign("allCreateReasons", $allCreateReasons);
209
210
        $allDeclineReasons = EmailTemplate::getAllActiveTemplates(
211
            EmailTemplate::ACTION_NOT_CREATED,
212
            $database,
213
            $domain->getId());
214
        $this->assign("allDeclineReasons", $allDeclineReasons);
215
216
        $allOtherReasons = EmailTemplate::getAllActiveTemplates(
217
            false,
218
            $database,
219
            $domain->getId());
220
        $this->assign("allOtherReasons", $allOtherReasons);
221
    }
222
223
    private function setupLogData(Request $request, PdoDatabase $database, bool $allowedPrivateData)
224
    {
225
        $currentUser = User::getCurrent($database);
226
227
        $logs = LogHelper::getRequestLogsWithComments($request->getId(), $database, $this->getSecurityManager());
228
        $requestLogs = array();
229
230
        /** @var User[] $nameCache */
231
        $nameCache = array();
232
233
        $editableComments = $this->barrierTest('editOthers', $currentUser, PageEditComment::class);
234
235
        $canFlag = $this->barrierTest(RoleConfigurationBase::MAIN, $currentUser, PageFlagComment::class);
236
        $canUnflag = $this->barrierTest('unflag', $currentUser, PageFlagComment::class);
237
238
        /** @var Log|Comment $entry */
239
        foreach ($logs as $entry) {
240
            // both log and comment have a 'user' field
241
            if (!array_key_exists($entry->getUser(), $nameCache)) {
242
                $entryUser = User::getById($entry->getUser(), $database);
243
                $nameCache[$entry->getUser()] = $entryUser;
244
            }
245
246
            if ($entry instanceof Comment) {
247
                // Determine if the comment contains private information.
248
                // Private defined as flagged or restricted visibility, but only when the user isn't allowed
249
                // to see private data
250
                $commentIsRestricted =
251
                    ($entry->getFlagged()
252
                        || $entry->getVisibility() == 'admin' || $entry->getVisibility() == 'checkuser')
253
                    && !$allowedPrivateData;
254
255
                // Only allow comment editing if the user is able to edit comments or this is the user's own comment,
256
                // but only when they're allowed to see the comment itself.
257
                $commentIsEditable = ($editableComments || $entry->getUser() == $currentUser->getId())
258
                    && !$commentIsRestricted;
259
260
                // Flagging/unflagging can only be done if you can see the comment
261
                $canFlagThisComment = $canFlag
262
                    && (
263
                        (!$entry->getFlagged() && !$commentIsRestricted)
264
                        || ($entry->getFlagged() && $canUnflag && $commentIsEditable)
265
                    );
266
267
                $requestLogs[] = array(
268
                    'type'          => 'comment',
269
                    'security'      => $entry->getVisibility(),
270
                    'user'          => $entry->getVisibility() == 'requester' ? $request->getName() : $nameCache[$entry->getUser()]->getUsername(),
271
                    'userid'        => $entry->getUser() == -1 ? null : $entry->getUser(),
272
                    'entry'         => null,
273
                    'time'          => $entry->getTime(),
274
                    'canedit'       => $commentIsEditable,
275
                    'id'            => $entry->getId(),
276
                    'comment'       => $entry->getComment(),
277
                    'flagged'       => $entry->getFlagged(),
278
                    'canflag'       => $canFlagThisComment,
279
                    'updateversion' => $entry->getUpdateVersion(),
280
                    'edited'        => $entry->getEdited(),
281
                    'hidden'        => $commentIsRestricted
282
                );
283
            }
284
285
            if ($entry instanceof Log) {
286
                $invalidUserId = $entry->getUser() === -1 || $entry->getUser() === 0;
287
                $entryUser = $invalidUserId ? User::getCommunity() : $nameCache[$entry->getUser()];
288
289
                $entryComment = $entry->getComment();
290
291
                if ($entry->getAction() === 'JobIssueRequest' || $entry->getAction() === 'JobCompletedRequest') {
292
                    $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

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