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

PageRequestAccount::createComment()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
eloc 9
c 0
b 0
f 0
dl 0
loc 15
ccs 0
cts 12
cp 0
rs 9.9666
cc 3
nc 2
nop 0
crap 12
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\Request;
10
11
use Exception;
12
use Waca\DataObjects\Comment;
13
use Waca\DataObjects\Request;
14
use Waca\Exceptions\OptimisticLockFailedException;
15
use Waca\Helpers\BanHelper;
16
use Waca\SessionAlert;
17
use Waca\Tasks\PublicInterfacePageBase;
18
use Waca\Validation\RequestValidationHelper;
19
use Waca\Validation\ValidationError;
20
use Waca\WebRequest;
21
22
class PageRequestAccount extends PublicInterfacePageBase
23
{
24
    /**
25
     * Main function for this page, when no specific actions are called.
26
     * @return void
27
     * @throws OptimisticLockFailedException
28
     * @throws Exception
29
     */
30
    protected function main()
31
    {
32
        // dual mode page
33
        if (WebRequest::wasPosted()) {
34
            $request = $this->createNewRequest();
35
            $comment = $this->createComment();
36
37
            $validationErrors = $this->validateRequest($request);
38
39
            if (count($validationErrors) > 0) {
40
                foreach ($validationErrors as $validationError) {
41
                    SessionAlert::error($validationError->getErrorMessage());
42
                }
43
44
                // Preserve the data after an error
45
                WebRequest::setSessionContext('accountReq',
46
                    array(
47
                        'username' => WebRequest::postString('name'),
48
                        'email'    => WebRequest::postEmail('email'),
49
                        'comments' => WebRequest::postString('comments'),
50
                    )
51
                );
52
53
                // Validation error, bomb out early.
54
                $this->redirect();
55
56
                return;
57
            }
58
59
            // actually save the request to the database
60
            if ($this->getSiteConfiguration()->getEmailConfirmationEnabled()) {
61
                $this->saveAsEmailConfirmation($request, $comment);
62
            }
63
            else {
64
                $this->saveWithoutEmailConfirmation($request, $comment);
65
            }
66
        }
67
        else {
68
            // set the form values from the session context
69
            $context = WebRequest::getSessionContext('accountReq');
70
            if ($context !== null && is_array($context)) {
71
                $this->assign('username', $context['username']);
72
                $this->assign('email', $context['email']);
73
                $this->assign('comments', $context['comments']);
74
            }
75
76
            // Clear it for a refresh
77
            WebRequest::setSessionContext('accountReq', null);
78
79
            $this->setTemplate('request/request-form.tpl');
80
        }
81
    }
82
83
    /**
84
     * @return Request
85
     */
86
    protected function createNewRequest()
87
    {
88
        $request = new Request();
89
        $request->setDatabase($this->getDatabase());
90
91
        $request->setName(WebRequest::postString('name'));
92
        $request->setEmail(WebRequest::postEmail('email'));
93
94
        $request->setIp(WebRequest::remoteAddress());
95
        $request->setForwardedIp(WebRequest::forwardedAddress());
96
97
        $request->setUserAgent(WebRequest::userAgent());
98
99
        return $request;
100
    }
101
102
    /**
103
     * @return Comment|null
104
     */
105
    private function createComment()
106
    {
107
        $commentText = WebRequest::postString('comments');
108
        if ($commentText === null || trim($commentText) === '') {
109
            return null;
110
        }
111
112
        $comment = new Comment();
113
        $comment->setDatabase($this->getDatabase());
114
115
        $comment->setVisibility('requester');
116
        $comment->setUser(null);
117
        $comment->setComment($commentText);
118
119
        return $comment;
120
    }
121
122
    /**
123
     * @param Request $request
124
     *
125
     * @return ValidationError[]
126
     */
127
    protected function validateRequest($request)
128
    {
129
        $validationHelper = new RequestValidationHelper(
130
            new BanHelper($this->getDatabase()),
131
            $request,
132
            WebRequest::postEmail('emailconfirm'),
133
            $this->getDatabase(),
134
            $this->getAntiSpoofProvider(),
135
            $this->getXffTrustProvider(),
136
            $this->getHttpHelper(),
137
            $this->getSiteConfiguration()->getMediawikiWebServiceEndpoint(),
138
            $this->getSiteConfiguration()->getTitleBlacklistEnabled(),
139
            $this->getTorExitProvider());
140
141
        // These are arrays of ValidationError.
142
        $nameValidation = $validationHelper->validateName();
143
        $emailValidation = $validationHelper->validateEmail();
144
        $otherValidation = $validationHelper->validateOther();
145
146
        $validationErrors = array_merge($nameValidation, $emailValidation, $otherValidation);
147
148
        return $validationErrors;
149
    }
150
151
    /**
152
     * @param Request      $request
153
     *
154
     * @param Comment|null $comment
155
     *
156
     * @throws OptimisticLockFailedException
157
     * @throws Exception
158
     */
159
    protected function saveAsEmailConfirmation(Request $request, $comment)
160
    {
161
        $request->generateEmailConfirmationHash();
162
        $request->save();
163
164
        if ($comment !== null) {
165
            $comment->setRequest($request->getId());
166
            $comment->save();
167
        }
168
169
        $trustedIp = $this->getXffTrustProvider()->getTrustedClientIp(
170
            $request->getIp(),
171
            $request->getForwardedIp());
172
173
        $this->assign("ip", $trustedIp);
174
        $this->assign("id", $request->getId());
175
        $this->assign("hash", $request->getEmailConfirm());
176
177
        // Sends the confirmation email to the user.
178
        $this->getEmailHelper()->sendMail(
179
            $request->getEmail(),
180
            "[ACC #{$request->getId()}] English Wikipedia Account Request",
181
            $this->fetchTemplate('request/confirmation-mail.tpl'));
182
183
        $this->redirect('emailConfirmationRequired');
184
    }
185
186
    /**
187
     * @param Request      $request
188
     *
189
     * @param Comment|null $comment
190
     *
191
     * @throws OptimisticLockFailedException
192
     * @throws Exception
193
     */
194
    protected function saveWithoutEmailConfirmation(Request $request, $comment)
195
    {
196
        $request->setEmailConfirm(0); // fixme Since it can't be null
197
        $request->save();
198
199
        if ($comment !== null) {
200
            $comment->setRequest($request->getId());
201
            $comment->save();
202
        }
203
204
        $this->getNotificationHelper()->requestReceived($request);
205
206
        $this->redirect('requestSubmitted');
207
    }
208
}