Issues (186)

includes/Pages/PageViewRequest.php (2 issues)

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
        $this->assign('createAccountReason', 'Requested account at [[WP:ACC]], request #');
173
174
        // FIXME: domains
175
        /** @var Domain $domain */
176
        $domain = Domain::getById(1, $database);
177
        $this->assign('defaultRequestState', RequestQueue::getDefaultQueue($database, 1)->getApiName());
178
        $this->assign('activeRequestQueues', RequestQueue::getEnabledQueues($database));
179
180
        /** @var EmailTemplate $createdTemplate */
181
        $createdTemplate = EmailTemplate::getById($domain->getDefaultClose(), $database);
182
183
        $this->assign('createdHasJsQuestion', $createdTemplate->getJsquestion() != '');
184
        $this->assign('createdId', $createdTemplate->getId());
185
        $this->assign('createdName', $createdTemplate->getName());
186
187
        $preferenceManager = PreferenceManager::getForCurrent($database);
188
        $skipJsAborts = $preferenceManager->getPreference(PreferenceManager::PREF_SKIP_JS_ABORT);
189
        $preferredCreationMode = (int)$preferenceManager->getPreference(PreferenceManager::PREF_CREATION_MODE);
190
        $this->assign('skipJsAborts', $skipJsAborts);
191
        $this->assign('preferredCreationMode', $preferredCreationMode);
192
193
        $createReasons = EmailTemplate::getActiveNonpreloadTemplates(
194
            EmailTemplate::ACTION_CREATED,
195
            $database,
196
            $domain->getId(),
197
            $domain->getDefaultClose());
198
        $this->assign("createReasons", $createReasons);
199
200
        $declineReasons = EmailTemplate::getActiveNonpreloadTemplates(
201
            EmailTemplate::ACTION_NOT_CREATED,
202
            $database,
203
            $domain->getId());
204
        $this->assign("declineReasons", $declineReasons);
205
206
        $allCreateReasons = EmailTemplate::getAllActiveTemplates(
207
            EmailTemplate::ACTION_CREATED,
208
            $database,
209
            $domain->getId());
210
        $this->assign("allCreateReasons", $allCreateReasons);
211
212
        $allDeclineReasons = EmailTemplate::getAllActiveTemplates(
213
            EmailTemplate::ACTION_NOT_CREATED,
214
            $database,
215
            $domain->getId());
216
        $this->assign("allDeclineReasons", $allDeclineReasons);
217
218
        $allOtherReasons = EmailTemplate::getAllActiveTemplates(
219
            false,
220
            $database,
221
            $domain->getId());
222
        $this->assign("allOtherReasons", $allOtherReasons);
223
    }
224
225
    private function setupLogData(Request $request, PdoDatabase $database, bool $allowedPrivateData)
226
    {
227
        $currentUser = User::getCurrent($database);
228
229
        $logs = LogHelper::getRequestLogsWithComments($request->getId(), $database, $this->getSecurityManager());
230
        $requestLogs = array();
231
232
        /** @var User[] $nameCache */
233
        $nameCache = array();
234
235
        $editableComments = $this->barrierTest('editOthers', $currentUser, PageEditComment::class);
236
237
        $canFlag = $this->barrierTest(RoleConfigurationBase::MAIN, $currentUser, PageFlagComment::class);
238
        $canUnflag = $this->barrierTest('unflag', $currentUser, PageFlagComment::class);
239
240
        /** @var Log|Comment $entry */
241
        foreach ($logs as $entry) {
242
            // both log and comment have a 'user' field
243
            if (!array_key_exists($entry->getUser(), $nameCache)) {
244
                $entryUser = User::getById($entry->getUser(), $database);
245
                $nameCache[$entry->getUser()] = $entryUser;
246
            }
247
248
            if ($entry instanceof Comment) {
249
                // Determine if the comment contains private information.
250
                // Private defined as flagged or restricted visibility, but only when the user isn't allowed
251
                // to see private data
252
                $commentIsRestricted =
253
                    ($entry->getFlagged()
254
                        || $entry->getVisibility() == 'admin' || $entry->getVisibility() == 'checkuser')
255
                    && !$allowedPrivateData;
256
257
                // Only allow comment editing if the user is able to edit comments or this is the user's own comment,
258
                // but only when they're allowed to see the comment itself.
259
                $commentIsEditable = ($editableComments || $entry->getUser() == $currentUser->getId())
260
                    && !$commentIsRestricted;
261
262
                // Flagging/unflagging can only be done if you can see the comment
263
                $canFlagThisComment = $canFlag
264
                    && (
265
                        (!$entry->getFlagged() && !$commentIsRestricted)
266
                        || ($entry->getFlagged() && $canUnflag && $commentIsEditable)
267
                    );
268
269
                $requestLogs[] = array(
270
                    'type'          => 'comment',
271
                    'security'      => $entry->getVisibility(),
272
                    'user'          => $entry->getVisibility() == 'requester' ? $request->getName() : $nameCache[$entry->getUser()]->getUsername(),
273
                    'userid'        => $entry->getUser() == -1 ? null : $entry->getUser(),
274
                    'entry'         => null,
275
                    'time'          => $entry->getTime(),
276
                    'canedit'       => $commentIsEditable,
277
                    'id'            => $entry->getId(),
278
                    'comment'       => $entry->getComment(),
279
                    'flagged'       => $entry->getFlagged(),
280
                    'canflag'       => $canFlagThisComment,
281
                    'updateversion' => $entry->getUpdateVersion(),
282
                    'edited'        => $entry->getEdited(),
283
                    'hidden'        => $commentIsRestricted
284
                );
285
            }
286
287
            if ($entry instanceof Log) {
288
                $invalidUserId = $entry->getUser() === -1 || $entry->getUser() === 0;
289
                $entryUser = $invalidUserId ? User::getCommunity() : $nameCache[$entry->getUser()];
290
291
                $entryComment = $entry->getComment();
292
293
                if ($entry->getAction() === 'JobIssueRequest' || $entry->getAction() === 'JobCompletedRequest') {
294
                    $data = unserialize($entry->getComment());
0 ignored issues
show
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

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